Compare commits

..
98 Commits
Author SHA1 Message Date
TrèsAbhi 0cb974acf5 feat: scales 2026-01-07 20:36:55 -06:00
TrèsAbhi 9bca5dccc7 feat: start of new protos 2026-01-04 15:35:58 -06:00
TrèsAbhi d707f1cc5d Merge branch 'main' into ue 2026-01-04 15:23:43 -06:00
TrèsAbhi 4ed4395535 feat: start of strings 2026-01-03 13:29:15 -06:00
TrèsAbhi 0209d48475 feat: backgrounds 2026-01-02 20:17:24 -06:00
TrèsAbhi 437bee4a85 feat: proxy avatars 2026-01-02 20:04:19 -06:00
TrèsAbhi 4b8e73fa57 feat: cache 2026-01-02 14:26:05 -06:00
TrèsAbhi b96f925d9a feat: avatars 2026-01-02 14:20:29 -06:00
TrèsAbhi 1551dc50fd Merge branch 'main' into ue 2026-01-02 12:51:20 -06:00
TrèsAbhi daf4cef61c feat: mode apis 2025-12-28 12:20:45 -06:00
TrèsAbhi 496e127f64 Merge branch 'main' into ue 2025-12-28 12:11:40 -06:00
TrèsAbhi da1af66c77 feat: start of mechanics 2025-12-26 20:07:22 -06:00
TrèsAbhi 01409985a2 feat: list 2025-12-26 19:43:44 -06:00
TrèsAbhi a86ac0619a feat: stop working on ranking since a lot of tanks are broken 2025-12-26 19:37:52 -06:00
TrèsAbhi 385d165512 feat: optimize tankList 2025-12-26 19:21:14 -06:00
TrèsAbhi fcfc97b964 feat: start of all tanks 2025-12-26 14:59:09 -06:00
TrèsAbhi 53d05e73a6 feat: some docs 2025-12-26 14:21:04 -06:00
TrèsAbhi 40a1eb861d feat: meta section 2025-12-26 14:14:29 -06:00
TrèsAbhi 1d3cb95b89 fix: assert wotb server 2025-12-26 11:33:04 -06:00
TrèsAbhi 010303a818 feat: camo 2025-12-24 20:30:19 -06:00
TrèsAbhi 7281b9fed0 feat: power_to_weight 2025-12-24 20:10:06 -06:00
TrèsAbhi c5785c7ae6 feat: more controllers 2025-12-24 19:57:26 -06:00
TrèsAbhi 698731cb9a feat: generalize render chars 2025-12-24 19:48:01 -06:00
TrèsAbhi 99bae8f2c5 fix: array rendering 2025-12-24 19:39:26 -06:00
TrèsAbhi 5034ec1aa0 feat: terrain hardness 2025-12-24 19:37:21 -06:00
TrèsAbhi be821c1f8b Merge branch 'ue' of https://github.com/blitzkit/blitzkit into ue 2025-12-24 19:33:04 -06:00
TrèsAbhi a364b79a9b feat: autoreloader dom 2025-12-24 19:33:01 -06:00
TrèsAbhi 0aa6e1e79a Update deployment condition for GitHub Pages 2025-12-20 20:03:27 -06:00
TrèsAbhi d2a6379131 feat: abstracted meta 2025-12-20 19:10:11 -06:00
TrèsAbhi 07ce61d19f fix: depression 2025-12-20 19:05:42 -06:00
TrèsAbhi ad9f2d8609 feat: start of pitch yaw limits 2025-12-20 19:03:57 -06:00
TrèsAbhi 57702d8a43 fix: repo 2025-12-20 18:10:24 -06:00
TrèsAbhi 9a30af3818 fix: proper pitch limits 2025-12-20 10:26:25 -06:00
TrèsAbhi 23751fbdf3 feat: dynamic dispersion 2025-12-20 10:15:23 -06:00
TrèsAbhi db6d181f78 feat: use max stage 2025-12-20 09:59:26 -06:00
TrèsAbhi 56ca4dcc61 feat: more accents 2025-12-19 22:23:03 -06:00
TrèsAbhi d08b537721 feat: some styling 2025-12-19 21:25:55 -06:00
TrèsAbhi c1a2edb489 feat: baselayout 2025-12-19 17:55:26 -06:00
TrèsAbhi 164b7fa454 feat: api renderer 2025-12-19 17:50:59 -06:00
TrèsAbhi 428483cf4c fix: disable minifySyntax 2025-12-19 16:14:36 -06:00
TrèsAbhi 89f02eb399 minifySyntax 2025-12-19 16:11:26 -06:00
TrèsAbhi 4ce127516c minifyWhitespace 2025-12-19 16:09:27 -06:00
TrèsAbhi 6f4f487dfe minifyIdentifiers 2025-12-19 16:07:34 -06:00
TrèsAbhi 57dd60e804 feat: no minify 2025-12-19 16:01:58 -06:00
TrèsAbhi d24fd2250c feat: deploy on ue 2025-12-19 15:53:30 -06:00
TrèsAbhi e00bcdfc06 feat: latest node 2025-12-19 15:51:47 -06:00
TrèsAbhi 67dd204ee6 fix: typo 2025-12-19 15:48:07 -06:00
TrèsAbhi e130583fa4 fix: build:catalogitemaccesssor 2025-12-19 15:46:40 -06:00
TrèsAbhi 6ad20a0fcf feat: cron 2025-12-19 15:44:32 -06:00
TrèsAbhi 9fad644d7a feat: workflow 2025-12-19 15:42:38 -06:00
TrèsAbhi 8cb523dd06 fix: remove pwa 2025-12-19 15:35:50 -06:00
TrèsAbhi b50ee23a26 feat: re-install 2025-12-19 15:34:16 -06:00
TrèsAbhi a973cf699b fix: cleaner stage0 hack 2025-12-19 15:26:47 -06:00
TrèsAbhi 102abf49c4 fix: default isPump 2025-12-19 15:20:58 -06:00
TrèsAbhi 8929e503ea fix: pump times 2025-12-19 15:17:45 -06:00
TrèsAbhi a2a794eb74 fix: use order instead of group 2025-12-19 15:11:33 -06:00
TrèsAbhi 2e95f5dd95 fix: unit conversion 2025-12-19 15:09:46 -06:00
TrèsAbhi 23a42230cb feat: units 2025-12-19 15:04:35 -06:00
TrèsAbhi e66daed7ae feat: dpm 2025-12-19 14:51:18 -06:00
TrèsAbhi f2d0f68f07 feat: primary_armor 2025-12-19 14:34:17 -06:00
TrèsAbhi be4af0bf84 feat: implement some 2025-12-18 21:29:10 -06:00
TrèsAbhi 15172e8b33 fix: fetch correct stages 2025-12-18 17:00:06 -06:00
TrèsAbhi c6b7918525 feat: shells 2025-12-18 16:45:02 -06:00
TrèsAbhi 4f1c4421e5 feat: some more 2025-12-18 16:29:13 -06:00
TrèsAbhi 7b830f5a71 feat: start of more attrs 2025-12-18 16:12:01 -06:00
TrèsAbhi 6ce1135835 feat: rename a bit 2025-12-18 15:30:18 -06:00
TrèsAbhi 66eaaef6de feat: implement shell attr 2025-12-18 15:07:04 -06:00
TrèsAbhi 48fbf59036 feat: override common data 2025-12-18 13:20:35 -06:00
TrèsAbhi 0e0f4fbe9f fix: find att0 correctly 2025-12-18 13:16:20 -06:00
TrèsAbhi 6ba6e10108 feat: rename 2025-12-18 13:08:42 -06:00
TrèsAbhi cf8fa4ffb4 feat: remaining stagers 2025-12-18 12:59:12 -06:00
TrèsAbhi 2b0180dce2 Merge branch 'main' into ue 2025-12-18 12:45:10 -06:00
TrèsAbhi caee848a47 Merge branch 'main' into ue 2025-12-15 22:29:11 -06:00
TrèsAbhi d01b7cf707 feat: shells 2025-12-14 22:00:45 -06:00
TrèsAbhi 8921f84c38 feat: verbose 2025-12-14 21:41:26 -06:00
TrèsAbhi 6830df01fa penetration_groups_upgrades 2025-12-14 21:38:18 -06:00
TrèsAbhi 67da59ef41 feat: start of stages 2025-12-13 23:35:38 -06:00
TrèsAbhi 036cc9915d feat: start of atts 2025-12-13 23:10:51 -06:00
TrèsAbhi 57b6ba19f0 feat: rename 2025-12-13 22:15:48 -06:00
TrèsAbhi 32b5593d07 feat: lenient strings 2025-12-13 13:16:42 -06:00
TrèsAbhi 3b757562d2 Merge branch 'main' into ue 2025-12-10 22:52:49 -06:00
TrèsAbhi 4c8c2d0868 feat: auto pick localization entity 2025-12-05 21:35:58 -06:00
TrèsAbhi b2f266401f Merge branch 'main' into ue 2025-12-05 21:23:39 -06:00
TrèsAbhi 5541eca23d feat: start of derived statistics 2025-12-01 16:51:11 -06:00
TrèsAbhi 122d65840e feat: aggregateAttributes 2025-12-01 13:09:55 -06:00
TrèsAbhi ed4b72d85c feat: upgrade stages 2025-11-30 22:26:13 -06:00
TrèsAbhi 4033e8618f feat: useAwait 2025-11-30 22:12:46 -06:00
TrèsAbhi 42cada1811 feat: move and api 2025-11-30 21:06:17 -06:00
TrèsAbhi ff7ed213c8 feat: complete 2025-11-30 21:01:53 -06:00
TrèsAbhi a0367af06b feat: start of stats 2025-11-30 20:54:36 -06:00
TrèsAbhi 58c2965c53 Merge branch 'main' into ue 2025-11-30 20:27:42 -06:00
TrèsAbhi edae41409a feat: tank data 2025-11-29 14:22:32 -06:00
TrèsAbhi 383d3a36ef feat: load tank data 2025-11-28 14:21:26 -06:00
TrèsAbhi 6a958da390 feat: implement strings 2025-11-28 14:13:03 -06:00
TrèsAbhi ef154f99d5 feat: start of scraping 2025-11-28 13:51:17 -06:00
TrèsAbhi 4a20102de3 feat: base work 2025-11-28 13:19:15 -06:00
TrèsAbhi 4e170f2917 feat: port minimal files 2025-11-28 13:03:33 -06:00
TrèsAbhi a70d788f6b feat: init ue website 2025-11-28 13:00:41 -06:00
124 changed files with 3902 additions and 2885 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ concurrency:
jobs:
build:
name: Build bot
name: Build
runs-on: ubuntu-latest
steps:
+66
View File
@@ -0,0 +1,66 @@
name: Website UE
on:
push:
workflow_dispatch:
schedule:
- cron: "0 4 * * *"
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref == 'refs/heads/main' }}
env:
WOTB_SERVER: ${{ secrets.WOTB_SERVER }}
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
token: ${{ secrets.GH_TOKEN }}
- uses: oven-sh/setup-bun@v2
- uses: actions/setup-node@v6
with:
node-version: latest
- uses: arduino/setup-protoc@v3
with:
repo-token: ${{ secrets.GH_TOKEN }}
- uses: actions/configure-pages@v5
- run: bun run setup
- name: Build website
run: bun run build:website
- name: Upload artifact
uses: actions/upload-pages-artifact@v4
with:
path: dist/website
deploy-github-pages:
if: ${{ github.ref == 'refs/heads/ue' && github.repository == 'blitzkit/host-beta' }}
name: Deploy to GitHub Pages
runs-on: ubuntu-latest
needs: build
environment:
name: Production
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+1 -1
View File
@@ -35,7 +35,7 @@ env:
jobs:
build:
name: Build website
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
+1 -1
View File
@@ -22,7 +22,7 @@ depots
public/sitemap*
/firebase.json
target
# packages/core/src/protos/*.ts
packages/website-ue/src/protos/*.ts
/.vercel
.astro
.vercel
+4 -2
View File
@@ -17,8 +17,6 @@
"astrojs",
"astrolib",
"atgm",
"Autoloader",
"Autoreloader",
"AYUV",
"battleresults",
"bbox",
@@ -61,6 +59,7 @@
"Ddpf",
"Ddsd",
"deadrail",
"DEBUFF",
"debugflags",
"deburr",
"decalmask",
@@ -177,6 +176,7 @@
"ratingleaderboard",
"raycaster",
"Redirector",
"REGEN",
"Relogin",
"researchable",
"Resvg",
@@ -191,10 +191,12 @@
"searchtanks",
"SHAREDEXP",
"SKLLD",
"sluggify",
"smoothstep",
"Smri",
"Specularity",
"SSAO",
"stackable",
"startcase",
"statkit",
"statsfull",
+459 -429
View File
File diff suppressed because it is too large. Load diff
-14
View File
@@ -1,14 +0,0 @@
# BlitzKit 1.29.10
Thank you to [Mark Greene](https://github.com/Hitjack007) for your contributions this update.
## Features
- Combined game mode passive and active abilities into a single dropdown
- [Mark Greene] Added tier filters to the Guess game
- Changing tiers will break your streak
## Fixes
- [Mark Greene] module damage is now properly shown when sorting with it in the tank search
- Duplicate abilities in the tank filters are now removed
-5
View File
@@ -1,5 +0,0 @@
# BlitzKit 1.29.11
## Fixes
- The Guesser game's toolbar now scales properly with screen size
-14
View File
@@ -1,14 +0,0 @@
# BlitzKit 1.29.12
## Fixes
- BlitzKit no longer uses BlitzStars for tank averages for some commands
- BlitzKit Performance was created to completely replace BlitzStars but BlitzStars was still used for some older commands
- But since BlitzStars keeps having downtime, it has been completely removed
- Upgraded all dependencies to the latest versions
- The replay command is now properly localized across all languages
- Special Chinese characters are now properly handled
- Commands are now registered synchronously, allowing errors to reveal their exact origins
- Error handling now properly exists the process after logging the error
- The bot now uses Discord's new `clientReady` instead of the ambiguous `ready` event
- Both the armor and model extractors now use the new BlitzKit `SteamVFS`
+8 -9
View File
@@ -1,41 +1,41 @@
{
"name": "blitzkit",
"version": "1.29.12",
"version": "2.0.0-beta.2",
"license": "BlitzKit License",
"private": true,
"scripts": {
"build:assets": "cd packages/scripts && bun run build:assets",
"build:averages": "bun --filter=@blitzkit/scripts run build:averages",
"build:bot": "cd packages/scripts && bun run build:bot",
"build:website": "cd packages/website && bun run build",
"build:website": "cd packages/website-ue && bun run build",
"build:prisma": "prisma generate",
"build:proxyclient": "cd packages/scripts && bun run build:proxyclient",
"build:catalogitemaccesssor": "cd packages/scripts && bun run build:catalogitemaccesssor",
"build:ratingleaderboard": "cd packages/scripts && bun run build:ratingleaderboard",
"build:app": "cd packages/app && bun run build",
"dev:bot": "bun run build:bot --dev && bun start:bot --dev",
"dev:bot": "bun run build:bot --dev && bun start:bot",
"start:bot": "bun dist/bot/main.js",
"dev:docs": "vitepress dev docs",
"dev:website": "cd packages/website && bun run dev",
"dev:website": "cd packages/website-ue && bun run dev",
"dev:app": "cd packages/app && bun run dev",
"dev": "bun run dev:website",
"dev:api": "bun --filter=@blitzkit/api run dev",
"setup:depotdownloader": "bun --filter=@blitzkit/scripts run setup:depotdownloader",
"setup:patches": "bun --filter=@blitzkit/scripts run setup:patches",
"start:website": "bun --filter=@blitzkit/website run start",
"start:website": "bun --filter=@blitzkit/website-ue run start",
"host:docs": "vitepress preview docs",
"lint": "tsc",
"lint:website": "cd packages/website && bun run lint",
"lint:website": "cd packages/website-ue && bun run lint",
"format": "prettier --write \"**/*.@(json|js|jsx|css|md|ts|tsx|html|xml|yml|gltf)\"",
"update": "yarn upgrade --latest",
"tunnel": "cloudflared tunnel --url http://localhost:3000",
"discoverids": "scripts/discoverIds.ts",
"build:protos": "cd packages/scripts && bun run build:protos",
"preview:website": "cd packages/website && bun run preview",
"preview:website": "cd packages/website-ue && bun run preview",
"build:reviews": "cd packages/scripts && bun build:reviews",
"build:ids": "cd packages/scripts && bun build:ids",
"prunestrings": "cd packages/scripts && bun prunestrings",
"setup": "bun install && bun run build:prisma && bun run build:protos && bun run build:proxyclient",
"setup": "bun install && bun run build:prisma && bun run build:protos && bun run build:proxyclient && bun run build:catalogitemaccesssor",
"patchnotes": "cd packages/scripts && bun run patchnotes"
},
"type": "module",
@@ -45,7 +45,6 @@
"dependencies": {
"@prisma/client": "^6.18.0",
"prisma": "^6.18.0",
"sharp": "^0.34.5",
"typescript": "^5.9.3"
}
}
+11 -11
View File
@@ -356,9 +356,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
version = "1.11.1"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
dependencies = [
"serde",
]
@@ -2105,9 +2105,9 @@ checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
[[package]]
name = "num-conv"
version = "0.2.0"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
[[package]]
name = "num-traits"
@@ -3907,30 +3907,30 @@ dependencies = [
[[package]]
name = "time"
version = "0.3.47"
version = "0.3.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d"
dependencies = [
"deranged",
"itoa",
"num-conv",
"powerfmt",
"serde_core",
"serde",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.8"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b"
[[package]]
name = "time-macros"
version = "0.2.27"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"
checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3"
dependencies = [
"num-conv",
"time-core",
+9 -10
View File
@@ -4,26 +4,25 @@
"@blitzkit/core": "workspace:*",
"@blitzkit/i18n": "workspace:*",
"@radix-ui/colors": "^3.0.0",
"@radix-ui/themes": "^3.3.0",
"@radix-ui/themes": "^3.2.1",
"@resvg/resvg-js": "^2.6.2",
"@types/adm-zip": "^0.5.7",
"@types/bun": "^1.3.9",
"@types/lodash-es": "^4.17.12",
"@types/markdown-escape": "^1.1.3",
"@types/react": "^19.2.14",
"@types/react": "^19.2.2",
"adm-zip": "^0.5.16",
"bepaint": "^0.1.0-beta.3",
"discord.js": "^14.25.1",
"dotenv": "^17.3.1",
"discord.js": "^14.22.1",
"dotenv": "^17.2.2",
"fuzzysort": "^3.1.0",
"lodash-es": "^4.17.23",
"lodash-es": "^4.17.21",
"markdown-escape": "^2.0.0",
"pickleparser": "^0.2.1",
"prisma": "^6.19.2",
"prisma": "^6.17.1",
"protobufjs": "^7.5.4",
"react": "^19.2.4",
"satori": "^0.18.4",
"sharp": "^0.34.5"
"react": "^19.2.0",
"satori": "^0.18.3",
"sharp": "^0.34.4"
},
"private": true,
"scripts": {
+4 -4
View File
@@ -1,7 +1,7 @@
import { createLocalizedCommand } from "../core/discord/createLocalizedCommand";
import { translator } from "../core/localization/translator";
import {
commandsArray,
COMMANDS_RAW,
type CommandRegistry,
} from "../events/interactionCreate";
@@ -35,7 +35,7 @@ export const aboutCommand = new Promise<CommandRegistry>(async (resolve) => {
if (subcommand === "commands") {
return `${strings.bot.commands.about.subcommands.commands.body}${(
await Promise.all(commandsArray)
await Promise.all(COMMANDS_RAW)
)
.sort((a, b) =>
(a.command.name_localizations?.[interaction.locale] ??
@@ -43,7 +43,7 @@ export const aboutCommand = new Promise<CommandRegistry>(async (resolve) => {
(b.command.name_localizations?.[interaction.locale] ??
b.command.name)
? -1
: 1,
: 1
)
.map(
(registry) =>
@@ -54,7 +54,7 @@ export const aboutCommand = new Promise<CommandRegistry>(async (resolve) => {
registry.command.description_localizations?.[
interaction.locale
] ?? registry.command.description
}`,
}`
)
.join("\n")}`;
}
+27 -32
View File
@@ -15,16 +15,11 @@ import { CommandWrapper } from "../../components/CommandWrapper";
import { NoData } from "../../components/NoData";
import { TitleBar } from "../../components/TitleBar";
import { filtersToDescription } from "../../core/blitzkit/filtersToDescription";
import {
averageDefinitions,
tankDefinitions,
} from "../../core/blitzkit/nonBlockingPromises";
import { tankDefinitions } from "../../core/blitzkit/nonBlockingPromises";
import { UserError } from "../../core/blitzkit/userError";
import {
filterStats,
type StatFilters,
} from "../../core/blitzstars/filterStats";
import { filterStats, type StatFilters } from "../../core/blitzstars/filterStats";
import { getStatsInPeriod } from "../../core/blitzstars/getStatsInPeriod";
import { blitzStarsTankAverages } from "../../core/blitzstars/tankAverages";
import type { ResolvedPeriod } from "../../core/discord/resolvePeriodFromCommand";
import type { ResolvedPlayer } from "../../core/discord/resolvePlayerFromCommand";
import { translator } from "../../core/localization/translator";
@@ -36,11 +31,11 @@ export async function renderBreakdown(
{ region, id }: ResolvedPlayer,
{ start, end, name }: ResolvedPeriod,
filters: StatFilters,
locale: Locale,
locale: Locale
) {
const { strings, unwrap } = translator(locale);
const awaitedTankDefinitions = await tankDefinitions;
const awaitedTankAverages = await averageDefinitions;
const awaitedTankAverages = await blitzStarsTankAverages;
const statsInPeriod = await getStatsInPeriod(region, id, start, end, locale);
const { filteredOrder } = await filterStats(statsInPeriod, filters);
const accountInfo = await getAccountInfo(region, id);
@@ -58,14 +53,14 @@ export async function renderBreakdown(
}
filteredOrder.forEach((id) => {
const tankAveragesEntry = awaitedTankAverages.averages[id];
const tankAveragesEntry = awaitedTankAverages[id];
const current = statsInPeriod.diff[id];
const career = tankStats.find((tank) => tank.tank_id === id)!.all;
const currentWN8 = tankAveragesEntry
? calculateWN8(tankAveragesEntry.mu, current)
? calculateWN8(tankAveragesEntry.all, current)
: undefined;
const careerWN8 = tankAveragesEntry
? calculateWN8(tankAveragesEntry.mu, career)
? calculateWN8(tankAveragesEntry.all, career)
: undefined;
orderedCurrentStats.push(current);
@@ -74,65 +69,65 @@ export async function renderBreakdown(
orderedCareerWN8.push(careerWN8);
});
tankStats.forEach((tank) => {
const tankAveragesEntry = awaitedTankAverages.averages[tank.tank_id];
const tankAveragesEntry = awaitedTankAverages[tank.tank_id];
orderedCareerWN8Full.push(
tankAveragesEntry
? calculateWN8(tankAveragesEntry.mu, tank.all)
: undefined,
? calculateWN8(tankAveragesEntry.all, tank.all)
: undefined
);
});
const currentBattles = orderedCurrentStats.reduce(
(accumulator, current) => accumulator + current.battles,
0,
0
);
const careerBattles = tankStats.reduce(
(accumulator, current) => accumulator + current.all.battles,
0,
0
);
const currentWinrate =
orderedCurrentStats.reduce(
(accumulator, current) => accumulator + current.wins,
0,
0
) / currentBattles;
const careerWinrate =
tankStats.reduce(
(accumulator, current) => accumulator + current.all.wins,
0,
0
) / careerBattles;
const currentWN8 =
orderedCurrentWN8.reduce<number>(
(accumulator, current, index) =>
accumulator + (current ?? 0) * orderedCurrentStats[index].battles,
0,
0
) /
orderedCurrentStats.reduce(
(accumulator, current, index) =>
accumulator +
(orderedCurrentWN8[index] === undefined ? 0 : current.battles),
0,
0
);
const careerWN8 =
orderedCareerWN8Full.reduce<number>(
(accumulator, current) => accumulator + (current ?? 0),
0,
0
) /
tankStats.reduce(
(accumulator, current, index) =>
accumulator +
(orderedCareerWN8Full[index] === undefined ? 0 : current.all.battles),
0,
0
);
const currentDamage =
orderedCurrentStats.reduce(
(accumulator, current) => accumulator + current.damage_dealt,
0,
0
) / currentBattles;
const careerDamage =
tankStats.reduce(
(accumulator, current) => accumulator + current.all.damage_dealt,
0,
0
) / careerBattles;
const children: React.JSX.Element[] = [];
@@ -177,7 +172,7 @@ export async function renderBreakdown(
delta: currentDamage - careerDamage,
},
]}
/>,
/>
);
filteredOrder.forEach((id, index) => {
@@ -211,7 +206,7 @@ export async function renderBreakdown(
{
title: strings.bot.commands.breakdown.body.winrate,
current: `${(100 * (current.wins / current.battles)).toFixed(
2,
2
)}%`,
career: `${(100 * (career.wins / career.battles)).toFixed(2)}%`,
delta:
@@ -235,24 +230,24 @@ export async function renderBreakdown(
{
title: strings.bot.commands.breakdown.body.damage,
current: Math.round(
current.damage_dealt / current.battles,
current.damage_dealt / current.battles
).toLocaleString(),
career: Math.round(
career.damage_dealt / career.battles,
career.damage_dealt / career.battles
).toLocaleString(),
delta:
current.damage_dealt / current.battles -
career.damage_dealt / career.battles,
},
]}
/>,
/>
);
});
}
const pages = chunk(
children,
Math.max(Math.ceil(children.length / MAX_PAGES), ROWS_PER_PAGE),
Math.max(Math.ceil(children.length / MAX_PAGES), ROWS_PER_PAGE)
);
if (filteredOrder.length > 0) {
+77 -92
View File
@@ -5,29 +5,28 @@ import {
idToRegion,
tankIcon,
TIER_ROMAN_NUMERALS,
} from "@blitzkit/core";
import { Locale } from "discord.js";
import { clamp } from "lodash-es";
import { CommandWrapper } from "../components/CommandWrapper";
import { TitleBar } from "../components/TitleBar";
import { iconPng } from "../core/blitzkit/iconPng";
} from '@blitzkit/core';
import { Locale } from 'discord.js';
import { clamp } from 'lodash-es';
import { CommandWrapper } from '../components/CommandWrapper';
import { TitleBar } from '../components/TitleBar';
import { iconPng } from '../core/blitzkit/iconPng';
import {
averageDefinitions,
mapDefinitions,
tankDefinitions,
} from "../core/blitzkit/nonBlockingPromises";
import { RenderConfiguration } from "../core/blitzkit/renderConfiguration";
import { buttonLink } from "../core/discord/buttonLink";
import { createLocalizedCommand } from "../core/discord/createLocalizedCommand";
import { localizationObject } from "../core/discord/localizationObject";
import { translator } from "../core/localization/translator";
import { type CommandRegistry } from "../events/interactionCreate";
import { theme } from "../stitches.config";
} from '../core/blitzkit/nonBlockingPromises';
import { RenderConfiguration } from '../core/blitzkit/renderConfiguration';
import { blitzStarsTankAverages } from '../core/blitzstars/tankAverages';
import { buttonLink } from '../core/discord/buttonLink';
import { createLocalizedCommand } from '../core/discord/createLocalizedCommand';
import { translator } from '../core/localization/translator';
import { type CommandRegistry } from '../events/interactionCreate';
import { theme } from '../stitches.config';
type WotInspectorReplaySubmission =
| { status: "error"; data: unknown; error: { message: string } }
| { status: 'error'; data: unknown; error: { message: string } }
| {
status: "ok";
status: 'ok';
data: {
download_url: string;
view_url: string;
@@ -210,9 +209,9 @@ function stat(value: string | number, flex = 2) {
<div
style={{
flex,
display: "flex",
alignItems: "center",
justifyContent: "center",
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<span style={{ fontSize: 16 }}>{value}</span>
@@ -228,15 +227,15 @@ async function playerListing(
recordingPlayer = false,
) {
const { unwrap } = translator(locale);
const awaitedTankAverages = await averageDefinitions;
const awaitedTankAverages = await blitzStarsTankAverages;
const awaitedTankDefinitions = await tankDefinitions;
const tank = awaitedTankDefinitions.tanks[player.vehicle_descr];
const blockAccent = recordingPlayer ? "_amber" : "";
const blockAccent = recordingPlayer ? '_amber' : '';
const healthAccent = protagonistTeam
? recordingPlayer
? "_amber"
: "_green"
: "_red";
? '_amber'
: '_green'
: '_red';
// our turret ids are always off by 1 or 2 lol so imma just grab the closest
// TODO: 💀
@@ -246,11 +245,11 @@ async function playerListing(
)[0];
const totalHealth = turret.health + tank.health;
const healthLeft = clamp(player.hitpoints_left / totalHealth, 0, 1);
const tankAveragesEntry = awaitedTankAverages.averages[player.vehicle_descr];
const tankAveragesEntry = awaitedTankAverages[player.vehicle_descr];
const wn8 =
tankAveragesEntry === undefined
? -1
: calculateWN8(tankAveragesEntry.mu, {
: calculateWN8(tankAveragesEntry.all, {
battles: 1,
damage_dealt: player.damage_made,
dropped_capture_points: player.base_defend_points,
@@ -263,8 +262,8 @@ async function playerListing(
<div
key={player.entity_id}
style={{
display: "flex",
alignItems: "center",
display: 'flex',
alignItems: 'center',
gap: 8,
backgroundColor: theme.colors[`appBackground2${blockAccent}`],
padding: 8,
@@ -272,11 +271,11 @@ async function playerListing(
>
<div
style={{
display: "flex",
display: 'flex',
gap: 8,
flex: 1,
overflow: "hidden",
alignItems: "center",
overflow: 'hidden',
alignItems: 'center',
}}
>
<img
@@ -285,22 +284,22 @@ async function playerListing(
style={{
width: 32,
height: 32,
objectFit: "contain",
objectFit: 'contain',
}}
/>
<div
style={{
display: "flex",
flexDirection: "column",
display: 'flex',
flexDirection: 'column',
// align
}}
>
<div
style={{
display: "flex",
display: 'flex',
gap: 4,
alignItems: "center",
alignItems: 'center',
}}
>
<span
@@ -325,23 +324,23 @@ async function playerListing(
style={{
fontSize: 16,
color: theme.colors[`textLowContrast${blockAccent}`],
whiteSpace: "nowrap",
whiteSpace: 'nowrap',
}}
>
{player.name}
{player.clan_tag ? ` [${player.clan_tag}]` : ""}
{player.clan_tag ? ` [${player.clan_tag}]` : ''}
</span>
</div>
</div>
<div
style={{
display: "flex",
display: 'flex',
flex: 1,
}}
>
{stat(player.damage_made.toLocaleString())}
{stat(wn8 === -1 ? "--" : Math.round(wn8).toLocaleString())}
{stat(wn8 === -1 ? '--' : Math.round(wn8).toLocaleString())}
{stat(player.exp.toLocaleString())}
{stat(player.enemies_destroyed, 1)}
</div>
@@ -350,15 +349,15 @@ async function playerListing(
style={{
borderRadius: 2,
backgroundColor: theme.colors[`componentInteractive${healthAccent}`],
display: "flex",
display: 'flex',
width: 4,
height: "100%",
transform: "scaleY(-1)",
height: '100%',
transform: 'scaleY(-1)',
}}
>
<div
style={{
width: "100%",
width: '100%',
height: `${healthLeft * 100}%`,
borderRadius: 2,
backgroundColor: theme.colors[`solidBackground${healthAccent}`],
@@ -374,8 +373,8 @@ function Header() {
<div
style={{
padding: 8,
display: "flex",
alignItems: "center",
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
@@ -383,16 +382,16 @@ function Header() {
<div
style={{
display: "flex",
display: 'flex',
flex: 1,
}}
>
<div
style={{
flex: 2,
display: "flex",
alignItems: "center",
justifyContent: "center",
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<span
@@ -407,9 +406,9 @@ function Header() {
<div
style={{
flex: 2,
display: "flex",
alignItems: "center",
justifyContent: "center",
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<span
@@ -424,9 +423,9 @@ function Header() {
<div
style={{
flex: 2,
display: "flex",
alignItems: "center",
justifyContent: "center",
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<span
@@ -441,9 +440,9 @@ function Header() {
<div
style={{
flex: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<span
@@ -461,42 +460,28 @@ function Header() {
}
export const replayCommand = new Promise<CommandRegistry>((resolve) => {
const { strings } = translator(Locale.EnglishUS);
resolve({
command: createLocalizedCommand("replay").addAttachmentOption((option) =>
option
.setName(strings.bot.commands.replay.options.file.name)
.setNameLocalizations(
localizationObject(
(strings) => strings.bot.commands.replay.options.file.name,
undefined,
true,
),
)
.setDescription(strings.bot.commands.replay.options.file.description)
.setDescriptionLocalizations(
localizationObject(
(strings) => strings.bot.commands.replay.options.file.description,
),
)
.setRequired(true),
command: createLocalizedCommand('replay').addAttachmentOption((option) =>
option.setName('file').setDescription('Replay file').setRequired(true),
),
async handler(interaction) {
const awaitedMapDefinitions = await mapDefinitions;
const file = interaction.options.getAttachment("file")!;
const file = interaction.options.getAttachment('file')!;
// const file = {
// url: 'https://cdn.discordapp.com/ephemeral-attachments/1232434891652861972/1232781496016834581/20240328_1530__TresAbhi_M60_1157057448155406708.wotbreplay?ex=662ab4bc&is=6629633c&hm=c784cd10e80232350ddaf291fa987b879c4d0a8083b78298c9eee4fa0d507f6c&',
// };
const submissionData = (await fetch(
`https://wotinspector.com/api/replay/upload/?url=${encodeURIComponent(
file.url,
)}`,
).then((response) => response.json())) as WotInspectorReplaySubmission;
if (submissionData.status === "error") {
if (submissionData.status === 'error') {
return `# Uh oh! WoT Inspector didn't like that.\n\nThere was an error processing your replay. Get help on [the official Discord server](https://discord.gg/nDt7AjGJQH).`;
}
const replayId = submissionData.data.download_url.split("/").at(-1)!;
const replayId = submissionData.data.download_url.split('/').at(-1)!;
const replayData = (await fetch(
`https://api.wotinspector.com/v2/blitz/replays/${replayId}/`,
).then((response) => response.json())) as WotInspectorReplay;
@@ -508,7 +493,7 @@ export const replayCommand = new Promise<CommandRegistry>((resolve) => {
await getClanAccountInfo(
idToRegion(replayData.protagonist),
replayData.protagonist,
["clan"],
['clan'],
)
)?.clan;
const clanImage = clan ? emblemURL(clan.emblem_set_id) : undefined;
@@ -521,22 +506,22 @@ export const replayCommand = new Promise<CommandRegistry>((resolve) => {
image={clanImage}
description={`${
replayData.protagonist_team === replayData.winner_team
? "Victory"
: "Defeat"
? 'Victory'
: 'Defeat'
} • ${awaitedMapDefinitions.maps[replayData.map_id].name}`}
/>
<div
style={{
display: "flex",
display: 'flex',
gap: 8,
}}
>
<div
style={{
flex: 1,
display: "flex",
flexDirection: "column",
display: 'flex',
flexDirection: 'column',
gap: 4,
}}
>
@@ -562,8 +547,8 @@ export const replayCommand = new Promise<CommandRegistry>((resolve) => {
<div
style={{
flex: 1,
display: "flex",
flexDirection: "column",
display: 'flex',
flexDirection: 'column',
gap: 4,
}}
>
@@ -584,8 +569,8 @@ export const replayCommand = new Promise<CommandRegistry>((resolve) => {
</div>
</div>
</CommandWrapper>,
buttonLink(submissionData.data.view_url, "WoT Inspector"),
buttonLink(submissionData.data.download_url, "Download"),
buttonLink(submissionData.data.view_url, 'WoT Inspector'),
buttonLink(submissionData.data.download_url, 'Download'),
];
},
});
@@ -1,13 +1,11 @@
import {
fetchAverageDefinitions,
fetchDiscoveredIdsDefinitions,
fetchGameDefinitions,
fetchMapDefinitions,
fetchTankDefinitions,
fetchTankNames,
} from "@blitzkit/core";
} from '@blitzkit/core';
export const averageDefinitions = fetchAverageDefinitions();
export const tankDefinitions = fetchTankDefinitions();
export const gameDefinitions = fetchGameDefinitions();
export const tankNames = fetchTankNames();
+18 -26
View File
@@ -1,37 +1,29 @@
import { usersDatabase } from "../db/users";
import { client } from "../discord/client";
import { usersDatabase } from '../db/users';
import { client } from '../discord/client';
const EXIT_EVENTS = ["SIGINT", "SIGTERM", "SIGUSR1", "SIGUSR2"];
const EXIT_EVENTS = [
'beforeExit',
'exit',
'SIGINT',
'SIGTERM',
'SIGUSR1',
'SIGUSR2',
];
let cleaningUp = false;
async function cleanup() {
console.log('Cleaning up...');
async function cleanup(signal: string) {
if (cleaningUp) return;
cleaningUp = true;
await Promise.all([usersDatabase.$disconnect(), client.destroy()]);
console.log(`Cleaning up... (${signal})`);
try {
await Promise.all([usersDatabase.$disconnect(), client.destroy()]);
} catch (err) {
console.error("Cleanup error:", err);
}
console.log("Gracefully exiting...");
console.log('Gracefully exiting...');
EXIT_EVENTS.forEach((event) => process.off(event, cleanup));
process.exit(0);
}
export function registerProcesses() {
process.on("uncaughtException", (err) => {
console.error("uncaughtException:", err);
});
process.on('uncaughtException', console.error);
client.on('error', console.error);
process.on("unhandledRejection", (err) => {
console.error("unhandledRejection:", err);
});
client.on("error", console.error);
EXIT_EVENTS.forEach((event) => process.on(event, () => cleanup(event)));
EXIT_EVENTS.forEach((event) => process.on(event, cleanup));
}
+11 -15
View File
@@ -3,10 +3,8 @@ import type { SupplementaryStats } from "@blitzkit/core/src/blitz/getAccountInfo
import { calculateWN8 } from "@blitzkit/core/src/statistics/calculateWN8";
import type { BlitzStats } from "@blitzkit/core/src/statistics/compositeStats";
import { sumAllStats } from "@blitzkit/core/src/statistics/sumAllStats";
import {
averageDefinitions,
tankDefinitions,
} from "../blitzkit/nonBlockingPromises";
import { tankDefinitions } from "../blitzkit/nonBlockingPromises";
import { blitzStarsTankAverages } from "./tankAverages";
export interface StatFilters {
nation?: string;
@@ -18,13 +16,13 @@ export interface StatFilters {
export async function filterStats(
{ diff, order }: DiffedTankStats,
filters: StatFilters,
filters: StatFilters
) {
// tank, if provided, takes priority over all other filters
if (filters.tank) filters = { tank: filters.tank };
const awaitedTankDefinitions = await tankDefinitions;
const awaitedTankAverages = await averageDefinitions;
const awaitedTankAverages = await blitzStarsTankAverages;
const filteredOrder = order.filter((id) => {
const entry = awaitedTankDefinitions.tanks[id];
@@ -46,28 +44,26 @@ export async function filterStats(
const stats = sumAllStats(filteredOrder.map((id) => diff[id]));
const battlesOfTanksWithAverages = filteredOrder.reduce<number>(
(accumulator, id) =>
awaitedTankAverages.averages[id]
? accumulator + diff[id].battles
: accumulator,
0,
awaitedTankAverages[id] ? accumulator + diff[id].battles : accumulator,
0
);
const battlesOfTanksWithTankDefinition = filteredOrder.reduce<number>(
(accumulator, id) =>
awaitedTankDefinitions.tanks[id]
? accumulator + diff[id].battles
: accumulator,
0,
0
);
const supplementary = {
WN8:
filteredOrder.reduce<number>(
(accumulator, id) =>
awaitedTankAverages.averages[id]
awaitedTankAverages[id]
? accumulator +
calculateWN8(awaitedTankAverages.averages[id].mu, diff[id]) *
calculateWN8(awaitedTankAverages[id].all, diff[id]) *
diff[id].battles
: accumulator,
0,
0
) / battlesOfTanksWithAverages,
tier:
filteredOrder.reduce<number>(
@@ -76,7 +72,7 @@ export async function filterStats(
? accumulator +
awaitedTankDefinitions.tanks[id]!.tier * diff[id].battles
: accumulator,
0,
0
) / battlesOfTanksWithTankDefinition,
} satisfies SupplementaryStats;
@@ -0,0 +1,101 @@
import { BlitzStats } from '@blitzkit/core';
import { context } from '@blitzkit/core/src/blitzkit/context';
interface SpecialStats {
winrate: number;
damageRatio: number;
kdr: number;
damagePerBattle: number;
killsPerBattle: number;
hitsPerBattle: number;
spotsPerBattle: number;
wpm: number;
dpm: number;
kpm: number;
hitRate: number;
survivalRate: number;
}
export type Percentiles = [
number,
number,
number,
number,
number,
number,
number,
number,
number,
];
export interface SpecialPercentiles {
winRate: Percentiles;
damageRatio: Percentiles;
kdr: Percentiles;
damagePerBattle: Percentiles;
killsPerBattle: Percentiles;
hitsPerBattle: Percentiles;
spotsPerBattle: Percentiles;
wpm: Percentiles;
dpm: Percentiles;
kpm: Percentiles;
hitRate: Percentiles;
survivalRate: Percentiles;
}
export interface MeanSd {
winrateMean: number;
winrateSd: number;
hitRateMean: number;
hitRateSd: number;
survivalRateMean: number;
survivalRateSd: number;
damageRatioMean: number;
damageRatioSd: number;
kdrMean: number;
kdrSd: number;
dpbMean: number;
dpbSd: number;
kpbMean: number;
kpbSd: number;
hpbMean: number;
hpbSd: number;
spbMean: number;
spbSd: number;
}
export interface IndividualTankAverage {
_id: number;
battle_life_time: number;
total_battle_life_time: number;
number_of_players: number;
tank_id: number;
all: BlitzStats;
special: SpecialStats;
percentiles: SpecialPercentiles;
percentiles_player_count: number;
meanSd: MeanSd;
shotEff: number;
last_update: number;
}
export type BlitzStarsTankAverages = Record<number, IndividualTankAverage>;
export const blitzStarsTankAverages = fetch(
'https://www.blitzstars.com/api/tankaverages.json',
)
.then((response) => response.json())
.then((json) => {
if (context === 'server') {
const partialTankAverages: BlitzStarsTankAverages = {};
(json as IndividualTankAverage[]).forEach((individualTankAverage) => {
partialTankAverages[individualTankAverage.tank_id] =
individualTankAverage;
});
return partialTankAverages;
} else {
return json as BlitzStarsTankAverages;
}
});
+5 -5
View File
@@ -1,9 +1,9 @@
import { Client, GatewayIntentBits } from "discord.js";
import { interactionCreate } from "../../events/interactionCreate";
import { ready } from "../../events/ready";
import { Client, GatewayIntentBits } from 'discord.js';
import { interactionCreate } from '../../events/interactionCreate';
import { ready } from '../../events/ready';
export const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
})
.on("clientReady", ready)
.on("interactionCreate", interactionCreate);
.on('ready', ready)
.on('interactionCreate', interactionCreate);
@@ -22,11 +22,11 @@ export function createLocalizedCommand(
command: string,
sub?:
| CreateLocalizedCommandSubcommand[]
| CreateLocalizedCommandSubcommandGroup[],
| CreateLocalizedCommandSubcommandGroup[]
) {
const commandPathItem = command.replaceAll(
"-",
"_",
"_"
) as keyof BlitzKitStrings["bot"]["commands"];
const { strings } = translator(Locale.EnglishUS);
const slashCommand = new SlashCommandBuilder()
@@ -35,14 +35,14 @@ export function createLocalizedCommand(
localizationObject(
(strings) => strings.bot.commands[commandPathItem].name,
undefined,
true,
),
true
)
)
.setDescription(strings.bot.commands[commandPathItem].description)
.setDescriptionLocalizations(
localizationObject(
(strings) => strings.bot.commands[commandPathItem].description,
),
(strings) => strings.bot.commands[commandPathItem].description
)
);
if (sub) {
@@ -56,7 +56,7 @@ export function createLocalizedCommand(
}
).subcommands[subItem.subcommand].name,
undefined,
true,
true
);
const subcommandDescriptionLocalizations = localizationObject(
(strings) =>
@@ -64,7 +64,7 @@ export function createLocalizedCommand(
strings.bot.commands[commandPathItem] as unknown as {
subcommands: Record<string, { description: string }>;
}
).subcommands[subItem.subcommand].description,
).subcommands[subItem.subcommand].description
);
slashCommand.addSubcommand((option) => {
@@ -78,7 +78,7 @@ export function createLocalizedCommand(
strings.bot.commands[commandPathItem] as unknown as {
subcommands: Record<string, { description: string }>;
}
).subcommands[subItem.subcommand].description,
).subcommands[subItem.subcommand].description
)
.setDescriptionLocalizations(subcommandDescriptionLocalizations);
});
@@ -91,7 +91,7 @@ export function createLocalizedCommand(
}
).groups[subItem.group].name,
undefined,
true,
true
);
const subcommandDescriptionLocalizations = localizationObject(
(strings) =>
@@ -99,7 +99,7 @@ export function createLocalizedCommand(
strings.bot.commands[commandPathItem] as unknown as {
groups: Record<string, { description: string }>;
}
).groups[subItem.group].description,
).groups[subItem.group].description
);
slashCommand.addSubcommandGroup((option) => {
@@ -113,7 +113,7 @@ export function createLocalizedCommand(
strings.bot.commands[commandPathItem] as unknown as {
groups: Record<string, { description: string }>;
}
).groups[subItem.group].description,
).groups[subItem.group].description
)
.setDescriptionLocalizations(subcommandDescriptionLocalizations);
});
@@ -1,10 +1,10 @@
import { AutocompleteInteraction, CacheType } from "discord.js";
import { commands } from "..";
import { AutocompleteInteraction, CacheType } from 'discord.js';
import { commands } from '..';
export async function handleAutocomplete(
interaction: AutocompleteInteraction<CacheType>,
) {
const command = commands[interaction.commandName];
const command = (await commands)[interaction.commandName];
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
@@ -1,13 +1,13 @@
import { ButtonInteraction, CacheType } from "discord.js";
import { commands } from "..";
import { normalizeInteractionReturnable } from "../../../core/discord/normalizeInteractionReturnable";
import { ButtonInteraction, CacheType } from 'discord.js';
import { commands } from '..';
import { normalizeInteractionReturnable } from '../../../core/discord/normalizeInteractionReturnable';
export async function handleButton(interaction: ButtonInteraction<CacheType>) {
await interaction.deferUpdate();
const url = new URL(`https://example.com/${interaction.customId}`);
const commandName = url.pathname.split("/")[1];
const button = commands[commandName]?.button;
const commandName = url.pathname.split('/')[1];
const button = (await commands)[commandName]?.button;
if (!button) {
throw new Error(`Button handler not found for "${commandName}"`);
@@ -16,7 +16,7 @@ export async function handleButton(interaction: ButtonInteraction<CacheType>) {
if (interaction.message.interaction?.user.id !== interaction.user.id) {
interaction.followUp({
ephemeral: true,
content: "You are not the author of this command.",
content: 'You are not the author of this command.',
});
return;
}
@@ -17,11 +17,12 @@ import { translator } from "../../../core/localization/translator";
import type { Writeable } from "../../../types/writable";
export async function handleChatInputCommand(
interaction: ChatInputCommandInteraction<CacheType>,
interaction: ChatInputCommandInteraction<CacheType>
) {
await interaction.deferReply();
const registry = commands[interaction.commandName];
const awaitedCommands = await commands;
const registry = awaitedCommands[interaction.commandName];
try {
const returnable = await registry.handler(interaction);
@@ -35,7 +36,7 @@ export async function handleChatInputCommand(
if (typeof object === "string") {
chunks.push([object]);
} else chunks.at(-1)?.push(object!);
},
}
);
let index = 0;
@@ -58,7 +59,7 @@ export async function handleChatInputCommand(
} else if (psa.data.type === "image") {
if (!reply.files) reply.files = [];
(reply.files as Writeable<typeof reply.files>).push(
new AttachmentBuilder(psa.data.image),
new AttachmentBuilder(psa.data.image)
);
reply.content = reply.content ?? psa.data.title;
}
@@ -71,7 +72,7 @@ export async function handleChatInputCommand(
(
reply.components[0] as ActionRowBuilder<ButtonBuilder>
).addComponents(
psa.data.links.map(({ title, url }) => buttonLink(url, title)),
psa.data.links.map(({ title, url }) => buttonLink(url, title))
);
}
}
@@ -102,7 +103,7 @@ export async function handleChatInputCommand(
} else if (psa.data.type === "image") {
if (!followUp.files) followUp.files = [];
(followUp.files as Writeable<typeof followUp.files>).push(
new AttachmentBuilder(psa.data.image),
new AttachmentBuilder(psa.data.image)
);
followUp.content = followUp.content ?? psa.data.title;
}
@@ -115,7 +116,7 @@ export async function handleChatInputCommand(
(
followUp.components[0] as ActionRowBuilder<ButtonBuilder>
).addComponents(
psa.data.links.map(({ title, url }) => buttonLink(url, title)),
psa.data.links.map(({ title, url }) => buttonLink(url, title))
);
}
@@ -132,7 +133,7 @@ export async function handleChatInputCommand(
new ButtonBuilder()
.setLabel(strings.bot.common.errors.get_help)
.setURL("https://discord.gg/nDt7AjGJQH")
.setStyle(ButtonStyle.Link),
.setStyle(ButtonStyle.Link)
),
];
if (error instanceof UserError) {
@@ -72,13 +72,13 @@ interface CommandRegistryImplicit extends CommandRegistryBase {
interface CommandRegistryExplicit extends CommandRegistryBase {
handlesInteraction?: false;
handler: (
interaction: ChatInputCommandInteraction<CacheType>,
interaction: ChatInputCommandInteraction<CacheType>
) => InteractionReturnable;
}
export type CommandRegistry = CommandRegistryImplicit | CommandRegistryExplicit;
export const commandsArray: Promise<CommandRegistry>[] = [
export const COMMANDS_RAW: Promise<CommandRegistry>[] = [
// auctionCommand,
permissionsCommand,
debugCommand,
@@ -101,28 +101,34 @@ export const commandsArray: Promise<CommandRegistry>[] = [
replayCommand,
];
export const commands: Record<string, CommandRegistry> = {};
const commandsFulfilled: CommandRegistry[] = [];
let index = 0;
for (const registry of await Promise.allSettled(commandsArray)) {
if (registry.status === "rejected") {
console.warn(`Command ${index} rejected`, registry.reason);
continue;
}
commandsFulfilled.push(registry.value);
commands[registry.value.command.name] = registry.value;
index++;
}
export const commands = Promise.allSettled(COMMANDS_RAW).then((rawCommands) => {
return rawCommands.reduce<Record<string, CommandRegistry>>(
(commands, registry, index) => {
if (registry.status === "rejected") {
console.warn(
`Command ${index} failed to load; skipping...`,
registry.reason
);
return commands;
}
return { ...commands, [registry.value.command.name]: registry.value };
},
{}
);
});
const rest = new REST().setToken(assertSecret(import.meta.env.DISCORD_TOKEN));
const body = commandsFulfilled.map((registry) => registry.command.toJSON());
const applicationCommandsRoute = Routes.applicationCommands(
assertSecret(import.meta.env.DISCORD_CLIENT_ID),
);
await rest.put(applicationCommandsRoute, { body });
commands.then((awaitedCommands) => {
const body = Object.values(awaitedCommands).map((registry) =>
registry.command.toJSON()
);
rest.put(
Routes.applicationCommands(assertSecret(import.meta.env.DISCORD_CLIENT_ID)),
{ body }
);
});
export async function interactionCreate(interaction: Interaction<CacheType>) {
if (interaction.isAutocomplete()) {
+9 -9
View File
@@ -1,9 +1,9 @@
import { assertSecret } from "@blitzkit/core";
import { ActivityType, ShardingManager } from "discord.js";
import { assertSecret } from '@blitzkit/core';
import { ActivityType, ShardingManager } from 'discord.js';
import {
discoveredIdsDefinitions,
tankDefinitions,
} from "./core/blitzkit/nonBlockingPromises";
} from './core/blitzkit/nonBlockingPromises';
let iteration = 0;
const interval = setInterval(async () => {
@@ -11,15 +11,15 @@ const interval = setInterval(async () => {
console.log(`Attempting launch on iteration ${iteration}`);
const manager = new ShardingManager("dist/bot/workers/bot.js", {
const manager = new ShardingManager('dist/bot/workers/bot.js', {
token: assertSecret(import.meta.env.DISCORD_TOKEN),
});
const shards = await manager
.on("shardCreate", (shard) => {
.on('shardCreate', (shard) => {
clearInterval(interval);
console.log(`🟡 Launching shard ${shard.id}`);
shard.on("ready", () => console.log(`🟢 Launched shard ${shard.id}`));
shard.on('ready', () => console.log(`🟢 Launched shard ${shard.id}`));
})
.spawn();
@@ -29,7 +29,7 @@ const interval = setInterval(async () => {
let users = 0;
for (const [, shard] of shards) {
const guilds = (await shard.fetchClientValue("guilds.cache")) as any;
const guilds = (await shard.fetchClientValue('guilds.cache')) as any;
servers += guilds.length;
@@ -66,7 +66,7 @@ const interval = setInterval(async () => {
for (const guild of client.guilds.cache.values()) {
try {
const botMember = await guild.members.fetch(client.user.id);
await botMember.setNickname("BlitzKit");
await botMember.setNickname('BlitzKit');
} catch {}
}
},
@@ -74,7 +74,7 @@ const interval = setInterval(async () => {
);
} catch (error) {
console.warn(
"An error occurred when setting up presence, ignoring to keep the process alive",
'An error occurred when setting up presence, ignoring to keep the process alive',
error,
);
}
+3 -3
View File
@@ -1,6 +1,6 @@
import { assertSecret } from "@blitzkit/core";
import { registerProcesses } from "../core/blitzkit/processes";
import { client } from "../core/discord/client";
import { assertSecret } from '@blitzkit/core';
import { registerProcesses } from '../core/blitzkit/processes';
import { client } from '../core/discord/client';
console.log(`🟡 Launching bot ${client.shard?.ids[0]}`);
+42 -41
View File
@@ -1,49 +1,50 @@
export * from './assertSecret';
export * from './asset';
export * from './availableProvisions';
export * from './averageDefinitions';
export * from "./assertSecret";
export * from "./asset";
export * from "./availableProvisions";
export * from "./averageDefinitions";
// export * from './camouflageDefinitions';
// export * from './checkConsumableProvisionInclusivity';
export * from './coefficient';
export * from './consumableDefinitions';
export * from "./coefficient";
export * from "./consumableDefinitions";
// export * from './context';
export * from './createDefaultSkills';
export * from './degressiveStat';
export * from './discoveredIdDefinitions';
export * from './emblemURL';
export * from './equipmentDefinitions';
export * from './eventManager';
export * from './gameDefinitions';
export * from './getArchivedLatestSeasonNumber';
export * from "./createDefaultSkills";
export * from "./degressiveStat";
export * from "./discoveredIdDefinitions";
export * from "./emblemURL";
export * from "./equipmentDefinitions";
export * from "./eventManager";
export * from "./gameDefinitions";
export * from "./getArchivedLatestSeasonNumber";
// export * from './getArchivedRatingInfo';
export * from './getArchivedRatingLeaderboard';
export * from "./getArchivedRatingLeaderboard";
// export * from './getArchivedRatingMidnightLeaderboard';
export * from './getTimeDaysAgo';
export * from './isExplosive';
export * from './mapDefinitions';
export * from './modelDefinitions';
export * from './normalizeBoundingBox';
export * from "./getTimeDaysAgo";
export * from "./isExplosive";
export * from "./mapDefinitions";
export * from "./modelDefinitions";
export * from "./normalizeBoundingBox";
// export * from './parseBkni';
// export * from './patientFetch';
export * from './patientFetchJSON';
export * from './progressiveStat';
export * from './provisionDefinitions';
export * from './resolveDpm';
export * from './resolvePenetrationCoefficient';
export * from './reviews';
export * from './skillDefinitions';
export * from './sum';
export * from './tankDefinitions';
export * from './tankIcon';
export * from './tankNames';
export * from './unionBoundingBox';
export * from './uniqueGuns';
export * from './unwrapBlitzkitResponse';
export * from './votes';
export * from "./patientFetchJSON";
export * from "./progressiveStat";
export * from "./provisionDefinitions";
export * from "./resolveDpm";
export * from "./resolvePenetrationCoefficient";
export * from "./reviews";
export * from "./skillDefinitions";
export * from "./sum";
export * from "./tankDefinitions";
export * from "./tankIcon";
export * from "./tankNames";
export * from "./unionBoundingBox";
export * from "./uniqueGuns";
export * from "./unwrapBlitzkitResponse";
export * from "./votes";
// export * from './withCORSProxy';
export * from './createDefaultProvisions';
export * from './gallery';
export * from './metaSortTank';
export * from './popularTanks';
export * from './romanize';
export * from './youtubers';
export * from "./createDefaultProvisions";
export * from "./gallery";
export * from "./metaSortTank";
export * from "./popularTanks";
export * from "./romanize";
export * from "./sluggify.ts";
export * from "./youtubers";
+16
View File
@@ -0,0 +1,16 @@
import { deburr } from "lodash-es";
const nonAlphanumericRegex = /[^a-z0-9]/g;
const multipleDashesRegex = /--+/g;
const trailingDashRegex = /-$/g;
const leadingDashRegex = /^-/g;
export function sluggify(value: string) {
let slug = deburr(value).toLowerCase();
slug = slug.replaceAll(nonAlphanumericRegex, "-");
slug = slug.replaceAll(multipleDashesRegex, "-");
slug = slug.replaceAll(trailingDashRegex, "");
slug = slug.replaceAll(leadingDashRegex, "");
return slug;
}
+1
View File
@@ -3,6 +3,7 @@ export * from "./fisherYates";
export * from "./formatCompact";
export * from "./isNumber";
export * from "./NaNFallback";
export * from "./normalizeAngleDeg";
export * from "./normalizeAngleRad";
export * from "./normalToEuler";
export * from "./numberToRomanNumeral";
@@ -0,0 +1,6 @@
export function normalizeAngleDeg(angle: number) {
const newAngle = angle % 360;
if (newAngle > 360) return newAngle - 360;
if (newAngle < -360) return newAngle + 360;
return newAngle;
}
+1 -1
View File
@@ -35,7 +35,7 @@ for (const locale in stringsRaw) {
const localeStrings = stringsRaw[locale];
STRINGS[locale] = merge(
stringsRaw[locales.default],
localeStrings,
localeStrings
) as BlitzKitStrings;
}
File diff suppressed because it is too large. Load diff
+1 -6
View File
@@ -671,8 +671,6 @@
"sorting_by": "Sorting by {name}",
"clear": "Limpiar",
"tier": "Tier {tier}",
"passive": "{name} (Passive)",
"active": "{name} (Active)",
"no_tanks_found": {
"body": "No se encontraron tanques.",
"search_again": "Intenta buscar de nuevo.",
@@ -825,10 +823,7 @@
"description": "Reveals the tank without showing the name. This round will be considered incorrect and break your streak!",
"cancel": "Cancelar",
"reveal": "Reveal"
},
"clear": "Limpiar",
"select_all": "Seleccionar todo",
"tier": "Tier {tier}"
}
},
"tankopedia": {
"search": "Search a stat...",
+89 -94
View File
@@ -1,7 +1,7 @@
{
"test": {
"default": "teste",
"long": "Ceci est une longue chaîne de test. Vous ne DEVEZ JAMAIS le voir dans l'interface utilisateur. Mon fruit préféré est {fruit}, car il a la couleur {color}. Je l'aime tellement que je vais dire son nom 3 fois ! {fruit}! {fruit}! {fruit} ! Encore une fois, c'est {color}, pas {not_color}.",
"long": "This is a long test string. You MUST NEVER see this in the UI. My favorite fruit is {fruit} because it has the color of {color}. I like it so much that I will say its name 3 times! {fruit}! {fruit}! {fruit}! Once again, it's {color}, not {not_color}.",
"fox": "Le renard brun et rapide saute par-dessus le chien paresseux."
},
"common": {
@@ -10,7 +10,7 @@
"m": "{value}m",
"mm": "{value}mm",
"deg": "{value}°",
"hp": "{value}pv",
"hp": "{value}hp",
"x": "x{value}",
"percentage": "{value}%",
"deg_s": "{value}°/s",
@@ -187,11 +187,11 @@
"bot": {
"common": {
"errors": {
"clan_not_found": "# Impossible de trouver le clan\nImpossible de trouver «{search} ». Essayez de sélectionner un clan dans le résultat de la recherche.",
"player_not_found": "# Impossible de trouver l'utilisateur\nJe n'ai pas pu trouver l'utilisateur \"{search}\". Essayez de choisir un utilisateur dans le résultat de la recherche, en tapant un nom d'utilisateur valide, ou en utilisant la commande `/link`.",
"clan_not_found": "# Could not find clan\nCouldn't find \"{search}\". Try selecting a clan from the search result.",
"player_not_found": "# Could not find user\nI couldn't find user \"{search}\". Try picking an user from the search result, typing in a valid username, or using the `/link` command.",
"player_not_linked": "# Utilisez `/link` pour commencer\nJe ne sais pas qui vous êtes, mais vous pouvez me le dire aujourd'hui !",
"tank_name_not_found": "# Char introuvable\nImpossible de trouver le char sous le nom \"{search}\".",
"tank_id_not_found": "# Char introuvable\nImpossible de trouver le char avec l'ID \"{search}\". Essayez de taper le nom du char au lieu d'un nombre.",
"tank_name_not_found": "# Tank not found\nCould not find tank by the name \"{search}\".",
"tank_id_not_found": "# Tank not found\nCould not find tank by the ID \"{search}\". Try typing the name of the tank instead of a number.",
"no_tank_stats": "# Aucune statistique de tank disponible\nCe joueur n'a pas de statistiques disponibles. Ce n'est peut-être pas le joueur que vous cherchez.",
"get_help": "Aidez le serveur Discord",
"uncaught_error": "# Blitzkit a rencontré une erreur !\nNous sommes désolés de cela. N'hésitez pas à [rejoindre le serveur officiel Discord](https://discord.gg/nDt7AjGJQH) pour obtenir de l'aide.",
@@ -285,19 +285,19 @@
"name": "rang",
"description": "Rang",
"choices": {
"tier": "Rang {tier_}1 - {tier_}2"
"tier": "Tier {tier_1} - {tier_2}"
}
}
},
"periods": {
"career": "Carrière",
"today": "Aujourd'hui",
"days": "{days} jours",
"custom": "{day_1} - {day_2} jours"
"days": "{days} days",
"custom": "{day_1} - {day_2} days"
},
"filters": {
"none": "Aucun filtre",
"tier": "Rang {tier}"
"tier": "Tier {tier}"
},
"no_data": {
"battles_in_period": "",
@@ -340,19 +340,19 @@
"body": {
"subtitle": "Recherche",
"total": "Total",
"research": "Recherche : {cost}",
"upgrades": "Améliorations : {cost}",
"purchase": "Achat : {cost}",
"equipment": "Équipement : {cost}",
"research": "Research: {cost}",
"upgrades": "Upgrades: {cost}",
"purchase": "Purchase: {cost}",
"equipment": "Equipment: {cost}",
"estimation": "# Ceci est une estimation !\n\nCette liste peut inclure des chars déjà recherchés en raison de l'information inexacte fournie par Wargaming. Essayez de fournir un `char de départ` depuis la ligne lorsque vous utilisez la commande si vous le pouvez."
},
"errors": {
"non_tech_tree": "# {tank} n'est pas dans l'arbre technologique\n\nVous ne pouvez pas rechercher un char premium/de collection.",
"tier_1": "# {tank} est un char de rang I\n\nLe char de rang 1 sont déverrouillé gratuitement pour tous les joueurs.",
"already_researched": "# {tank} est déjà recherché\n\nEssayez de fournir un `char de départ` en utilisant la commande pour voir la progression d'une lignée.",
"start_end_equal": "# {tank} a été fourni deux fois\n\nAssurez-vous que `starting-tank` et `target-tank` sont différents.",
"tanks_not_on_line": "{tank_}1 et {tank_}2 ne sont pas sur la même ligne \n\nAssurez-vous que `starting-tank` et `target-tank` sont sur la même ligne d'arbre technologique.",
"unordered": "# {tank_1} niveau supérieur à {tank_2}\n\nAssurez-vous de fournir {tank_2} comme le `starting-tank` à la place car c'est le char de niveau inférieur."
"non_tech_tree": "# {tank} is not on the tech tree\n\nYou cannot research a premium/collector tank.",
"tier_1": "# {tank} is a tier I\n\nTier I tanks are always unlocked for free for all players.",
"already_researched": "# {tank} is already researched\n\nTry providing a `starting-tank` when using the command to view the totals for a line you have already researched.",
"start_end_equal": "# {tank} was provided twice\n\nMake sure `starting-tank` and `target-tank` are different.",
"tanks_not_on_line": "# {tank_1} and {tank_2} are not on the same line\n\nMake sure `starting-tank` and `target-tank` are on the same tech-tree line.",
"unordered": "# {tank_1} higher tiered to {tank_2}\n\nMake sure to provide {tank_2} as the `starting-tank` instead as it is the lower tiered tank."
}
},
"about": {
@@ -395,7 +395,7 @@
"wn8": "WN8",
"winrate": "Taux de victoires",
"damage": "Dégâts",
"unknown_tank": "Char {id} inconnu"
"unknown_tank": "Unknown tank {id}"
}
},
"debug": {
@@ -431,12 +431,12 @@
"options": {
"threshold": {
"name": "seuil",
"description": "Le nombre de jours inactifs (par défaut: {days} jours)"
"description": "The number of days inactive (default: {days} days)"
}
},
"body": {
"subtitle": "Inactif depuis plus de {days} jours",
"listing": "{days} jours"
"subtitle": "Inactive for {days}+ days",
"listing": "{days} days"
}
},
"full_stats": {
@@ -479,7 +479,7 @@
"body": {
"accounts_linked": "Comptes liés",
"no_role_permissions": {
"title": "La vérification de {name} a échouée",
"title": "{name} failed to verify",
"description": "Je n'ai pas l'autorisation de gérer les rôles."
}
},
@@ -494,11 +494,11 @@
"options": {
"limit": {
"name": "limite",
"description": "Nombre maximum de résultats du clan (par défaut: {limit})"
"description": "The max number of clan results (default: {limit})"
}
},
"body": {
"title": "Recherche de clan {search} dans la région {region}",
"title": "Clan search for {search} in region {region}",
"no_results": "Pas de clan trouvé"
}
},
@@ -508,11 +508,11 @@
"options": {
"limit": {
"name": "limite",
"description": "Le nombre maximum de résultats de joueur (par défaut: {limit})"
"description": "The max number of player results (default: {limit})"
}
},
"body": {
"title": "Recherche de {search} dans la région {region}",
"title": "Player search for {search} in region {region}",
"no_results": "Pas de joueur de trouvé"
}
},
@@ -532,13 +532,13 @@
"options": {
"limit": {
"name": "limite",
"description": "Combien de voisins afficher (par défaut : {count})"
"description": "How many neighbors to display (default: {count})"
},
"season": {
"name": "saison",
"description": "Numéro de saison (défaut : courant)",
"choices": {
"current": "{season} (actuel)"
"current": "{season} (current)"
}
},
"league": {
@@ -547,12 +547,12 @@
}
},
"body": {
"top_players": "Top {count} joueurs",
"no_participation": "# {player} n'a pas joué de cotées dans la saison {season}\n\nCe joueur n'a pas participé à cette saison ou n'a pas dépassé l'étalonnage.",
"top_players": "Top {count} players",
"no_participation": "# {player} didn't play rating in season {season}\n\nThis player did not participate in this season or did not get past calibration.",
"no_ongoing_season": "Pas de saison en cours\n\nIl n'y a pas de saison de notation en cours actuellement.",
"deleted_player": "{id} supprimé",
"deleted_player": "Deleted {id}",
"neighbors": "évaluer les voisins",
"more": "+ {count} plus"
"more": "+ {count} more"
}
},
"today": {
@@ -567,7 +567,7 @@
"name": "chars possédés",
"description": "Affiche tous les chars d'un niveau",
"body": {
"title": "# Les chars du palier {tier} possédés par {name}"
"title": "# {name}'s owned tier {tier} tanks\n\n"
}
},
"permissions": {
@@ -603,96 +603,94 @@
"name": "info-joueur",
"description": "Informations de base sur un joueur",
"body": {
"title": "Informations de {name}",
"nickname": "Pseudo",
"title": "{name}'s information",
"nickname": "Nickname",
"battles": "Batailles",
"winrate": "Taux de victoires",
"account_id": "Account ID",
"created": "Créé",
"last_battle": "Dernière bataille"
"created": "Created",
"last_battle": "Last battle"
}
},
"rating": {
"name": "côtée",
"description": "Statistiques des batailles cotées du joueur",
"description": "Rating player's statistics",
"subcommands": {
"today": {
"name": "aujourd'hui",
"description": "Statistiques des batailles cotées d'aujourd'hui"
"description": "Today's rating statistics"
},
"season": {
"name": "saison",
"description": "Statistiques des batailles cotées de cette saison"
"description": "This season's rating statistics"
}
},
"body": {
"subtitle": {
"today": "Statistiques de batailles cotées d'aujourd'hui",
"season": "Statistiques de batailles cotées cette saison"
"today": "Today's rating statistics",
"season": "This season's rating statistics"
}
},
"errors": {
"no_participation": "# {name} n’a pas joué en cotée\n\nCe joueur n’a pas participé au mode cotée cette saison.",
"unrecorded_stats": "# Statistiques actuellement indisponibles\n\nWargaming rencontre peut-être une interruption de service.\nSi une saison est en cours, les statistiques devraient être disponibles sous 24 heures."
"no_participation": "# {name} hasn't played rating\n\nThis player hasn't participated in the rating gamemode this season.",
"unrecorded_stats": "# Statistics currently unavailable\n\nWargaming may be currently be facing server downtime. If there is an on-going season, statistics should be available withing 24 hours."
}
}
}
},
"website": {
"redirect": {
"title": "301 : déplacé définitivement",
"body": "Cette page a été déplacée. Redirection en cours…"
"title": "301: moved permanently",
"body": "This page has moved. Redirecting..."
},
"settings": {
"title": "Paramètres",
"description": "Modifier les paramètres de BlitzKit",
"dev_mode": "Mode développement",
"language": "Langue"
"title": "Settings",
"description": "Change BlitzKit settings",
"dev_mode": "Development mode",
"language": "Language"
},
"common": {
"player_search": {
"hint": "Recherche de joueurs...",
"no_results": "Aucun résultat",
"searching": "Recherche..."
"hint": "Search players...",
"no_results": "No results",
"searching": "Searching..."
},
"copy_button": {
"copied": "Copié !"
"copied": "Copied!"
},
"tank_search": {
"select_dialog_title": "Recherche de chars",
"swap_dialog_title": "Échanger le char",
"clear_filters": "Supprimer les filtres",
"login": "Connectez-vous pour utiliser ceci",
"search_bar_hint": "Recherche des tanks...",
"recent": "Vu récemment",
"select_all": "Sélectionner tout",
"count_singular": "1 char",
"count_plural": "{count} chars",
"sorting_by": "Trier par {name}",
"clear": "Effacer",
"tier": "Rang {tier}",
"passive": "{name} (Passif)",
"active": "{name} (actif)",
"select_dialog_title": "Search for tanks",
"swap_dialog_title": "Swap tank",
"clear_filters": "Clear filters",
"login": "Login to use this",
"search_bar_hint": "Search tanks...",
"recent": "Recently viewed",
"select_all": "Select all",
"count_singular": "1 tank",
"count_plural": "{count} tanks",
"sorting_by": "Sorting by {name}",
"clear": "Clear",
"tier": "Tier {tier}",
"no_tanks_found": {
"body": "Aucun tank trouvé.",
"search_again": "Essayez de chercher à nouveau.",
"clear_filters": "Essayez de supprimer les filtres."
"body": "No tanks found.",
"search_again": "Try searching again.",
"clear_filters": "Try clearing filters."
},
"sort": {
"meta.none": "aucun",
"survivability.health": "santé",
"survivability.viewRange": "portée de vue",
"survivability.camouflageStill": "camouflage à l’arrêt",
"survivability.camouflageMoving": "camouflage en movement",
"survivability.camouflageShooting": "camouflage en tirant",
"meta.none": "none",
"survivability.health": "health",
"survivability.viewRange": "view range",
"survivability.camouflageStill": "camouflage still",
"survivability.camouflageMoving": "camouflage moving",
"survivability.camouflageShooting": "camouflage shooting",
"survivability.volume": "volume",
"survivability.length": "longueur",
"fire.dpm": "DPM standard",
"fire.dpmPremium": "DPM premium",
"fire.reload": "rechargement",
"fire.caliber": "calibration",
"fire.standardPenetration": "pénétration standard",
"fire.premiumPenetration": "pénétration premium",
"survivability.length": "length",
"fire.dpm": "standard DPM",
"fire.dpmPremium": "premium DPM",
"fire.reload": "reload",
"fire.caliber": "caliber",
"fire.standardPenetration": "standard penetration",
"fire.premiumPenetration": "premium penetration",
"fire.tertiaryPenetration": "tertiary penetration",
"fire.damage": "damage",
"fire.moduleDamage": "module damage",
@@ -817,7 +815,7 @@
"skip": "Skip",
"guess": "Guess",
"next": "Next",
"no_results": "Aucun résultat"
"no_results": "No results"
},
"stats": "{correct} / {total} guessed correctly",
"help": {
@@ -825,10 +823,7 @@
"description": "Reveals the tank without showing the name. This round will be considered incorrect and break your streak!",
"cancel": "Cancel",
"reveal": "Reveal"
},
"clear": "Clear",
"select_all": "Sélectionner tout",
"tier": "Rang {tier}"
}
},
"tankopedia": {
"search": "Search a stat...",
@@ -1211,8 +1206,8 @@
"seo_description": "Track your stats in real time as you play World of Tanks Blitz",
"search": {
"lookup": "Look up a player to get started",
"hint": "Recherche de joueurs...",
"searching": "Recherche...",
"hint": "Search players...",
"searching": "Searching...",
"no_results": "Pas de joueur de trouvé"
},
"controls": {
+7 -12
View File
@@ -187,11 +187,11 @@
"bot": {
"common": {
"errors": {
"clan_not_found": "",
"player_not_found": "# ユーザーが見つかりませんでした\nユーザー「{search}」が見つかりませんでした。検索結果からユーザーを選択するか、有効なユーザー名を入力するか、/link コマンドを使用してください。",
"clan_not_found": "# Could not find clan\nCouldn't find \"{search}\". Try selecting a clan from the search result.",
"player_not_found": "# Could not find user\nI couldn't find user \"{search}\". Try picking an user from the search result, typing in a valid username, or using the `/link` command.",
"player_not_linked": "# `/link`を使用して始めましょう\nはじめまして!あなたが誰か、私に教えてください。",
"tank_name_not_found": "# Tank not found\nCould not find tank by the name \"{search}\".",
"tank_id_not_found": "# 車両が見つかりません\nID「{search}」の戦車が見つかりませんでした。数字ではなく戦車の名前を入力してみてください。",
"tank_id_not_found": "# Tank not found\nCould not find tank by the ID \"{search}\". Try typing the name of the tank instead of a number.",
"no_tank_stats": "# 利用可能な車輌統計がありません\nこのプレイヤーには利用可能な統計がありません。あなたが探しているプレイヤーではない可能性があります。",
"get_help": "Discordサーバーに参加する",
"uncaught_error": "# BlitzKitがエラーに遭遇しました!\n申し訳ありません。お気軽に[公式Discordサーバー](https://discord.gg/nDt7AjGJQH)にお問い合わせください。",
@@ -395,7 +395,7 @@
"wn8": "WN8",
"winrate": "勝率",
"damage": "ダメージ",
"unknown_tank": "不明な車両{id}"
"unknown_tank": "Unknown tank {id}"
}
},
"debug": {
@@ -560,7 +560,7 @@
"description": "Today's played tanks and statistics"
},
"stats": {
"name": "",
"name": "stats",
"description": "Quick statistics for a period"
},
"owned_tanks": {
@@ -671,8 +671,6 @@
"sorting_by": "Sorting by {name}",
"clear": "クリア",
"tier": "Tier {tier}",
"passive": "{name} (Passive)",
"active": "{name} (Active)",
"no_tanks_found": {
"body": "該当する車輌が存在しません。",
"search_again": "もう一度検索してください。",
@@ -783,7 +781,7 @@
"tank": "車輌名",
"last_played": "Last played",
"battles": "Career battles",
"unrecorded": "",
"unrecorded": "--",
"wins": "勝利"
},
"large_warning": {
@@ -825,10 +823,7 @@
"description": "Reveals the tank without showing the name. This round will be considered incorrect and break your streak!",
"cancel": "Cancel",
"reveal": "Reveal"
},
"clear": "クリア",
"select_all": "全て選択",
"tier": "Tier {tier}"
}
},
"tankopedia": {
"search": "Search a stat...",
+5 -10
View File
@@ -493,7 +493,7 @@
"description": "Search clans",
"options": {
"limit": {
"name": "",
"name": "limit",
"description": "The max number of clan results (default: {limit})"
}
},
@@ -507,7 +507,7 @@
"description": "Search players",
"options": {
"limit": {
"name": "",
"name": "limit",
"description": "The max number of player results (default: {limit})"
}
},
@@ -531,7 +531,7 @@
},
"options": {
"limit": {
"name": "",
"name": "limit",
"description": "How many neighbors to display (default: {count})"
},
"season": {
@@ -671,11 +671,9 @@
"sorting_by": "Sorting by {name}",
"clear": "Clear",
"tier": "Tier {tier}",
"passive": "{name} (Passive)",
"active": "{name} (Active)",
"no_tanks_found": {
"body": "No tanks found.",
"search_again": "",
"search_again": "Try searching again.",
"clear_filters": "Try clearing filters."
},
"sort": {
@@ -825,10 +823,7 @@
"description": "Reveals the tank without showing the name. This round will be considered incorrect and break your streak!",
"cancel": "Cancel",
"reveal": "Reveal"
},
"clear": "Clear",
"select_all": "Select all",
"tier": "Tier {tier}"
}
},
"tankopedia": {
"search": "Search a stat...",
+1 -6
View File
@@ -671,8 +671,6 @@
"sorting_by": "Sorting by {name}",
"clear": "Limpar",
"tier": "Tier {tier}",
"passive": "{name} (Passive)",
"active": "{name} (Active)",
"no_tanks_found": {
"body": "Nenhum tanque encontrado.",
"search_again": "Tente pesquisar novamente.",
@@ -825,10 +823,7 @@
"description": "Reveals the tank without showing the name. This round will be considered incorrect and break your streak!",
"cancel": "Cancelar",
"reveal": "Reveal"
},
"clear": "Limpar",
"select_all": "Selecionar todos",
"tier": "Tier {tier}"
}
},
"tankopedia": {
"search": "Search a stat...",
+5 -10
View File
@@ -24,7 +24,7 @@
"shells": {
"ap": "ББ",
"ap_cr": "БП",
"hc": "КС",
"hc": "ОФ",
"he": "ОФ"
},
"player_count_period": {
@@ -39,7 +39,7 @@
"branches": {
"local": "dev",
"dev": "бета",
"opentest": "общий тест",
"opentest": "открытый тест",
"preview": "превью"
},
"locales": {
@@ -297,7 +297,7 @@
},
"filters": {
"none": "Без фильтров",
"tier": "{tier} уровень"
"tier": " {tier} уровня"
},
"no_data": {
"battles_in_period": "За этот период боёв не было",
@@ -670,9 +670,7 @@
"count_plural": "Танков: {count}",
"sorting_by": "Сортировать по {name}",
"clear": "Очистить",
"tier": "{tier} уровень",
"passive": "{name} (Пассивный)",
"active": "{name} (Активный)",
"tier": " {tier} уровня",
"no_tanks_found": {
"body": "Танков не найдено.",
"search_again": "Попробуйте повторить поиск.",
@@ -825,10 +823,7 @@
"description": "Показывает танк не показывая название. Этот раунд будет считаться проигранным и прекратит серию!",
"cancel": "Отмена",
"reveal": "Раскрыть"
},
"clear": "Очистить",
"select_all": "Выбрать всё",
"tier": "{tier} уровень"
}
},
"tankopedia": {
"search": "Поиск характеристик...",
+67 -72
View File
@@ -79,11 +79,11 @@
"10": "Супер винятковий"
},
"nations": {
"ussr": "С.Р.С.Р.",
"ussr": "СРСР",
"germany": "Німеччина",
"usa": "С.Ш.А.",
"usa": "ЗША",
"china": "Китай",
"uk": "Сполучене Королівство ",
"uk": "Велика Британія",
"france": "Франція",
"japan": "Японія",
"european": "Європейська нація",
@@ -121,7 +121,7 @@
"3": "ПТ-САУ"
},
"tree_type": {
"-1": "не розпізнаний",
"-1": "не розпізнано",
"0": "Звичайний",
"1": "Преміум",
"2": "Колекційний"
@@ -341,18 +341,18 @@
"subtitle": "Дослідження",
"total": "Загалом",
"research": "Дослідження: {cost}",
"upgrades": "Прокачування: {cost}",
"upgrades": "Upgrades: {cost}",
"purchase": "Вартість: {cost}",
"equipment": "Спорядження: {cost}",
"estimation": "# Це оцінка!\n\nЦей список може включати вже досліджені танки через неточну інформацію для вантажу. Спробуйте використати \"початковий танк\" з рядка за допомогою команди."
},
"errors": {
"non_tech_tree": "#{tank} відсутній в дереві дослідження\n\nВи не можете дослідити преміум/колеційний танк.",
"tier_1": "#{tank} І рівня \n\nТанки І рівня завжди розблоковані для всіх гравців безкоштовно",
"already_researched": "# {tank} вже було досліджено\n\nСпробуйте використати `початковий-танк` коли використовуєте команду для перегляду загальної гілки, яку ви вже дослідили",
"start_end_equal": "#{tank} було введено двічі \n\nПереконайтесь що `початковий-танк` та `ціль-танк` різні",
"tanks_not_on_line": "# {tank_1} та {tank_2} не в одній гілці\n\nПереконайтесь що `початковий-танк` та `ціль-танк` знаходяться в єдиній гілці дерева дослідження",
"unordered": "# {tank_1} вище рівнем відносно {tank_2}\n\nОбов’язково вкажіть {tank_2} як `початковий-танк`, оскільки це танк нижчого рівня."
"non_tech_tree": "# {tank} is not on the tech tree\n\nYou cannot research a premium/collector tank.",
"tier_1": "# {tank} is a tier I\n\nTier I tanks are always unlocked for free for all players.",
"already_researched": "# {tank} is already researched\n\nTry providing a `starting-tank` when using the command to view the totals for a line you have already researched.",
"start_end_equal": "# {tank} was provided twice\n\nMake sure `starting-tank` and `target-tank` are different.",
"tanks_not_on_line": "# {tank_1} and {tank_2} are not on the same line\n\nMake sure `starting-tank` and `target-tank` are on the same tech-tree line.",
"unordered": "# {tank_1} higher tiered to {tank_2}\n\nMake sure to provide {tank_2} as the `starting-tank` instead as it is the lower tiered tank."
}
},
"about": {
@@ -395,7 +395,7 @@
"wn8": "WN8",
"winrate": "Відсоток перемог",
"damage": "Шкода",
"unknown_tank": "Невідомий танк {id}"
"unknown_tank": "Unknown tank {id}"
}
},
"debug": {
@@ -431,11 +431,11 @@
"options": {
"threshold": {
"name": "поріг",
"description": "Кількість днів неактивності (за замовчуванням: {days} днів)"
"description": "The number of days inactive (default: {days} days)"
}
},
"body": {
"subtitle": "Неактивний {days}+ днів",
"subtitle": "Inactive for {days}+ days",
"listing": "{days} днів"
}
},
@@ -479,7 +479,7 @@
"body": {
"accounts_linked": "Прив'язані акаунти",
"no_role_permissions": {
"title": "{name} не вдалося перевірити",
"title": "{name} failed to verify",
"description": "У мене немає дозволу керувати ролями."
}
},
@@ -494,11 +494,11 @@
"options": {
"limit": {
"name": "ліміт",
"description": "Максимальна кількість результатів клану (за замовчуванням: {limit})"
"description": "The max number of clan results (default: {limit})"
}
},
"body": {
"title": "Пошук клану для {search} в регіоні {region}",
"title": "Clan search for {search} in region {region}",
"no_results": "Жодного клану не знайдено"
}
},
@@ -508,11 +508,11 @@
"options": {
"limit": {
"name": "ліміт",
"description": "Максимальна кількість результатів гравця (за замовчуванням: {limit})"
"description": "The max number of player results (default: {limit})"
}
},
"body": {
"title": "Пошук гравця для {search} у регіоні {region}",
"title": "Player search for {search} in region {region}",
"no_results": "Гравця не знайдено"
}
},
@@ -521,8 +521,8 @@
"description": "Статистика рейтингових боїв",
"subcommands": {
"neighbors": {
"name": "сусіди",
"description": "Сусідуючі гравці в лідерборді"
"name": "neighbors",
"description": "Neighboring players on the leaderboard"
},
"league": {
"name": "ліга",
@@ -532,32 +532,32 @@
"options": {
"limit": {
"name": "ліміт",
"description": "Скільки сусідів відобразити (за замовчуванням: {count})"
"description": "How many neighbors to display (default: {count})"
},
"season": {
"name": "сезон",
"description": "Базова інформація про гравця",
"choices": {
"current": "{season} (поточний)"
"current": "{season} (current)"
}
},
"league": {
"name": "ліга",
"description": "Ліга для відображення"
"description": "The league to display"
}
},
"body": {
"top_players": "Топ {count} гравців",
"no_participation": "# {player} не грав у рейтингу в сезоні {season}\n\nЦей гравець не брав участь у цьому сезоні або не проходив калібрування",
"no_ongoing_season": "# Немає поточного сезону\n\nВ даний час немає сезону рейтингу.",
"top_players": "Top {count} players",
"no_participation": "# {player} didn't play rating in season {season}\n\nThis player did not participate in this season or did not get past calibration.",
"no_ongoing_season": "# No ongoing season\n\nThere isn't a currently running rating season.",
"deleted_player": "",
"neighbors": "Сусіди по рейтингу",
"more": "+ {count} ще"
"neighbors": "Rating neighbors",
"more": "+ {count} more"
}
},
"today": {
"name": "сьогодні",
"description": "Сьогодні зіграні танки та статистика"
"description": "Today's played tanks and statistics"
},
"stats": {
"name": "статистика",
@@ -567,43 +567,43 @@
"name": "отримані танки",
"description": "Показує всі ваші танки даного рівня",
"body": {
"title": "# {name} отриманих рівнів {tier} танків\n\n"
"title": "# {name}'s owned tier {tier} tanks\n\n"
}
},
"permissions": {
"name": "дозволи",
"description": "Перевіряє чи бот має необхідні дозволи для роботи",
"description": "Checks wether the bot has the required permissions to function",
"body": {
"title": "# Дозволи\n\n{body}",
"view_channels": "Перегляньте канали: необхідне для знаходження повідомлення, на якому використовувалася кнопка оновлення",
"read_message_history": "Прочитайте історію повідомлень: потрібно знайти повідомлення для оновлення",
"attach_files": "Закріпіть файли: потрібно для додавання зображень до команд на основі зображень",
"external_emojis": "Зовнішні емодзі: потрібні для додавання емодзі національних прапорів та класів техніки"
"title": "# Permissions\n\n{body}",
"view_channels": "View channels: needed to find the message the refresh button was used on",
"read_message_history": "Read message history: needed to find the message to refresh",
"attach_files": "Attach files: needed to add images to image-based commands",
"external_emojis": "External emojis: needed to add national flags and tank class emojis"
}
},
"ping": {
"name": "",
"description": "Перевірити чи бот живий",
"description": "Check wether the bot is alive.",
"body": {
"pong": "Понг🏓",
"pong_with_time": "Понг🏓 - {time}мс"
"pong": "Pong 🏓",
"pong_with_time": "Pong 🏓 - {time}ms"
},
"subcommands": {
"blitzkit": {
"name": "BlitzKit",
"name": "blitzkit",
"description": "Ping BlitzKit"
},
"wotb": {
"name": "WoTB",
"name": "wotb",
"description": "Ping World of Tanks Blitz"
}
}
},
"player_info": {
"name": "інформація про гравця",
"name": "player-info",
"description": "Базова інформація про гравця",
"body": {
"title": "інформація про {name}",
"title": "{name}'s information",
"nickname": "Нік",
"battles": "Бої",
"winrate": "Відсоток перемог",
@@ -614,33 +614,33 @@
},
"rating": {
"name": "рейтинг",
"description": "Статистика рейтингових боїв гравця ",
"description": "Rating player's statistics",
"subcommands": {
"today": {
"name": "сьогодні",
"description": "Сьогоднішня статистика рейтингових боїв"
"description": "Today's rating statistics"
},
"season": {
"name": "сезон",
"description": "Статистика рейтингових боїв поточного сезону"
"description": "This season's rating statistics"
}
},
"body": {
"subtitle": {
"today": "Сьогоднішня статистика рейтингових боїв",
"season": "Статистика рейтингових боїв даного сезону"
"today": "Today's rating statistics",
"season": "This season's rating statistics"
}
},
"errors": {
"no_participation": "# {name} не грав рейтингові бої\n\nЦей гравець не брав участь у рейтинговому режимі цього сезону.",
"unrecorded_stats": "# Статистика на цей момент недоступна\n\nWargaming наразі зіткнулась з технічними несправностями. Якщо зараз проходить сезон, статистика буде доступною в найближчі 24 години."
"no_participation": "# {name} hasn't played rating\n\nThis player hasn't participated in the rating gamemode this season.",
"unrecorded_stats": "# Statistics currently unavailable\n\nWargaming may be currently be facing server downtime. If there is an on-going season, statistics should be available withing 24 hours."
}
}
}
},
"website": {
"redirect": {
"title": "301: переміщено назавжди",
"title": "301: moved permanently",
"body": "This page has moved. Redirecting..."
},
"settings": {
@@ -671,8 +671,6 @@
"sorting_by": "Відсортувати за {name}",
"clear": "Clear",
"tier": "Рівень {tier}",
"passive": "{name} (Passive)",
"active": "{name} (Active)",
"no_tanks_found": {
"body": "Нічого не знайдено.",
"search_again": "Спробуйте шукати заново.",
@@ -825,10 +823,7 @@
"description": "Reveals the tank without showing the name. This round will be considered incorrect and break your streak!",
"cancel": "Cancel",
"reveal": "Reveal"
},
"clear": "Clear",
"select_all": "Вибрати все",
"tier": "Рівень {tier}"
}
},
"tankopedia": {
"search": "Search a stat...",
@@ -837,33 +832,33 @@
"description": "Танкова енциклопедія",
"seo_description": "Характеристики, броня та інше для всіх танків WoT Blitz",
"tank_seo_title": "{name} - Tier {tier} {nationality} {class} | {website} Tankopedia | World of Tanks Blitz (WoTB)",
"tank_seo_description": "{name} броня, характеристики, обладнання, амуніція і т.д. {dpm} шкода на хвилину, {alpha} разова шкода, {penetration}мм пробиття, {speed} км/год максимальна швидкість, {health} міцність.",
"tank_seo_description": "{name} armor, statistics, equipment, provisions, and more. {dpm} DPM, {alpha}hp alpha, {penetration}mm penetration, {speed}kph top speed, {health}hp health.",
"visualizers": {
"reload": {
"skip": "Пропустити"
"skip": "Skip"
},
"assault": {
"title": "Штурмові снаряди"
"title": "Assault shells"
},
"rotator": {
"hull": "Корпус",
"turret": "Башта",
"hard": "Жорстко",
"hull": "Hull",
"turret": "Turret",
"hard": "Hard",
"medium": "Середній",
"soft": "Ніжно",
"effective": "Ефективний"
"soft": "Soft",
"effective": "Effective"
},
"ricochet": {
"angle": "Кут",
"angle": "Angle",
"normalization": "Нормалізація",
"effective_angle": "Ефективний кут",
"effective_angle": "Effective angle",
"armor": "Броня",
"no_ricochet": "Фугасні снаряди не рикошетять"
"no_ricochet": "Explosive shells don't ricochet"
},
"view_range": {
"camo": "Камуфляж",
"ghost_factory": "Промзона",
"dead_rail": "Ешелон"
"camo": "Camo",
"ghost_factory": "Ghost Factory",
"dead_rail": "Dead Rail"
},
"flexibility": {
"yaw": "Yaw",
+8 -13
View File
@@ -23,8 +23,8 @@
},
"shells": {
"ap": "穿甲弹",
"ap_cr": "硬式复合穿甲弹",
"hc": "反战车高爆弹",
"ap_cr": "APCR",
"hc": "HEAT",
"he": "高爆弹"
},
"player_count_period": {
@@ -671,8 +671,6 @@
"sorting_by": "按 {name} 排序",
"clear": "清除",
"tier": "{tier} 阶",
"passive": "{name} (被动)",
"active": "{name} (主动)",
"no_tanks_found": {
"body": "找不到战车。",
"search_again": "请尝试重新搜索。",
@@ -821,14 +819,11 @@
},
"stats": "猜对了 {correct} / {total}",
"help": {
"title": "显示坦克?",
"description": "显示坦克而不显示名字。这轮会被视为不正确,并打破你的连续记录!",
"title": "Partially reveal tank?",
"description": "Reveals the tank without showing the name. This round will be considered incorrect and break your streak!",
"cancel": "取消",
"reveal": "显示"
},
"clear": "清除",
"select_all": "全选",
"tier": "{tier} 阶"
"reveal": "Reveal"
}
},
"tankopedia": {
"search": "搜索属性……",
@@ -1150,11 +1145,11 @@
},
"provisions": {
"clear": "清除",
"clear_all": "清除所有坦克"
"clear_all": "Clear all tanks"
},
"consumables": {
"clear": "清除",
"clear_all": "清除所有坦克"
"clear_all": "Clear all tanks"
}
}
},
+4 -4
View File
@@ -44,9 +44,9 @@ for (const module of await readdir(`${modulesRoot}/@resvg`)) {
.map((file) =>
cp(
`${modulesRoot}/@resvg/${module}/${file}`,
`${distRoot}/workers/${file}`,
),
),
`${distRoot}/workers/${file}`
)
)
);
}
@@ -54,7 +54,7 @@ if (!dev) {
await cp(`${projectDir}/prisma`, `${distRoot}/prisma`, { recursive: true });
for (const file of await readdir(`${modulesRoot}/prisma`).then((files) =>
files.filter((file) => file.endsWith(".node")),
files.filter((file) => file.endsWith(".node"))
)) {
cp(`${modulesRoot}/prisma/${file}`, `${distRoot}/prisma/${file}`);
}
+11 -11
View File
@@ -6,7 +6,7 @@ import {
} from "@blitzkit/core";
import { Accessor, Document, Node, Scene } from "@gltf-transform/core";
import { times } from "lodash-es";
import { SteamVFS } from "../vfs/steam";
import { SteamVFS } from "../vfs/vfs";
import {
vertexAttributeGLTFName,
vertexAttributeGltfVectorSizes,
@@ -16,10 +16,10 @@ export async function extractArmor(vfs: SteamVFS, fileName: string) {
const sc2Path = `Data/3d/Tanks/CollisionMeshes/${fileName}.sc2`;
const scgPath = `Data/3d/Tanks/CollisionMeshes/${fileName}.scg`;
const sc2 = new Sc2ReadStream(
(await vfs.file(sc2Path)).buffer as ArrayBuffer,
(await vfs.file(sc2Path)).buffer as ArrayBuffer
).sc2();
const scg = new ScgReadStream(
(await vfs.file(scgPath)).buffer as ArrayBuffer,
(await vfs.file(scgPath)).buffer as ArrayBuffer
).scg();
const document = new Document();
const scene = document.createScene();
@@ -29,7 +29,7 @@ export async function extractArmor(vfs: SteamVFS, fileName: string) {
hierarchies.forEach((hierarchy) => {
const components = times(
hierarchy.components.count,
(index) => hierarchy.components[index.toString().padStart(4, "0")],
(index) => hierarchy.components[index.toString().padStart(4, "0")]
);
components.forEach((component) => {
@@ -43,7 +43,7 @@ export async function extractArmor(vfs: SteamVFS, fileName: string) {
if (!polygonGroup) {
console.warn(
`Missing polygon group ${batch["rb.datasource"]} (${hierarchy.name}); skipping...`,
`Missing polygon group ${batch["rb.datasource"]} (${hierarchy.name}); skipping...`
);
break;
@@ -73,7 +73,7 @@ export async function extractArmor(vfs: SteamVFS, fileName: string) {
VertexAttribute.TANGENT,
attributes
.get(VertexAttribute.TANGENT)!
.map((tangent) => [...tangent, 1]),
.map((tangent) => [...tangent, 1])
);
}
@@ -94,7 +94,7 @@ export async function extractArmor(vfs: SteamVFS, fileName: string) {
hardJointIndices.forEach((hardJointIndex) => {
const node = document.createNode(
`${hierarchy.name}_armor_${hardJointIndex}`,
`${hierarchy.name}_armor_${hardJointIndex}`
);
const mesh = document.createMesh(batch["##name"]);
const indicesAccessor = document
@@ -104,9 +104,9 @@ export async function extractArmor(vfs: SteamVFS, fileName: string) {
new Uint16Array(
polygonGroup.indices.filter(
(index) =>
vertexHardJointIndices.get(index) === hardJointIndex,
),
),
vertexHardJointIndices.get(index) === hardJointIndex
)
)
)
.setBuffer(buffer);
const primitive = document
@@ -127,7 +127,7 @@ export async function extractArmor(vfs: SteamVFS, fileName: string) {
default:
throw new TypeError(
`Unhandled component type: ${component["comp.typename"]}`,
`Unhandled component type: ${component["comp.typename"]}`
);
}
});
@@ -9,7 +9,7 @@ import { Document, Material, Node, Scene } from "@gltf-transform/core";
import { dedup, prune } from "@gltf-transform/functions";
import { times } from "lodash-es";
import { dirname } from "path";
import { SteamVFS } from "../../vfs/steam";
import { SteamVFS } from "../../vfs/vfs";
import { readBaseColor } from "../readBaseColor";
import { readNormal } from "../readNormal";
import { readRoughnessMetallic } from "../readRoughnessMetallic";
@@ -29,10 +29,10 @@ export async function extractModel(vfs: SteamVFS, path: string) {
const sc2Path = `Data/3d/${path}.sc2`;
const scgPath = `Data/3d/${path}.scg`;
const sc2 = new Sc2ReadStream(
(await vfs.file(sc2Path)).buffer as ArrayBuffer,
(await vfs.file(sc2Path)).buffer as ArrayBuffer
).sc2();
const scg = new ScgReadStream(
(await vfs.file(scgPath)).buffer as ArrayBuffer,
(await vfs.file(scgPath)).buffer as ArrayBuffer
).scg();
const document = new Document();
const scene = document.createScene();
@@ -72,9 +72,9 @@ export async function extractModel(vfs: SteamVFS, path: string) {
}`,
textures.miscMap
? `Data/3d/${dirname(path)}/${textures.miscMap}`
: undefined,
),
),
: undefined
)
)
);
if (node.configCount) {
@@ -103,9 +103,9 @@ export async function extractModel(vfs: SteamVFS, path: string) {
.setMimeType("image/webp")
.setImage(
await readRoughnessMetallic(
`Data/3d/${dirname(path)}/${textures.baseRMMap}`,
),
),
`Data/3d/${dirname(path)}/${textures.baseRMMap}`
)
)
);
}
@@ -121,9 +121,9 @@ export async function extractModel(vfs: SteamVFS, path: string) {
`Data/3d/${dirname(path)}/${
textures.baseNormalMap ?? textures.normalmap
}`,
isBase,
),
),
isBase
)
)
);
}
@@ -157,7 +157,7 @@ export async function extractModel(vfs: SteamVFS, path: string) {
const node = document.createNode(hierarchy.name);
const components = times(
hierarchy.components.count,
(index) => hierarchy.components[index.toString().padStart(4, "0")],
(index) => hierarchy.components[index.toString().padStart(4, "0")]
);
components.forEach((component) => {
@@ -194,7 +194,7 @@ export async function extractModel(vfs: SteamVFS, path: string) {
}
if (polygonGroup === undefined) {
throw new Error(
`Missing polygon group ${batch["rb.datasource"]}`,
`Missing polygon group ${batch["rb.datasource"]}`
);
}
@@ -255,7 +255,7 @@ export async function extractModel(vfs: SteamVFS, path: string) {
default: {
if (ERROR_ON_UNKNOWN_COMPONENT) {
throw new Error(
`Unhandled component type: ${component["comp.typename"]}`,
`Unhandled component type: ${component["comp.typename"]}`
);
}
}
+63 -39
View File
@@ -1,21 +1,16 @@
import { exec as execSync } from "child_process";
import { execFile } from "child_process";
import { existsSync } from "fs";
import { readdir, rm } from "fs/promises";
import { promisify } from "util";
import { mkdir, readdir, rm, writeFile } from "fs/promises";
const MAX_COMMAND_LENGTH = 2 ** 11;
const TS_PROTO_EXECUTABLE_LOCATIONS = [
"./node_modules/.bin/protoc-gen-ts_proto",
"../../node_modules/.bin/protoc-gen-ts_proto",
];
const roots = [
// "../../packages/core/src/protos",
const ROOTS = [
"../../packages/closed/protos",
"../../packages/website-ue/src/protos",
];
const exec = promisify(execSync);
let tsProtoExecutableLocation: string | undefined = undefined;
for (const location of TS_PROTO_EXECUTABLE_LOCATIONS) {
@@ -36,7 +31,63 @@ if (!tsProtoExecutableLocation) {
);
}
for (const root of roots) {
// for (const root of ROOTS) {
// const filesRaw = await readdir(`${root}`);
// const files: string[] = [];
// for (const file of filesRaw) {
// if (file.endsWith(".proto")) files.push(file);
// if (file.endsWith(".ts")) await rm(`${root}/${file}`);
// }
// while (files.length > 0) {
// let command = [
// "protoc",
// `--plugin=${tsProtoExecutableLocation}`,
// "--ts_proto_opt=esModuleInterop=true",
// "--ts_proto_opt=oneof=unions-value",
// // "--ts_proto_opt=removeEnumPrefix=true",
// "--ts_proto_opt=unrecognizedEnum=false",
// "--ts_proto_opt=snakeToCamel=false",
// `--ts_proto_out=${root}`,
// ...ROOTS.map((root) => `-I=${root}`),
// ].join(" ");
// while (true) {
// if (files.length === 0) break;
// const file = files.at(-1);
// const newLine = ` ${root}/${file}`;
// if (command.length + newLine.length < MAX_COMMAND_LENGTH) {
// const file = files.pop();
// command += newLine;
// // console.log(` ${file}`);
// } else {
// break;
// }
// }
// await exec(command);
// }
// }
await mkdir("temp", { recursive: true });
for (const root of ROOTS) {
let args = "";
for (const include of ROOTS) {
args += `-I=${include}\n`;
}
args += `--plugin=${tsProtoExecutableLocation}\n`;
args += "--ts_proto_opt=esModuleInterop=true\n";
args += "--ts_proto_opt=oneof=unions-value\n";
args += "--ts_proto_opt=unrecognizedEnum=false\n";
args += "--ts_proto_opt=snakeToCamel=false\n";
args += `--ts_proto_out=${root}\n`;
const filesRaw = await readdir(`${root}`);
const files: string[] = [];
@@ -45,33 +96,6 @@ for (const root of roots) {
if (file.endsWith(".ts")) await rm(`${root}/${file}`);
}
while (files.length > 0) {
let command = [
"protoc",
`--plugin=${tsProtoExecutableLocation}`,
"--ts_proto_opt=esModuleInterop=true",
"--ts_proto_opt=oneof=unions-value",
// "--ts_proto_opt=removeEnumPrefix=true",
"--ts_proto_opt=unrecognizedEnum=false",
"--ts_proto_opt=snakeToCamel=false",
`--ts_proto_out=${root}`,
`-I=${root}`,
].join(" ");
while (true) {
if (files.length === 0) break;
const file = files.at(-1);
const newLine = ` ${root}/${file}`;
if (command.length + newLine.length < MAX_COMMAND_LENGTH) {
command += newLine;
files.pop();
} else {
break;
}
}
await exec(command);
}
await writeFile("temp/protoc.txt", args);
execFile("protoc", ["@temp/protoc.txt"]);
}
+104
View File
@@ -0,0 +1,104 @@
import node from "@astrojs/node";
import react from "@astrojs/react";
import locales from "@blitzkit/i18n/locales.json";
import strings from "@blitzkit/i18n/strings/en.json";
import { mauve, mauveDark } from "@radix-ui/colors";
import favicons from "astro-favicons";
import { defineConfig } from "astro/config";
import packageJSON from "../../package.json";
const POSSIBLE_TARGETS = ["app", "web"];
const target = process.env.PUBLIC_TARGET;
if (!target || !POSSIBLE_TARGETS.includes(target)) {
throw new Error("Invalid target");
}
export default defineConfig({
devToolbar: { enabled: false },
vite: {
server: { allowedHosts: [] },
esbuild: {
minifyIdentifiers: true,
minifySyntax: false,
minifyWhitespace: true,
},
},
output: target === "web" ? "static" : "server",
site: "https://blitzkit.app",
outDir: "../../dist/website",
prefetch: { defaultStrategy: "hover", prefetchAll: true },
// build: { concurrency: 4 },
adapter: target === "app" ? node({ mode: "standalone" }) : undefined,
integrations: [
favicons({
name: strings.common.name,
short_name: strings.common.name,
background: mauveDark.mauve1,
themes: [mauve.mauve1, mauveDark.mauve1],
appleStatusBarStyle: "black-translucent",
version: packageJSON.version,
// shortcuts: Object.values(tools)
// .filter((tool) => !tool.disabled && !tool.href)
// .map((tool) => {
// const stringId = (tool.strings ??
// tool.id) as keyof typeof strings.website.tools;
// return {
// name: strings.website.tools[stringId].name,
// name_localized: wrapper(
// (strings) => strings.website.tools[stringId].name
// ),
// description: strings.website.tools[stringId].description,
// description_localized: wrapper(
// (strings) => strings.website.tools[stringId].description
// ),
// short_name: strings.website.tools[stringId].name,
// short_name_localized: wrapper(
// (strings) => strings.website.tools[stringId].name
// ),
// url: `/${tool.id}`,
// icon: `public/assets/tools/${tool.id}.webp`,
// };
// }),
manifest: {
// description: strings.website.home.seo_description,
// description_localized: wrapper(
// (strings) => strings.website.home.seo_description
// ),
dir: "ltr",
categories: ["utilities", "games", "developer", "developer tools"],
id: "com.tresabhi.blitzkit",
start_url: "/",
launch_handler: { client_mode: "navigate-new" },
display: "fullscreen",
display_override: ["fullscreen", "standalone", "minimal-ui"],
lang: locales.default,
orientation: "any",
},
icons: {
windows: true,
android: true,
appleIcon: true,
appleStartup: true,
favicons: true,
yandex: true,
},
}),
react(),
],
});
+47
View File
@@ -0,0 +1,47 @@
{
"name": "@blitzkit/website-ue",
"type": "module",
"scripts": {
"dev": "PUBLIC_TARGET=web astro dev",
"build": "PUBLIC_TARGET=web astro build",
"preview": "PUBLIC_TARGET=web astro preview",
"lint": "PUBLIC_TARGET=web astro check",
"astro": "astro"
},
"dependencies": {
"@astrojs/check": "^0.9.4",
"@astrojs/node": "^9.4.4",
"@astrojs/react": "^4.4.0",
"@astrolib/seo": "^1.0.0-beta.8",
"@blitzkit/closed": "workspace:*",
"@blitzkit/core": "workspace:*",
"@blitzkit/i18n": "workspace:*",
"@bufbuild/protobuf": "^2.10.2",
"@fontsource-variable/inter": "^5.2.8",
"@fontsource-variable/roboto-flex": "^5.2.8",
"@radix-ui/colors": "^3.0.0",
"@radix-ui/react-icons": "^1.3.2",
"@react-three/drei": "^10.7.6",
"@react-three/fiber": "^9.4.0",
"@types/lodash-es": "^4.17.12",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@types/three": "^0.180.0",
"@vite-pwa/astro": "^1.1.0",
"astro": "^5.14.4",
"astro-favicons": "^3.1.5",
"fuzzysort": "^3.1.0",
"immer": "^10.1.3",
"lodash-es": "^4.17.21",
"quicklime": "^1.2.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-promise-suspense": "^0.3.4",
"three": "^0.180.0",
"three-stdlib": "^2.36.0",
"typescript": "^5.9.3",
"varuna": "workspace:*",
"vite": "^7.1.9",
"yaml": "^2.8.1"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 481 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 443 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 715 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 676 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 367 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 274 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 346 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 406 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 360 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

+46
View File
@@ -0,0 +1,46 @@
<svg width="426" height="426" viewBox="0 0 426 426" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M416.628 244.997L235.625 372.974C223.13 381.809 202.87 381.809 190.375 372.974L9.37173 244.997C3.1239 240.58 -3.95076e-06 234.79 0 229V196.6H426V229C426 234.79 422.876 240.58 416.628 244.997Z" fill="#0D2847"/>
<path d="M416.628 180.603L235.625 52.6262C223.13 43.7913 202.87 43.7913 190.375 52.6262L9.37172 180.603C-3.12391 189.438 -3.12391 203.762 9.37173 212.597L190.375 340.574C202.87 349.409 223.13 349.409 235.625 340.574L416.628 212.597C429.124 203.762 429.124 189.438 416.628 180.603Z" fill="#D9D9D9"/>
<path d="M416.628 180.603L235.625 52.6262C223.13 43.7913 202.87 43.7913 190.375 52.6262L9.37172 180.603C-3.12391 189.438 -3.12391 203.762 9.37173 212.597L190.375 340.574C202.87 349.409 223.13 349.409 235.625 340.574L416.628 212.597C429.124 203.762 429.124 189.438 416.628 180.603Z" fill="url(#paint0_linear_764_240)"/>
<path d="M416.628 180.603L235.625 52.6262C223.13 43.7913 202.87 43.7913 190.375 52.6262L9.37172 180.603C-3.12391 189.438 -3.12391 203.762 9.37173 212.597L190.375 340.574C202.87 349.409 223.13 349.409 235.625 340.574L416.628 212.597C429.124 203.762 429.124 189.438 416.628 180.603Z" fill="url(#paint1_linear_764_240)"/>
<g filter="url(#filter0_d_764_240)">
<path d="M197.056 150.108L201.368 153.051L290.596 213.945L306.6 202.599L310.832 199.599L289.153 184.23L288.86 177.31L335.236 182.298L351.706 170.622L359.102 165.378L288.049 158.111L286.355 118L263.968 133.871L265.867 167.722L217.292 135.762L197.056 150.108Z" fill="#111927" fill-opacity="0.5" shape-rendering="crispEdges"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M192.905 289L74.2242 204.714L70 201.714L116.393 168.767C129.906 159.17 143.124 153.539 156.048 151.875C168.971 150.211 180.919 153.275 191.893 161.069C198.702 165.905 202.718 171.006 203.941 176.372C205.165 181.658 204.302 186.506 201.354 190.918L201.692 191.158C208.978 188.301 216.935 187.286 225.563 188.113C234.247 188.9 242.613 192.151 250.66 197.866C261.803 205.779 266.398 214.825 264.446 225.004C262.551 235.142 254.96 244.929 241.672 254.366L192.905 289ZM221.999 242.08L200.456 257.38L163.905 231.422L185.448 216.123C192.007 211.465 198.473 209.23 204.846 209.42C211.22 209.529 217.193 211.562 222.764 215.519C228.392 219.516 231.31 223.797 231.521 228.364C231.732 232.85 228.558 237.422 221.999 242.08ZM165.937 205.64L146.77 219.252L114.693 196.472L133.861 182.859C140.363 178.241 146.435 175.887 152.076 175.798C157.717 175.708 163.07 177.462 168.135 181.059C173.256 184.696 175.809 188.557 175.796 192.643C175.726 196.69 172.44 201.022 165.937 205.64Z" fill="#111927" fill-opacity="0.5" shape-rendering="crispEdges"/>
<path d="M197.056 156.108L290.596 219.945L310.832 205.599L306.6 202.599L289.153 190.23L288.86 183.31L335.236 188.298L359.102 171.378L351.706 170.622L288.049 164.111L286.355 124L263.968 139.871L265.867 173.722L217.292 141.762L201.368 153.051L197.056 156.108Z" fill="#111927" fill-opacity="0.5" shape-rendering="crispEdges"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M192.905 295L70 207.714L74.2242 204.714L116.393 174.767C129.906 165.17 143.124 159.539 156.048 157.875C168.971 156.211 180.919 159.275 191.893 167.069C198.702 171.905 202.718 177.006 203.941 182.372C205.165 187.658 204.302 192.506 201.354 196.918L201.692 197.158C208.978 194.301 216.935 193.286 225.563 194.113C234.247 194.9 242.613 198.151 250.66 203.866C261.803 211.779 266.398 220.825 264.446 231.004C262.551 241.142 254.96 250.929 241.672 260.366L192.905 295ZM221.999 248.08L200.456 263.38L163.905 237.422L185.448 222.123C192.007 217.465 198.473 215.23 204.846 215.42C211.22 215.529 217.193 217.562 222.764 221.519C228.392 225.516 231.31 229.797 231.521 234.364C231.732 238.85 228.558 243.422 221.999 248.08ZM165.937 211.64L146.77 225.252L114.693 202.472L133.861 188.859C140.363 184.241 146.435 181.887 152.076 181.798C157.717 181.708 163.07 183.462 168.135 187.059C173.256 190.696 175.809 194.557 175.796 198.643C175.726 202.69 172.44 207.022 165.937 211.64Z" fill="#111927" fill-opacity="0.5" shape-rendering="crispEdges"/>
<path d="M310.832 199.599L306.6 202.599L310.832 205.599V199.599Z" fill="#111927" fill-opacity="0.5" shape-rendering="crispEdges"/>
<path d="M359.102 165.378L351.706 170.622L359.102 171.378V165.378Z" fill="#111927" fill-opacity="0.5" shape-rendering="crispEdges"/>
<path d="M201.368 153.051L197.056 150.108V156.108L201.368 153.051Z" fill="#111927" fill-opacity="0.5" shape-rendering="crispEdges"/>
<path d="M74.2242 204.714L70 201.714V207.714L74.2242 204.714Z" fill="#111927" fill-opacity="0.5" shape-rendering="crispEdges"/>
</g>
<path d="M197.056 150.108L290.596 213.945L310.832 199.599L289.153 184.23L288.86 177.31L335.236 182.298L359.102 165.378L288.049 158.111L286.355 118L263.968 133.871L265.867 167.722L217.292 135.762L197.056 150.108Z" fill="url(#paint2_linear_764_240)"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M192.905 289L70 201.714L116.393 168.767C129.906 159.17 143.124 153.539 156.048 151.875C168.971 150.211 180.919 153.275 191.893 161.069C198.702 165.905 202.718 171.006 203.941 176.372C205.165 181.658 204.302 186.506 201.354 190.918L201.692 191.158C208.978 188.301 216.935 187.286 225.563 188.113C234.247 188.9 242.613 192.151 250.66 197.866C261.803 205.779 266.398 214.825 264.446 225.004C262.551 235.142 254.96 244.929 241.672 254.366L192.905 289ZM221.999 242.08L200.456 257.38L163.905 231.422L185.448 216.123C192.007 211.465 198.473 209.23 204.846 209.42C211.22 209.529 217.193 211.562 222.764 215.519C228.392 219.516 231.31 223.797 231.521 228.364C231.732 232.85 228.558 237.422 221.999 242.08ZM165.937 205.64L146.77 219.252L114.693 196.472L133.861 182.859C140.363 178.241 146.435 175.887 152.076 175.798C157.717 175.708 163.07 177.462 168.135 181.059C173.256 184.696 175.809 188.557 175.796 192.643C175.726 196.69 172.44 201.022 165.937 205.64Z" fill="url(#paint3_linear_764_240)"/>
<defs>
<filter id="filter0_d_764_240" x="66" y="116" width="297.103" height="185" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feOffset dy="2"/>
<feGaussianBlur stdDeviation="2"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_764_240"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_764_240" result="shape"/>
</filter>
<linearGradient id="paint0_linear_764_240" x1="213" y1="46" x2="213" y2="347.2" gradientUnits="userSpaceOnUse">
<stop stop-color="#10243E"/>
<stop offset="1" stop-color="#0F1B2D"/>
</linearGradient>
<linearGradient id="paint1_linear_764_240" x1="127.008" y1="96.51" x2="241.48" y2="334.974" gradientUnits="userSpaceOnUse">
<stop stop-color="#262A65"/>
<stop offset="1" stop-color="#104D87"/>
</linearGradient>
<linearGradient id="paint2_linear_764_240" x1="215" y1="98.5" x2="299.5" y2="210.5" gradientUnits="userSpaceOnUse">
<stop offset="0.379808" stop-color="#C2E6FF"/>
<stop offset="0.706731" stop-color="#70B8FF"/>
</linearGradient>
<linearGradient id="paint3_linear_764_240" x1="215" y1="98.5" x2="299.5" y2="210.5" gradientUnits="userSpaceOnUse">
<stop offset="0.379808" stop-color="#C2E6FF"/>
<stop offset="0.706731" stop-color="#70B8FF"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 7.3 KiB

@@ -0,0 +1,3 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="sitemap" href="/sitemap-index.xml" />
@@ -0,0 +1,41 @@
<style is:global>
@import "@radix-ui/colors/mauve-dark.css";
@import "@radix-ui/colors/mauve-alpha.css";
@import "@fontsource-variable/roboto-flex";
body {
--space-0: 0.0625rem;
--space-1: 0.125rem;
--space-2: 0.25rem;
--space-3: 0.5rem;
--space-4: 1rem;
--space-5: 2rem;
--space-6: 4rem;
--space-7: 8rem;
--space-8: 16rem;
--space-9: 32rem;
--weight-thin: 100;
--weight-extra-light: 200;
--weight-light: 300;
--weight-regular: 400;
--weight-medium: 500;
--weight-semibold: 600;
--weight-bold: 700;
--weight-extra-bold: 800;
--weight-black: 900;
--font-size-regular: 1rem;
background-color: var(--gray-1);
color: var(--gray-12);
font-family: "Roboto Flex", sans-serif;
display: flex;
flex-direction: column;
}
body {
margin: 0;
}
</style>
@@ -0,0 +1,23 @@
---
import type { Color } from "../pages/styles/colors/[accent].css";
interface Props {
color: Color;
alias: string;
}
const { color, alias } = Astro.props;
let styles = "";
styles += ":root{";
for (let i = 0; i < 12; i++) {
const n = i + 1;
styles += `--${alias}-${n}:var(--${color}-${n});`;
}
styles += "}";
---
<style set:html={styles}></style>
@@ -0,0 +1,25 @@
---
import * as colors from "@radix-ui/colors";
import type { Color } from "../pages/styles/colors/[accent].css";
interface Props {
color: Color;
}
const { color } = Astro.props;
const scale = colors[`${color}Dark`];
let styles = "";
styles += ":root{";
for (let i = 0; i < 12; i++) {
const n = i + 1;
const value = scale[`${color}${n}` as keyof typeof scale];
styles += `--${color}-${n}:${value};`;
}
styles += "}";
---
<style set:html={styles}></style>
@@ -0,0 +1,44 @@
---
import { TextField } from "./TextField";
---
<style>
.home-hero {
display: flex;
flex-direction: column;
align-items: center;
.wallpaper {
width: 100%;
background-image: url(/assets/home-hero.webp);
background-size: cover;
background-position: top;
height: 13rem;
.wrapper {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: var(--space-7);
width: 100%;
height: 100%;
background: linear-gradient(transparent, var(--gray-1));
}
}
input {
width: 100%;
}
}
</style>
<div class="home-hero">
<div class="wallpaper">
<div class="wrapper"></div>
</div>
<TextField placeholder="asdasdasd" />
</div>
Whitespace-only changes.
@@ -0,0 +1,26 @@
import type { CharacteristicOutput } from "../core/tankopedia/characteristics";
import type { CharacteristicRenderConfig } from "../core/tankopedia/characteristicsOrder";
import { renderCharacteristic } from "../core/tankopedia/renderCharacteristic";
interface Props {
characteristic: CharacteristicOutput;
others: CharacteristicOutput[];
config: CharacteristicRenderConfig;
}
export function TankopediaCharacteristic({
characteristic,
others,
config,
}: Props) {
if (characteristic === null) return null;
const rendered = renderCharacteristic(characteristic, config);
return (
<p>
{config.name}: {rendered} {config.units && `${config.units}`} (1 /{" "}
{others.length})
</p>
);
}
@@ -0,0 +1,7 @@
interface Props {
toy: string;
}
export function TankopediaToy({ toy }: Props) {
return <p>toy: {toy}</p>;
}
@@ -0,0 +1,19 @@
.text-field {
min-width: 0;
max-width: var(--space-9);
border-radius: 9999px;
background-color: var(--gray-3);
border: solid 1px var(--gray-6);
color: var(--gray-12);
padding: var(--space-3) var(--space-4);
margin: 0 var(--space-4);
font-weight: var(--weight-medium);
font-size: var(--font-size-regular);
&[data-has-icon="true"] {
padding-left: var(--space-3);
}
}
@@ -0,0 +1,6 @@
import type { ComponentProps } from "react";
import "./index.css";
export function TextField(props: ComponentProps<"input">) {
return <input className="text-field" {...props} />;
}
@@ -0,0 +1,23 @@
import type { CatalogItemAccessor } from "@blitzkit/closed";
import type { Tank } from "../../protos/tank";
import type { TankList } from "../../protos/tank_list";
import type { Tanks } from "../../protos/tanks";
export abstract class AbstractAPI {
abstract tanks(): Promise<Tanks>;
abstract tankList(): Promise<TankList>;
abstract strings(
locale: string,
prefix?: string
): Promise<Record<string, string>>;
abstract tank(id: string): Promise<Tank>;
abstract avatars(): Promise<CatalogItemAccessor[]>;
abstract avatar(id: string): Promise<CatalogItemAccessor>;
abstract backgrounds(): Promise<CatalogItemAccessor[]>;
abstract background(id: string): Promise<CatalogItemAccessor>;
}
@@ -0,0 +1,19 @@
import { fetchPB } from "@blitzkit/core";
import { Tank } from "../../protos/tank";
import { TankList } from "../../protos/tank_list";
import { Tanks } from "../../protos/tanks";
import { AbstractAPI } from "./abstract";
export class ClientAPI extends AbstractAPI {
tanks() {
return fetchPB("/api/tanks/all.pb", Tanks);
}
tankList() {
return fetchPB("/api/tanks/list.pb", TankList);
}
tank(id: string) {
return fetchPB(`/api/tanks/${id}.pb`, Tank);
}
}
@@ -0,0 +1,22 @@
import { assertSecret } from "@blitzkit/core";
import type { AbstractAPI } from "./abstract";
let dynamicAPI: AbstractAPI;
if (typeof window === "undefined") {
const { ProxyClient } = await import("@blitzkit/closed");
const { ServerAPI } = await import("./server");
const proxyClient = await new ProxyClient(
assertSecret(import.meta.env.WOTB_SERVER)
).handshake();
const metadata = await proxyClient.metadata();
dynamicAPI = new ServerAPI(metadata);
} else {
const { ClientAPI } = await import("./client");
dynamicAPI = new ClientAPI();
}
export const api = dynamicAPI;
+165
View File
@@ -0,0 +1,165 @@
import type { MetadataAccessor } from "@blitzkit/closed";
import { sluggify } from "@blitzkit/core";
import type { RemoteStorageComponent } from "@protos/blitz_static_remote_storage_component";
import { parse } from "yaml";
import type { Tank } from "../../protos/tank";
import type { TankList, TankListEntry } from "../../protos/tank_list";
import type { Tanks } from "../../protos/tanks";
import { AbstractAPI } from "./abstract";
if (typeof window !== "undefined") {
throw new Error("ServerAPI is being evaluated in the browser");
}
interface LocalizationConfig {
namespaces: string[];
}
export class ServerAPI extends AbstractAPI {
constructor(private metadata: MetadataAccessor) {
super();
}
async strings(locale: string) {
const group = this.metadata.group("ClientConfigsEntity");
if (group.length !== 1) {
throw new RangeError(
`Don't know how to handle ${group.length} ClientConfigsEntities`
);
}
const clientConfig = this.metadata.item(group[0].id);
const localizationResources = clientConfig.LocalizationResources();
if (!localizationResources.remote_storage) {
throw new Error("Localization resources not found");
}
let remoteStorage: RemoteStorageComponent | undefined = undefined;
for (const candidateId of localizationResources.remote_storage
.remote_urls) {
const item = this.metadata.item(candidateId);
const candidate = item.RemoteStorage();
if (
remoteStorage === undefined ||
candidate.download_speed_weight > remoteStorage.download_speed_weight
) {
remoteStorage = candidate;
}
}
if (remoteStorage === undefined) {
throw new Error("No suitable production remote storage found");
}
const strings: Record<string, string> = {};
const configPath = `${remoteStorage.url}/${remoteStorage.relative_path}/config.yaml`;
try {
const config = await fetch(configPath)
.then((response) => response.text())
.then((text) => parse(text) as LocalizationConfig);
for (const namespace of config.namespaces) {
Object.assign(
strings,
await fetch(
`${remoteStorage.url}/${remoteStorage.relative_path}/${namespace}/${locale}.yaml`
)
.then((response) => response.text())
.then((text) => {
const strings: Record<string, string> = {};
const parsed = parse(text) as Record<string, string>;
for (const key in parsed) {
strings[key] = parsed[key].replaceAll('\\"', '"');
}
return strings;
})
);
}
} catch (error) {
console.warn(
`Failed to fetch config from ${configPath}. Returning empty strings. This will throw an error in production. Error:`,
error
);
}
return strings;
}
_tankList: TankList | undefined;
async tankList() {
if (this._tankList === undefined) {
const group = this.metadata.group("TankEntity");
const list: TankListEntry[] = [];
const strings = await this.strings("en");
for (const item of group) {
const tankCatalog = item.TankCatalog();
if (!tankCatalog.name) continue;
const name = strings[tankCatalog.name.value];
if (!name) continue;
const id = item.name;
const slug = sluggify(name);
list.push({ id, slug });
}
this._tankList = { list };
}
return this._tankList;
}
async tanks() {
const tankList = await this.tankList();
const data: Tanks = { tanks: {} };
for (const { id } of tankList.list) {
data.tanks[id] = await this.tank(id);
}
return data;
}
async tank(id: string) {
const tankList = await this.tankList();
const tankListEntry = tankList.list.find((tank) => tank.id === id);
if (!tankListEntry) {
throw new Error(`Tank with id ${id} not found`);
}
const { slug } = tankListEntry;
const item = this.metadata.item(`TankEntity.${id}`);
const tank = item.TankCatalog();
const compensation = item.Compensation();
return { tank, compensation, slug } satisfies Tank;
}
async avatars() {
return this.metadata.group("ProfileAvatarEntity");
}
async avatar(id: string) {
return this.metadata.item(`ProfileAvatarEntity.${id}`);
}
async backgrounds() {
return this.metadata.group("ProfileBackgroundEntity");
}
async background(id: string) {
return this.metadata.item(`ProfileBackgroundEntity.${id}`);
}
}
@@ -0,0 +1,205 @@
import { StandardSinglePrice } from "@protos/blitz_static_standard_single_price";
import { PenetrationGroup } from "@protos/blitz_static_tank_penetration_group";
import {
PenetrationGroupUpgrade,
PitchLimit,
ShellUpgrade,
ShellUpgrageSingleChange,
StageParameters,
TankAttributeChange,
TankAttributeChange_AttributeName,
TankAttributeChange_Modifier,
VisualChanges,
} from "@protos/blitz_static_tank_upgrade_single_stage";
function patch(stage0: StageParameters, stage1: StageParameters) {
if (stage1.stage_number !== ++stage0.stage_number) {
throw new Error("Change stage number must be 1 greater than base");
}
for (const attribute1 of stage1.attributes) {
let value1: number;
switch (attribute1.modifier) {
case TankAttributeChange_Modifier.MODIFIER_OVERRIDE:
value1 = attribute1.value;
break;
case TankAttributeChange_Modifier.MODIFIER_MULTIPLY:
case TankAttributeChange_Modifier.MODIFIER_ADD:
const attribute0 = stage0.attributes.find(
(attribute0) =>
attribute0.attribute_name === attribute1.attribute_name
);
if (!attribute0) {
throw new Error(
`Missing attribute ${
TankAttributeChange_AttributeName[attribute1.attribute_name]
} (${attribute1.attribute_name}) to modify`
);
}
case TankAttributeChange_Modifier.MODIFIER_MULTIPLY: {
value1 = attribute0!.value! * attribute1.value;
break;
}
case TankAttributeChange_Modifier.MODIFIER_ADD: {
value1 = attribute0!.value! + attribute1.value;
break;
}
default:
throw new Error(
`Unhandled modified ${
TankAttributeChange_Modifier[attribute1.modifier]
}`
);
}
const attribute0 = TankAttributeChange.create({
modifier: TankAttributeChange_Modifier.MODIFIER_OVERRIDE,
attribute_name: attribute1.attribute_name,
value: value1,
});
const index0 = stage0.attributes.findIndex(
(attribute) => attribute.attribute_name === attribute1.attribute_name
);
if (index0 === -1) {
stage0.attributes.push(attribute0);
} else {
stage0.attributes[index0] = attribute0;
}
}
for (const penetrationGroupUpgrade1 of stage1.penetration_groups_upgrades) {
const penetrationGroupUpgrade0 = stage0.penetration_groups_upgrades.find(
(group) => group.tank_part === penetrationGroupUpgrade1.tank_part
);
if (penetrationGroupUpgrade0) {
penetrationGroupUpgrade0.primary_armor = [
...penetrationGroupUpgrade1.primary_armor,
];
for (const penetrationGroup1 of penetrationGroupUpgrade1.penetration_groups) {
const penetrationGroup0 =
penetrationGroupUpgrade0.penetration_groups.find(
(baseGroup) => baseGroup.group_name === penetrationGroup1.group_name
);
if (penetrationGroup0) {
penetrationGroup0.common_data = penetrationGroup1.common_data;
penetrationGroup0.armor = penetrationGroup1.armor;
} else {
penetrationGroupUpgrade0.penetration_groups.push(
PenetrationGroup.create(penetrationGroup1)
);
}
}
} else {
stage0.penetration_groups_upgrades.push(
PenetrationGroupUpgrade.create(penetrationGroupUpgrade1)
);
}
}
if (stage1.modules_upgrades.length > 0) {
throw new Error("Modules upgrades not implemented");
}
for (const shellUpgrades1 of stage1.shells_upgrades) {
let shellUpgrades0 = stage0.shells_upgrades.find(
(baseShell) => baseShell.shell_id === shellUpgrades1.shell_id
);
if (shellUpgrades0) {
shellUpgrades0.shell_type = shellUpgrades1.shell_type;
for (const changedShellUpgrade of shellUpgrades1.changes) {
const shellUpgrade0 = shellUpgrades0.changes.find(
(baseShellUpgrade) =>
baseShellUpgrade.attribute_name ===
changedShellUpgrade.attribute_name
);
if (shellUpgrade0) {
shellUpgrade0.value = changedShellUpgrade.value;
} else {
shellUpgrades0.changes.push(
ShellUpgrageSingleChange.create(changedShellUpgrade)
);
}
}
shellUpgrades0.silver_price =
shellUpgrades1.silver_price === undefined
? undefined
: StandardSinglePrice.create(shellUpgrades1.silver_price);
} else {
stage0.shells_upgrades.push(ShellUpgrade.create(shellUpgrades1));
}
}
if (stage1.pump_reload_times.length > 0) {
stage0.pump_reload_times = [...stage1.pump_reload_times];
}
if (stage1.pitch_limits_up.length > 0 && stage0.pitch_limits_up.length > 0) {
throw new Error("Pitch limits not implemented");
}
for (const pitchLimitUp1 of stage1.pitch_limits_up) {
stage0.pitch_limits_up.push(PitchLimit.create(pitchLimitUp1));
}
if (
stage1.pitch_limits_down.length > 0 &&
stage0.pitch_limits_down.length > 0
) {
throw new Error("Pitch limits not implemented");
}
for (const pitchLimitDown1 of stage1.pitch_limits_down) {
stage0.pitch_limits_down.push(PitchLimit.create(pitchLimitDown1));
}
for (const visualChange1 of stage1.visual_changes) {
const visualChange0 = stage0.visual_changes.find(
(baseVisualChange) =>
baseVisualChange.tank_part === visualChange1.tank_part
);
if (visualChange0) {
visualChange0.name = visualChange1.name;
} else {
stage0.visual_changes.push(VisualChanges.create(visualChange1));
}
}
}
export function aggregateStageParameters(
base: StageParameters,
stages: StageParameters[]
) {
const stage0 = StageParameters.create({ ...base, stage_number: 0 });
/**
* Bug in Reforged: base stats are stage 1, so is the first upgrade. Manually
* setting it to stage 0 below and if the bug's been fixed, throw an error
* in dev mode to allow clean up in the future. Also, update the initial
* stage number to -1.
*/
if (base.stage_number === 0 && import.meta.env.DEV) {
throw new Error(
"Base stats are now stage 0. In-game bug fixed, please remove hack."
);
}
stages.forEach((stage) => patch(stage0, stage));
return stage0;
}
@@ -0,0 +1,100 @@
import { normalizeAngleDeg } from "@blitzkit/core";
import type { PitchLimit } from "@protos/blitz_static_tank_upgrade_single_stage";
import { clamp, degToRad, lerp, radToDeg } from "three/src/math/MathUtils.js";
export function applyPitchYawLimits(
givenPitch: number,
givenYaw: number,
pitchLimitsUp: PitchLimit[],
pitchLimitsDown: PitchLimit[]
) {
const givenYawDeg = normalizeAngleDeg(radToDeg(givenYaw));
const givenPitchDeg = normalizeAngleDeg(radToDeg(givenPitch));
const yawDeg = givenYawDeg;
const yaw = degToRad(givenYawDeg);
let leftLimitUp: PitchLimit | undefined;
let rightLimitUp: PitchLimit | undefined;
let leftLimitDown: PitchLimit | undefined;
let rightLimitDown: PitchLimit | undefined;
for (const limit of pitchLimitsUp) {
const normalizedAngle = normalizeAngleDeg(limit.angle);
if (normalizedAngle <= yawDeg) {
if (
!leftLimitUp ||
normalizeAngleDeg(yawDeg - normalizedAngle) <
normalizeAngleDeg(yawDeg - leftLimitUp.angle)
) {
leftLimitUp = limit;
}
}
if (normalizedAngle >= yawDeg) {
if (
!rightLimitUp ||
normalizeAngleDeg(normalizedAngle - yawDeg) <
normalizeAngleDeg(rightLimitUp.angle - yawDeg)
) {
rightLimitUp = limit;
}
}
}
for (const limit of pitchLimitsDown) {
const normalizedAngle = normalizeAngleDeg(limit.angle);
if (normalizedAngle <= yawDeg) {
if (
!leftLimitDown ||
normalizeAngleDeg(yawDeg - normalizedAngle) <
normalizeAngleDeg(yawDeg - leftLimitDown.angle)
) {
leftLimitDown = limit;
}
}
if (normalizedAngle >= yawDeg) {
if (
!rightLimitDown ||
normalizeAngleDeg(normalizedAngle - yawDeg) <
normalizeAngleDeg(rightLimitDown.angle - yawDeg)
) {
rightLimitDown = limit;
}
}
}
if (!leftLimitUp || !rightLimitUp || !leftLimitDown || !rightLimitDown) {
throw new Error("Pitch limits not found");
}
const spanUp = rightLimitUp.angle - leftLimitUp.angle;
const spanDown = rightLimitDown.angle - leftLimitDown.angle;
let limitUp: number;
let limitDown: number;
if (spanUp === 0) {
limitUp = leftLimitUp.limit;
} else {
const delta = givenYawDeg - leftLimitUp.angle;
const t = delta / spanUp;
limitUp = lerp(leftLimitUp.limit, rightLimitUp.limit, t);
}
if (spanDown === 0) {
limitDown = leftLimitDown.limit;
} else {
const delta = givenYawDeg - leftLimitDown.angle;
const t = delta / spanDown;
limitDown = lerp(leftLimitDown.limit, rightLimitDown.limit, t);
}
const pitchDeg = clamp(givenPitchDeg, -limitDown, limitUp);
const pitch = degToRad(pitchDeg);
return { pitch, yaw };
}
@@ -0,0 +1,423 @@
import { TankClass } from "@blitzkit/core";
import {
ShellUpgrageSingleChange_AttributeName,
StageParameters,
TankAttributeChange_AttributeName,
} from "@protos/blitz_static_tank_upgrade_single_stage";
import { radToDeg } from "three/src/math/MathUtils.js";
import type { Tank } from "../../protos/tank";
import { applyPitchYawLimits } from "./applyPitchYawLimits";
import { TerrainHardness, type TankState } from "./tankState";
export type CharacteristicOutput = number | number[] | string | null;
type Characteristic = (helpers: {
characteristic: (name: CharacteristicName) => CharacteristicOutput;
attribute: (name: TankAttributeChange_AttributeName) => number;
attributeSafe: (name: TankAttributeChange_AttributeName) => number | null;
shell: (name: ShellUpgrageSingleChange_AttributeName) => number;
shellSafe: (name: ShellUpgrageSingleChange_AttributeName) => number | null;
state: TankState;
tank: Tank;
parameters: StageParameters;
id: string;
}) => CharacteristicOutput;
export type CharacteristicName = keyof typeof characteristics;
export enum GunType {
Regular,
AutoLoader,
AutoReloader,
}
export const characteristics = {
gun_type({ attributeSafe, attribute }) {
const isPump =
attributeSafe(TankAttributeChange_AttributeName.ATTRIBUTE_NAME_IS_PUMP) ??
0;
if (isPump === 1) return GunType.AutoReloader;
const clipSize = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_CLIP_SIZE
);
if (clipSize === 1) return GunType.Regular;
return GunType.AutoLoader;
},
clip_size({ attribute, characteristic }) {
const gunType = characteristic("gun_type")!;
if (gunType === GunType.Regular) return null;
return attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_CLIP_SIZE
);
},
damage({ shell }) {
return shell(
ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_ARMOR_DAMAGE
);
},
module_damage({ shell }) {
return shell(
ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_MODULE_DAMAGE
);
},
penetration({ shell }) {
return shell(
ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_PIERCING_POWER
);
},
reload({ characteristic, attribute }) {
const gunType = characteristic("gun_type")!;
if (gunType === GunType.AutoReloader) return null;
return attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_RELOAD_TIME
);
},
reloads({ characteristic, parameters }) {
const gunType = characteristic("gun_type")!;
if (gunType !== GunType.AutoReloader) return null;
return parameters.pump_reload_times;
},
intra_clip({ characteristic, attribute }) {
const gunType = characteristic("gun_type")!;
if (gunType === GunType.Regular) return null;
const clipRate = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_CLIP_RATE
);
return 60 / clipRate;
},
optimal_shell({ characteristic }) {
const gunType = characteristic("gun_type")!;
if (gunType !== GunType.AutoReloader) return null;
const intraClip = characteristic("intra_clip") as number;
const reloads = characteristic("reloads") as number[];
let optimal: number | undefined = undefined;
for (let index = 0; index < reloads.length; index++) {
const reload = reloads[index] + (index > 0 ? intraClip : 0);
if (optimal === undefined || reload < reloads[optimal]) optimal = index;
}
if (optimal === undefined) {
throw new Error("Unable to find optimal shell");
}
return optimal;
},
dpm({ characteristic }) {
let dps: number;
const gunType = characteristic("gun_type")!;
const damage = characteristic("damage") as number;
switch (gunType) {
case GunType.Regular: {
const reload = characteristic("reload") as number;
dps = damage / reload;
break;
}
case GunType.AutoLoader: {
const reload = characteristic("reload") as number;
const intraClip = characteristic("intra_clip") as number;
const clipSize = characteristic("clip_size") as number;
dps = (damage * clipSize) / (reload + (clipSize - 1) * intraClip);
break;
}
case GunType.AutoReloader: {
const reloads = characteristic("reloads") as number[];
const optimalShell = characteristic("optimal_shell") as number;
const intraClip = characteristic("intra_clip") as number;
const reload =
reloads[optimalShell] + (optimalShell > 0 ? intraClip : 0);
dps = damage / reload;
break;
}
default:
throw new Error("Unknown gun type");
}
return 60 * dps;
},
caliber({ shell }) {
return shell(ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_CALIBER);
},
normalization({ shellSafe }) {
return shellSafe(
ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_NORMALIZATION
);
},
ricochet({ shell }) {
return shell(
ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_RICOCHET_ANGLE
);
},
shell_velocity({ shell }) {
return (
shell(ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_SPEED) / 100
);
},
shell_range({ shellSafe }) {
const maxDistance = shellSafe(
ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_MAX_DISTANCE
);
return maxDistance === null ? Infinity : maxDistance / 100;
},
shell_capacity({ shellSafe }) {
const count = shellSafe(
ShellUpgrageSingleChange_AttributeName.ATTRIBUTE_NAME_MAX_COUNT
);
return count === -1 || count === null ? Infinity : count;
},
aim_time({ attribute }) {
return attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_AIMING_TIME
);
},
speed_forward({ attribute }) {
return attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_FORWARD_MAX_SPEED
);
},
speed_backward({ attribute }) {
return attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_BACKWARD_MAX_SPEED
);
},
dispersion({ attribute, characteristic, state }) {
const base = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_DISPERSION_ANGLE
);
const movement = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_DISPERSION_FACTOR_VEHICLE_MOVEMENT
);
const vehicleRotation = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_DISPERSION_FACTOR_VEHICLE_ROTATION
);
const turretRotation = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_DISPERSION_FACTOR_TURRET_ROTATION
);
const afterShot = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_DISPERSION_FACTOR_AFTER_SHOT
);
const gunDamaged = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_DISPERSION_FACTOR_WHILE_GUN_DAMAGED
);
const maxSpeed = characteristic("speed_forward") as number;
return (
(state.isGunDamaged ? gunDamaged : 1) *
(base +
(state.speed / maxSpeed) * movement +
(state.isHullTraversing ? vehicleRotation : 0) +
(state.isTurretTraversing ? turretRotation : 0) +
(state.isShooting ? afterShot : 0))
);
},
gun_depression({ parameters, tank }) {
return -radToDeg(
applyPitchYawLimits(
-Math.PI / 2,
0,
parameters.pitch_limits_up,
parameters.pitch_limits_down
).pitch
);
},
gun_elevation({ parameters }) {
return radToDeg(
applyPitchYawLimits(
Math.PI / 2,
0,
parameters.pitch_limits_up,
parameters.pitch_limits_down
).pitch
);
},
engine_power({ attribute }) {
return attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_ENGINE_POWER
);
},
weight({ attribute }) {
return (
attribute(TankAttributeChange_AttributeName.ATTRIBUTE_NAME_MASS) / 1000
);
},
terrain_coefficient({ attribute, state }) {
let name: TankAttributeChange_AttributeName;
switch (state.terrainHardness) {
case TerrainHardness.Soft:
name =
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_TERRAIN_RESISTANCE_SOFT;
break;
case TerrainHardness.Medium:
name =
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_TERRAIN_RESISTANCE_MEDIUM;
break;
case TerrainHardness.Hard:
name =
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_TERRAIN_RESISTANCE_HARD;
break;
}
return attribute(name);
},
power_to_weight({ characteristic }) {
const power = characteristic("engine_power") as number;
const weight = characteristic("weight") as number;
const terrainCoefficient = characteristic("terrain_coefficient") as number;
return power / weight / terrainCoefficient;
},
turret_traverse_speed({ attribute }) {
return attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_TURRET_ROTATION_SPEED
);
},
hull_traverse_speed() {
return -Infinity;
},
health({ attribute }) {
return attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_MAX_HEALTH
);
},
fire_chance({ attribute }) {
return (
attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_FIRE_START_CHANCE
) * 100
);
},
view_range({ attribute }) {
return (
attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_CIRCULAR_VISION_RADIUS
) / 100
);
},
class({ tank }) {
return tank.tank!.tank_class;
},
camouflage({ attribute, characteristic, attributeSafe, state }) {
const tankClass = characteristic("class");
const base = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_CONCEALMENT_STILL
);
const moving =
tankClass === TankClass.LIGHT
? 0
: attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_CONCEALMENT_MOVING
);
const shooting = attribute(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_CONCEALMENT_FACTOR_AT_SHOT
);
if (
attributeSafe(
TankAttributeChange_AttributeName.ATTRIBUTE_NAME_CONCEALMENT_FIRE_PENALTY
)
) {
throw new Error("Fire penalty implemented! Code it in!!");
}
return (
100 *
base *
(1 + moving * state.speed) *
(state.isShooting ? shooting : 1)
);
},
height() {
return -Infinity;
},
length() {
return -Infinity;
},
volume() {
return -Infinity;
},
nation({ tank }) {
return tank.tank!.nation;
},
name({ tank }) {
return tank.tank!.name!.value;
},
tier({ tank }) {
return tank.tank!.tier_catalog_id;
},
type({ tank }) {
return tank.tank!.tank_type;
},
id({ id }) {
return id;
},
slug({ tank }) {
return tank.slug;
},
compensation({ tank }) {
return tank.compensation!.compensation?.currency_reward?.amount ?? null;
},
} satisfies Record<string, Characteristic>;
@@ -0,0 +1,138 @@
import {
Nation,
TankClass,
TankType,
} from "@protos/blitz_static_tank_component";
import {
GunType,
type CharacteristicName,
type CharacteristicOutput,
} from "./characteristics";
export enum BetterDirection {
Higher,
Lower,
}
export interface CharacteristicRenderConfig {
name: CharacteristicName;
decimals?: number;
units?: string;
render?: (output: CharacteristicOutput) => string;
}
type CharacteristicsOrder = {
group: string;
order: (
| CharacteristicRenderConfig
| {
toy: string;
}
)[];
}[];
export const characteristicsOrder: CharacteristicsOrder = [
{
group: "meta",
order: [
{ name: "name" },
{ name: "tier" },
{
name: "nation",
render(output) {
return Nation[output as Nation];
},
},
{
name: "class",
render(output) {
return TankClass[output as TankClass];
},
},
{
name: "type",
render(output) {
return TankType[output as TankType];
},
},
{ name: "compensation" },
{ name: "id" },
{ name: "slug" },
],
},
{
group: "firepower",
order: [
{
name: "gun_type",
render(output) {
return GunType[output as GunType];
},
},
{ name: "dpm", decimals: 0, units: "hp_min" },
{ name: "reload", decimals: 2, units: "s" },
{ name: "reloads", decimals: 2, units: "s" },
{ name: "damage", units: "hp" },
{ name: "module_damage", units: "hp" },
{ name: "penetration", units: "mm" },
{ name: "clip_size" },
{ name: "intra_clip", decimals: 2, units: "s" },
{ toy: "reload" },
{ name: "caliber", units: "mm" },
{ name: "normalization", units: "deg" },
{ name: "ricochet", units: "deg" },
{ toy: "ricochet" },
{ name: "shell_velocity", units: "m_s" },
{ name: "shell_range", units: "m" },
{ name: "shell_capacity" },
{ name: "aim_time", decimals: 1, units: "s" },
{ toy: "aim_time" },
{ name: "dispersion", decimals: 3, units: "m" },
{ name: "gun_depression", decimals: 0, units: "deg" },
{ name: "gun_elevation", decimals: 0, units: "deg" },
{ toy: "flexibility" },
],
},
{
group: "maneuverability",
order: [
{ name: "speed_forward", units: "km_h" },
{ name: "speed_backward", units: "km_h" },
{ name: "engine_power", units: "bhp" },
{ name: "weight", decimals: 1, units: "t" },
{ name: "terrain_coefficient" },
{ name: "power_to_weight", decimals: 1, units: "bhp_t" },
{ name: "hull_traverse_speed", units: "deg_s" },
{ name: "turret_traverse_speed", units: "deg_s" },
{ toy: "traverse" },
],
},
{
group: "survivability",
order: [
{ name: "health", units: "hp" },
{ name: "fire_chance", units: "%" },
{ name: "view_range", units: "m" },
{ toy: "view_range" },
{ name: "camouflage", decimals: 0, units: "%" },
{ name: "height", units: "m" },
{ name: "length", units: "m" },
{ name: "volume", units: "m" },
],
},
];
@@ -0,0 +1,106 @@
import {
ShellUpgrageSingleChange_AttributeName,
TankAttributeChange_AttributeName,
} from "@protos/blitz_static_tank_upgrade_single_stage";
import type { Tank } from "../../protos/tank";
import { aggregateStageParameters } from "./aggregateStageParameters";
import {
characteristics,
type CharacteristicName,
type CharacteristicOutput,
} from "./characteristics";
import type { TankState } from "./tankState";
export type ComputedCharacteristics = Record<
CharacteristicName,
CharacteristicOutput
>;
export function computeCharacteristics(
id: string,
tank: Tank,
state: TankState
) {
const parameters = aggregateStageParameters(
tank.tank!.base_stats!,
tank.tank!.upgrade_stages.slice(0, state.stage)
);
const computed: Partial<ComputedCharacteristics> = {};
function characteristic(name: CharacteristicName) {
if (name in computed) return computed[name] as CharacteristicOutput;
throw new Error(`${name} not computed yet`);
}
function attributeSafe(name: TankAttributeChange_AttributeName) {
const attribute = parameters.attributes.find(
(attribute) => attribute.attribute_name === name
);
return attribute ? attribute.value : null;
}
function attribute(name: TankAttributeChange_AttributeName) {
const attribute = attributeSafe(name);
if (attribute === null) {
throw new Error(
`Attribute ${TankAttributeChange_AttributeName[name]} (${name}) not found`
);
}
return attribute;
}
function shellSafe(name: ShellUpgrageSingleChange_AttributeName) {
const shell = parameters.shells_upgrades.find(
(shell) => shell.shell_id === state.shell
);
if (!shell) {
throw new Error(
`Shell ${ShellUpgrageSingleChange_AttributeName[name]} (${name}) not found`
);
}
const attribute = shell.changes.find(
(change) => change.attribute_name === name
);
return attribute ? attribute.value : null;
}
function shell(name: ShellUpgrageSingleChange_AttributeName) {
const attribute = shellSafe(name);
if (attribute === null) {
throw new Error(
`Shell attribute ${ShellUpgrageSingleChange_AttributeName[name]} (${name}) not found`
);
}
return attribute;
}
for (const _name in characteristics) {
const name = _name as CharacteristicName;
const value = characteristics[name]({
characteristic,
attribute,
attributeSafe,
shell,
shellSafe,
state,
tank,
parameters,
id,
});
computed[name] = value;
}
return {
characteristics: computed as ComputedCharacteristics,
parameters,
};
}
@@ -0,0 +1,16 @@
import type { TankCatalogComponent } from "@protos/blitz_static_tank_component";
import { TerrainHardness } from "./tankState";
export function createTankState(tank: TankCatalogComponent) {
return {
stage: tank.upgrade_stages.length,
shell: 0,
isGunDamaged: false,
isHullTraversing: false,
isShooting: false,
isTurretTraversing: false,
speed: 0,
terrainHardness: TerrainHardness.Hard,
isCaughtOnFire: false,
};
}
@@ -0,0 +1,29 @@
import type { CharacteristicOutput } from "./characteristics";
import type { CharacteristicRenderConfig } from "./characteristicsOrder";
export function renderCharacteristic(
characteristic: CharacteristicOutput,
config: CharacteristicRenderConfig
): string | null {
if (characteristic === null) return null;
if (config.render) return config.render(characteristic);
if (typeof characteristic === "number") {
if (Number.isFinite(characteristic)) {
if (config.decimals === undefined) {
return characteristic.toString();
}
return characteristic.toFixed(config.decimals);
}
return `${characteristic < 0 ? "-" : ""}∞`;
}
if (typeof characteristic === "string") {
return characteristic;
}
return characteristic.map((c) => renderCharacteristic(c, config)).join(", ");
}
@@ -0,0 +1,17 @@
export enum TerrainHardness {
Soft,
Medium,
Hard,
}
export interface TankState {
stage: number;
shell: number;
speed: number;
isHullTraversing: boolean;
isTurretTraversing: boolean;
isShooting: boolean;
isGunDamaged: boolean;
terrainHardness: TerrainHardness;
isCaughtOnFire: boolean;
}
@@ -0,0 +1,36 @@
import type { ButtonProps } from "@radix-ui/themes";
export interface Tool {
id: string;
strings?: string;
button: ButtonProps["color"];
significant?: boolean;
disabled?: boolean;
href?: string;
}
export const tools: Record<string, Tool> = {
tanks: {
id: "tanks",
strings: "tankopedia",
button: "purple",
significant: true,
},
avatars: {
id: "avatars",
button: "gold",
},
backgrounds: {
id: "backgrounds",
button: "amber",
},
api: {
id: "api",
disabled: true,
button: "bronze",
},
};
+19
View File
@@ -0,0 +1,19 @@
import { use } from "react";
const cache = new Map<string, Promise<unknown>>();
export function useAwait<Type>(
creator: () => Promise<Type>,
discriminator: string
) {
let promise;
if (cache.has(discriminator)) {
promise = cache.get(discriminator) as Promise<Type>;
} else {
promise = creator();
cache.set(discriminator, promise);
}
return use(promise);
}
@@ -0,0 +1,33 @@
---
import "@fontsource-variable/inter";
import BaseMeta from "../components/BaseMeta.astro";
import BaseStyles from "../components/BaseStyles.astro";
import ColorAlias from "../components/ColorAlias.astro";
import ColorScale from "../components/ColorScale.astro";
import Navbar from "../components/Navbar.astro";
import type { Color } from "../pages/styles/colors/[accent].css";
interface Props {
accent: Color;
noNavbar?: boolean;
}
const { accent, noNavbar } = Astro.props;
---
<html>
<head>
<BaseMeta />
<ColorScale color="mauve" />
<ColorScale color={accent} />
<ColorAlias color="mauve" alias="gray" />
<ColorAlias color={accent} alias="accent" />
<BaseStyles />
</head>
<body class="dark">
{!noNavbar && <Navbar />}
<slot />
</body>
</html>
@@ -0,0 +1,27 @@
import type { APIContext, GetStaticPaths } from "astro";
import { api } from "../../../core/api/dynamic";
export const getStaticPaths = (async () => {
const avatars = await api.avatars();
return avatars.map((avatar) => ({
params: { id: avatar.name },
}));
}) satisfies GetStaticPaths;
/**
* One day I will write documentation for this
*/
export async function GET({ params }: APIContext<never, { id: string }>) {
const avatar = await api.avatar(params.id);
const profileAvatar = avatar.ProfileAvatar();
if (import.meta.env.DEV) {
return Response.redirect(profileAvatar.avatar);
}
const response = await fetch(profileAvatar.avatar);
const buffer = await response.arrayBuffer();
return new Response(buffer);
}
@@ -0,0 +1,27 @@
import type { APIContext, GetStaticPaths } from "astro";
import { api } from "../../../core/api/dynamic";
export const getStaticPaths = (async () => {
const backgrounds = await api.backgrounds();
return backgrounds.map((avatar) => ({
params: { id: avatar.name },
}));
}) satisfies GetStaticPaths;
/**
* One day I will write documentation for this
*/
export async function GET({ params }: APIContext<never, { id: string }>) {
const avatar = await api.background(params.id);
const profileBackground = avatar.ProfileBackground();
if (import.meta.env.DEV) {
return Response.redirect(profileBackground.background);
}
const response = await fetch(profileBackground.background);
const buffer = await response.arrayBuffer();
return new Response(buffer);
}
@@ -0,0 +1,39 @@
import { TankClass, TankType } from "@blitzkit/core";
import { Nation } from "@protos/blitz_static_tank_component";
import type { APIContext, GetStaticPaths } from "astro";
import { GunType } from "../../../core/tankopedia/characteristics";
const enums = {
nation: Nation,
"tank-class": TankClass,
"tank-type": TankType,
"gun-type": GunType,
};
export const getStaticPaths = (() => {
return Object.keys(enums).map((name) => ({ params: { enum: name } }));
}) satisfies GetStaticPaths;
/**
* Enumerations used within BlitzKit, for nominal development reference only.
*
* DO NOT programmatically use this API as it is designed solely for human
* reference.
*
* DO NOT blindly copy entries as naming conventions vary. Most enums come
* directly from the game which uses a SCREAMING_SNAKE_CASE convention while
* BlitzKit uses PascalCase.
*/
export function GET({
params,
}: APIContext<never, { enum: keyof typeof enums }>) {
const map: Record<number, string> = {};
for (const key in enums[params.enum]) {
const value = enums[params.enum][key];
if (typeof value !== "string") continue;
map[key] = value;
}
return Response.json(map);
}
@@ -0,0 +1,58 @@
---
import "@radix-ui/colors/amber-dark.css";
import {
createProgram,
displayPartsToString,
forEachChild,
isFunctionDeclaration,
} from "typescript";
import BaseLayout from "../../layouts/BaseLayout.astro";
const root = `/src/pages/api`;
const globbed = import.meta.glob("/src/pages/api/**/*.ts", {
eager: true,
query: "?raw",
});
const paths: {
path: string;
documentation: string;
}[] = [];
for (const fullPath in globbed) {
const relativePath = `.${fullPath}`;
const path = fullPath.slice(root.length + 1, -3);
const program = createProgram([relativePath], {});
const source = program.getSourceFile(relativePath);
if (!source) throw new Error(`Could not find source for ${fullPath}`);
const checker = program.getTypeChecker();
const getter = forEachChild(source, (node) => {
if (!isFunctionDeclaration(node) || node.name?.text !== "GET") return;
return checker.getSymbolAtLocation(node.name);
});
const documentationComment = getter?.getDocumentationComment(checker);
if (!documentationComment) continue;
const documentation = displayPartsToString(documentationComment);
if (documentation.length === 0) continue;
paths.push({ path, documentation });
}
paths.sort((a, b) => a.path.localeCompare(b.path));
---
<BaseLayout accent="amber">
<h1>api</h1>
{
paths.map(({ path, documentation }) => (
<>
<h2>{path}</h2>
<pre>{documentation}</pre>
</>
))
}
</BaseLayout>
@@ -0,0 +1,12 @@
import type { APIContext } from "astro";
import { api } from "../../../core/api/dynamic";
export { getStaticPaths } from "./[id].pb";
/**
* Even Noah can't save these animals.
*/
export async function GET({ params }: APIContext<never, { id: string }>) {
const tank = await api.tank(params.id);
return Response.json(tank);
}
@@ -0,0 +1,16 @@
import type { APIContext, GetStaticPaths } from "astro";
import { api } from "../../../core/api/dynamic";
import { Tank } from "../../../protos/tank";
export const getStaticPaths = (async () => {
const { list } = await api.tankList();
return list.map(({ id }) => ({ params: { id } }));
}) satisfies GetStaticPaths;
/**
* Even Noah can't save these animals.
*/
export async function GET({ params }: APIContext<never, { id: string }>) {
const tank = await api.tank(params.id);
return new Response(Tank.encode(tank).finish());
}
@@ -0,0 +1,9 @@
import { api } from "../../../core/api/dynamic";
/**
* Literally all the tanks in one place lmao.
*/
export async function GET() {
const tanks = await api.tanks();
return Response.json(tanks);
}
@@ -0,0 +1,10 @@
import { api } from "../../../core/api/dynamic";
import { Tanks } from "../../../protos/tanks";
/**
* Literally all the tanks in one place lmao.
*/
export async function GET() {
const tanks = await api.tanks();
return new Response(Tanks.encode(tanks).finish());
}
@@ -0,0 +1,8 @@
import { characteristicsOrder } from "../../../core/tankopedia/characteristicsOrder";
/**
* The naked man fears no pickpocket.
*/
export function GET() {
return Response.json(characteristicsOrder);
}
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more