augment trees, pitch-limit fallback, and cached definitions

This commit is contained in:
tresabhi committed 2026-11-15 17:28:43 -06:00
1 parent da9c5272bc
commit 79129ff3c0
57 files changed
+2196 -717

No files matched your search

+1
View File
@@ -227,6 +227,7 @@
"UNLOCALIZED", "UNLOCALIZED",
"UNORM", "UNORM",
"unpickled", "unpickled",
"unranked",
"Unregistering", "Unregistering",
"unrotate", "unrotate",
"unwrapper", "unwrapper",
+13
View File
@@ -16,12 +16,15 @@ import { fetchPB } from "../../api";
import { fetchJSON } from "../../api/fetchJSON"; import { fetchJSON } from "../../api/fetchJSON";
import { BlitzScripts } from "../../types/blitzScripts"; import { BlitzScripts } from "../../types/blitzScripts";
import { AbstractBlitzKitAPI } from "./abstract"; import { AbstractBlitzKitAPI } from "./abstract";
import { Cache } from "./server/0_base";
export class ClientBlitzKitAPI extends AbstractBlitzKitAPI { export class ClientBlitzKitAPI extends AbstractBlitzKitAPI {
@Cache()
game() { game() {
return fetchPB(alias("api", "/definitions/game.pb"), GameDefinitions); return fetchPB(alias("api", "/definitions/game.pb"), GameDefinitions);
} }
@Cache()
consumables() { consumables() {
return fetchPB( return fetchPB(
alias("api", "/definitions/consumables.pb"), alias("api", "/definitions/consumables.pb"),
@@ -29,10 +32,12 @@ export class ClientBlitzKitAPI extends AbstractBlitzKitAPI {
); );
} }
@Cache()
tanks() { tanks() {
return fetchPB(alias("api", "/definitions/tanks.pb"), TankDefinitions); return fetchPB(alias("api", "/definitions/tanks.pb"), TankDefinitions);
} }
@Cache()
camouflages() { camouflages() {
return fetchPB( return fetchPB(
alias("api", "/definitions/camouflage.pb"), alias("api", "/definitions/camouflage.pb"),
@@ -40,6 +45,7 @@ export class ClientBlitzKitAPI extends AbstractBlitzKitAPI {
); );
} }
@Cache()
provisions() { provisions() {
return fetchPB( return fetchPB(
alias("api", "/definitions/provisions.pb"), alias("api", "/definitions/provisions.pb"),
@@ -47,14 +53,17 @@ export class ClientBlitzKitAPI extends AbstractBlitzKitAPI {
); );
} }
@Cache()
models() { models() {
return fetchPB(alias("api", "/definitions/models.pb"), ModelDefinitions); return fetchPB(alias("api", "/definitions/models.pb"), ModelDefinitions);
} }
@Cache()
skills() { skills() {
return fetchPB(alias("api", "/definitions/skills.pb"), SkillDefinitions); return fetchPB(alias("api", "/definitions/skills.pb"), SkillDefinitions);
} }
@Cache()
equipment() { equipment() {
return fetchPB( return fetchPB(
alias("api", "/definitions/equipment.pb"), alias("api", "/definitions/equipment.pb"),
@@ -62,18 +71,22 @@ export class ClientBlitzKitAPI extends AbstractBlitzKitAPI {
); );
} }
@Cache()
gallery() { gallery() {
return fetchPB(alias("api", "/definitions/gallery.pb"), Gallery); return fetchPB(alias("api", "/definitions/gallery.pb"), Gallery);
} }
@Cache()
maps() { maps() {
return fetchPB(alias("api", "/definitions/maps.pb"), MapDefinitions); return fetchPB(alias("api", "/definitions/maps.pb"), MapDefinitions);
} }
@Cache()
scripts() { scripts() {
return fetchJSON<BlitzScripts>(alias("api", "/definitions/scripts.json")); return fetchJSON<BlitzScripts>(alias("api", "/definitions/scripts.json"));
} }
@Cache()
strings(locale: string) { strings(locale: string) {
return fetchJSON<Strings>(alias("api", `/strings/${locale}.json`)); return fetchJSON<Strings>(alias("api", `/strings/${locale}.json`));
} }
@@ -13,11 +13,20 @@ import {
toUniqueId, toUniqueId,
TurretDefinitionsList, TurretDefinitionsList,
UnlocksListing, UnlocksListing,
UpgradeAttributesXml,
UpgradeProgressionXml,
UpgradeProgressionXmlNode,
UpgradeProgressionXmlRequirement,
VehicleDefinitionList, VehicleDefinitionList,
VehicleDefinitions, VehicleDefinitions,
} from "@blitzkit/core"; } from "@blitzkit/core";
import { import {
AssaultRanges, AssaultRanges,
AugmentAttribute,
AugmentNode,
AugmentNodeType,
AugmentProgression,
AugmentRequirement,
Crew, Crew,
Equalizer, Equalizer,
GunDefinition, GunDefinition,
@@ -32,6 +41,14 @@ import {
} from "@blitzkit/protos"; } from "@blitzkit/protos";
import { Cache, ServerBlitzKitAPI0 } from "./0_base"; import { Cache, ServerBlitzKitAPI0 } from "./0_base";
// What an augment attribute shows, by attribute name
interface AugmentAttributeDefinition {
icon: string;
title: string;
}
type AugmentAttributeDefinitions = Map<string, AugmentAttributeDefinition>;
export abstract class ServerBlitzKitAPI1 extends ServerBlitzKitAPI0 { export abstract class ServerBlitzKitAPI1 extends ServerBlitzKitAPI0 {
private parseResearchCost(raw: number | string) { private parseResearchCost(raw: number | string) {
if (typeof raw === "number") { if (typeof raw === "number") {
@@ -51,6 +68,129 @@ export abstract class ServerBlitzKitAPI1 extends ServerBlitzKitAPI0 {
} }
} }
private parseAugmentProgression(
xml: UpgradeProgressionXml,
attributeDefinitions: AugmentAttributeDefinitions,
) {
const iconName = (path?: string) => path?.split("/").at(-1);
const types = {
NODETYPE_COMMON: AugmentNodeType.AUGMENT_NODE_TYPE_COMMON,
NODETYPE_MECHANIC: AugmentNodeType.AUGMENT_NODE_TYPE_MECHANIC,
NODETYPE_ALTERNATIVE_MECHANIC:
AugmentNodeType.AUGMENT_NODE_TYPE_ALTERNATIVE,
} satisfies Record<UpgradeProgressionXmlNode["nodeType"], AugmentNodeType>;
const parseRequirements = (
requiredNodes: UpgradeProgressionXmlNode["requiredNodes"],
) =>
(requiredNodes === undefined || requiredNodes === ""
? []
: requiredNodes.node
).map((requirement: UpgradeProgressionXmlRequirement) =>
typeof requirement === "string"
? ({
tech_name: requirement,
vertical_first: false,
} satisfies AugmentRequirement)
: ({
tech_name: requirement["#text"],
vertical_first: requirement["@_verticalFirst"] === "true",
} satisfies AugmentRequirement),
);
const parseNode = (node: UpgradeProgressionXmlNode) =>
({
id: node.id,
tech_name: node.techName,
type: types[node.nodeType],
xp_cost: node.xpCost ?? 0,
position:
node.gridPosition === undefined
? undefined
: { x: node.gridPosition.column, y: node.gridPosition.row },
requires: parseRequirements(node.requiredNodes),
attributes: (node.attributes?.attribute ?? []).map(
({ attributeName, value }) => {
const definition = attributeDefinitions.get(attributeName);
return {
name: attributeName,
value: typeof value === "boolean" ? Number(value) : value,
icon: iconName(definition?.icon),
title:
definition === undefined
? undefined
: this.getString(definition.title),
} satisfies AugmentAttribute;
},
),
name:
node.displayName === undefined
? undefined
: this.getString(node.displayName),
} satisfies AugmentNode);
const parsedNodes = xml.nodes.node.map(parseNode);
const byTechName = new Map(
parsedNodes.map((node) => [node.tech_name, node]),
);
const groups =
xml.alternativeMechanicGroups?.alternativeMechanicGroup ?? [];
if (groups.length > 1) {
throw new Error(
"Upgrade progression with more than one alternative group",
);
}
const group = groups.at(0);
const alternativeNames = new Set(group?.alternativeNodes.node);
for (const node of parsedNodes) {
if (
node.type === AugmentNodeType.AUGMENT_NODE_TYPE_ALTERNATIVE &&
!alternativeNames.has(node.tech_name)
) {
throw new Error(
`Alternative upgrade ${node.tech_name} belongs to no group`,
);
}
}
return {
rows: xml.matrix.rows,
columns: xml.matrix.columns,
nodes: parsedNodes.filter(
(node) => node.type !== AugmentNodeType.AUGMENT_NODE_TYPE_ALTERNATIVE,
),
group:
group === undefined
? undefined
: {
tech_name: group.techName,
name: this.getString(group.displayName),
description: this.getString(group.description),
icon: iconName(group.icon),
xp_cost: group.xpCost,
position: {
x: group.gridPosition.column,
y: group.gridPosition.row,
},
requires: parseRequirements(group.requiredNodes),
alternatives: group.alternativeNodes.node.map((techName) => {
const node = byTechName.get(techName);
if (node === undefined) {
throw new Error(`Unknown alternative upgrade ${techName}`);
}
return node;
}),
},
} satisfies AugmentProgression;
}
@Cache() @Cache()
async tanks() { async tanks() {
const tankDefinitions = TankDefinitions.create(); const tankDefinitions = TankDefinitions.create();
@@ -164,6 +304,23 @@ export abstract class ServerBlitzKitAPI1 extends ServerBlitzKitAPI0 {
const tankXps = new Map<number, ResearchCost>(); const tankXps = new Map<number, ResearchCost>();
// Only some builds ship augment trees
const upgradeAttributesPath =
"Data/XML/item_defs/vehicles/common/tank_upgrade_attributes.xml";
const upgradeAttributeDefinitions: AugmentAttributeDefinitions = new Map();
if ((await this.vfs.resolve(upgradeAttributesPath)) !== null) {
const upgradeAttributes =
await this.vfs.xmlWithAttributes<UpgradeAttributesXml>(
upgradeAttributesPath,
);
for (const { attributeName, icon, title } of upgradeAttributes.root
.attributes.attribute) {
upgradeAttributeDefinitions.set(attributeName, { icon, title });
}
}
for (const nation of this.nationsDir!) { for (const nation of this.nationsDir!) {
const tankList = await this.vfs.xml<{ root: VehicleDefinitionList }>( const tankList = await this.vfs.xml<{ root: VehicleDefinitionList }>(
`Data/XML/item_defs/vehicles/${nation}/list.xml`, `Data/XML/item_defs/vehicles/${nation}/list.xml`,
@@ -429,12 +586,25 @@ export abstract class ServerBlitzKitAPI1 extends ServerBlitzKitAPI0 {
} }
} }
const augment_progression =
tankDefinition.root.upgradeProgression === undefined
? undefined
: this.parseAugmentProgression(
(
await this.vfs.xmlWithAttributes<{
root: { upgradeProgression: UpgradeProgressionXml };
}>(`Data/XML/item_defs/vehicles/${nation}/${tankKey}.xml`)
).root.upgradeProgression,
upgradeAttributeDefinitions,
);
tankDefinitions.tanks[tankId] = { tankDefinitions.tanks[tankId] = {
ancestors: [], ancestors: [],
successors: [], successors: [],
id: tankId, id: tankId,
dev_name: tankKey, dev_name: tankKey,
module_positions, module_positions,
augment_progression,
roles: {}, roles: {},
camouflages: camouflages, camouflages: camouflages,
fixed_camouflage: fixedCamouflage, fixed_camouflage: fixedCamouflage,
@@ -21,6 +21,13 @@ import { MathUtils, Vector3 as THREEVector3, Vector3Tuple } from "three";
import { Cache } from "./0_base"; import { Cache } from "./0_base";
import { ServerBlitzKitAPI2 } from "./2_camouflages"; import { ServerBlitzKitAPI2 } from "./2_camouflages";
// The `front` and `back` tags hold "min max range" in degrees
function parseExtraPitchLimitValues(raw: string | undefined) {
if (raw === undefined) return undefined;
return raw.trim().split(/\s+/).map(Number);
}
export abstract class ServerBlitzKitAPI3 extends ServerBlitzKitAPI2 { export abstract class ServerBlitzKitAPI3 extends ServerBlitzKitAPI2 {
private vector3TupleToBlitzkit(tuple: Vector3Tuple) { private vector3TupleToBlitzkit(tuple: Vector3Tuple) {
return { x: tuple[0], y: tuple[1], z: -tuple[2] } satisfies ProtoVector3; return { x: tuple[0], y: tuple[1], z: -tuple[2] } satisfies ProtoVector3;
@@ -350,17 +357,21 @@ export abstract class ServerBlitzKitAPI3 extends ServerBlitzKitAPI2 {
gunModel = 2; gunModel = 2;
} }
const front = gun.extraPitchLimits?.front // The client merges shared and per-tank values one field at a time:
? gun.extraPitchLimits.front.split(" ").map(Number) // front, back and transition each fall back on the shared gun
: undefined; const extraPitchLimits = {
const back = gun.extraPitchLimits?.back ...gunListEntry.extraPitchLimits,
? gun.extraPitchLimits.back.split(" ").map(Number) ...gun.extraPitchLimits,
: undefined; };
const transition = gun.extraPitchLimits?.transition const front = parseExtraPitchLimitValues(extraPitchLimits.front);
? typeof gun.extraPitchLimits.transition === "number" const back = parseExtraPitchLimitValues(extraPitchLimits.back);
? gun.extraPitchLimits.transition // A repeated tag overwrites the last one, and one value covers both
: gun.extraPitchLimits.transition.at(-1)! const transition =
: undefined; extraPitchLimits.transition === undefined
? undefined
: typeof extraPitchLimits.transition === "number"
? extraPitchLimits.transition
: extraPitchLimits.transition.at(-1)!;
const gunArmor: Armor = { thickness: {}, spaced: [] }; const gunArmor: Armor = { thickness: {}, spaced: [] };
const maskName = `gun_${gunModel.toString().padStart(2, "0")}`; const maskName = `gun_${gunModel.toString().padStart(2, "0")}`;
const maskEnabled = const maskEnabled =
@@ -4,9 +4,21 @@ import { XMLParser } from "fast-xml-parser";
import type { normalize } from "node:path/posix"; import type { normalize } from "node:path/posix";
import { parse as parseYaml } from "yaml"; import { parse as parseYaml } from "yaml";
// Tags of an upgrade progression that are lists even with a single child
const UPGRADE_PROGRESSION_LIST_TAGS = new Set([
"node",
"attribute",
"alternativeMechanicGroup",
]);
export abstract class AbstractVFS { export abstract class AbstractVFS {
textDecoder = new TextDecoder(); textDecoder = new TextDecoder();
private xmlParser = new XMLParser(); private xmlParser = new XMLParser();
private attributeXmlParser = new XMLParser({
ignoreAttributes: false,
// A lone child would otherwise parse to an object instead of a list
isArray: (name) => UPGRADE_PROGRESSION_LIST_TAGS.has(name),
});
protected normalizePath?: typeof normalize; protected normalizePath?: typeof normalize;
@@ -80,6 +92,12 @@ export abstract class AbstractVFS {
return this.xmlParser.parse(file) as Type; return this.xmlParser.parse(file) as Type;
} }
// Keeps attributes as `@_name` and lists as arrays, which `xml` drops
async xmlWithAttributes<Type>(path: string) {
const file = await this.text(path);
return this.attributeXmlParser.parse(file) as Type;
}
protected async _csv(text: string, options: Options = {}) { protected async _csv(text: string, options: Options = {}) {
const parsed = parseCSV(text, options); const parsed = parseCSV(text, options);
return parsed; return parsed;
@@ -17,6 +17,11 @@ export interface GunDefinitionsList {
tags: string; tags: string;
level: number; level: number;
pitchLimits: string; pitchLimits: string;
extraPitchLimits?: {
front?: string;
back?: string;
transition?: number | number[];
};
burst?: { count: number; rate: number }; burst?: { count: number; rate: number };
clip?: { count: number; rate: number }; clip?: { count: number; rate: number };
shots: { shots: {
+1
View File
@@ -23,6 +23,7 @@ export * from "./tankParameters";
export * from "./tanksStats"; export * from "./tanksStats";
export * from "./techTreeLayoutYaml"; export * from "./techTreeLayoutYaml";
export * from "./turretDefinitionsList"; export * from "./turretDefinitionsList";
export * from "./upgradeProgressionXml";
export * from "./vehicleDefinitionArmor"; export * from "./vehicleDefinitionArmor";
export * from "./vehicleDefinitionList"; export * from "./vehicleDefinitionList";
export * from "./vehicleDefinitions"; export * from "./vehicleDefinitions";
@@ -0,0 +1,61 @@
// Parsed with attributes and with these elements forced to arrays, see
// `AbstractVFS.xmlWithAttributes`
// Plain text unless the connector carries `verticalFirst`
export type UpgradeProgressionXmlRequirement =
| string
// Attribute values stay strings
| { "#text": string; "@_verticalFirst"?: string };
export interface UpgradeProgressionXmlAttribute {
attributeName: string;
// Numbers, or `true`/`false` for switches
value: number | boolean;
}
export interface UpgradeProgressionXmlNode {
id: number;
techName: string;
nodeType:
| "NODETYPE_COMMON"
| "NODETYPE_MECHANIC"
| "NODETYPE_ALTERNATIVE_MECHANIC";
xpCost?: number;
displayName?: string;
icon?: string;
gridPosition?: { row: number; column: number };
// Empty elements parse to an empty string
requiredNodes?: "" | { node: UpgradeProgressionXmlRequirement[] };
attributes?: { attribute: UpgradeProgressionXmlAttribute[] };
}
export interface UpgradeProgressionXmlGroup {
techName: string;
displayName: string;
description: string;
icon?: string;
xpCost: number;
gridPosition: { row: number; column: number };
requiredNodes: { node: UpgradeProgressionXmlRequirement[] };
alternativeNodes: { node: string[] };
}
export interface UpgradeProgressionXml {
matrix: { rows: number; columns: number };
alternativeMechanicGroups?: {
alternativeMechanicGroup: UpgradeProgressionXmlGroup[];
};
nodes: { node: UpgradeProgressionXmlNode[] };
}
export interface UpgradeAttributesXml {
root: {
attributes: {
attribute: {
attributeName: string;
icon: string;
title: string;
}[];
};
};
}
@@ -1,4 +1,4 @@
import { BlitzModuleType } from "@blitzkit/core"; import { BlitzModuleType, VehicleDefinitionArmor } from "@blitzkit/core";
export interface VehicleDefinitions { export interface VehicleDefinitions {
invisibility: { invisibility: {
@@ -13,6 +13,8 @@ export interface VehicleDefinitions {
}; };
consumableSlots: number; consumableSlots: number;
provisionSlots: number; provisionSlots: number;
// Tier 11 tanks only, parsed separately because it needs attributes
upgradeProgression?: object;
optDevicePreset: string | string[]; optDevicePreset: string | string[];
hull: { hull: {
armor: VehicleDefinitionArmor; armor: VehicleDefinitionArmor;
+6 -3
View File
@@ -178,7 +178,9 @@
"flexibility": "Flexibility", "flexibility": "Flexibility",
"maneuverability": "Maneuverability", "maneuverability": "Maneuverability",
"survivability": "Survivability", "survivability": "Survivability",
"concealment": "Concealment" "concealment": "Concealment",
"assault_shells": "Assault shells"
}, },
"items": { "items": {
@@ -225,8 +227,8 @@
"gun_rear_elevation": "Rear elevation", "gun_rear_elevation": "Rear elevation",
"azimuth_left": "Azimuth left", "azimuth_left": "Azimuth left",
"azimuth_right": "Azimuth right", "azimuth_right": "Azimuth right",
"speed_forward": "Forward", "speed_forward": "Top speed",
"speed_backward": "Backward", "speed_backward": "Reverse speed",
"speeds": "Speed", "speeds": "Speed",
"engine_power": "Engine power", "engine_power": "Engine power",
"brake_force": "Brake force", "brake_force": "Brake force",
@@ -288,6 +290,7 @@
"consumables": "Consumables", "consumables": "Consumables",
"provisions": "Provisions", "provisions": "Provisions",
"modules": "Modules", "modules": "Modules",
"augments": "Augments",
"camouflage": "Camouflage", "camouflage": "Camouflage",
"module_types": { "module_types": {
"turret": "Turret", "turret": "Turret",
@@ -10,40 +10,41 @@ message TankDefinitions {
} }
message TankDefinition { message TankDefinition {
uint32 id = 1; uint32 id = 1;
string slug = 2; string slug = 2;
map<string, uint32> roles = 3; map<string, uint32> roles = 3;
bool fixed_camouflage = 5; bool fixed_camouflage = 5;
repeated int32 camouflages = 6; repeated int32 camouflages = 6;
repeated int32 ancestors = 7; repeated int32 ancestors = 7;
repeated int32 successors = 8; repeated int32 successors = 8;
repeated Crew crew = 9; repeated Crew crew = 9;
uint32 health = 10; uint32 health = 10;
string nation = 11; string nation = 11;
I18nString name = 12; I18nString name = 12;
TankType type = 13; TankType type = 13;
uint32 max_consumables = 14; uint32 max_consumables = 14;
uint32 max_provisions = 15; uint32 max_provisions = 15;
uint32 tier = 16; uint32 tier = 16;
TankClass class = 17; TankClass class = 17;
bool testing = 18; bool testing = 18;
bool deprecated = 19; bool deprecated = 19;
repeated TurretDefinition turrets = 20; repeated TurretDefinition turrets = 20;
repeated EngineDefinition engines = 21; repeated EngineDefinition engines = 21;
repeated TrackDefinition tracks = 22; repeated TrackDefinition tracks = 22;
TankPrice price = 23; TankPrice price = 23;
optional ResearchCost research_cost = 24; optional ResearchCost research_cost = 24;
float speed_forwards = 25; float speed_forwards = 25;
float speed_backwards = 26; float speed_backwards = 26;
float camouflage_still = 27; float camouflage_still = 27;
float camouflage_moving = 28; float camouflage_moving = 28;
float camouflage_on_fire = 29; float camouflage_on_fire = 29;
string equipment_preset = 30; string equipment_preset = 30;
uint32 weight = 31; uint32 weight = 31;
string dev_name = 32; string dev_name = 32;
optional Equalizer equalizer = 33; optional Equalizer equalizer = 33;
optional I18nString name_full = 34; optional I18nString name_full = 34;
repeated ModulePosition module_positions = 35; repeated ModulePosition module_positions = 35;
optional AugmentProgression augment_progression = 36;
} }
// Hand-authored cell in the modules screen grid. Tanks without any use the // Hand-authored cell in the modules screen grid. Tanks without any use the
@@ -54,6 +55,63 @@ message ModulePosition {
ProtoVector2 position = 3; ProtoVector2 position = 3;
} }
// Tier 11 augment tree (`upgradeProgression` in the game files). Cells are
// placed by hand on a 1-based grid and the connectors are routed by the
// client, see the loadout augments layout.
message AugmentProgression {
uint32 rows = 1;
uint32 columns = 2;
repeated AugmentNode nodes = 3;
optional AugmentGroup group = 4;
}
// TODO: render these differently in the browser
enum AugmentNodeType {
AUGMENT_NODE_TYPE_COMMON = 0;
AUGMENT_NODE_TYPE_MECHANIC = 1;
AUGMENT_NODE_TYPE_ALTERNATIVE = 2;
}
message AugmentNode {
int32 id = 1;
string tech_name = 2;
AugmentNodeType type = 3;
// Alternative nodes live in their group and cost nothing on their own
int32 xp_cost = 4;
// Missing for alternative nodes
optional ProtoVector2 position = 5;
repeated AugmentRequirement requires = 6;
repeated AugmentAttribute attributes = 7;
optional I18nString name = 8;
}
message AugmentRequirement {
string tech_name = 1;
// Route the connector along the column before the row
bool vertical_first = 2;
}
message AugmentAttribute {
string name = 1;
// Switches are stored as 0 or 1
float value = 2;
// Icon file name, missing for attributes the client has no art for
optional string icon = 3;
optional I18nString title = 4;
}
// Mutually exclusive final choice that all of its requirements lead into
message AugmentGroup {
string tech_name = 1;
I18nString name = 2;
I18nString description = 3;
optional string icon = 4;
int32 xp_cost = 5;
ProtoVector2 position = 6;
repeated AugmentRequirement requires = 7;
repeated AugmentNode alternatives = 8;
}
message Equalizer { message Equalizer {
float health = 1; float health = 1;
float penetration = 2; float penetration = 2;
@@ -19,7 +19,7 @@
&[data-size="major"] { &[data-size="major"] {
--padding: var(--space-3); --padding: var(--space-3);
--content-size: calc(1.5 * var(--font-size-regular)); --content-size: calc(1.75 * var(--font-size-regular));
} }
padding: var(--padding) calc(2 * var(--padding)); padding: var(--padding) calc(2 * var(--padding));
@@ -1,5 +1,5 @@
.discriminator { .discriminator {
--inset: var(--space-3); --inset: var(--space-2);
&[data-inset="small"] { &[data-inset="small"] {
--inset: var(--space-2); --inset: var(--space-2);
@@ -0,0 +1,87 @@
.tree {
--line-thickness: calc(var(--space-1) * 2);
--line-color: var(--gray-6);
.cell {
.north,
.south,
.west,
.east {
position: absolute;
background-color: var(--line-color);
}
.north,
.south {
left: 50%;
width: var(--line-thickness);
transform: translateX(-50%);
}
.west,
.east {
top: 50%;
height: var(--line-thickness);
transform: translateY(-50%);
}
/* An empty cell passes a line through, out to the middle of the gaps */
.north {
top: calc(var(--depth-gap) / -2);
height: calc(50% + var(--depth-gap) / 2);
}
.south {
bottom: calc(var(--depth-gap) / -2);
height: calc(50% + var(--depth-gap) / 2);
}
.west {
left: calc(var(--sibling-gap) / -2);
width: calc(50% + var(--sibling-gap) / 2);
}
.east {
right: calc(var(--sibling-gap) / -2);
width: calc(50% + var(--sibling-gap) / 2);
}
/* The buttons are translucent, so around a node the lines stay in the gaps */
&[data-node="true"] {
.north {
top: auto;
bottom: 100%;
height: calc(var(--depth-gap) / 2);
}
.south {
bottom: auto;
top: 100%;
height: calc(var(--depth-gap) / 2);
}
.west {
left: auto;
right: 100%;
width: calc(var(--sibling-gap) / 2);
}
.east {
right: auto;
left: 100%;
width: calc(var(--sibling-gap) / 2);
}
}
}
.alternatives {
grid-column: 1 / -1;
display: flex;
justify-content: center;
gap: var(--sibling-gap);
/* Prices hang below the nodes */
padding-bottom: calc(var(--space-2) + var(--font-size-minor));
}
}
@@ -0,0 +1,244 @@
import { alias, formatCompact } from "@blitzkit/core";
import {
AugmentNodeType,
type AugmentGroup,
type AugmentNode,
type AugmentProgression,
} from "@blitzkit/protos";
import {
DoubleArrowDownIcon,
DoubleArrowUpIcon,
LightningBoltIcon,
StarFilledIcon,
} from "@radix-ui/react-icons";
import { useCallback, useMemo } from "react";
import { useLocale } from "../../hooks/useLocale";
import { useStrings } from "../../hooks/useStrings";
import { layoutAugmentTree } from "../../tankopedia/augmentTreeLayout";
import { AUGMENT_GROUP_ID } from "../../tankopedia/augments";
import { classNames } from "../../ui/classNames";
import { IconButton } from "../IconButton";
import { LoadoutSection } from "../LoadoutSection";
import shared from "../LoadoutTree/index.module.css";
import { Text } from "../Text";
import styles from "./index.module.css";
interface AugmentIconProps {
icon?: string;
isCommon: boolean;
}
function AugmentIcon({ icon, isCommon }: AugmentIconProps) {
if (icon !== undefined) {
return (
<img
alt=""
src={alias("api", `/icons/augments/${icon}.webp`)}
className={shared.icon}
/>
);
}
return isCommon ? (
<StarFilledIcon className={shared.icon} />
) : (
<LightningBoltIcon className={shared.icon} />
);
}
interface PriceProps {
xp: number;
}
function Price({ xp }: PriceProps) {
const locale = useLocale();
if (xp <= 0) return null;
return (
<div className={shared.price}>
<Text size="minor">{formatCompact(locale, xp)}</Text>
<img alt="xp" src={alias("api", "/icons/currencies/xp.webp")} />
</div>
);
}
interface AugmentButtonProps {
node: AugmentNode;
isSelected: boolean;
onToggle: (id: number) => void;
}
function AugmentButton({ node, isSelected, onToggle }: AugmentButtonProps) {
const isCommon = node.type === AugmentNodeType.AUGMENT_NODE_TYPE_COMMON;
const handleClick = useCallback(() => onToggle(node.id), [onToggle, node]);
return (
<IconButton
radius="1"
size="major"
variant={isSelected ? "surface" : "soft"}
color={isSelected ? (isCommon ? undefined : "amber") : "gray"}
className={shared.node}
data-notable={!isCommon}
onClick={handleClick}
>
<AugmentIcon
icon={node.attributes.find((attribute) => attribute.icon)?.icon}
isCommon={isCommon}
/>
<Price xp={node.xp_cost} />
</IconButton>
);
}
interface GroupButtonProps {
group: AugmentGroup;
// One of its alternatives is installed
isSelected: boolean;
onToggle: (id: number) => void;
}
// Where the branches meet; the choice itself hangs below
function GroupButton({ group, isSelected, onToggle }: GroupButtonProps) {
const handleClick = useCallback(() => onToggle(AUGMENT_GROUP_ID), [onToggle]);
return (
<IconButton
radius="1"
size="major"
variant={isSelected ? "surface" : "soft"}
color={isSelected ? "amber" : "gray"}
className={shared.node}
data-notable
onClick={handleClick}
>
<AugmentIcon icon={group.icon} isCommon={false} />
<Price xp={group.xp_cost} />
</IconButton>
);
}
interface ContentProps {
progression: AugmentProgression;
selected: number[];
onToggle: (id: number) => void;
}
function Content({ progression, selected, onToggle }: ContentProps) {
const { group } = progression;
const installed = useMemo(() => new Set(selected), [selected]);
const isGroupSelected =
group?.alternatives.some(({ id }) => installed.has(id)) ?? false;
const { cells, columns, rows } = useMemo(
() => layoutAugmentTree(progression),
[progression],
);
return (
<div
className={classNames(shared.tree, styles.tree)}
style={{
gridTemplateColumns: `repeat(${columns}, auto)`,
gridTemplateRows: `repeat(${rows}, auto) auto`,
}}
>
{cells.map((cell) => (
<div
key={`${cell.row},${cell.column}`}
className={classNames(shared.cell, styles.cell)}
data-node={cell.node !== undefined || cell.group !== undefined}
style={{ gridColumn: cell.column, gridRow: cell.row }}
>
{cell.north && <span className={styles.north} />}
{cell.south && <span className={styles.south} />}
{cell.west && <span className={styles.west} />}
{cell.east && <span className={styles.east} />}
{cell.node && (
<AugmentButton
node={cell.node}
isSelected={installed.has(cell.node.id)}
onToggle={onToggle}
/>
)}
{cell.group && (
<GroupButton
group={cell.group}
isSelected={isGroupSelected}
onToggle={onToggle}
/>
)}
</div>
))}
{group !== undefined && (
// The mutually exclusive choice, hanging below the cell that leads in
<div className={styles.alternatives} style={{ gridRow: rows + 1 }}>
{group.alternatives.map((node) => (
<AugmentButton
key={node.id}
node={node}
isSelected={installed.has(node.id)}
onToggle={onToggle}
/>
))}
</div>
)}
</div>
);
}
interface LoadoutAugmentsProps {
progression: AugmentProgression;
selected: number[];
onToggle: (id: number) => void;
onStock: () => void;
onMaximize: () => void;
}
export function LoadoutAugments({
progression,
selected,
onToggle,
onStock,
onMaximize,
}: LoadoutAugmentsProps) {
const strings = useStrings();
return (
<LoadoutSection
title={strings.tanks.loadout.augments}
actions={
<>
<IconButton
highContrast
color="gray"
size="minor"
variant="ghost"
onClick={onStock}
>
<DoubleArrowUpIcon />
</IconButton>
<IconButton
highContrast
color="gray"
size="minor"
variant="ghost"
onClick={onMaximize}
>
<DoubleArrowDownIcon />
</IconButton>
</>
}
>
<Content
progression={progression}
selected={selected}
onToggle={onToggle}
/>
</LoadoutSection>
);
}
@@ -1,7 +1,4 @@
.tree { .tree {
/* The game lays the tree out left to right; here depth runs top to bottom */
--depth-gap: var(--space-5);
--sibling-gap: var(--space-4);
--line-thickness: var(--space-1); --line-thickness: var(--space-1);
--line-border: var(--space-1) solid var(--gray-6); --line-border: var(--space-1) solid var(--gray-6);
@@ -9,12 +6,7 @@
margin-bottom: calc(var(--space-2) + var(--font-size-minor)); margin-bottom: calc(var(--space-2) + var(--font-size-minor));
} }
display: grid;
gap: var(--depth-gap) var(--sibling-gap);
.cell { .cell {
position: relative;
.trunk-left, .trunk-left,
.trunk-right { .trunk-right {
position: absolute; position: absolute;
@@ -71,41 +63,5 @@
.snake-right { .snake-right {
left: 100%; left: 100%;
} }
.module {
position: relative;
.icon {
width: 2em;
height: 2em;
.module[data-major="true"] & {
transform: scale(1.25);
}
}
.price {
display: flex;
gap: var(--space-1);
font-size: var(--font-size-minor);
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
margin-top: var(--space-2);
background-color: var(--gray-2);
svg,
img {
width: 1em;
height: 1em;
}
}
}
} }
} }
@@ -16,10 +16,12 @@ import { useStrings } from "../../hooks/useStrings";
import { useUnwrapper } from "../../hooks/useUnwrapper"; import { useUnwrapper } from "../../hooks/useUnwrapper";
import { layoutModuleTree } from "../../tankopedia/moduleTreeLayout"; import { layoutModuleTree } from "../../tankopedia/moduleTreeLayout";
import type { TankState } from "../../tankopedia/tankState"; import type { TankState } from "../../tankopedia/tankState";
import { classNames } from "../../ui/classNames";
import { Discriminator } from "../Discriminator"; import { Discriminator } from "../Discriminator";
import { IconButton } from "../IconButton"; import { IconButton } from "../IconButton";
import { LinkI18n } from "../LinkI18n"; import { LinkI18n } from "../LinkI18n";
import { LoadoutSection } from "../LoadoutSection"; import { LoadoutSection } from "../LoadoutSection";
import shared from "../LoadoutTree/index.module.css";
import { Text } from "../Text"; import { Text } from "../Text";
import { Tooltip } from "../Tooltip"; import { Tooltip } from "../Tooltip";
import styles from "./index.module.css"; import styles from "./index.module.css";
@@ -76,11 +78,11 @@ function Content({ tank, selected, onSelect }: ContentProps) {
tank.turrets tank.turrets
.flatMap((turret) => turret.guns) .flatMap((turret) => turret.guns)
.toReversed() .toReversed()
.map((gun) => [gun.id, gun]) .map((gun) => [gun.id, gun]),
), ),
], ],
]), ]),
[tank] [tank],
); );
const resolve = useCallback( const resolve = useCallback(
@@ -88,7 +90,7 @@ function Content({ tank, selected, onSelect }: ContentProps) {
unlock.type === ModuleType.MODULE_TYPE_VEHICLE unlock.type === ModuleType.MODULE_TYPE_VEHICLE
? (tanks.tanks[unlock.id] as TankDefinition | undefined) ? (tanks.tanks[unlock.id] as TankDefinition | undefined)
: modules.get(unlock.type)?.get(unlock.id), : modules.get(unlock.type)?.get(unlock.id),
[modules] [modules],
); );
const { cells, columns, rows } = useMemo( const { cells, columns, rows } = useMemo(
@@ -107,9 +109,9 @@ function Content({ tank, selected, onSelect }: ContentProps) {
return children.filter((child) => resolve(child) !== undefined); return children.filter((child) => resolve(child) !== undefined);
}, },
tank.module_positions tank.module_positions,
), ),
[tank, resolve] [tank, resolve],
); );
// Prices hang below the modules, so room is only reserved if the bottom row has one // Prices hang below the modules, so room is only reserved if the bottom row has one
@@ -118,12 +120,12 @@ function Content({ tank, selected, onSelect }: ContentProps) {
(cell) => (cell) =>
cell.position[0] === bottomRow && cell.position[0] === bottomRow &&
cell.unlock !== undefined && cell.unlock !== undefined &&
cell.unlock.cost!.value > 0 cell.unlock.cost!.value > 0,
); );
return ( return (
<div <div
className={styles.tree} className={classNames(shared.tree, styles.tree)}
data-has-bottom-cost={hasBottomCost} data-has-bottom-cost={hasBottomCost}
style={{ style={{
// Transposed: the layout's columns (depth) become rows // Transposed: the layout's columns (depth) become rows
@@ -137,7 +139,7 @@ function Content({ tank, selected, onSelect }: ContentProps) {
return ( return (
<div <div
key={cell.position.join(",")} key={cell.position.join(",")}
className={styles.cell} className={classNames(shared.cell, styles.cell)}
style={{ gridColumn: cell.position[1], gridRow: cell.position[0] }} style={{ gridColumn: cell.position[1], gridRow: cell.position[0] }}
> >
{cell.trunkUp && <span className={styles["trunk-left"]} />} {cell.trunkUp && <span className={styles["trunk-left"]} />}
@@ -209,9 +211,10 @@ function ModuleNode({
const button = ( const button = (
<IconButton <IconButton
radius="1" radius="1"
size="major"
variant={isSelected ? "surface" : "soft"} variant={isSelected ? "surface" : "soft"}
color={isSelected ? (isTop ? "amber" : undefined) : "gray"} color={isSelected ? (isTop ? "amber" : undefined) : "gray"}
className={styles.module} className={shared.node}
data-major={unlock.type === ModuleType.MODULE_TYPE_VEHICLE} data-major={unlock.type === ModuleType.MODULE_TYPE_VEHICLE}
onClick={() => { onClick={() => {
if (!isTank) onSelect(unlock); if (!isTank) onSelect(unlock);
@@ -224,16 +227,15 @@ function ModuleNode({
? tankIcon(unlock.id) ? tankIcon(unlock.id)
: alias( : alias(
"api", "api",
`/icons/modules/${moduleIconNames[unlock.type]}.webp` `/icons/modules/${moduleIconNames[unlock.type]}.webp`,
) )
} }
className={styles.icon}
/> />
<Discriminator corner="top-left">{romanize(module.tier)}</Discriminator> <Discriminator corner="top-left">{romanize(module.tier)}</Discriminator>
{unlock.cost!.value > 0 && ( {unlock.cost!.value > 0 && (
<div className={styles.price}> <div className={shared.price}>
<Text size="minor">{formatCompact(locale, unlock.cost!.value)}</Text> <Text size="minor">{formatCompact(locale, unlock.cost!.value)}</Text>
<img <img
alt={unlock.cost!.type} alt={unlock.cost!.type}
@@ -0,0 +1,41 @@
/* What the modules and the augments have in common; each draws its own lines */
.tree {
/* The game lays the tree out left to right; here depth runs top to bottom */
--depth-gap: var(--space-5);
--sibling-gap: var(--space-4);
display: grid;
gap: var(--depth-gap) var(--sibling-gap);
}
.cell {
position: relative;
}
.node {
position: relative;
.price {
display: flex;
gap: var(--space-1);
font-size: var(--font-size-minor);
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
margin-top: var(--space-2);
background-color: var(--gray-2);
svg,
img {
width: 1em;
height: 1em;
}
}
}
@@ -8,12 +8,12 @@ import { useStrings } from "../hooks/useStrings";
import { TankopediaSortDirection } from "../stores/tankopediaPersistent"; import { TankopediaSortDirection } from "../stores/tankopediaPersistent";
import { TankSort } from "../stores/tankopediaSort"; import { TankSort } from "../stores/tankopediaSort";
import { sortableCharacteristics } from "../tankopedia/sortableCharacteristics"; import { sortableCharacteristics } from "../tankopedia/sortableCharacteristics";
import type { CharacteristicName } from "../types/characteristics"; import type { RenderedCharacteristicName } from "../types/characteristics";
import { Button } from "./Button"; import { Button } from "./Button";
import { DropdownMenu } from "./DropdownMenu"; import { DropdownMenu } from "./DropdownMenu";
interface ItemProps { interface ItemProps {
by: CharacteristicName; by: RenderedCharacteristicName;
} }
function Item({ by }: ItemProps) { function Item({ by }: ItemProps) {
@@ -77,6 +77,8 @@ export function TankSearchSort() {
(item) => "name" in item && sortableCharacteristics.has(item.name), (item) => "name" in item && sortableCharacteristics.has(item.name),
); );
if (items.length === 0) return null;
return ( return (
<DropdownMenu.Sub key={group.name}> <DropdownMenu.Sub key={group.name}>
<DropdownMenu.SubTrigger> <DropdownMenu.SubTrigger>
@@ -88,6 +88,10 @@
align-items: center; align-items: center;
gap: var(--space-3); gap: var(--space-3);
/* Same height with or without the number, so the bars line up */
font-size: var(--font-size-minor);
height: 1em;
.bar-wrapper { .bar-wrapper {
flex: 1; flex: 1;
height: var(--space-1); height: var(--space-1);
@@ -1,6 +1,6 @@
import { romanize } from "@blitzkit/core"; import { romanize } from "@blitzkit/core";
import { literals } from "@blitzkit/i18n/src/literals"; import { literals } from "@blitzkit/i18n/src/literals";
import { useRef } from "react"; import { Fragment, useRef } from "react";
import { characteristicsGroups } from "../../config/characteristicsGroups"; import { characteristicsGroups } from "../../config/characteristicsGroups";
import { toys } from "../../config/toys"; import { toys } from "../../config/toys";
import { useDuelModules } from "../../hooks/useDuelModules"; import { useDuelModules } from "../../hooks/useDuelModules";
@@ -15,6 +15,7 @@ import type {
CharacteristicsGroup, CharacteristicsGroup,
ComputedCharacteristics, ComputedCharacteristics,
ToyName, ToyName,
ToyRenderConfig,
} from "../../types/characteristics"; } from "../../types/characteristics";
import { Heading } from "../Heading"; import { Heading } from "../Heading";
import { SegmentedControl } from "../SegmentedControl"; import { SegmentedControl } from "../SegmentedControl";
@@ -36,28 +37,35 @@ export function TankopediaCharacteristics({
<CompareOptions /> <CompareOptions />
<div className={styles.characteristics}> <div className={styles.characteristics}>
{characteristicsGroups.map((group) => { {characteristicsGroups.map((group) => (
const items = group.order.filter( <Group
(item) => "name" in item && characteristics.has(item.name), key={group.name}
).length; group={group}
const shouldRender = items > 0; characteristics={characteristics}
rankings={rankings}
if (!shouldRender) return null; />
))}
return (
<Group
key={group.name}
group={group}
characteristics={characteristics}
rankings={rankings}
/>
);
})}
</div> </div>
</div> </div>
); );
} }
type GroupItem = CharacteristicsGroup["order"][number];
// A toy that needs a characteristic only shows for the tanks that have it
function hasToy(
{ requires }: ToyRenderConfig,
characteristics: ComputedCharacteristics,
) {
return requires === undefined || characteristics.has(requires);
}
function itemKey(item: GroupItem) {
if ("toy" in item) return `toy:${item.toy}`;
if ("label" in item) return `label:${item.label}`;
return item.name;
}
interface GroupProps { interface GroupProps {
group: CharacteristicsGroup; group: CharacteristicsGroup;
characteristics: ComputedCharacteristics; characteristics: ComputedCharacteristics;
@@ -66,15 +74,25 @@ interface GroupProps {
function Group({ group, characteristics, rankings }: GroupProps) { function Group({ group, characteristics, rankings }: GroupProps) {
const strings = useStrings(); const strings = useStrings();
const toys = group.order.filter((item) => "toy" in item).length; let toys = 0;
const characteristicsCount = group.order.filter( let characteristicsCount = 0;
(item) => "name" in item && characteristics.has(item.name), let labelsCount = 0;
).length;
const labelsCount = for (const item of group.order) {
characteristicsCount > 0 if ("toy" in item) {
? group.order.filter((item) => "label" in item).length if (hasToy(item, characteristics)) toys++;
: 0; } else if ("label" in item) {
const items = characteristicsCount + labelsCount; labelsCount++;
} else if (characteristics.has(item.name)) {
characteristicsCount++;
}
}
if (toys + characteristicsCount === 0) return null;
// Labels only head characteristics, so they go when there are none
const hasLabels = characteristicsCount > 0;
const items = characteristicsCount + (hasLabels ? labelsCount : 0);
const groupSpan = `calc(${toys} * var(--group-span) + ${items} + 2)`; const groupSpan = `calc(${toys} * var(--group-span) + ${items} + 2)`;
const contentSpan = `calc(${toys} * var(--group-span) + ${items})`; const contentSpan = `calc(${toys} * var(--group-span) + ${items})`;
@@ -105,11 +123,11 @@ function Group({ group, characteristics, rankings }: GroupProps) {
}} }}
> >
{group.order.map((item) => ( {group.order.map((item) => (
<> <Fragment key={itemKey(item)}>
{"toy" in item && ( {"toy" in item && hasToy(item, characteristics) && (
<ToyAssigner characteristics={characteristics} {...item} /> <ToyAssigner characteristics={characteristics} toy={item.toy} />
)} )}
{"label" in item && <Label {...item} />} {"label" in item && hasLabels && <Label {...item} />}
{"name" in item && characteristics.has(item.name) && ( {"name" in item && characteristics.has(item.name) && (
<Item <Item
config={item} config={item}
@@ -117,7 +135,7 @@ function Group({ group, characteristics, rankings }: GroupProps) {
ranking={rankings.get(item.name)} ranking={rankings.get(item.name)}
/> />
)} )}
</> </Fragment>
))} ))}
<div className={styles.dead} /> <div className={styles.dead} />
@@ -165,18 +183,18 @@ function Item({ config, value, ranking }: ItemProps) {
<CharacteristicValue config={config} value={value} /> <CharacteristicValue config={config} value={value} />
</div> </div>
{ranking && ( <div className={styles.ranking}>
<div className={styles.ranking}> {ranking ? <Bar value={ranking.score} /> : <BarStub />}
<Bar value={ranking.score} />
{ranking && (
<Text lowContrast size="minor" className={styles.number}> <Text lowContrast size="minor" className={styles.number}>
{literals(strings.units.fraction, { {literals(strings.units.fraction, {
numerator: ranking.rank, numerator: ranking.rank,
denominator: ranking.total, denominator: ranking.total,
})} })}
</Text> </Text>
</div> )}
)} </div>
</span> </span>
); );
} }
@@ -229,6 +247,18 @@ function CompareOptions() {
); );
} }
// Unranked items get a full neutral bar
function BarStub() {
return (
<div className={styles["bar-wrapper"]}>
<div
className={styles.bar}
style={{ backgroundColor: "var(--gray-3)", width: "100%" }}
/>
</div>
);
}
interface BarProps { interface BarProps {
value: number; value: number;
} }
@@ -1,7 +1,9 @@
import { MAX_SKILL_LEVEL } from "@blitzkit/core"; import { MAX_SKILL_LEVEL } from "@blitzkit/core";
import { useCallback } from "react";
import { useDuelModules } from "../../hooks/useDuelModules"; import { useDuelModules } from "../../hooks/useDuelModules";
import { Tankopedia } from "../../stores/tankopedia"; import { Tankopedia } from "../../stores/tankopedia";
import { selectModule } from "../../tankopedia/selectModule"; import { selectModule } from "../../tankopedia/selectModule";
import { createAugments, toggleAugment } from "../../tankopedia/augments";
import { LoadoutConsumables } from "../LoadoutConsumables"; import { LoadoutConsumables } from "../LoadoutConsumables";
import { LoadoutEquipment } from "../LoadoutEquipment"; import { LoadoutEquipment } from "../LoadoutEquipment";
import { LoadoutModules } from "../LoadoutModules"; import { LoadoutModules } from "../LoadoutModules";
@@ -9,11 +11,13 @@ import { LoadoutProvisions } from "../LoadoutProvisions";
import { LoadoutShells } from "../LoadoutShells"; import { LoadoutShells } from "../LoadoutShells";
import { LoadoutSkills } from "../LoadoutSkills"; import { LoadoutSkills } from "../LoadoutSkills";
import { LoadoutStatus } from "../LoadoutStatus"; import { LoadoutStatus } from "../LoadoutStatus";
import { LoadoutAugments } from "../LoadoutAugments";
export function TankopediaLoadout() { export function TankopediaLoadout() {
return ( return (
<> <>
<Modules /> <Modules />
<Augments />
<Shells /> <Shells />
<Equipment /> <Equipment />
<Provisions /> <Provisions />
@@ -58,6 +62,47 @@ function Modules() {
); );
} }
function Augments() {
const protagonist = useDuelModules("protagonist");
const selected = Tankopedia.use((state) => state.protagonist.augments);
const progression = protagonist.tank.augment_progression;
const handleToggle = useCallback(
(id: number) => {
if (progression === undefined) return;
Tankopedia.mutate((draft) => {
toggleAugment(draft.protagonist, progression, id);
});
},
[progression],
);
const handleStock = useCallback(() => {
Tankopedia.mutate((draft) => {
draft.protagonist.augments = [];
});
}, []);
const handleMaximize = useCallback(() => {
Tankopedia.mutate((draft) => {
draft.protagonist.augments = createAugments(progression);
});
}, [progression]);
if (progression === undefined) return null;
return (
<LoadoutAugments
progression={progression}
selected={selected}
onToggle={handleToggle}
onStock={handleStock}
onMaximize={handleMaximize}
/>
);
}
function Shells() { function Shells() {
const protagonist = useDuelModules("protagonist"); const protagonist = useDuelModules("protagonist");
@@ -541,3 +541,85 @@
} }
} }
} }
.assault {
--axis-width: var(--space-8);
--axis-height: var(--space-7);
position: relative;
width: 100%;
height: 100%;
padding: var(--space-4) var(--space-5) var(--axis-height) var(--axis-width);
border-radius: inherit;
background-color: var(--gray-2);
user-select: none;
.assault-damage {
position: absolute;
top: var(--space-4);
bottom: var(--axis-height);
left: var(--space-2);
span {
position: absolute;
left: 0;
transform: translateY(50%);
color: var(--gray-11);
font-size: var(--font-size-minor);
white-space: nowrap;
}
}
.assault-plot {
position: relative;
display: flex;
align-items: flex-end;
width: 100%;
height: 100%;
cursor: ew-resize;
touch-action: none;
}
.assault-sector {
background: linear-gradient(
45deg,
color-mix(in hsl, var(--tomato-7), var(--jade-7) var(--mix)),
color-mix(in hsl, var(--tomato-9), var(--jade-9) var(--mix))
);
border-top: 1px solid var(--gray-11);
}
.assault-cursor {
position: absolute;
top: 0;
bottom: 0;
width: 2px;
transform: translateX(-50%);
background-color: var(--accent-11);
pointer-events: none;
}
.assault-distances {
position: absolute;
bottom: 0;
left: var(--axis-width);
right: var(--space-5);
display: flex;
height: var(--axis-height);
div {
position: relative;
height: 100%;
}
span {
position: absolute;
right: 0;
margin-top: var(--space-2);
transform: translateX(50%);
color: var(--gray-11);
font-size: var(--font-size-minor);
writing-mode: vertical-rl;
}
}
}
@@ -22,6 +22,11 @@ import { useDuelModels } from "../../hooks/useDuelModels";
import { useDuelModules } from "../../hooks/useDuelModules"; import { useDuelModules } from "../../hooks/useDuelModules";
import { useEquipment } from "../../hooks/useEquipment"; import { useEquipment } from "../../hooks/useEquipment";
import { useStrings } from "../../hooks/useStrings"; import { useStrings } from "../../hooks/useStrings";
import {
fakeLogSquishyHigh,
fakeLogSquishyHighInverse,
fakeLogSquishyLow,
} from "../../core/blitzkit/fakeLog";
import { Tankopedia } from "../../stores/tankopedia"; import { Tankopedia } from "../../stores/tankopedia";
import type { ComputedCharacteristics } from "../../types/characteristics"; import type { ComputedCharacteristics } from "../../types/characteristics";
import { Button } from "../Button"; import { Button } from "../Button";
@@ -901,3 +906,131 @@ export function FlexibilityToy() {
</div> </div>
); );
} }
// Where the pointer is across the plot, from 0 to 1
function plotFraction(event: PointerEvent<HTMLDivElement>) {
const rect = event.currentTarget.getBoundingClientRect();
return clamp((event.clientX - rect.left) / rect.width, 0, 1);
}
export function AssaultShellsToy({ characteristics }: ToyProps) {
const strings = useStrings();
const distance = Tankopedia.use((state) => state.environment.distance);
// Where the cursor is while it is dragged, as a fraction of the plot
const [dragged, setDragged] = useState<number>();
const distances = characteristics.get("_assault_distances") as number[];
const factors = characteristics.get("_assault_factors") as number[];
const baseDamage = characteristics.get("_base_damage") as number;
const maxDistance = distances.at(-1)!;
// Sector widths are stretched so the near ones stay readable. The last one
// always ends at the far edge
const sectors = useMemo(() => {
const maxFactor = Math.max(...factors);
let start = 0;
return distances.map((sectorDistance, index) => {
const end = fakeLogSquishyHigh(sectorDistance / maxDistance);
const relative = factors[index] / maxFactor;
const sector = {
distance: sectorDistance,
factor: factors[index],
width: `${(end - start) * 100}%`,
height: `${fakeLogSquishyLow(relative) * 100}%`,
mix: `${clamp(2 * relative - 1, 0, 1) * 100}%`,
};
start = end;
return sector;
});
}, [distances, factors, maxDistance]);
const cursor =
dragged ??
fakeLogSquishyHigh(Math.min(distance, maxDistance) / maxDistance);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
event.currentTarget.setPointerCapture(event.pointerId);
setDragged(plotFraction(event));
},
[],
);
const handlePointerMove = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
setDragged(plotFraction(event));
},
[],
);
// Only the release writes the distance, so dragging recomputes nothing
const handlePointerUp = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
const fraction = plotFraction(event);
Tankopedia.mutate((draft) => {
draft.environment.distance =
fakeLogSquishyHighInverse(fraction) * maxDistance;
});
setDragged(undefined);
},
[maxDistance],
);
const handlePointerCancel = useCallback(() => setDragged(undefined), []);
return (
<div className={styles.assault}>
<div className={styles["assault-damage"]}>
{sectors.map(({ distance: sectorDistance, factor, height }) => (
<span key={sectorDistance} style={{ bottom: height }}>
{literals(strings.common.units.hp, {
value: Math.round(baseDamage * factor),
})}
</span>
))}
</div>
<div
className={styles["assault-plot"]}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerCancel}
>
{sectors.map(({ distance: sectorDistance, width, height, mix }) => (
<div
key={sectorDistance}
className={styles["assault-sector"]}
style={{ width, height, "--mix": mix } as CSSProperties}
/>
))}
<div
className={styles["assault-cursor"]}
style={{ left: `${cursor * 100}%` }}
/>
</div>
<div className={styles["assault-distances"]}>
{sectors.map(({ distance: sectorDistance, width }) => (
<div key={sectorDistance} style={{ width }}>
<span>
{literals(strings.common.units.m, {
value: Math.round(sectorDistance),
})}
</span>
</div>
))}
</div>
</div>
);
}
+250 -107
View File
@@ -1,4 +1,3 @@
import type { Vector2Tuple } from "three";
import { import {
blitzkitToBlitzShellKind, blitzkitToBlitzShellKind,
isExplosive, isExplosive,
@@ -6,6 +5,8 @@ import {
unionBoundingBox, unionBoundingBox,
} from "@blitzkit/core"; } from "@blitzkit/core";
import { ShellType, TankClass } from "@blitzkit/protos"; import { ShellType, TankClass } from "@blitzkit/protos";
import type { Vector2Tuple } from "three";
import { shellSlot } from "../tankopedia/augments";
import { hullTraverseSpeed } from "../tankopedia/hullTraverseSpeed"; import { hullTraverseSpeed } from "../tankopedia/hullTraverseSpeed";
import { rawTerrainCoefficient } from "../tankopedia/rawTerrainCoefficient"; import { rawTerrainCoefficient } from "../tankopedia/rawTerrainCoefficient";
import { tankClassToBlitzTankClass } from "../tankopedia/tankClass"; import { tankClassToBlitzTankClass } from "../tankopedia/tankClass";
@@ -30,10 +31,11 @@ export const characteristics = {
}, },
}, },
damage: { // Compute time only: damage before the assault shell falloff
_base_damage: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ shell, environment, equalizer, script, gun }) { compute({ shell, environment, equalizer, script, gun, augment }) {
let coefficient = 1; let coefficient = 1;
if (environment.equalize) coefficient *= equalizer.damage; if (environment.equalize) coefficient *= equalizer.damage;
@@ -56,15 +58,29 @@ export const characteristics = {
coefficient *= effect.bonusValues!.factor; coefficient *= effect.bonusValues!.factor;
}); });
if (gun.assault_ranges?.types.includes(shell.type)) { let damage = shell.armor_damage;
const range = gun.assault_ranges.ranges.find(
({ distance }) => distance >= environment.distance,
);
coefficient *= range?.factor ?? 0; augment(`SHELL_DAMAGE_SLOT_${shellSlot(gun, shell)}`, (value) => {
} damage += value;
});
return coefficient * shell.armor_damage; return coefficient * damage;
},
},
damage: {
type: CharacteristicType.Number,
compute({ shell, environment, gun, characteristic }) {
const damage = characteristic("_base_damage") as number;
if (!gun.assault_ranges?.types.includes(shell.type)) return damage;
const range = gun.assault_ranges.ranges.find(
({ distance }) => distance >= environment.distance,
);
return damage * (range?.factor ?? 0);
}, },
}, },
@@ -100,16 +116,23 @@ export const characteristics = {
return gun.gun_type!.$case !== "auto_reloader"; return gun.gun_type!.$case !== "auto_reloader";
}, },
compute({ gun, characteristic }): number { compute({ gun, characteristic, augment }): number {
if (gun.gun_type!.$case === "auto_reloader") return -Infinity; if (gun.gun_type!.$case === "auto_reloader") return -Infinity;
const c = characteristic("_reload_coefficient") as number; const c = characteristic("_reload_coefficient") as number;
let reload = 0;
augment("GUN_RELOAD_TIME", (value) => {
reload += value;
});
if (gun.gun_type!.$case === "regular") { if (gun.gun_type!.$case === "regular") {
return c * gun.gun_type!.value.reload; reload += gun.gun_type!.value.reload;
} else {
reload += gun.gun_type!.value.clip_reload;
} }
return c * gun.gun_type!.value.clip_reload; return c * reload;
}, },
}, },
@@ -120,14 +143,23 @@ export const characteristics = {
return gun.gun_type!.$case === "auto_reloader"; return gun.gun_type!.$case === "auto_reloader";
}, },
compute({ gun, characteristic }) { compute({ gun, characteristic, augment }) {
if (gun.gun_type!.$case !== "auto_reloader") return []; if (gun.gun_type!.$case !== "auto_reloader") return [];
const reloadCoefficient = characteristic("_reload_coefficient") as number; const reloadCoefficient = characteristic("_reload_coefficient") as number;
let bonus = 0;
return gun.gun_type!.value.shell_reloads.map( augment("GUN_RELOAD_TIME", (value) => {
(reload) => reload * reloadCoefficient, bonus += value;
); });
return gun.gun_type!.value.shell_reloads.map((base) => {
let reload = base;
reload += bonus;
return reload * reloadCoefficient;
});
}, },
}, },
@@ -237,7 +269,11 @@ export const characteristics = {
const rest = reloads.length - 1; const rest = reloads.length - 1;
const cycle = characteristic("_optimal_shell_cycle") as number; const cycle = characteristic("_optimal_shell_cycle") as number;
return damage * rest + (damage * (60 - rest * intraClip)) / cycle; let dpm = damage * rest;
dpm += (damage * (60 - rest * intraClip)) / cycle;
return dpm;
}, },
}, },
@@ -381,7 +417,7 @@ export const characteristics = {
penetration: { penetration: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ shell, environment, equalizer, script }) { compute({ gun, shell, environment, equalizer, script, augment }) {
let c = 1; let c = 1;
script("protagonist", "CalibratedShells", (effect) => { script("protagonist", "CalibratedShells", (effect) => {
@@ -391,26 +427,43 @@ export const characteristics = {
if (environment.equalize) c *= equalizer.penetration; if (environment.equalize) c *= equalizer.penetration;
return c * shell.penetration!.near; let penetration = shell.penetration!.near;
augment(
`SHELL_PIERCING_POWER_100_SLOT_${shellSlot(gun, shell)}`,
(value) => {
penetration += value;
},
);
return c * penetration;
}, },
}, },
penetration_loss_by_distance: { penetration_loss_by_distance: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ shell, script }) { compute({ gun, shell, script, augment }) {
let c = 1; let c = 1;
script("protagonist", "StaticMiscAttrsModifier", (effect) => { script("protagonist", "StaticMiscAttrsModifier", (effect) => {
c += effect.bonusValues!.piercingPenaltyFactor500m / 100; c += effect.bonusValues!.piercingPenaltyFactor500m / 100;
}); });
return ( const slot = shellSlot(gun, shell);
c * let near = shell.penetration!.near;
100 * let far = shell.penetration!.far;
((shell.penetration!.near - shell.penetration!.far) /
shell.penetration!.near) augment(`SHELL_PIERCING_POWER_100_SLOT_${slot}`, (value) => {
); near += value;
});
augment(`SHELL_PIERCING_POWER_500_SLOT_${slot}`, (value) => {
far += value;
});
const loss = (near - far) / near;
return 100 * c * loss;
}, },
}, },
@@ -429,7 +482,7 @@ export const characteristics = {
shell_velocity: { shell_velocity: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ shell, script }) { compute({ gun, shell, script, augment }) {
let c = 1; let c = 1;
script("protagonist", "StaticMiscAttrsModifier", (effect) => { script("protagonist", "StaticMiscAttrsModifier", (effect) => {
@@ -440,7 +493,13 @@ export const characteristics = {
c += effect.bonusValues!.projectileSpeedFactor / 100; c += effect.bonusValues!.projectileSpeedFactor / 100;
}); });
return c * shell.velocity; let velocity = shell.velocity;
augment(`SHELL_SPEED_SLOT_${shellSlot(gun, shell)}`, (value) => {
velocity += value;
});
return c * velocity;
}, },
}, },
@@ -506,45 +565,53 @@ export const characteristics = {
speed_forward: { speed_forward: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ tank, script }) { compute({ tank, script, augment }) {
let bias = 0; let speed = tank.speed_forwards;
let factor = 1; let factor = 1;
augment("FORWARD_MAX_SPEED", (value) => {
speed += value;
});
script("protagonist", "GearOil", (effect) => { script("protagonist", "GearOil", (effect) => {
bias += effect.bonusValues?.fwdSpeedLimitBias ?? 0; speed += effect.bonusValues?.fwdSpeedLimitBias ?? 0;
}); });
script("protagonist", "ImprovedAfterburning", (effect) => { script("protagonist", "ImprovedAfterburning", (effect) => {
bias += effect.fwdSpeedLimitBias ?? 0; speed += effect.fwdSpeedLimitBias ?? 0;
}); });
script("protagonist", "AttributesModifier", (effect) => { script("protagonist", "AttributesModifier", (effect) => {
factor *= effect.attributes?.speedLimitsFactor ?? 1; factor *= effect.attributes?.speedLimitsFactor ?? 1;
}); });
return (tank.speed_forwards + bias) * factor; return speed * factor;
}, },
}, },
speed_backward: { speed_backward: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ tank, script }) { compute({ tank, script, augment }) {
let bias = 0; let speed = tank.speed_backwards;
let factor = 1; let factor = 1;
augment("BACKWARD_MAX_SPEED", (value) => {
speed += value;
});
script("protagonist", "GearOil", (effect) => { script("protagonist", "GearOil", (effect) => {
bias += effect.bonusValues?.bkwdSpeedLimitBias ?? 0; speed += effect.bonusValues?.bkwdSpeedLimitBias ?? 0;
}); });
script("protagonist", "ImprovedAfterburning", (effect) => { script("protagonist", "ImprovedAfterburning", (effect) => {
bias += effect.bkwdSpeedLimitBias ?? 0; speed += effect.bkwdSpeedLimitBias ?? 0;
}); });
script("protagonist", "AttributesModifier", (effect) => { script("protagonist", "AttributesModifier", (effect) => {
factor *= effect.attributes?.speedLimitsFactor ?? 1; factor *= effect.attributes?.speedLimitsFactor ?? 1;
}); });
return (tank.speed_backwards + bias) * factor; return speed * factor;
}, },
}, },
@@ -552,9 +619,8 @@ export const characteristics = {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ tank, gun, turret, track, degressive, script }): number { compute({ tank, gun, turret, track, degressive, script }): number {
/* /*
Mirrors the game's hangar params builder (wotblitz.exe 11.21, aim time Mirrors how the game computes aim time in the hangar. Consumables such as
at 0x19eb300). Consumables such as FireControlSystem are battle-time FireControlSystem are battle-time only and are not part of it.
only and are not part of it.
T = (A × C) × ln(√(1 + k² × S)) / (1 − p/100) T = (A × C) × ln(√(1 + k² × S)) / (1 − p/100)
@@ -601,9 +667,13 @@ export const characteristics = {
dispersion: { dispersion: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ gun, degressive, script }) { compute({ gun, degressive, script, augment }) {
let coefficient = 1; let coefficient = 1;
augment("DISPERSION_ANGLE_FACTOR_BONUS", (value) => {
coefficient += value;
});
script("protagonist", "miscAttrs/shotDispersionAngleFactor", (effect) => { script("protagonist", "miscAttrs/shotDispersionAngleFactor", (effect) => {
coefficient += effect.bonusValues!.percent / 100; coefficient += effect.bonusValues!.percent / 100;
}); });
@@ -684,12 +754,18 @@ export const characteristics = {
compute(context): number { compute(context): number {
const skill = (context.environment.skills.smooth_driving ?? 0) / 100; const skill = (context.environment.skills.smooth_driving ?? 0) / 100;
return ( const stabilizer = context.characteristic(
context.track.dispersion_move * "_stabilizer_coefficient",
(1 + ) as number;
(context.characteristic("_stabilizer_coefficient") as number) - let coefficient = 1;
skill)
); context.augment("DISPERSION_VEHICLE_MOVEMENT_FACTOR", (value) => {
coefficient *= value;
});
coefficient *= 1 + stabilizer - skill;
return context.track.dispersion_move * coefficient;
}, },
}, },
@@ -698,12 +774,18 @@ export const characteristics = {
compute(context): number { compute(context): number {
const skill = (context.environment.skills.smooth_turn ?? 0) / 100; const skill = (context.environment.skills.smooth_turn ?? 0) / 100;
return ( const stabilizer = context.characteristic(
context.track.dispersion_traverse * "_stabilizer_coefficient",
(1 + ) as number;
(context.characteristic("_stabilizer_coefficient") as number) - let coefficient = 1;
skill)
); context.augment("DISPERSION_VEHICLE_ROTATION_FACTOR", (value) => {
coefficient *= value;
});
coefficient *= 1 + stabilizer - skill;
return context.track.dispersion_traverse * coefficient;
}, },
}, },
@@ -712,12 +794,18 @@ export const characteristics = {
compute(context): number { compute(context): number {
const skill = (2 * (context.environment.skills.smooth_turret ?? 0)) / 100; const skill = (2 * (context.environment.skills.smooth_turret ?? 0)) / 100;
return ( const stabilizer = context.characteristic(
context.gun.dispersion_traverse * "_stabilizer_coefficient",
(1 + ) as number;
(context.characteristic("_stabilizer_coefficient") as number) - let coefficient = 1;
skill)
); context.augment("DISPERSION_TURRET_ROTATION_FACTOR", (value) => {
coefficient *= value;
});
coefficient *= 1 + stabilizer - skill;
return context.gun.dispersion_traverse * coefficient;
}, },
}, },
@@ -726,62 +814,74 @@ export const characteristics = {
compute(context): number { compute(context): number {
const skill = (context.environment.skills.soft_recoil ?? 0) / 100; const skill = (context.environment.skills.soft_recoil ?? 0) / 100;
return ( const stabilizer = context.characteristic(
context.gun.dispersion_shot * "_stabilizer_coefficient",
(1 + ) as number;
(context.characteristic("_stabilizer_coefficient") as number) - const coefficient = 1 + stabilizer - skill;
skill)
); return context.gun.dispersion_shot * coefficient;
}, },
}, },
dispersion_gun_damaged: { dispersion_gun_damaged: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute(context): number { compute(context): number {
return ( const stabilizer = context.characteristic(
context.gun.dispersion_damaged * "_stabilizer_coefficient",
(1 + (context.characteristic("_stabilizer_coefficient") as number)) ) as number;
); const coefficient = 1 + stabilizer;
return context.gun.dispersion_damaged * coefficient;
}, },
}, },
// dispersion_angle: unavailable, dispersion_angle: {
type: CharacteristicType.Number,
compute({ characteristic }) {
// Dispersion is the radius of the circle at 100 m
const dispersion = characteristic("dispersion") as number;
return Math.atan(dispersion / 100) * (180 / Math.PI);
},
},
gun_depression: { gun_depression: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ state, turret, gun, script }) { compute({ state, turret, gun, script, augment }) {
const turretModel = state.model.turrets[turret.id]; const turretModel = state.model.turrets[turret.id];
const gunModel = turretModel.guns[gun.id]; const gunModel = turretModel.guns[gun.id];
let bonus = 0; let depression = gunModel.pitch!.max;
script("protagonist", "ImprovedPitchLimitsSystem", (effect) => { depression += state.model.initial_turret_rotation?.pitch ?? 0;
bonus += effect.bonusValues?.lowerPitchLimitIncrease ?? 0; augment("PITCH_LIMIT_DOWN", (value) => {
depression += value;
}); });
return ( script("protagonist", "ImprovedPitchLimitsSystem", (effect) => {
gunModel.pitch!.max + depression += effect.bonusValues?.lowerPitchLimitIncrease ?? 0;
(state.model.initial_turret_rotation?.pitch ?? 0) + });
bonus
); return depression;
}, },
}, },
gun_elevation: { gun_elevation: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ state, turret, gun, script }) { compute({ state, turret, gun, script, augment }) {
const turretModel = state.model.turrets[turret.id]; const turretModel = state.model.turrets[turret.id];
const gunModel = turretModel.guns[gun.id]; const gunModel = turretModel.guns[gun.id];
let bonus = 0; let elevation = -gunModel.pitch!.min;
script("protagonist", "ImprovedPitchLimitsSystem", (effect) => { elevation -= state.model.initial_turret_rotation?.pitch ?? 0;
bonus += effect.bonusValues?.upperPitchLimitIncrease ?? 0; augment("PITCH_LIMIT_UP", (value) => {
elevation += value;
}); });
return ( script("protagonist", "ImprovedPitchLimitsSystem", (effect) => {
-gunModel.pitch!.min - elevation += effect.bonusValues?.upperPitchLimitIncrease ?? 0;
(state.model.initial_turret_rotation?.pitch ?? 0) + });
bonus
); return elevation;
}, },
}, },
@@ -856,14 +956,14 @@ export const characteristics = {
weight: { weight: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ tank, engine, track, turret, gun }) { compute({ tank, engine, track, turret, gun }) {
return ( let weight = tank.weight;
(tank.weight +
engine.weight + weight += engine.weight;
track.weight + weight += track.weight;
turret.weight + weight += turret.weight;
gun.weight) / weight += gun.weight;
1000
); return weight / 1000;
}, },
}, },
@@ -906,10 +1006,15 @@ export const characteristics = {
engine_power: { engine_power: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
// explicit return type breaks the circular inference through characteristic() // explicit return type breaks the circular inference through characteristic()
compute({ engine, characteristic }): number { compute({ engine, characteristic, augment }): number {
return ( const coefficient = characteristic("_engine_power_coefficient") as number;
engine.power * (characteristic("_engine_power_coefficient") as number) let power = engine.power;
);
augment("ENGINE_POWER", (value) => {
power += value;
});
return power * coefficient;
}, },
}, },
@@ -1047,9 +1152,13 @@ export const characteristics = {
_turret_traverse_coefficient: { _turret_traverse_coefficient: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ progressive, script }) { compute({ progressive, script, augment }) {
let c = 1; let c = 1;
augment("TURRET_ROTATION_SPEED_FACTOR_BONUS", (value) => {
c += value;
});
script("protagonist", "Fuel", (effect) => { script("protagonist", "Fuel", (effect) => {
c += (effect.bonusValues?.turretRotationSpeedIncrease ?? 0) / 100; c += (effect.bonusValues?.turretRotationSpeedIncrease ?? 0) / 100;
}); });
@@ -1076,7 +1185,7 @@ export const characteristics = {
health: { health: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ tank, turret, environment, equalizer, script }) { compute({ tank, turret, environment, equalizer, script, augment }) {
let c0 = 1; let c0 = 1;
script("protagonist", "SmallHPStock", (effect) => { script("protagonist", "SmallHPStock", (effect) => {
@@ -1093,8 +1202,12 @@ export const characteristics = {
c1 *= equalizer.health; c1 *= equalizer.health;
} }
let health = tank.health + turret.health; let health = tank.health;
health += turret.health;
augment("MAX_HEALTH", (value) => {
health += value;
});
health *= c0 * c1; health *= c0 * c1;
if (environment.equalize) { if (environment.equalize) {
@@ -1107,14 +1220,19 @@ export const characteristics = {
fire_chance: { fire_chance: {
type: CharacteristicType.Number, type: CharacteristicType.Number,
compute({ engine, script }) { compute({ engine, script, augment }) {
// Augments are a fraction of the chance, not points of it
let c = 1; let c = 1;
augment("FIRE_START_CHANCE", (value) => {
c += value;
});
script("protagonist", "SafetySet", (effect) => { script("protagonist", "SafetySet", (effect) => {
c -= (effect.bonusValues?.fireProtectionIncrease ?? 0) / 100; c -= (effect.bonusValues?.fireProtectionIncrease ?? 0) / 100;
}); });
return 100 * c * engine.fire_chance; return 100 * Math.max(0, c) * engine.fire_chance;
}, },
}, },
@@ -1239,4 +1357,29 @@ export const characteristics = {
return size.y; return size.y;
}, },
}, },
// Compute time only: what the assault shells visualizer is drawn from
_assault_distances: {
type: CharacteristicType.NumberList,
should_render({ gun, shell }) {
return gun.assault_ranges?.types.includes(shell.type) === true;
},
compute({ gun }) {
return gun.assault_ranges!.ranges.map(({ distance }) => distance);
},
},
_assault_factors: {
type: CharacteristicType.NumberList,
should_render({ gun, shell }) {
return gun.assault_ranges?.types.includes(shell.type) === true;
},
compute({ gun }) {
return gun.assault_ranges!.ranges.map(({ factor }) => factor);
},
},
} satisfies Record<string, Characteristic>; } satisfies Record<string, Characteristic>;
@@ -68,6 +68,12 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
// ], // ],
// }, // },
{
name: "assault_shells",
sortable: false,
order: [{ toy: "assault_shells", requires: "_assault_distances" }],
},
{ {
name: "gun", name: "gun",
// render: CharacteristicsGroupRender.Statistical, // render: CharacteristicsGroupRender.Statistical,
@@ -83,45 +89,45 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
{ name: "dpm", decimals: 0, units: "hp", localize: true }, { name: "dpm", decimals: 0, units: "hp", localize: true },
{ {
name: "dpm_effective", name: "dpm_effective",
indent: true,
decimals: 0, decimals: 0,
units: "hp", units: "hp",
localize: true, localize: true,
indent: true,
}, },
{ {
name: "dpm_peekaboo", name: "dpm_peekaboo",
indent: true,
decimals: 0, decimals: 0,
units: "hp", units: "hp",
localize: true, localize: true,
indent: true,
}, },
{ name: "damage", decimals: 0, units: "hp", localize: true }, { name: "damage", decimals: 0, units: "hp", localize: true },
{ {
name: "damage_range", name: "damage_range",
indent: true,
decimals: 0, decimals: 0,
units: "hp", units: "hp",
localize: true, localize: true,
indent: true,
}, },
{ name: "module_damage", decimals: 0, units: "hp", localize: true }, { name: "module_damage", decimals: 0, units: "hp", localize: true },
{ {
name: "module_damage_range", name: "module_damage_range",
indent: true,
decimals: 0, decimals: 0,
units: "hp", units: "hp",
localize: true, localize: true,
indent: true,
}, },
{ {
name: "reload", name: "reload",
ranking: CharacteristicRanking.LowerIsBetter,
decimals: 1, decimals: 1,
units: "s", units: "s",
ranking: CharacteristicRanking.LowerIsBetter,
}, },
{ {
name: "reloads", name: "reloads",
ranking: CharacteristicRanking.LowerIsBetter,
decimals: 1, decimals: 1,
units: "s", units: "s",
ranking: CharacteristicRanking.LowerIsBetter,
}, },
{ toy: "reload" }, { toy: "reload" },
@@ -134,12 +140,15 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
order: [ order: [
{ name: "clipping_potential", localize: true, units: "hp" }, { name: "clipping_potential", localize: true, units: "hp" },
{ name: "clip_size" }, { name: "clip_size" },
{ name: "optimal_shell", ranking: CharacteristicRanking.None }, {
name: "optimal_shell",
ranking: CharacteristicRanking.None,
},
{ {
name: "intra_clip", name: "intra_clip",
ranking: CharacteristicRanking.LowerIsBetter,
decimals: 2, decimals: 2,
units: "s", units: "s",
ranking: CharacteristicRanking.LowerIsBetter,
}, },
{ name: "burst_size" }, { name: "burst_size" },
{ name: "intra_burst", decimals: 2, units: "s" }, { name: "intra_burst", decimals: 2, units: "s" },
@@ -158,15 +167,15 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
{ name: "penetration", units: "mm" }, { name: "penetration", units: "mm" },
{ {
name: "penetration_loss_by_distance", name: "penetration_loss_by_distance",
units: "percentage",
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
units: "percentage",
}, },
{ {
name: "penetration_loss_after_ricochet", name: "penetration_loss_after_ricochet",
units: "percentage",
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
units: "percentage",
}, },
{ name: "shell_velocity", units: "m_s" }, { name: "shell_velocity", units: "m_s" },
{ name: "shell_range", units: "m" }, { name: "shell_range", units: "m" },
@@ -174,19 +183,19 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
{ name: "caliber", units: "mm" }, { name: "caliber", units: "mm" },
{ {
name: "ricochet", name: "ricochet",
units: "deg",
ranking: CharacteristicRanking.None, ranking: CharacteristicRanking.None,
units: "deg",
}, },
{ {
name: "normalization", name: "normalization",
units: "deg",
ranking: CharacteristicRanking.None, ranking: CharacteristicRanking.None,
units: "deg",
}, },
{ {
name: "explosion_radius", name: "explosion_radius",
ranking: CharacteristicRanking.None,
decimals: 2, decimals: 2,
units: "m", units: "m",
ranking: CharacteristicRanking.None,
}, },
{ toy: "ricochet" }, { toy: "ricochet" },
@@ -199,53 +208,53 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
order: [ order: [
{ {
name: "aim_time", name: "aim_time",
ranking: CharacteristicRanking.LowerIsBetter,
decimals: 2, decimals: 2,
units: "s", units: "s",
ranking: CharacteristicRanking.LowerIsBetter,
}, },
{ {
name: "dispersion", name: "dispersion",
ranking: CharacteristicRanking.LowerIsBetter,
decimals: 3, decimals: 3,
units: "m", units: "m",
ranking: CharacteristicRanking.LowerIsBetter,
}, },
{ name: "dispersion_angle", decimals: 3, units: "deg" }, { name: "dispersion_angle", decimals: 3, units: "deg" },
{ label: "dispersion_penalties" }, { label: "dispersion_penalties" },
{ {
name: "dispersion_moving", name: "dispersion_moving",
decimals: 3,
units: "plus",
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
decimals: 3,
units: "plus",
}, },
{ {
name: "dispersion_hull_traversing", name: "dispersion_hull_traversing",
decimals: 3,
units: "plus",
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
decimals: 3,
units: "plus",
}, },
{ {
name: "dispersion_turret_traversing", name: "dispersion_turret_traversing",
decimals: 3,
units: "plus",
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
decimals: 3,
units: "plus",
}, },
{ {
name: "dispersion_shooting", name: "dispersion_shooting",
decimals: 3,
units: "plus",
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
decimals: 3,
units: "plus",
}, },
{ {
name: "dispersion_gun_damaged", name: "dispersion_gun_damaged",
decimals: 1,
units: "x",
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
decimals: 1,
units: "x",
}, },
// { toy: "aim_time" }, // { toy: "aim_time" },
@@ -273,15 +282,14 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
name: "maneuverability", name: "maneuverability",
// render: CharacteristicsGroupRender.Statistical, // render: CharacteristicsGroupRender.Statistical,
order: [ order: [
{ label: "speeds" }, { name: "speed_forward", units: "km_h" },
{ name: "speed_forward", units: "km_h", indent: true }, { name: "speed_backward", units: "km_h" },
{ name: "speed_backward", units: "km_h", indent: true },
{ {
name: "weight", name: "weight",
ranking: CharacteristicRanking.LowerIsBetter,
decimals: 1, decimals: 1,
units: "t", units: "t",
ranking: CharacteristicRanking.LowerIsBetter,
}, },
{ name: "engine_power", units: "bhp" }, { name: "engine_power", units: "bhp" },
{ name: "power_to_weight", decimals: 1, units: "bhp_t" }, { name: "power_to_weight", decimals: 1, units: "bhp_t" },
@@ -289,54 +297,78 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
{ label: "power_to_weight_on_terrain" }, { label: "power_to_weight_on_terrain" },
{ {
name: "power_to_weight_hard", name: "power_to_weight_hard",
indent: true,
decimals: 1, decimals: 1,
units: "bhp_t", units: "bhp_t",
indent: true,
}, },
{ {
name: "power_to_weight_medium", name: "power_to_weight_medium",
indent: true,
decimals: 1, decimals: 1,
units: "bhp_t", units: "bhp_t",
indent: true,
}, },
{ {
name: "power_to_weight_soft", name: "power_to_weight_soft",
indent: true,
decimals: 1, decimals: 1,
units: "bhp_t", units: "bhp_t",
indent: true,
}, },
// { name: "brake_force", decimals: 1, units: "kN" }, // { name: "brake_force", decimals: 1, units: "kN" },
{ label: "hull_traverse_speeds" }, { label: "hull_traverse_speeds" },
{ name: "hull_traverse_speed_hard", units: "deg_s", indent: true }, {
{ name: "hull_traverse_speed_medium", units: "deg_s", indent: true }, name: "hull_traverse_speed_hard",
{ name: "hull_traverse_speed_soft", units: "deg_s", indent: true }, indent: true,
units: "deg_s",
},
{
name: "hull_traverse_speed_medium",
indent: true,
units: "deg_s",
},
{
name: "hull_traverse_speed_soft",
indent: true,
units: "deg_s",
},
{ name: "turret_traverse_speed", units: "deg_s" }, { name: "turret_traverse_speed", units: "deg_s" },
{ name: "gun_traverse_speed", units: "deg_s" }, { name: "gun_traverse_speed", units: "deg_s" },
{ label: "terrain_coefficient" }, { label: "terrain_coefficient" },
{ name: "hard_terrain_coefficient", decimals: 0, indent: true }, {
{ name: "medium_terrain_coefficient", decimals: 0, indent: true }, name: "hard_terrain_coefficient",
{ name: "soft_terrain_coefficient", decimals: 0, indent: true }, indent: true,
decimals: 0,
},
{
name: "medium_terrain_coefficient",
indent: true,
decimals: 0,
},
{
name: "soft_terrain_coefficient",
indent: true,
decimals: 0,
},
{ label: "raw_terrain_coefficient" }, { label: "raw_terrain_coefficient" },
{ {
name: "hard_terrain_coefficient_raw", name: "hard_terrain_coefficient_raw",
decimals: 2,
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
decimals: 2,
}, },
{ {
name: "medium_terrain_coefficient_raw", name: "medium_terrain_coefficient_raw",
decimals: 2,
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
decimals: 2,
}, },
{ {
name: "soft_terrain_coefficient_raw", name: "soft_terrain_coefficient_raw",
decimals: 2,
indent: true, indent: true,
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
decimals: 2,
}, },
{ toy: "traverse" }, { toy: "traverse" },
@@ -354,9 +386,9 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
{ name: "health", units: "hp" }, { name: "health", units: "hp" },
{ {
name: "fire_chance", name: "fire_chance",
ranking: CharacteristicRanking.LowerIsBetter,
decimals: 0, decimals: 0,
units: "percentage", units: "percentage",
ranking: CharacteristicRanking.LowerIsBetter,
}, },
{ name: "crew_count" }, { name: "crew_count" },
// { name: "fire_rate", units: "hp_s" }, // { name: "fire_rate", units: "hp_s" },
@@ -377,51 +409,51 @@ export const characteristicsGroups: CharacteristicsGroup[] = [
{ label: "camouflages" }, { label: "camouflages" },
{ {
name: "camouflage", name: "camouflage",
indent: true,
decimals: 2, decimals: 2,
units: "percentage", units: "percentage",
indent: true,
}, },
{ {
name: "camouflage_moving", name: "camouflage_moving",
indent: true,
decimals: 2, decimals: 2,
units: "percentage", units: "percentage",
indent: true,
}, },
{ {
name: "camouflage_shooting_still", name: "camouflage_shooting_still",
indent: true,
decimals: 2, decimals: 2,
units: "percentage", units: "percentage",
indent: true,
}, },
{ {
name: "camouflage_shooting_moving", name: "camouflage_shooting_moving",
indent: true,
decimals: 2, decimals: 2,
units: "percentage", units: "percentage",
indent: true,
}, },
{ {
name: "camouflage_on_fire", name: "camouflage_on_fire",
indent: true,
decimals: 2, decimals: 2,
units: "percentage", units: "percentage",
indent: true,
}, },
{ toy: "view_range" }, { toy: "view_range" },
{ {
name: "width", name: "width",
units: "m",
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
units: "m",
}, },
{ {
name: "height", name: "height",
units: "m",
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
units: "m",
}, },
{ {
name: "length", name: "length",
units: "m",
ranking: CharacteristicRanking.LowerIsBetter, ranking: CharacteristicRanking.LowerIsBetter,
units: "m",
}, },
], ],
}, },
+2
View File
@@ -1,5 +1,6 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { import {
AssaultShellsToy,
FlexibilityToy, FlexibilityToy,
ReloadToy, ReloadToy,
RicochetToy, RicochetToy,
@@ -18,4 +19,5 @@ export const toys: Record<string, (props: ToyProps) => ReactNode> = {
reload: ReloadToy, reload: ReloadToy,
view_range: ViewRangeToy, view_range: ViewRangeToy,
flexibility: FlexibilityToy, flexibility: FlexibilityToy,
assault_shells: AssaultShellsToy,
}; };
@@ -1,9 +1,10 @@
import { normalizeAngleRad } from "@blitzkit/core"; import { normalizeAngleRad } from "@blitzkit/core";
import type { PitchLimits, YawLimits } from "@blitzkit/protos"; import type { PitchLimits, YawLimits } from "@blitzkit/protos";
import { clamp } from "lodash-es"; import { clamp } from "lodash-es";
import { degToRad } from "three/src/math/MathUtils.js"; import { degToRad, radToDeg } from "three/src/math/MathUtils.js";
export const DEFAULT_PITCH_TRANSITION = 20; // The game's default is 0.4 rad
export const DEFAULT_PITCH_TRANSITION = radToDeg(0.4);
export function applyPitchYawLimits( export function applyPitchYawLimits(
pitch: number, // rad pitch: number, // rad
@@ -27,5 +27,5 @@ export async function extractPackedIcon(texture: sharp.Sharp, sizes: number[]) {
); );
} }
return await texture.clone().extract({ left, top, width, height }).toBuffer(); return await texture.clone().extract({ left, top, width, height }).webp().toBuffer();
} }
@@ -0,0 +1,54 @@
import sharp from "sharp";
import { vfs } from "../blitzkit/vfs";
import { extractPackedIcon } from "./extractPackedIcon";
import { parsePackedSpriteRect } from "./parsePackedSpriteRect";
// Route props that point at a sprite, for each way of reading one
export interface PackedSpriteProps {
packed: string;
}
export interface DiscreteSpriteProps {
descriptor: string;
texture: string;
}
// A standalone texture; the sprite rect lives in its RIFF `extr` chunk. Reads
// it the way the client does, as webp. Trimming is only a guess, so it is
// used solely for textures that carry no rect.
export async function readPackedSprite(path: string) {
const packed = await vfs.file(path);
const texture = sharp(packed);
const rect = parsePackedSpriteRect(packed);
if (rect === null) {
return new Uint8Array(await texture.trim().webp().toBuffer());
}
return new Uint8Array(await extractPackedIcon(texture, rect));
}
// A rect in a `.txt` descriptor (line 4) cut out of a shared atlas texture
export async function readDiscreteSprite(descriptor: string, texture: string) {
const rect = (await vfs.text(descriptor))
.split("\n")[4]
.split(" ")
.map(Number);
return new Uint8Array(
await extractPackedIcon(sharp(await vfs.file(texture)), rect)
);
}
// Sprites in the UI styles are named without an extension and are either a
// standalone texture or an entry of the `texture0` atlas next to them
export async function readStyleSprite(path: string) {
const packed = `${path}.packed.webp`;
if (await vfs.resolve(packed)) return await readPackedSprite(packed);
return await readDiscreteSprite(
`${path}.txt`,
`${path.split("/").slice(0, -1).join("/")}/texture0.packed.webp`
);
}
@@ -6,10 +6,12 @@ import {
} from "@blitzkit/core"; } from "@blitzkit/core";
import type { BlitzEffectScript } from "@blitzkit/core/src/types/blitzEffectScript"; import type { BlitzEffectScript } from "@blitzkit/core/src/types/blitzEffectScript";
import { CrewType, type TankDefinition } from "@blitzkit/protos"; import { CrewType, type TankDefinition } from "@blitzkit/protos";
import { useMemo } from "react";
import { api } from "../api/dynamic"; import { api } from "../api/dynamic";
import { characteristics } from "../config/characteristics"; import { characteristics } from "../config/characteristics";
import { defaultEqualizer } from "../config/equalizer"; import { defaultEqualizer } from "../config/equalizer";
import { Tankopedia } from "../stores/tankopedia"; import { Tankopedia } from "../stores/tankopedia";
import { augmentAttributes } from "../tankopedia/augments";
import { createTankState } from "../tankopedia/createTankState"; import { createTankState } from "../tankopedia/createTankState";
import type { TankState } from "../tankopedia/tankState"; import type { TankState } from "../tankopedia/tankState";
import type { import type {
@@ -152,6 +154,13 @@ export function computeCharacteristics(
} }
} }
const augments = augmentAttributes(tank, states.protagonist);
function augment(name: string, callback: (value: number) => void) {
if (!augments.has(name)) return;
for (const value of augments.get(name)!) callback(value);
}
const context = { const context = {
state: states.protagonist, state: states.protagonist,
environment, environment,
@@ -170,6 +179,7 @@ export function computeCharacteristics(
characteristic, characteristic,
script, script,
augment,
} satisfies CharacteristicContext; } satisfies CharacteristicContext;
for (const name in characteristics) { for (const name in characteristics) {
@@ -198,7 +208,12 @@ export function useCharacteristics(side: DuelSide) {
); );
const environment = Tankopedia.use((state) => state.environment); const environment = Tankopedia.use((state) => state.environment);
return computeCharacteristics({ protagonist: A, antagonist: B }, environment); // A stable map, so what reads it only recomputes when the loadout changes
return useMemo(
() =>
computeCharacteristics({ protagonist: A, antagonist: B }, environment),
[A, B, environment],
);
} }
export function computeDefaultCharacteristics(tank: TankDefinition) { export function computeDefaultCharacteristics(tank: TankDefinition) {
@@ -1,6 +1,9 @@
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readPackedSprite,
type PackedSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -13,8 +16,8 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
files.filter( files.filter(
(flag) => (flag) =>
flag.startsWith("flag_profile-stat_") && flag.startsWith("flag_profile-stat_") &&
!flag.endsWith("@2x.packed.webp"), !flag.endsWith("@2x.packed.webp")
), )
); );
for (const flag of circleFiles) { for (const flag of circleFiles) {
@@ -23,17 +26,13 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
paths.push({ paths.push({
params: { id }, params: { id },
props: { path }, props: { packed: path },
}); });
} }
return paths; return paths;
}); });
export async function GET({ props }: APIContext<{ path: string }>) { export async function GET({ props }: APIContext<PackedSpriteProps>) {
const image = sharp(await vfs.file(props.path)); return new Response(await readPackedSprite(props.packed));
const content = await image.trim({ threshold: 100 }).toBuffer();
const bytes = new Uint8Array(content);
return new Response(bytes);
} }
@@ -1,6 +1,9 @@
import sharp from "sharp";
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readPackedSprite,
type PackedSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -12,8 +15,8 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
.then((files) => .then((files) =>
files.filter( files.filter(
(flag) => (flag) =>
flag.startsWith("flag_filter_") && flag.endsWith("@2x.packed.webp"), flag.startsWith("flag_filter_") && flag.endsWith("@2x.packed.webp")
), )
); );
for (const flag of fadedFiles) { for (const flag of fadedFiles) {
@@ -22,18 +25,13 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
paths.push({ paths.push({
params: { id }, params: { id },
props: { path }, props: { packed: path },
}); });
} }
return paths; return paths;
}); });
export async function GET({ props }: APIContext<{ path: string }>) { export async function GET({ props }: APIContext<PackedSpriteProps>) {
const bytes = await sharp(new Uint8Array(await vfs.file(props.path))) return new Response(await readPackedSprite(props.packed));
.trim({ background: { r: 0, g: 0, b: 0, alpha: 0 }, threshold: 1 })
.webp()
.toBuffer();
return new Response(new Uint8Array(bytes));
} }
@@ -1,7 +1,10 @@
import type { SquadBattleTypeStylesYaml } from "@blitzkit/core"; import type { SquadBattleTypeStylesYaml } from "@blitzkit/core";
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readPackedSprite,
type PackedSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -9,26 +12,26 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
const paths: GetStaticPathsItem[] = []; const paths: GetStaticPathsItem[] = [];
const gameTypeSelectorStyles = await vfs.yaml<SquadBattleTypeStylesYaml>( const gameTypeSelectorStyles = await vfs.yaml<SquadBattleTypeStylesYaml>(
`Data/UI/Screens/Lobby/Hangar/GameTypeSelector.yaml`, `Data/UI/Screens/Lobby/Hangar/GameTypeSelector.yaml`
); );
const squadBattleTypeStyles = await vfs.yaml<SquadBattleTypeStylesYaml>( const squadBattleTypeStyles = await vfs.yaml<SquadBattleTypeStylesYaml>(
`Data/UI/Screens3/Lobby/Hangar/Squad/SquadBattleType.yaml`, `Data/UI/Screens3/Lobby/Hangar/Squad/SquadBattleType.yaml`
); );
const bannerMatches: { name: string; path: string }[] = []; const bannerMatches: { name: string; path: string }[] = [];
for (const match of gameTypeSelectorStyles.Prototypes[0].components.UIDataLocalBindingsComponent.data[1][2].matchAll( for (const match of gameTypeSelectorStyles.Prototypes[0].components.UIDataLocalBindingsComponent.data[1][2].matchAll(
/eGameMode\.(\w+) -> "~res:([^"]+)"/g, /eGameMode\.(\w+) -> "~res:([^"]+)"/g
)) { )) {
bannerMatches.push({ name: match[1], path: match[2] }); bannerMatches.push({ name: match[1], path: match[2] });
} }
for (const match of squadBattleTypeStyles.Prototypes[0].components.UIDataLocalBindingsComponent.data[1][2].matchAll( for (const match of squadBattleTypeStyles.Prototypes[0].components.UIDataLocalBindingsComponent.data[1][2].matchAll(
/eGameMode\.(\w+) -> "battleType\/([a-zA-Z]+)"/g, /eGameMode\.(\w+) -> "battleType\/([a-zA-Z]+)"/g
)) { )) {
const id = match[1]; const id = match[1];
const name = match[2]; const name = match[2];
let path = bannerMatches.find( let path = bannerMatches.find(
(bannerMatch) => bannerMatch.name.toLowerCase() === name.toLowerCase(), (bannerMatch) => bannerMatch.name.toLowerCase() === name.toLowerCase()
)?.path; )?.path;
if (path === undefined) { if (path === undefined) {
@@ -37,18 +40,13 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
paths.push({ paths.push({
params: { id }, params: { id },
props: { path: `Data${path}.packed.webp` }, props: { packed: `Data${path}.packed.webp` },
}); });
} }
return paths; return paths;
}); });
export async function GET({ props }: APIContext<{ path: string }>) { export async function GET({ props }: APIContext<PackedSpriteProps>) {
const buffer = await sharp(await vfs.file(props.path)) return new Response(await readPackedSprite(props.packed));
.trim({ background: { r: 0, g: 0, b: 0, alpha: 0 } })
.toBuffer();
const bytes = new Uint8Array(buffer);
return new Response(bytes);
} }
@@ -0,0 +1,35 @@
import type { APIContext, GetStaticPathsItem } from "astro";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readPackedSprite,
type PackedSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index";
const ROOT = "Data/Gfx/Lobby/icons/upgrades";
export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
const paths: GetStaticPathsItem[] = [];
const files = await vfs.dir(ROOT);
for (const file of files) {
if (file.endsWith("@2x.packed.webp")) continue;
const match = file.match(/^(.+)\.packed\.webp$/);
if (match === null) continue;
paths.push({
params: { id: match[1] },
props: { packed: `${ROOT}/${file}` },
});
}
return paths;
});
export async function GET({ props }: APIContext<PackedSpriteProps>) {
return new Response(await readPackedSprite(props.packed));
}
@@ -1,6 +1,9 @@
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readDiscreteSprite,
type DiscreteSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -11,8 +14,8 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
.dir("Data/Gfx/Shared/boosters") .dir("Data/Gfx/Shared/boosters")
.then((files) => .then((files) =>
files.filter( files.filter(
(file) => !file.includes("@2x.txt") && !file.startsWith("texture0"), (file) => !file.includes("@2x.txt") && !file.startsWith("texture0")
), )
); );
for (const file of boosterFiles) { for (const file of boosterFiles) {
@@ -20,34 +23,20 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
if (id === undefined) continue; if (id === undefined) continue;
const sizes = (await vfs.text(`Data/Gfx/Shared/boosters/${file}`))
.split("\n")[4]
.split(" ")
.map(Number);
paths.push({ paths.push({
params: { id }, params: { id },
props: { sizes }, props: {
descriptor: `Data/Gfx/Shared/boosters/${file}`,
texture: `Data/Gfx/Shared/boosters/texture0.packed.webp`,
},
}); });
} }
return paths; return paths;
}); });
export async function GET({ props }: APIContext<{ sizes: number[] }>) { export async function GET({ props }: APIContext<DiscreteSpriteProps>) {
const image = sharp( return new Response(
await vfs.file(`Data/Gfx/Shared/boosters/texture0.packed.webp`), await readDiscreteSprite(props.descriptor, props.texture)
); );
const buffer = await image
.clone()
.extract({
left: props.sizes[0],
top: props.sizes[1],
width: props.sizes[2],
height: props.sizes[3],
})
.toBuffer();
const bytes = new Uint8Array(buffer);
return new Response(bytes);
} }
@@ -1,14 +1,9 @@
import sharp from "sharp"; import { readPackedSprite } from "../../../core/blitz/readSprite";
import { vfs } from "../../../core/blitzkit/vfs";
export { getStaticPaths } from "../_index"; export { getStaticPaths } from "../_index";
export async function GET() { export async function GET() {
const buffer = await sharp( return new Response(
await vfs.file("Data/Gfx/UI/Hangar/IconCamouflage.packed.webp"), await readPackedSprite("Data/Gfx/UI/Hangar/IconCamouflage.packed.webp"),
) );
.trim()
.toBuffer();
return new Response(new Uint8Array(buffer));
} }
@@ -3,8 +3,7 @@ import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp"; import sharp from "sharp";
import { api } from "../../../../api/dynamic"; import { api } from "../../../../api/dynamic";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import { extractPackedIcon } from "../../../../core/blitz/extractPackedIcon"; import { readPackedSprite } from "../../../../core/blitz/readSprite";
import { parsePackedSpriteRect } from "../../../../core/blitz/parsePackedSpriteRect";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -38,16 +37,8 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
}); });
export async function GET({ props }: APIContext<{ path: string }>) { export async function GET({ props }: APIContext<{ path: string }>) {
const path = (await vfs.resolve(`${props.path}@2x.packed.webp`)) const packed = (await vfs.resolve(`${props.path}@2x.packed.webp`))
? `${props.path}@2x.packed.webp` ? `${props.path}@2x.packed.webp`
: `${props.path}.packed.webp`; : `${props.path}.packed.webp`;
const packed = await vfs.file(path); return new Response(await readPackedSprite(packed));
const texture = sharp(packed);
const sizes = parsePackedSpriteRect(packed);
const image = sizes
? sharp(await extractPackedIcon(texture, sizes))
: texture;
const bytes = await image.webp().toBuffer();
return new Response(new Uint8Array(bytes));
} }
@@ -1,9 +1,7 @@
import type { ConsumablesCommon } from "@blitzkit/core"; import type { ConsumablesCommon } from "@blitzkit/core";
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import { extractPackedIcon } from "../../../../core/blitz/extractPackedIcon"; import { readStyleSprite } from "../../../../core/blitz/readSprite";
import { parsePackedSpriteRect } from "../../../../core/blitz/parsePackedSpriteRect";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -70,43 +68,5 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
}); });
export async function GET({ props }: APIContext<{ path: string }>) { export async function GET({ props }: APIContext<{ path: string }>) {
let buffer: Buffer; return new Response(await readStyleSprite(`Data/${props.path}`));
if (await vfs.resolve(`Data/${props.path}.packed.webp`)) {
const packedBuffer = await vfs.file(`Data/${props.path}.packed.webp`);
const consumablesTexture = sharp(packedBuffer);
const sizes = parsePackedSpriteRect(packedBuffer);
if (sizes) {
buffer = await extractPackedIcon(consumablesTexture, sizes);
} else {
buffer = await consumablesTexture.trim({ threshold: 80 }).toBuffer();
}
} else {
const consumablesTexture = sharp(
await vfs.file(
`${`Data/${props.path}`
.split("/")
.slice(0, -1)
.join("/")}/texture0.packed.webp`,
),
);
const sizes = (await vfs.text(`Data/${props.path}.txt`))
.split("\n")[4]
.split(" ")
.map(Number);
buffer = await consumablesTexture
.clone()
.extract({
left: sizes[0],
top: sizes[1],
width: sizes[2],
height: sizes[3],
})
.toBuffer();
}
const bytes = new Uint8Array(buffer);
return new Response(bytes);
} }
@@ -5,9 +5,8 @@ import {
} from "@blitzkit/core"; } from "@blitzkit/core";
import locales from "@blitzkit/i18n/locales.json"; import locales from "@blitzkit/i18n/locales.json";
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import { vfs } from "../../../../core/blitzkit/vfs"; import { readPackedSprite } from "../../../../core/blitz/readSprite";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
const ICONS = [ const ICONS = [
@@ -36,13 +35,11 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
} }
const glossary = await fetch( const glossary = await fetch(
`${WOTB_GLOSSARY_DOMAIN}/${locales.default}/${WOTB_GLOSSARY_PATH}`, `${WOTB_GLOSSARY_DOMAIN}/${locales.default}/${WOTB_GLOSSARY_PATH}`
) )
.then((response) => response.json() as Promise<BlitzGlossary>) .then((response) => response.json() as Promise<BlitzGlossary>)
.then((glossary) => .then((glossary) =>
Object.values(glossary) Object.entries(glossary).filter(([key]) => /^prx_season_\d+$/.test(key))
.entries()
.filter(([key]) => /^prx_season_\d+$/.test(`${key}`)),
); );
for (const [id, item] of glossary) { for (const [id, item] of glossary) {
@@ -63,25 +60,12 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
export async function GET({ export async function GET({
props, props,
}: APIContext<{ local: boolean; source: string }>) { }: APIContext<{ local: boolean; source: string }>) {
let buffer: Buffer;
if (props.local) { if (props.local) {
buffer = await sharp(await vfs.file(props.source)) return new Response(await readPackedSprite(props.source));
.trim()
.toBuffer();
} else {
const imageRaw = await fetch(props.source).then((response) =>
response.arrayBuffer(),
);
buffer = await sharp(imageRaw)
.trim({
threshold: 100,
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.toBuffer();
} }
const bytes = new Uint8Array(buffer); // The glossary already serves these cropped
return new Response(
return new Response(bytes); await fetch(props.source).then((response) => response.arrayBuffer())
);
} }
@@ -1,7 +1,12 @@
import type { OptionalDevices } from "@blitzkit/core"; import type { OptionalDevices } from "@blitzkit/core";
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readDiscreteSprite,
readPackedSprite,
type DiscreteSpriteProps,
type PackedSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -14,16 +19,18 @@ interface Mappings {
}[]; }[];
} }
type Props = PackedSpriteProps | DiscreteSpriteProps;
export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => { export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
const paths: GetStaticPathsItem[] = []; const paths: GetStaticPathsItem[] = [];
console.log("Building equipment icons..."); console.log("Building equipment icons...");
const optionalDevices = await vfs.xml<{ root: OptionalDevices }>( const optionalDevices = await vfs.xml<{ root: OptionalDevices }>(
`Data/XML/item_defs/vehicles/common/optional_devices.xml`, `Data/XML/item_defs/vehicles/common/optional_devices.xml`
); );
const mappings = await vfs.yaml<Mappings>( const mappings = await vfs.yaml<Mappings>(
`Data/UI/Screens3/Lobby/Inventory/OptionalDevices/OptionalDevicesItemImage.style.yaml`, `Data/UI/Screens3/Lobby/Inventory/OptionalDevices/OptionalDevicesItemImage.style.yaml`
); );
for (const optionalDeviceKey in optionalDevices.root) { for (const optionalDeviceKey in optionalDevices.root) {
@@ -33,8 +40,8 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
const mapping = mappings.StyleSheets.find((mapping) => const mapping = mappings.StyleSheets.find((mapping) =>
mapping.selectors.includes( mapping.selectors.includes(
`.optional_device_item.${optionalDevice.icon} #Img`, `.optional_device_item.${optionalDevice.icon} #Img`
), )
); );
if (!mapping) { if (!mapping) {
@@ -50,20 +57,14 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
paths.push({ paths.push({
params: { id: optionalDevice.id }, params: { id: optionalDevice.id },
props: { props: { packed: `Data/${configPathWebp}.packed.webp` },
sizes: undefined,
source: `Data/${configPathWebp}.packed.webp`,
},
}); });
} else { } else {
const config = await vfs.text(`Data/${configPath}`);
const sizes = config.split("\n")[4].split(" ").map(Number);
paths.push({ paths.push({
params: { id: optionalDevice.id }, params: { id: optionalDevice.id },
props: { props: {
sizes, descriptor: `Data/${configPath}`,
source: `Data/Gfx/UI/InventoryIcons/Big/OptionalDevices/texture0.packed.webp`, texture: `Data/Gfx/UI/InventoryIcons/Big/OptionalDevices/texture0.packed.webp`,
}, },
}); });
} }
@@ -72,26 +73,10 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
return paths; return paths;
}); });
export async function GET({ export async function GET({ props }: APIContext<Props>) {
props, return new Response(
}: APIContext<{ sizes?: number[]; source: string }>) { "packed" in props
const image = sharp(await vfs.file(props.source)); ? await readPackedSprite(props.packed)
let buffer: Buffer; : await readDiscreteSprite(props.descriptor, props.texture)
);
if (props.sizes) {
buffer = await image
.extract({
left: props.sizes[0],
top: props.sizes[1],
width: props.sizes[2],
height: props.sizes[3],
})
.toBuffer();
} else {
buffer = await image.trim().toBuffer();
}
const bytes = new Uint8Array(buffer);
return new Response(bytes);
} }
@@ -1,6 +1,9 @@
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readPackedSprite,
type PackedSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -12,8 +15,8 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
.then((files) => .then((files) =>
files.filter( files.filter(
(file) => (file) =>
!file.endsWith("@2x.packed.webp") && file.startsWith("vehicle"), !file.endsWith("@2x.packed.webp") && file.startsWith("vehicle")
), )
); );
for (const file of files) { for (const file of files) {
@@ -23,18 +26,13 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
paths.push({ paths.push({
params: { id }, params: { id },
props: { path }, props: { packed: path },
}); });
} }
return paths; return paths;
}); });
export async function GET({ props }: APIContext<{ path: string }>) { export async function GET({ props }: APIContext<PackedSpriteProps>) {
const buffer = await sharp(await vfs.file(props.path)) return new Response(await readPackedSprite(props.packed));
.trim()
.toBuffer();
const bytes = new Uint8Array(buffer);
return new Response(bytes);
} }
@@ -1,9 +1,7 @@
import type { ProvisionsCommon } from "@blitzkit/core"; import type { ProvisionsCommon } from "@blitzkit/core";
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { extractPackedIcon } from "../../../../core/blitz/extractPackedIcon";
import { parsePackedSpriteRect } from "../../../../core/blitz/parsePackedSpriteRect";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import { readStyleSprite } from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -70,43 +68,5 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
}); });
export async function GET({ props }: APIContext<{ path: string }>) { export async function GET({ props }: APIContext<{ path: string }>) {
let buffer: Buffer; return new Response(await readStyleSprite(`Data/${props.path}`));
if (await vfs.resolve(`Data/${props.path}.packed.webp`)) {
const packedBuffer = await vfs.file(`Data/${props.path}.packed.webp`);
const provisionsTexture = sharp(packedBuffer);
const sizes = parsePackedSpriteRect(packedBuffer);
if (sizes) {
buffer = await extractPackedIcon(provisionsTexture, sizes);
} else {
buffer = await provisionsTexture.trim({ threshold: 80 }).toBuffer();
}
} else {
const provisionsTexture = sharp(
await vfs.file(
`${`Data/${props.path}`
.split("/")
.slice(0, -1)
.join("/")}/texture0.packed.webp`,
),
);
const sizes = (await vfs.text(`Data/${props.path}.txt`))
.split("\n")[4]
.split(" ")
.map(Number);
buffer = await provisionsTexture
.clone()
.extract({
left: sizes[0],
top: sizes[1],
width: sizes[2],
height: sizes[3],
})
.toBuffer();
}
const bytes = new Uint8Array(buffer);
return new Response(bytes);
} }
@@ -1,6 +1,9 @@
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readDiscreteSprite,
type DiscreteSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -13,38 +16,21 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
for (const file of files) { for (const file of files) {
const id = file.match(/(.+)_l\.txt/)![1]; const id = file.match(/(.+)_l\.txt/)![1];
const sizes = (
await vfs.text(`Data/Gfx/Shared/tank-supply/ammunition/big/${file}`)
)
.split("\n")[4]
.split(" ")
.map(Number);
paths.push({ paths.push({
params: { id }, params: { id },
props: { sizes }, props: {
descriptor: `Data/Gfx/Shared/tank-supply/ammunition/big/${file}`,
texture: `Data/Gfx/Shared/tank-supply/ammunition/big/texture0.packed.webp`,
},
}); });
} }
return paths; return paths;
}); });
export async function GET({ props }: APIContext<{ sizes: number[] }>) { export async function GET({ props }: APIContext<DiscreteSpriteProps>) {
const image = sharp( return new Response(
await vfs.file( await readDiscreteSprite(props.descriptor, props.texture)
`Data/Gfx/Shared/tank-supply/ammunition/big/texture0.packed.webp`,
),
); );
const buffer = await image
.clone()
.extract({
left: props.sizes[0],
top: props.sizes[1],
width: props.sizes[2],
height: props.sizes[3],
})
.toBuffer();
const bytes = new Uint8Array(buffer);
return new Response(bytes);
} }
@@ -1,7 +1,10 @@
import type { TankmenAvatar } from "@blitzkit/core"; import type { TankmenAvatar } from "@blitzkit/core";
import type { APIContext, GetStaticPathsItem } from "astro"; import type { APIContext, GetStaticPathsItem } from "astro";
import sharp from "sharp";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths"; import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import {
readPackedSprite,
type PackedSpriteProps,
} from "../../../../core/blitz/readSprite";
import { vfs } from "../../../../core/blitzkit/vfs"; import { vfs } from "../../../../core/blitzkit/vfs";
import { getStaticPaths as _getStaticPaths } from "../../_index"; import { getStaticPaths as _getStaticPaths } from "../../_index";
@@ -9,7 +12,7 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
const paths: GetStaticPathsItem[] = []; const paths: GetStaticPathsItem[] = [];
const avatar = await vfs.xml<{ root: TankmenAvatar }>( const avatar = await vfs.xml<{ root: TankmenAvatar }>(
`Data/XML/item_defs/tankmen/avatar.xml`, `Data/XML/item_defs/tankmen/avatar.xml`
); );
for (const key in avatar.root.skills) { for (const key in avatar.root.skills) {
@@ -20,18 +23,13 @@ export const getStaticPaths = mixStaticPaths(_getStaticPaths, async () => {
paths.push({ paths.push({
params: { id }, params: { id },
props: { path }, props: { packed: path },
}); });
} }
return paths; return paths;
}); });
export async function GET({ props }: APIContext<{ path: string }>) { export async function GET({ props }: APIContext<PackedSpriteProps>) {
const buffer = await sharp(await vfs.file(props.path)) return new Response(await readPackedSprite(props.packed));
.trim()
.toBuffer();
const bytes = new Uint8Array(buffer);
return new Response(bytes);
} }
@@ -4,8 +4,7 @@ import {
type VehicleDefinitionList, type VehicleDefinitionList,
} from "@blitzkit/core"; } from "@blitzkit/core";
import type { APIContext } from "astro"; import type { APIContext } from "astro";
import sharp from "sharp"; import { readPackedSprite } from "../../../../../core/blitz/readSprite";
import { parsePackedSpriteRect } from "../../../../../core/blitz/parsePackedSpriteRect";
import { vfs } from "../../../../../core/blitzkit/vfs"; import { vfs } from "../../../../../core/blitzkit/vfs";
export { getStaticPaths } from "../_index"; export { getStaticPaths } from "../_index";
@@ -33,52 +32,11 @@ export async function GET({ props }: APIContext<{ id: number }>) {
const parameters = await vfs.yaml<TankParameters>( const parameters = await vfs.yaml<TankParameters>(
`Data/3d/Tanks/Parameters/${nation}/${tankKey}.yaml`, `Data/3d/Tanks/Parameters/${nation}/${tankKey}.yaml`,
); );
const bigPath = `Data/${parameters.resourcesPath.bigIconPath const packed = `Data/${parameters.resourcesPath.bigIconPath
.replace(/~res:\//, "") .replace(/~res:\//, "")
.replace(/\..+/, "")}.packed.webp`; .replace(/\..+/, "")}.packed.webp`;
const big = await extractPackedTankIcon(await vfs.file(bigPath));
return new Response(big); return new Response(await readPackedSprite(packed));
} }
} }
} }
export async function extractPackedTankIcon(bytes: Uint8Array) {
const texture = sharp(bytes);
const spriteRect = parsePackedSpriteRect(bytes);
if (!spriteRect) {
throw new Error(`Missing RIFF sprite bounds`);
}
const [left, top, width, height] = spriteRect;
const bounds = [left, top, width, height];
if (!bounds.every(Number.isInteger)) {
throw new Error(`Invalid RIFF sprite bounds: ${bounds.join(" ")}`);
}
const metadata = await texture.metadata();
if (metadata.width === undefined || metadata.height === undefined) {
throw new Error(`Failed to read image dimensions`);
}
if (
left < 0 ||
top < 0 ||
width <= 0 ||
height <= 0 ||
left + width > metadata.width ||
top + height > metadata.height
) {
throw new Error(
`Out-of-bounds RIFF sprite: ${bounds.join(" ")} in ${metadata.width}x${metadata.height}`,
);
}
const buffer = await texture.extract({ left, top, width, height }).toBuffer();
const array = new Uint8Array(buffer);
return array;
}
@@ -4,8 +4,8 @@ import {
type VehicleDefinitionList, type VehicleDefinitionList,
} from "@blitzkit/core"; } from "@blitzkit/core";
import type { APIContext } from "astro"; import type { APIContext } from "astro";
import { readPackedSprite } from "../../../../../core/blitz/readSprite";
import { vfs } from "../../../../../core/blitzkit/vfs"; import { vfs } from "../../../../../core/blitzkit/vfs";
import { extractPackedTankIcon } from "./big.webp";
export { getStaticPaths } from "../_index"; export { getStaticPaths } from "../_index";
@@ -32,12 +32,11 @@ export async function GET({ props }: APIContext<{ id: number }>) {
const parameters = await vfs.yaml<TankParameters>( const parameters = await vfs.yaml<TankParameters>(
`Data/3d/Tanks/Parameters/${nation}/${tankKey}.yaml`, `Data/3d/Tanks/Parameters/${nation}/${tankKey}.yaml`,
); );
const bigPath = `Data/${parameters.resourcesPath.smallIconPath const packed = `Data/${parameters.resourcesPath.smallIconPath
.replace(/~res:\//, "") .replace(/~res:\//, "")
.replace(/\..+/, "")}.packed.webp`; .replace(/\..+/, "")}.packed.webp`;
const big = await extractPackedTankIcon(await vfs.file(bigPath));
return new Response(big); return new Response(await readPackedSprite(packed));
} }
} }
} }
@@ -1,9 +1,9 @@
import { Soapstone } from "soapstone"; import { Soapstone } from "soapstone";
import type { CharacteristicName } from "../types/characteristics"; import type { RenderedCharacteristicName } from "../types/characteristics";
import { TankopediaSortDirection } from "./tankopediaPersistent"; import { TankopediaSortDirection } from "./tankopediaPersistent";
export interface TankSort { export interface TankSort {
by: CharacteristicName | null; by: RenderedCharacteristicName | null;
direction: TankopediaSortDirection; direction: TankopediaSortDirection;
} }
@@ -0,0 +1,239 @@
import type {
AugmentGroup,
AugmentNode,
AugmentProgression,
AugmentRequirement,
} from "@blitzkit/protos";
import type { Vector2Tuple } from "three";
import { CellGrid } from "./cellGrid";
/**
* Follows how the game routes the connectors of its augment tree.
*
* Every node is placed by hand on a shared grid and the connectors are
* per-cell flags, same as the modules screen. Each requirement becomes an
* edge that is routed along one row and one column, never diagonally. The
* game's arrowheads are left out, the same as on the modules screen.
*/
export interface AugmentTreeCell {
// 1-based grid column (depth) and row
position: Vector2Tuple;
// Missing for empty cells that only carry a connector line
node?: AugmentNode;
// The final choice every branch ends in. Takes the cell its edges point at
group?: AugmentGroup;
// Line from the cell center to the left
left: boolean;
// Line from the cell center to the right
right: boolean;
// Line from the cell center up to the previous row
top: boolean;
// Line from the cell center down to the next row
bottom: boolean;
}
// A cell as the website shows it. The game lays the tree out left to right
// and the website top to bottom, so the game's depth becomes the row
export interface AugmentTreeDisplayCell {
// 1-based grid row (depth) and column
row: number;
column: number;
node?: AugmentNode;
group?: AugmentGroup;
north: boolean;
south: boolean;
west: boolean;
east: boolean;
}
// Source row and column, then target row and column
type Edge = readonly [
fromRow: number,
fromColumn: number,
toRow: number,
toColumn: number,
verticalFirst: boolean,
];
function emptyCell(column: number, row: number) {
return {
position: [column, row],
left: false,
right: false,
top: false,
bottom: false,
} satisfies AugmentTreeCell;
}
export function layoutAugmentTree({ nodes, group }: AugmentProgression) {
// Only placed nodes can have a line drawn from them
const byTechName = new Map(
nodes
.filter((node) => node.position !== undefined)
.map((node) => [node.tech_name, node]),
);
const edges: Edge[] = [];
const connect = (
requires: AugmentRequirement[],
toRow: number,
toColumn: number,
) => {
for (const { tech_name, vertical_first } of requires) {
// Nothing to draw from a node the tank doesn't have
if (!byTechName.has(tech_name)) continue;
const from = byTechName.get(tech_name)!.position!;
edges.push([from.y, from.x, toRow, toColumn, vertical_first]);
}
};
for (const node of nodes) {
if (node.position === undefined) continue;
connect(node.requires, node.position.y, node.position.x);
}
if (group !== undefined) {
connect(group.requires, group.position!.y, group.position!.x);
}
const grid = new CellGrid<AugmentTreeCell>(emptyCell);
const { cellAt } = grid;
for (const node of nodes) {
if (node.position !== undefined) {
cellAt(node.position.x, node.position.y).node = node;
}
}
if (group !== undefined) {
cellAt(group.position!.x, group.position!.y).group = group;
}
// Cells strictly between two ends, which stay untouched here
const runHorizontally = (row: number, from: number, to: number) => {
const step = from < to ? 1 : -1;
for (let column = from + step; column !== to; column += step) {
const cell = cellAt(column, row);
cell.left = true;
cell.right = true;
}
};
const runVertically = (column: number, from: number, to: number) => {
const step = from < to ? 1 : -1;
for (let row = from + step; row !== to; row += step) {
const cell = cellAt(column, row);
cell.top = true;
cell.bottom = true;
}
};
// Where a run turns, joining the vertical and horizontal pieces
const corner = (
row: number,
column: number,
otherRow: number,
otherColumn: number,
) => {
const cell = cellAt(column, row);
if (row <= otherRow) cell.bottom = true;
else cell.top = true;
if (column <= otherColumn) cell.right = true;
else cell.left = true;
};
// Attaches the line to both nodes
const attach = (
fromRow: number,
fromColumn: number,
toRow: number,
toColumn: number,
verticalFirst: boolean,
) => {
const from = cellAt(fromColumn, fromRow);
const to = cellAt(toColumn, toRow);
if (fromColumn === toColumn) {
if (fromRow < toRow) {
from.bottom = true;
to.top = true;
} else {
from.top = true;
to.bottom = true;
}
} else if (fromRow === toRow) {
if (toColumn <= fromColumn) {
from.left = true;
to.right = true;
} else {
from.right = true;
to.left = true;
}
} else if (verticalFirst) {
if (fromRow < toRow) from.bottom = true;
else from.top = true;
if (toColumn <= fromColumn) to.right = true;
else to.left = true;
} else {
if (fromColumn < toColumn) from.right = true;
else from.left = true;
if (fromRow < toRow) to.top = true;
else to.bottom = true;
}
};
for (const [fromRow, fromColumn, toRow, toColumn, verticalFirst] of edges) {
// The client draws nothing for an edge that starts where it ends
if (fromRow === toRow && fromColumn === toColumn) continue;
// Touching ends are left to `attach`
if (fromRow === toRow) {
if (fromColumn !== toColumn)
runHorizontally(fromRow, fromColumn, toColumn);
} else if (fromColumn === toColumn) {
runVertically(fromColumn, fromRow, toRow);
} else if (verticalFirst) {
// Down the source column, then along the target row
runVertically(fromColumn, fromRow, toRow);
corner(toRow, fromColumn, fromRow, toColumn);
runHorizontally(toRow, fromColumn, toColumn);
} else {
// Along the source row, then down the target column
runHorizontally(fromRow, fromColumn, toColumn);
corner(fromRow, toColumn, toRow, fromColumn);
runVertically(toColumn, fromRow, toRow);
}
attach(fromRow, fromColumn, toRow, toColumn, verticalFirst);
}
return {
cells: grid.cells().map(
({ position: [column, row], node, group, left, right, top, bottom }) =>
({
row: column,
column: row,
node,
group,
north: left,
south: right,
west: top,
east: bottom,
} satisfies AugmentTreeDisplayCell),
),
rows: grid.columns,
columns: grid.rows,
};
}
+177
View File
@@ -0,0 +1,177 @@
import {
AugmentNodeType,
type AugmentNode,
type AugmentProgression,
type TankDefinition,
} from "@blitzkit/protos";
import type { TankState } from "./tankState";
function isAlternative(node: AugmentNode) {
return node.type === AugmentNodeType.AUGMENT_NODE_TYPE_ALTERNATIVE;
}
// Alternatives live in the final group, outside the grid
export function listAugmentNodes({ nodes, group }: AugmentProgression) {
return [...nodes, ...(group?.alternatives ?? [])];
}
// Standing in for the final group, which has no id of its own
export const AUGMENT_GROUP_ID = -1;
function directPrerequisites(
progression: AugmentProgression,
node: AugmentNode,
) {
const byTechName = new Map(
progression.nodes.map((other) => [other.tech_name, other.id]),
);
const requires = isAlternative(node)
? progression.group?.requires ?? []
: node.requires;
return requires.flatMap(({ tech_name }) => byTechName.get(tech_name) ?? []);
}
// Everything the given nodes stand on, the nodes themselves included
function foundations(progression: AugmentProgression, ids: number[]) {
const byId = new Map(
listAugmentNodes(progression).map((node) => [node.id, node]),
);
const found = new Set<number>();
const pending = [...ids];
while (pending.length > 0) {
const id = pending.pop()!;
const node = byId.get(id);
if (found.has(id) || node === undefined) continue;
found.add(id);
pending.push(...directPrerequisites(progression, node));
}
return found;
}
/**
* Like picking a module: choosing an augment installs everything on the way to
* it. Choosing one that is already installed steps back to it by removing
* what was built on top, and removes it too once nothing is left on top. The
* final group is a choice, so installing one alternative replaces the other.
*/
export function toggleAugment(
draft: Pick<TankState, "augments">,
progression: AugmentProgression,
id: number,
) {
const nodes = listAugmentNodes(progression);
const installed = new Set(draft.augments);
const alternatives = new Set(
progression.group?.alternatives.map((alternative) => alternative.id),
);
if (id === AUGMENT_GROUP_ID) {
const { group } = progression;
if (group === undefined) return;
const needed = directPrerequisites(progression, group.alternatives[0]);
if (needed.every((other) => installed.has(other))) {
// Already there, so back out of the choice
draft.augments = draft.augments.filter(
(other) => !alternatives.has(other),
);
} else {
for (const other of foundations(progression, needed))
installed.add(other);
draft.augments = [...installed];
}
return;
}
const node = nodes.find((candidate) => candidate.id === id);
if (node === undefined) return;
if (!installed.has(id)) {
for (const other of foundations(progression, [id])) installed.add(other);
if (alternatives.has(id)) {
for (const other of alternatives)
if (other !== id) installed.delete(other);
}
draft.augments = [...installed];
return;
}
// Everything installed that stands on this one, however far up
const above = new Set<number>();
let grew = true;
while (grew) {
grew = false;
for (const other of nodes) {
if (!installed.has(other.id) || above.has(other.id)) continue;
const stands = directPrerequisites(progression, other).some(
(prerequisite) => prerequisite === id || above.has(prerequisite),
);
if (!stands) continue;
above.add(other.id);
grew = true;
}
}
const removed = above.size > 0 ? above : new Set([id]);
draft.augments = draft.augments.filter((other) => !removed.has(other));
}
// Everything in the grid. The final group still needs a choice
export function createAugments(progression?: AugmentProgression) {
if (!progression) return [];
return progression.nodes.map((node) => node.id);
}
// Every value the installed augments give each attribute, keyed by the
// attribute's name without the `ATTRIBUTE_NAME_` prefix
export function augmentAttributes(
{ augment_progression }: TankDefinition,
state: TankState,
) {
const attributes = new Map<string, number[]>();
if (augment_progression === undefined) return attributes;
const installed = new Set(state.augments);
for (const node of listAugmentNodes(augment_progression)) {
if (!installed.has(node.id)) continue;
for (const { name, value } of node.attributes) {
const key = name.replace(/^ATTRIBUTE_NAME_/, "");
if (!attributes.has(key)) attributes.set(key, []);
attributes.get(key)!.push(value);
}
}
return attributes;
}
// Slots are the position of the shell in the gun's list, counted from 1
export function shellSlot(
gun: { shells: { id: number }[] },
shell: { id: number },
) {
return gun.shells.findIndex(({ id }) => id === shell.id) + 1;
}
@@ -0,0 +1,41 @@
import type { Vector2Tuple } from "three";
// A sparse grid that grows to fit whatever is placed on it, shared by the
// module and augment trees. Cells are indexed column first, then row
export class CellGrid<Cell extends { position: Vector2Tuple }> {
private readonly columnCells = new Map<number, Map<number, Cell>>();
// Highest 1-based column and row anything has been placed at
columns = 0;
rows = 0;
constructor(
private readonly createCell: (column: number, row: number) => Cell,
) {}
// An arrow, so it can be pulled off the grid and called on its own
cellAt = (column: number, row: number) => {
let cells = this.columnCells.get(column);
if (cells === undefined) {
cells = new Map();
this.columnCells.set(column, cells);
}
let cell = cells.get(row);
if (cell === undefined) {
cell = this.createCell(column, row);
cells.set(row, cell);
this.columns = Math.max(this.columns, column);
this.rows = Math.max(this.rows, row);
}
return cell;
};
cells() {
return [...this.columnCells.values()].flatMap((cells) => [
...cells.values(),
]);
}
}
@@ -1,6 +1,7 @@
import { createDefaultProvisions } from "@blitzkit/core"; import { createDefaultProvisions } from "@blitzkit/core";
import type { TankDefinition } from "@blitzkit/protos"; import type { TankDefinition } from "@blitzkit/protos";
import { api } from "../api/dynamic"; import { api } from "../api/dynamic";
import { createAugments } from "./augments";
import { createTankEquipment } from "./createTankEquipment"; import { createTankEquipment } from "./createTankEquipment";
import { createTankStatus } from "./createTankStatus"; import { createTankStatus } from "./createTankStatus";
import type { TankState } from "./tankState"; import type { TankState } from "./tankState";
@@ -36,6 +37,7 @@ export function createTankState(tank: TankDefinition) {
model: models.models[tank.id], model: models.models[tank.id],
consumables: [], consumables: [],
augments: createAugments(tank.augment_progression),
provisions: createDefaultProvisions(tank, gun, provisions, scripts), provisions: createDefaultProvisions(tank, gun, provisions, scripts),
camouflage: true, camouflage: true,
cooldown_booster: 0, cooldown_booster: 0,
@@ -1,30 +1,4 @@
import type { import type { CharacteristicContext } from "../types/characteristics";
CharacteristicContext,
CharacteristicScript,
} from "../types/characteristics";
function hullTraverseRotationCoefficient(
driverCoefficient: number,
virtuosoSkill: number,
script: CharacteristicScript,
) {
let coefficient = 1 + virtuosoSkill / 100;
let rotationSpeedFactor = 1;
script("protagonist", "StaticPhysicsAttrsModifier", (effect) => {
coefficient += (effect.bonusPercentage?.rotationSpeedFactor ?? 0) / 100;
});
script("protagonist", "ImprovedAfterburning", (effect) => {
rotationSpeedFactor *= effect.rotationSpeedFactor ?? 1;
});
script("protagonist", "AfterburnerAbility", (effect) => {
rotationSpeedFactor *= effect.bonusValues?.rotationSpeedFactor ?? 1;
});
return driverCoefficient * coefficient * rotationSpeedFactor;
}
export function hullTraverseSpeed( export function hullTraverseSpeed(
rawTerrainResistance: number, rawTerrainResistance: number,
@@ -38,6 +12,7 @@ export function hullTraverseSpeed(
gun, gun,
progressive, progressive,
script, script,
augment,
environment, environment,
characteristic, characteristic,
} = context; } = context;
@@ -54,14 +29,32 @@ export function hullTraverseSpeed(
stockGun.weight; stockGun.weight;
const weight = const weight =
tank.weight + engine.weight + track.weight + turret.weight + gun.weight; tank.weight + engine.weight + track.weight + turret.weight + gun.weight;
// Engine augments are flat, so this goes through the finished stat
const enginePower = const enginePower =
(engine.power * (characteristic("_engine_power_coefficient") as number)) / (characteristic("engine_power") as number) / stockEngine.power;
stockEngine.power; const virtuosoSkill = environment.skills.virtuoso ?? 0;
const rotationSpeed = hullTraverseRotationCoefficient( let rotationCoefficient = 1 + virtuosoSkill / 100;
progressive("driver"), let rotationSpeedFactor = 1;
environment.skills.virtuoso ?? 0,
script, augment("HULL_ROTATION_SPEED_FACTOR_BONUS", (value) => {
); rotationCoefficient += value;
});
script("protagonist", "StaticPhysicsAttrsModifier", (effect) => {
rotationCoefficient +=
(effect.bonusPercentage?.rotationSpeedFactor ?? 0) / 100;
});
script("protagonist", "ImprovedAfterburning", (effect) => {
rotationSpeedFactor *= effect.rotationSpeedFactor ?? 1;
});
script("protagonist", "AfterburnerAbility", (effect) => {
rotationSpeedFactor *= effect.bonusValues?.rotationSpeedFactor ?? 1;
});
const rotationSpeed =
progressive("driver") * rotationCoefficient * rotationSpeedFactor;
return ( return (
enginePower * enginePower *
@@ -1,9 +1,10 @@
import { ModuleType, type ModulePosition, type Unlock } from "@blitzkit/protos"; import { ModuleType, type ModulePosition, type Unlock } from "@blitzkit/protos";
import type { Vector2Tuple } from "three"; import type { Vector2Tuple } from "three";
import { CellGrid } from "./cellGrid";
/** /**
* Port of the game client's modules screen layout (wotblitz.exe 11.21, * Follows how the game lays out its modules screen: automatic placement and
* `ModulesTreeInfoCache` auto-layout + `TankModulesTreeController` arrows). * the arrows.
* *
* Every node lives on one shared grid: depth is the column, and leaves take * Every node lives on one shared grid: depth is the column, and leaves take
* consecutive rows with each parent centered over its children. Connectors are * consecutive rows with each parent centered over its children. Connectors are
@@ -58,13 +59,6 @@ function key(unlock: Unlock) {
return `${unlock.type}:${unlock.id}`; return `${unlock.type}:${unlock.id}`;
} }
// Cells are indexed column first, then row
type CellGrid = Map<number, Map<number, ModuleTreeCell>>;
function flattenGrid(grid: CellGrid) {
return [...grid.values()].flatMap((column) => [...column.values()]);
}
function emptyCell(x: number, y: number) { function emptyCell(x: number, y: number) {
return { return {
position: [x, y], position: [x, y],
@@ -93,7 +87,7 @@ function layoutSnake(placements: Placement[]) {
// The client takes this from whichever deep module sorts last // The client takes this from whichever deep module sorts last
const lastOnFirstRow = deep.length > 0 && deep.at(-1)!.position[1] === 1; const lastOnFirstRow = deep.length > 0 && deep.at(-1)!.position[1] === 1;
const grid: CellGrid = new Map(); const grid = new CellGrid<ModuleTreeCell>(emptyCell);
for (const { for (const {
unlock, unlock,
@@ -113,17 +107,10 @@ function layoutSnake(placements: Placement[]) {
: offset + 1; : offset + 1;
} }
let columnCells = grid.get(column); grid.cellAt(column, row).unlock = unlock;
if (columnCells === undefined) {
columnCells = new Map();
grid.set(column, columnCells);
}
columnCells.set(row, { ...emptyCell(column, row), unlock });
} }
const cells = flattenGrid(grid); const cells = grid.cells();
const width = Math.ceil(ordered.length / height); const width = Math.ceil(ordered.length / height);
for (const cell of cells) { for (const cell of cells) {
@@ -149,15 +136,11 @@ function layoutSnake(placements: Placement[]) {
} }
} }
let columns = width; return {
let rows = height; cells,
columns: Math.max(width, grid.columns),
for (const cell of cells) { rows: Math.max(height, grid.rows),
columns = Math.max(columns, cell.position[0]); };
rows = Math.max(rows, cell.position[1]);
}
return { cells, columns, rows };
} }
function sortSiblings(unlocks: Unlock[]) { function sortSiblings(unlocks: Unlock[]) {
@@ -259,29 +242,8 @@ export function layoutModuleTree(
if (isSnake) return layoutSnake([...placements.values()]); if (isSnake) return layoutSnake([...placements.values()]);
const grid: CellGrid = new Map(); const grid = new CellGrid<ModuleTreeCell>(emptyCell);
let columns = 0; const { cellAt } = grid;
let rows = 0;
const cellAt = (x: number, y: number) => {
let columnCells = grid.get(x);
if (columnCells === undefined) {
columnCells = new Map();
grid.set(x, columnCells);
}
let cell = columnCells.get(y);
if (cell === undefined) {
cell = emptyCell(x, y);
columnCells.set(y, cell);
columns = Math.max(columns, x);
rows = Math.max(rows, y);
}
return cell;
};
for (const { for (const {
unlock, unlock,
@@ -316,5 +278,5 @@ export function layoutModuleTree(
} }
} }
return { cells: flattenGrid(grid), columns, rows }; return { cells: grid.cells(), columns: grid.columns, rows: grid.rows };
} }
@@ -2,7 +2,7 @@ import { characteristics } from "../config/characteristics";
import { characteristicsGroups } from "../config/characteristicsGroups"; import { characteristicsGroups } from "../config/characteristicsGroups";
import { import {
CharacteristicType, CharacteristicType,
type CharacteristicName, type RenderedCharacteristicName,
} from "../types/characteristics"; } from "../types/characteristics";
const sortableCharacteristicTypes = new Set<CharacteristicType>([ const sortableCharacteristicTypes = new Set<CharacteristicType>([
@@ -11,9 +11,11 @@ const sortableCharacteristicTypes = new Set<CharacteristicType>([
CharacteristicType.Interval, CharacteristicType.Interval,
]); ]);
export const sortableCharacteristics = new Set<CharacteristicName>(); export const sortableCharacteristics = new Set<RenderedCharacteristicName>();
for (const group of characteristicsGroups) { for (const group of characteristicsGroups) {
if (!group.sortable) continue;
for (const config of group.order) { for (const config of group.order) {
if (!("name" in config)) continue; if (!("name" in config)) continue;
@@ -18,6 +18,7 @@ export interface TankState {
consumables: number[]; consumables: number[];
provisions: number[]; provisions: number[];
augments: number[];
camouflage: boolean; camouflage: boolean;
cooldown_booster: number; cooldown_booster: number;
} }
+14 -1
View File
@@ -65,6 +65,10 @@ export interface CharacteristicContext {
): ReturnType<Characteristic["compute"]>; ): ReturnType<Characteristic["compute"]>;
script: CharacteristicScript; script: CharacteristicScript;
// Like scripts, but for each value the installed augments give an attribute,
// named without the `ATTRIBUTE_NAME_` prefix
augment(name: string, callback: (value: number) => void): void;
} }
export type CrewStatRole = "commander" | "loader" | "gunner" | "driver"; export type CrewStatRole = "commander" | "loader" | "gunner" | "driver";
@@ -83,6 +87,11 @@ export enum CharacteristicRanking {
} }
export type CharacteristicName = keyof typeof characteristics; export type CharacteristicName = keyof typeof characteristics;
// The ones with strings; underscored characteristics are compute time only
export type RenderedCharacteristicName = Exclude<
CharacteristicName,
`_${string}`
>;
export type CharacteristicReturnType = ReturnType<Characteristic["compute"]>; export type CharacteristicReturnType = ReturnType<Characteristic["compute"]>;
export type ComputedCharacteristics = Map< export type ComputedCharacteristics = Map<
@@ -91,7 +100,7 @@ export type ComputedCharacteristics = Map<
>; >;
export interface CharacteristicRenderConfig { export interface CharacteristicRenderConfig {
name: CharacteristicName; name: RenderedCharacteristicName;
decimals?: number; decimals?: number;
units?: keyof Strings["units"]; units?: keyof Strings["units"];
@@ -108,6 +117,8 @@ export interface CharacteristicRenderConfig {
export interface ToyRenderConfig { export interface ToyRenderConfig {
toy: string; toy: string;
// Only shown when this characteristic is computed for the tank
requires?: CharacteristicName;
} }
export interface LabelRenderConfig { export interface LabelRenderConfig {
@@ -118,5 +129,7 @@ export type ToyName = keyof typeof toys;
export type CharacteristicsGroup = { export type CharacteristicsGroup = {
name: string; name: string;
// Groups that only some tanks have are no use as a sort key
sortable?: boolean;
order: (CharacteristicRenderConfig | LabelRenderConfig | ToyRenderConfig)[]; order: (CharacteristicRenderConfig | LabelRenderConfig | ToyRenderConfig)[];
}; };