diff --git a/.claude/skills/add-strings/SKILL.md b/.claude/skills/add-strings/SKILL.md new file mode 100644 index 0000000..a891e78 --- /dev/null +++ b/.claude/skills/add-strings/SKILL.md @@ -0,0 +1,85 @@ +--- +name: add-strings +description: Add or change player-facing text in Series of Tubes: labels in the code, English in src/i18n/en.js, and every translation (site/i18n/*.js) kept complete. +--- + +# Adding or changing player-facing text + +Text is keyed by **label** ([docs/adr/0003-translations-by-label.md](../../../docs/adr/0003-translations-by-label.md)). +The code says `tr('pnis.delivery_2_to_6_weeks')`; the English is in `src/i18n/en.js`; Italian, Portuguese +and French are `site/i18n/it.js`, `pt.js`, `fr.js`. Every label the code uses needs English, and every +language needs every label. + +## In the code + +- `tr('area.label', {name})`: translate now and fill `{placeholders}`. +- `trn('area.label', n, vars)`: plurals. One label, whose entries are `{"one": "…", "other": "…"}`; + `{n}` is filled in for you. +- `N_('area.label')`: a label kept in a table or a save and translated where it is shown with + `tr(x)`. Anything stored in `S` must be an `N_()` label (or an index), never translated text and never + a label written any other way: the build shortens every label it sees in `tr()`/`trn()` to an id that + changes between releases, and keeps the `N_()` ones whole. +- The label is always a string literal, the first argument of `tr`/`trn`/`N_`. A label anywhere else + (`const x='pnis.ready'`) is an error in `npm run i18n:check`. +- Static HTML in `src/index.html`: `data-i18n="area.label"` on the element, with its English inside it; + `data-i18n-aria-label="…"` and `data-i18n-title="…"` next to those attributes. +- Keep HTML (``, `
`, ``) and `{placeholders}` identical in every language. +- Don't build sentences from translated fragments; translate whole sentences. + +## Naming a label + +`area.some_words`: the area is the file or topic it is shown in (`pnis`, `own_cable`, `dashboard`, +`page` for the static markup), or `common` for text used all over and short everyday words +(`common.close`, `common.customers`). The words are the first few words of the English, lower case, +`_` between them: `pnis.ready_in_about_n_days`. Labels are only for finding things; players never see +them. Reuse an existing label when the text and the meaning are the same (`grep -n '"Close"' src/i18n/en.js`). + +## In the dictionaries + +Every dictionary is one entry per line, **sorted by label**, so new text from different pull requests +lands on different lines. Don't edit them by hand; the script writes English and translations together: + +```bash +cat > /tmp/strings.json <<'JSON' +{ + "en": { "pnis.ready_in_about_n_days": "Ready in about {n} days", + "save.n_pop": { "one": "{n} POP", "other": "{n} POPs" } }, + "it": { "pnis.ready_in_about_n_days": "Pronto tra circa {n} giorni", + "save.n_pop": { "one": "{n} POP", "other": "{n} POP" } }, + "pt": { "pnis.ready_in_about_n_days": "Pronto em cerca de {n} dias" }, + "fr": { "pnis.ready_in_about_n_days": "Prêt dans environ {n} jours" } +} +JSON +node scripts/i18n-add.js /tmp/strings.json # a string or {one, other} sets an entry, null removes it +node scripts/i18n-add.js --rename old.label new.label # in every dictionary and everywhere in src/ +``` + +- **Changing English wording** (a typo, a clearer phrase, same meaning): change only the English. The + translations stay right. +- **Changing the meaning**: give the text a new label (`--rename`, then update the English and every + translation), so no language keeps a translation that now says something else. +- **Removing text**: `null` under `"en"` removes the label from every dictionary. + +`npm run i18n:fix` re-sorts a dictionary that got out of order (a hand edit, a merge). + +## Italian style + +Natural, friendly Italian, informal "tu". Keep networking terms that Italian engineers +use in English (peering, transit, router, POP, PNI, LAG, dark fiber). Translate puns +into an Italian joke when one fits; otherwise keep the pun name and translate the rest. + +## German style + +Natural, friendly German, informal "du". Networking terms that German engineers say in English stay +English (Peering, Transit, Dark Fiber, Wave, Port, Router, POP, IX, Exchange, Backbone, Link, Traffic, +Route Server, Line System, LAG, PNI, Fabric, Scrubbing), but plain "fiber" is "Glasfaser", +"fiber pair" is "Faserpaar" and "eyeballs" are always "Privatkunden". "/mo" is "/Monat", "{n}d" is +"{n} T.", money keeps the game's `$100k` style, quotes are „…“. Translate puns into a German joke +when one fits; otherwise keep the pun name. + +## Check + +```bash +node scripts/i18n-check.js # en.js: 0 problems; each language: 0 missing, 0 unused, 0 broken +npm test # includes tests/i18n.test.js (every screen in every language) and the shipped page +``` diff --git a/.claude/skills/edit-the-game/SKILL.md b/.claude/skills/edit-the-game/SKILL.md new file mode 100644 index 0000000..aca2564 --- /dev/null +++ b/.claude/skills/edit-the-game/SKILL.md @@ -0,0 +1,79 @@ +--- +name: edit-the-game +description: Find, change and add game code in Series of Tubes, which lives in many small files under src/ that the build joins into one page. Use for any feature, fix or refactor in the game itself (anything in src/). +--- + +# Editing the game + +The game's source is `src/`. The build (`scripts/lib/page.js`) pastes the files together, in path order, +into one `index.html` with one inline `` at the start of a line. +File names are `NN-lower-case.js` / `.css`; `tests/build.test.js` checks both. + +## Still the same rules + +Everything in CLAUDE.md applies unchanged: translate every string (`add-strings`), sanitize saves, +phones first, a test with every change (`write-tests`), performance shown against `main` +(`performance`), hosting on GitHub Pages only (`github-pages`), a CHANGELOG bullet for players. +The CHANGELOG is the one file every change touches; a conflict there is expected: keep both bullets. diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md new file mode 100644 index 0000000..a5de18c --- /dev/null +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -0,0 +1,102 @@ +--- +name: gameplay-rules +description: The design rules of Series of Tubes, each with an id and the test that enforces it. Use whenever you add or change cities, countries, networks (NETS, upstreams, traffic shares, presence), cables, exchanges, data centers, customers, scenarios, puzzles, presets or rules, balance numbers or progression, and before committing any such change. +--- + +# Gameplay rules + +These are what the game promises, held up by `tests/gameplay-rules.test.js` (one `test()` per id, on the live +`CITIES`, `NETS`, `CABLES`, `SCN`, `PZ`, `PRESETS`…). Each rule is true of the intended design. + +## Procedure + +1. Changing anything above? Run `npm test -- tests/gameplay-rules.test.js` (under a minute) before committing. + Changing orbit prices, crusts, incidents or orbit customers? Also run `npm test -- tests/pie-balance.test.js` (O7's + game-loop half, about a minute). +2. A failure names what breaks the rule and how to fix it. Fix the data or the code. +3. Only when real life really is different, add an entry to `EXCEPTIONS` in the test (keyed by rule id, sorted, with + its reason in plain words). Never delete or loosen a check to make it pass. A stale exception fails too. +4. A new rule gets an id in the right section here, one line, a why, and its own `test('ID: …')`. + +## World + +| Id | Rule | Why | +| --- | --- | --- | +| W1 | Every city has a country code (`cc`, ISO 3166-1 alpha-2; territories have their own: PR, GU, RE, MQ, CW…), a region, a landmass and coordinates. | Borders, prices and the eyeball rule all hang off the country. | +| W2 | Every country on the map has at least two consumer networks of its own: an eyeball network, or a Tier 1 or Tier 2 incumbent that sells to homes, whose home markets (`cc` on the network) include that country and which has a PoP there. | Real countries have competing local ISPs, and peering locally is half the game. Add real operators in `src/game/30-networks/32-homegrown-eyeballs.js`. | +| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, reach it through a pie dish, or rent a satellite circuit from a teleport; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. | +| W4 | Cable pairs join two distinct real cities, have a length, and cable ids are unique. | Broken landings break routing and the own-cable planner. | +| W5 | A city alone on its landmass has a cable or a beach to land one. | Islands are reachable. | +| W6 | Every island Wi-Fi zone (`WISP`, #83) hangs off a satellite city (`satRemote`) within 1,000 km of it, seen together with it by a GEO bird; its pool is 3 to 12 G of homes; its spur is at most 1,500 km, or there is none (`km:0`); ids are sorted. | A zone is the outer islands of the city they look to, reachable from the first teleport; smaller ones never pay, and pie terminals serve them. | + +## Networks + +| Id | Rule | Why | +| --- | --- | --- | +| N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. | +| N2 | Names are puns: no network, cable, exchange, data center, router, optic, satellite or satellite operator, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. | +| N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. | +| N4 | No upstream cycles. | Cones must be trees, not loops. | +| N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. | +| N6 | Every network has a type, a peering policy (selective ones state `minIx`/`minPni`), a colour and a translated blurb; carriers have a price. | Panels and the peering rules read them. | +| N7 | PoPs are real, distinct cities; exchange ports only where the city has an exchange and the network has a PoP. | Presence follows PeeringDB-style reality. | +| N8 | A POP's traffic to the networks that sell to homes (`cc`) goes mostly to those whose users live near it: at home above the world share, on other continents below (`locSh()`, `45-home-markets.js`). Only that split moves: a city's total and every network without home markets keep their shares. | People mostly talk to people near them, and peering with an eyeball where its users are must beat hauling its traffic to two cities (#48). | + +## Modes and rules + +| Id | Rule | Why | +| --- | --- | --- | +| M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. | +| M2 | Presets are ordered: Best Effort never harsher than Change Freeze, Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). Only Best Effort mends sea cuts without ships, skips conferences, rescues instead of game over, has patient customers and instant PNIs. | The names promise it. | +| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4, CGNAT and IPv6-only homes behind NAT64 (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | +| M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. | +| M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. | +| M6 | A Normal game picks its charter once, when it starts (sandbox, puzzles and scenarios never do). A charter changes what you set out to do, never what things cost: the Cable broker gets glass (fiber, line systems, optics, own subsea cables and the routers to light them) from day one at the prices everyone pays at the top level, and everything else by level. | Same prices and rules for every charter (#300). | + +## Content + +| Id | Rule | Why | +| --- | --- | --- | +| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. | +| C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. | +| C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. | +| C4 | Every Architect run, handmade (`REF` in `tests/architect.test.js`) or weekly (`ref` in its file, `scripts/weekly-architect.js --check`), has a reference build that passes every brief's chaos monkey review and earns three stars; every weekly brief takes at least one change (a tube, a bigger tube, a move), and later briefs' cities stay hidden until they come. | A run you cannot finish, or a brief that asks for nothing, is not a puzzle; knowing the next brief makes it a chore. | + +## Fun and fairness + +| Id | Rule | Why | +| --- | --- | --- | +| F1 | A new network gets a gentle start (counted from the network's own first day; hardware prices hold for the calendar's first 180 days, see F11): no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | New players learn before they get punished. | +| F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. | +| F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. | +| F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. | +| F5 | Capacity you rent to other carriers never outgrows the route's market: the capacity market sells a listing over time as carriers between the two cities want it, never past what they want that day (both cities' eyeballs, a landing town counting the big city it serves, grown about 15% a year up to 8 times, and at most 2.5 times its usual size on its hottest day), and a random offer never past what the eyeballs alone support. | Rent that scales with your own glass and not with demand is a money machine (#203); a market that never moves or grows makes no decisions. | +| F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). | +| F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). | +| F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. | +| F9 | A strict latency contract (`BIZ_T.lowlat`, #137) comes only from customer level 7, is 1.6T or 3.2T and never grows past 3.2T, has a latency limit something you can build meets (`latMaxOf`, as trading links), pays more per Gbps than any other big circuit on the same route even with all their extras, and once its 15-day grace is over credits a day's fee and loses patience faster for every day over its limit. | Real low-latency routes sell at a premium for guaranteed milliseconds and pay service credits when they miss; the cap keeps one contract from carrying a level. | +| F10 | Growth goes sideways, plus one paid way up: a PNI bundles eight members per router at its POP, up to 32 (`pniLagMax()`); transit, exchange and fabric LAGs stay at eight (`LAG_MAX`). Giant AI circuits land at campuses (`MEGA`) in at least 30 metros, no metro more than two, picked less often where giant circuits already crowd the city. | Raising caps only moves the wall; a fatter PNI costs a router (its price and its port slots), and the late game's demand spreads over many metros as real AI and cloud campuses do (#61, #323). | +| F11 | A network that joins a server session after its first 180 days starts on the session's date with F1's gentle start, the charter and the tutorial counted from its own first day, a starting-cash top-up as large as the rise in hardware prices (START_CASH × (hwTrend − 1), at most $60k), and its first 365 days of home broadband income matched (after wholesale cuts, outside investors' share); the market stays on the session's date. | One market for everyone, and a friend who joins late still gets a fair start. | +| F12 | Island Wi-Fi (#83), on a zone's own books at full take-up in era 1 (its homes at island prices less the towers' upkeep and the backhaul rent; the teleport, tracking antennas and a Starblink gateway are shared and left out), makes money on at least one way in; a spur earns more than any satellite option, MEO at least as much as GEO and LEO at least as much as MEO where both reach; spurs up to 250 km pay back within 5 years against the best GEO or MEO stage, up to 1,000 km within 10. | The ladder (GEO, then MEO or LEO, then your own cable) must be worth climbing, and its first rung must not lose money; the longest spurs are a choice, not a given. | + +## DDoS + +| Id | Rule | Why | +| --- | --- | --- | +| D1 | Attack sizes come from the world, never from your network: a heavy tail (median near 9 G, one in a hundred over 650 G) scaled by the era, capped at the era's record, and for the first 180 days (or with one POP) never more than twice your biggest port. Ten times the subscribers means the same attacks. | Sizes that grew with the network made every late-game flood larger than the internet's record (#242). | +| D2 | A flood enters on every port the internet reaches you on, by each network's share, and a port carries only what fits: everyone on a full port loses the same share. | Real floods are spread by geography; one fat port at a single POP is the weak spot (#242). | +| D3 | Only upstream tools (RTBH, clean pipe) and an engaged scrubbing center keep a flood off your ports. Flowspec acts on the ingress router, after the port, within that router's own rule budget. | Flowspec protects customers, not the external connections; TCAM is finite. | +| D4 | RTBH costs only the target: it goes dark (and its mood drops once), everyone else is saved, and the attack counts as sacrificed, not held. | RTBH is the tool that saves the network and is bad for that one customer, so it must be a real choice. | + +## Orbit (Pie in the Sky, `docs/plans/pie-in-the-sky.md`) + +| Id | Rule | Why | +| --- | --- | --- | +| O1 | The rocket company unlocks only on the Tier 1 win of a save started on its version (`S.pieV>=1`, set by `newGame()`; a save without it loads as 0), or from day 0 with open gates (sandbox). Never in puzzles, the Architect or scenarios. Losing Tier 1 keeps everything flying but builds nothing new. | An endgame for people who earned it; old won saves must not change under their players. | +| O2 | A crust under 40% coverage carries nothing; from 40% a half-baked crust carries a share that grows to all of its capacity at 60% (a slope, not a cliff), and orbit never carries more than the pie dishes' antennas (x rain, jamming): terminals and sky paths share each dish. | Satellites are not magic bandwidth; the ground segment is the bottleneck, as in real life. | +| O3 | A cut-off pie dish (its POP on an island the backbone does not reach) carries only its own POP's traffic (backhaul, to a landing dish on the backbone) and local terminals, never transit between other cities: no POP on the backbone routes through it. Backhaul is small (the dish's antennas, the landing dish's and the crust's room) and pays the orbit's latency. | Orbit extends your network to a town no cable reaches; it does not replace building one, and laying fiber stays the real fix. | +| O4 | Through space with lasers, light travels at c in vacuum (about 1.47 times glass), up and down at the shell's height; orbit never carries traffic between cities under 3,000 km apart and only latency-routed circuits fly: IP traffic, bulk and scenic circuits stay on fiber. | Real constellations win only on long routes, and their capacity is small. | +| O5 | Launches fail only with chaos on (`rule('chaos')`), and never in the first 90 days after the unlock; heavy test flights explode by design, not by chance. Orbit incidents and geopolitical spats (`pieChaos()`) follow the same rule. | Like F1: learn the thing before it punishes you. | +| O7 | A fresh Tier 1 cannot afford a full Shortcrust from its first year's money: even a big network's yearly profit plus the largest loan a bank would offer (and the Ex-Im Pie Bank's most) stays below the cheapest full build (`pieFullCost('short')`). And a full lasered Shortcrust, played through the game loop on the big-network save by a sensible policy (reusable rockets, two pads, no launches past the crust's size except replacements, safe mode in storms, dishes grown with demand at well-served POPs, every orbit offer signed), pays back on its own books (`S.pie.book`: every launch, replacement, dish, licence and running cost against orbit income) in 5 to 10 years, never sooner; government money (the Rural Digital Pie Fund, Pitcairn's satellite grant) brings that forward by at most two years, never under four (`tests/pie-balance.test.js`; `PIE_BALANCE_YEARS=10` prints the long run). | Obscenely expensive is the joke and the goal; a constellation in year one would be a cheat code. | +| O8 | Rented LEO (Starblink, #83) reaches only within `SAT_ORB.leo.km` of a gateway under its shell (`SAT_ORB.leo.lat`) at a POP on your fiber (the mainland, or an island with a lit wired link or transit); once a crust of your own carries traffic it sells nothing new (no gateway, circuit or growth), while circuits already rented keep running; and every size costs more per Gbps than any subsea wave over its whole reach. | A bent pipe is regional; the rented tier must not undercut your own constellation; and a cable stays the better buy wherever one can go. | + diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md new file mode 100644 index 0000000..52010f0 --- /dev/null +++ b/.claude/skills/github-pages/SKILL.md @@ -0,0 +1,70 @@ +--- +name: github-pages +description: Series of Tubes is hosted on GitHub Pages and nowhere else, non-negotiably. Use before any change to hosting, deploys, the build output, caching, the service worker, new runtime requests or anything that would need a server, and whenever someone suggests another host. +--- + +# GitHub Pages, always + +Series of Tubes is served by GitHub Pages at https://seriesoftub.es and **only** there. This is settled +([docs/adr/0001-github-pages-only.md](../../../docs/adr/0001-github-pages-only.md)) and not up for +discussion: do not propose, prepare or "keep the door open" for another host, a CDN in front, a +backend or server-side rendering, even when asked to evaluate options. If a feature seems to need +one, redesign the feature. + +## What that means for a change + +- **The output is static files.** `npm run build` writes `_site/`: the assembled page, `site/`'s files, + `version.json`. No server code, no runtime secrets: everything there is public. +- **No HTTP headers, redirects or rewrites.** Pages ignores `_headers`, `_redirects`, `.htaccess`, + `vercel.json`, `netlify.toml`. Need a policy? Use a `` tag. Need a different URL? Add a + static file there. +- **Caching is Pages' (short, the same for every file) plus the service worker's.** Offline play and + updates are `site/sw.js`'s job; its cache name carries the version. When you add a file the game + needs offline, add it to `CORE` there. +- **Same origin.** The page, dictionaries, icons and data come from seriesoftub.es. Do not add CDN + libraries or third-party APIs the game needs to work; the web fonts and the analytics counter are + the only exceptions and the game runs without them. +- **More files are fine, from the same origin.** Pages serves many small files well over HTTP/2. + Still: the game page itself stays one assembled `index.html` (see + [ADR 0002](../../../docs/adr/0002-one-page-assembled-at-build.md)), and anything the first frame + needs must not add a round trip. +- **Limits:** about 1 GB for the whole site, 100 MB per file. +- **Paths:** the site lives at the domain root (`site/CNAME`), so `/` paths are fine; unknown paths get + `404.html`. +- **Local tools are not hosting.** `npm run dev` and the MCP server (`npm run mcp`, also over `--http`) + run on a developer's own machine against a checkout; nothing they serve is deployed, and the game + never depends on them. Their code stays out of `_site/` (`src/agent/` is development-only, see + `docs/adr/0004-dev-only-code.md`). +- **The container image is a tool too.** `docker/` packages those tools; `docker.yml` publishes it to GHCR for releases + (version tags only, no `latest`) and never to Pages. Someone may run its development server where they like; that is + not a host of the game, and the game never depends on it. + +## How it deploys + +Only releases deploy. Bumping `version` in `package.json` on `main` runs `auto-release.yml`, which tags, +publishes the GitHub release and starts `release.yml`: test, `REQUIRE_NOTES=1 npm run build`, +`actions/upload-pages-artifact` with `./_site`, `actions/deploy-pages`. That job is the only one with +`pages: write`. Pushes to `main` and pull requests build but never deploy. The `release` skill has the +steps. + +**The one exception: the weekly puzzle.** Every Sunday at 03:37 UTC `weekly-puzzle.yml` commits the new +`site/puzzles/weekly/.json` to `main` (data only, no version bump) and starts `release.yml` for the **live +release tag** with `weekly=true`. That run rebuilds exactly the live release, with every weekly file from `main` +added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in the same `pages` concurrency group. +Players get no update banner (the version does not change). Every release build also copies all weekly files from +`main`, so a release never drops a published week, and regenerates (in the build, deterministically) any week +not over yet that the release's prices no longer fit. Weekly files are plain JSON the game fetches only when the +Puzzles list opens and never trusts; the service worker serves them network-first. The weekly scenario rides along in +the same run: `scripts/weekly-scenario.js` writes `site/scenarios/weekly/.json` (fetched when the Scenarios list +opens), committed and deployed with the puzzle, never by a second workflow. See `docs/ARCHITECTURE.md`. + +## Before you hand back a change that touches the build, deploy or loading + +```bash +npm run build && npm run serve # the production build, served as static files +npm test -- tests/pages.test.js # static-only, all references resolve, Pages-only deploy +``` + +`tests/pages.test.js` fails on host configuration files, files over the limits, local references +that do not exist in `_site/`, scripts loaded from other origins, and any workflow that deploys +anywhere else. Do not weaken it to make a change pass; change the change. diff --git a/.claude/skills/performance/SKILL.md b/.claude/skills/performance/SKILL.md new file mode 100644 index 0000000..c071f46 --- /dev/null +++ b/.claude/skills/performance/SKILL.md @@ -0,0 +1,104 @@ +--- +name: performance +description: Measure and demonstrate the performance of every Series of Tubes change on a very large network, compare it with main, and report the numbers. +--- + +# Performance is always demonstrated + +Every change to the game (anything in `src/` or `site/`) shows its performance on a very large network, +compared with `main`, before it is merged or released. A speed claim without numbers does not +count, and neither does "it feels fine on my small game". Most players who complain about lag +have huge late-game networks, and most of them are on phones. + +## Measure + +```bash +npm run perf -- --base-ref origin/main # headless only, a few minutes +npm run perf -- --base-ref origin/main --browser # plus real Chromium, desktop and phone (what CI runs) +``` + +`--base-ref` assembles that commit's page with its own scripts (`node scripts/lib/page.js --ref REF`; +for commits from before the split it reads their `site/index.html`). `--base FILE` takes a built page +instead. The head is always this checkout's `src/`, assembled the way the build does it. + +`scripts/perf-bench.js` loads `tests/fixtures/big-network.json` (about 100 POPs, 150 links, +950 PNIs, 830 cache boxes, 110 IX ports, 170 customers) into the base and into this checkout and +times them in alternating turns, 15 runs each. It prints one table per environment: + +- **Headless (jsdom):** our JavaScript. The most stable numbers for routing and simulation, but jsdom's + DOM is about 30× slower than a browser's and it has no layout, so its panel and dashboard rows say + little about what players feel. +- **Chromium, desktop** and **Chromium, phone** (`--browser`, `scripts/perf-browser.js`): the real DOM, + layout and canvas. The phone is 390×844 at 3× pixel density with the CPU slowed down 4×, about a + mid-range Android. Each version runs in its own browser. Use these rows for anything in the interface, + and to catch forced layouts (reading `scrollTop`, `offsetHeight` and friends right after changing the + DOM), which jsdom cannot see at all. + Browsers leave layout and canvas drawing for the next frame, so each timed run ends by forcing both; + without that, DOM and map work would look free. For the same reason, a profile that puts a lot of + time on a line reading `scrollTop` is usually showing layout that has to happen anyway, not waste: + check with the benchmark before "fixing" it. + +Each table has these rows: + +- Routing: `compute()` +- One game day: `dayTick()` +- An action: `after()` +- Side panel and left list +- NOC dashboard tabs +- Map at three zoom levels + +and it says whether both versions route the save's traffic identically. + +`--browser` needs Chromium: a local `playwright` with its browser works as is; otherwise +`playwright-core` (a dev dependency, installed by `npm ci`) drives the Chrome in `PERF_CHROME` or +`--chrome PATH`. CI uses the Chrome that ships with GitHub's Ubuntu runners. + +Without `--base` it just times this checkout. `--runs N`, `--md FILE`, `--json FILE` and +`--summary FILE` are there for CI and for digging. + +`--save FILE` swaps the fixture for another save, such as a laggy save from a bug report. Both a plain +save and a file from the in-game menu's Export save work: + +```bash +npm run perf -- --save ~/Downloads/series-of-tubes-save.json --base-ref origin/main +``` + +Routing speed-ups must also keep the two equivalence tests green: `tests/speed.test.js` (the fast +path against the same code with its shortcuts switched off) and `tests/routing-reference.test.js` +(the indexed exit choice against a plain scan of every exit, across preferences, RouteScript, +incidents and failures). + +## Demonstrate + +- **Every pull request**: the Performance workflow runs the same comparison and posts the table as a + comment on the PR (updated on every push). Read it before merging. Locally, paste the table into + the PR description or the commit summary you report. +- **Everything you hand back to Frederic** that touched `src/` or `site/`: include the table, or at least the + rows that moved, in your summary. Say plainly when something got slower. +- **Before a release**: compare the release against the previous tag + (`npm run perf -- --base-ref v`) and mention notable changes. + +## Read the table + +- Shared machines (CI runners, cloud sandboxes) swing a single run by ±30% on identical code, and no + timing method gets around it: CPU time is as noisy as wall time there. So a row only gets a verdict + when it moved by 15% or more **and** the samples say it is real: p < 0.01 in a Mann–Whitney U test + (`scripts/perf-stats.js`), and more than 2 ms (8 ms on the phone). Otherwise it shows ≈, whatever + the percentage. The `p` column says how sure each row is. +- A big percentage with ≈ means "could be noise". If it matters for the change, run again (or with + `--runs 25`) and report both runs; do not report a single noisy number as a finding. +- ⚠️ slower (15% or more) or 🔴 slower (50% or more) needs a reason in the PR, or a fix. A new + feature may cost time; a refactor or a fix should not. +- "Routing results differ" is expected when a change is meant to change gameplay (new cities, + balance, routing rules), and a bug when it only promises to be faster. +- Headless Chromium draws the canvas in software, real phones usually on the GPU, so map rows in the + Chromium tables overstate drawing cost. For drawing changes, also look at the game on a phone. +- Absolute numbers depend on the machine. Compare base and head from the same run, never numbers + from different runs or machines. + +## Keeping the fixture useful + +The save loads through `migrate()` like any player's save, so new state gets its defaults. Only +regenerate it (`node scripts/perf-fixture.js`, several minutes) when the save format changes in a +way old saves cannot load, or the game grows new heavy systems the save does not exercise. Say in +the commit that the baseline changed, because numbers before and after are no longer comparable. diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md new file mode 100644 index 0000000..157d3c1 --- /dev/null +++ b/.claude/skills/release/SKILL.md @@ -0,0 +1,109 @@ +--- +name: release +description: Cut and ship a Series of Tubes release (patch or minor) from main via the auto-release workflow. +--- + +# Releasing Series of Tubes + +Bumping `version` in `package.json` on `main` is the release button. CI tests the push +as usual; when it passes, `auto-release.yml` (which runs after every CI on `main`) sees +the new version, tags `v` on the commit CI tested, publishes a GitHub release with +that version's CHANGELOG section as notes, and dispatches `release.yml`, which builds +`_site/` (`npm run build`: the page assembled from `src/` plus `site/`) and deploys it +to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the +`github-pages` skill. + +## Weekly puzzles are not releases + +`weekly-puzzle.yml` publishes a new puzzle every Sunday morning without a release: it commits the JSON under +`site/puzzles/weekly/` to `main` and redeploys the live tag through `release.yml` (`weekly=true`). Never bump the +version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly-puzzle.js --key 2026-W45 --force`, +`node scripts/weekly-puzzle.js --check`, commit to `main`, then run the "Weekly puzzle" workflow (or +`gh workflow run release.yml --ref -f tag= -f weekly=true`). A release includes every weekly +file on `main` when it builds. + +The weekly scenario (`site/scenarios/weekly/`, `scripts/weekly-scenario.js`) ships in the same run and the same way: +`--key`, `--force` and `--check` work alike. Its `--check` replays each week not over yet with the reference plan in +the file; a new par is just written, a week the reference no longer wins is regenerated with `rev` + 1. + +**Prices change, weeks follow.** `--check` re-solves every week not over yet with the game it runs; a week whose +budget no longer verifies is regenerated deterministically (the same puzzle with a new budget if that works, else a +fresh one for the same key) with `rev` + 1, which resets players' stars for that week only. Past weeks are left alone +unless the game rejects them. `release.yml` runs it before the tests on every deploy and fails only if a week cannot be +regenerated. A change to prices, cables or cities fails `npm test` until you run `node scripts/weekly-puzzle.js --check` +and commit the regenerated files with it (and `node scripts/weekly-scenario.js --check` for the scenarios). + +## Only release when Frederic says so + +Never bump the version on your own. Finished work is committed and pushed with its +bullets under `## [Unreleased]`, and you say it is ready to ship. A release happens only +when Frederic explicitly asks for one ("release", "ship it"), and then it includes +everything under `## [Unreleased]`. Docs, skills, CI, issue templates, tests and +refactors are just pushed and never need a release. + +## At most one release per hour + +Players get an update banner and a "What's new" window for every release, so ship at +most one release an hour. Before bumping, check when the last one went out: + +```bash +gh api repos/fjaeckel/seriesoftubes/releases/latest --jq '.tag_name+" "+.published_at' +``` + +- **Less than 60 minutes ago:** even when asked, say so and suggest waiting until the hour + is up; release only if Frederic still wants it now. +- **60 minutes or more:** release everything under `## [Unreleased]` together, as one + version. +- **Live game broken for players** (it won't start, saves are lost, a phone can't get + past a screen): tell Frederic right away and propose a hotfix release; still wait for + his go. + +## Pick the version + +- Several changes batched together: use the biggest one (any feature → minor). +- Patch (`x.y.Z`): fixes, small tweaks, wording, icons. +- Minor (`x.Y.0`): new features or content. + +## Steps + +1. Don't run the test suite, the game or benchmarks before a release: CI tests the + version bump (a red CI releases nothing), and the Performance workflow benchmarks it. Just + check that the latest CI run on `main` is green (`gh run list --repo fjaeckel/seriesoftubes --limit 4`). +2. In `CHANGELOG.md`, move the bullets from `## [Unreleased]` into a new section + right below it: `## [x.y.z] — YYYY-MM-DD` (em dash, today's date). Keep an empty + `## [Unreleased]` heading above it. The build fails if the section has no bullets. +3. Bump the version in **both** files: + - `package.json` → `"version"` + - `package-lock.json` → top-level `"version"` and `packages[""].version` +4. (Nothing to run here: the workflow tests the release before it tags it.) +5. Commit on `main` as Frederic, with no attribution trailers: + ```bash + git -c user.name="Frederic Jung" -c user.email="frederic@jc-ix.net" commit \ + --author="Frederic Jung " -m "Short summary (x.y.z)" + git push origin main + ``` +6. Watch the workflows until all three finish (CI, then Auto-release, then Release to GitHub Pages): + ```bash + gh run list --repo fjaeckel/seriesoftubes --limit 4 + gh run watch --repo fjaeckel/seriesoftubes + ``` +7. Confirm it is live: `https://seriesoftub.es/version.json` shows the new version. + +## Release notes rules + +- The first sentence of each bullet is all the in-app "What's new" shows (at most five + bullets; longer notes get a link to the full GitHub release). Make that sentence + stand on its own: "Tier 1 networks can lay their own subsea cable (#22)." Detail goes + after it. +- Written for players, in plain English. One bullet per change, issue numbers like `(#37)`. +- Never mention hidden easter eggs or explain jokes. +- No internal function names. + +## If something fails + +- "not newer than the latest release": the version was not bumped, or was bumped + backwards. +- "CHANGELOG.md has no notes under ## [x.y.z]": the heading doesn't match the version + exactly or has no bullets. +- Tests fail in the workflow but pass locally: look for unseeded randomness in a test. +- Fix forward with a new patch version; never move or delete an existing tag. diff --git a/.claude/skills/write-tests/SKILL.md b/.claude/skills/write-tests/SKILL.md new file mode 100644 index 0000000..33f7aa9 --- /dev/null +++ b/.claude/skills/write-tests/SKILL.md @@ -0,0 +1,71 @@ +--- +name: write-tests +description: Write deterministic jsdom tests for Series of Tubes features and fixes in tests/*.test.js. +--- + +# Writing tests + +Tests use `node:test` and `tests/harness.js`, which assembles the game page from `src/` +(once per test file) and loads it in jsdom with the animation loop off, a seeded `Math.random` and a recording fake canvas. +Code runs inside the page through `ev()`. `load()` is the page players get; tests of the agent facade +(`src/agent/`, `window.TUBES`) ask for the development page with `load({ agent: true })`. + +## Pattern + +```js +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('what the player should see happen', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()"); + assert.ok(ev("R.served") > 0); + assert.deepEqual(errors, []); // always: no page errors +}); +``` + +## Where to put it + +Pick the suite by topic: `game` (core loop), `build`, `persist` (save/import/migrate), +`services` (customers), `peering`, `issues` (GitHub issue regressions, name them +`#NN …`), `regions`, `modes` (scenarios, sandbox, weekly), `i18n`, `pages` (hosting). +For a new feature, prefer a new file named after it (`tests/route-servers.test.js`): every +`tests/*.test.js` runs on its own (`scripts/test.js`), and a file of your own never conflicts +with someone else's tests. Appending to the big suites (`issues`, `regions`) is where +pull requests collide. Run one file with `npm test -- tests/route-servers.test.js`. + +## Rules + +- **Text in assertions:** match what the player sees (`/Ready in about 3 days/`), or compare with + `ev("tr('pnis.ready_in_about_n_days',{n:3})")`. Tests run the source page, where labels are readable; + the shipped page (ids instead of labels) is covered by `tests/pages.test.js`. +- **Deterministic.** Never rely on luck. Use the default seed, `window.__reseed(n)`, + or set state directly (`S.day=…`, `S.ev.x=…`). +- **Force a specific random failure or event** by patching the picker: + ```js + ev("runNow(eval('('+failureRun.toString().replace('if(only)type=only;',\"type='crash';\")+')')())"); + ``` + `failureRun()` is a generator (its yield is the routing): play it with `runNow()`. Check the current source for the + exact line first (`grep -rn "function\* failureRun" src/game`); it may differ. Or simply `fireFailure('crash')`. +- **Drive the game through `ACT`** like a player would, then `compute()` or `dayTick()`. +- **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through + `parseSave()`/`migrate()`, and test that an *old* save without the new field still loads. +- **UI:** render with `renderAll()` and query `dom.window.document`; check phone + layouts by setting `window.innerWidth = 390` before rendering. +- Run `npm test`; the whole suite must pass, not just the new test. + +## Servers, sockets and anything async + +CI runs four parts at once, each with its files in parallel, so a test can wait seconds for things that take +milliseconds on your machine. Never sleep a fixed time and then assert: wait for the state with `tests/net.js`. + +- `until(() => condition)` resolves true as soon as it holds (false after 20 s); assert on its result. +- `freePort()` asks the OS for a free port; never a fixed or random one. +- `kill(child)` stops a spawned server and resolves once it is gone. +- Listen and connect on `127.0.0.1`, not `localhost` (it can resolve to `::1` only on a CI runner). +- For HTTP to a test server, pass `agent: false`: a kept-alive socket can be reset by the server's idle timer. +- A fixed wait is fine only to prove that something does *not* happen. + +Hunt a suspected flake before pushing: `npm test -- --stress 8 tests/x.test.js` runs 8 copies at once, busier than CI. diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..fbf5463 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +# The image takes only what docker/Dockerfile copies; everything else (git history, tests, docs, local saves, +# node_modules, _site) stays out of the build context. +* +!package.json +!package-lock.json +!src/ +!site/ +!scripts/ +!tests/harness.js +!docker/docker-entrypoint.sh diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..cb714b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# The assembler joins src/ byte for byte and refuses CR line endings; keep LF everywhere it reads. +src/** text eol=lf +site/i18n/*.js text eol=lf diff --git a/.github/ISSUE_TEMPLATE/1-bug.yml b/.github/ISSUE_TEMPLATE/1-bug.yml new file mode 100644 index 0000000..d76444d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/1-bug.yml @@ -0,0 +1,87 @@ +name: Bug report +description: Something in the game is broken, looks wrong or crashes. +title: "[bug] " +labels: [bug, triage] +body: + - type: markdown + attributes: + value: | + Thanks for reporting! The more of this you fill in, the faster it gets fixed. + **One bug per issue, please.** + - type: textarea + id: what + attributes: + label: What happened? + description: Describe what went wrong. Screenshots or a screen recording help a lot. Drag them into this box. + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + description: What did you do right before it happened? + placeholder: | + 1. Open the Infra tab in Frankfurt + 2. Tap "Upgrade to 400G" + 3. … + validations: + required: true + - type: textarea + id: expected + attributes: + label: What did you expect instead? + validations: + required: true + - type: input + id: version + attributes: + label: Game version + description: Shown at the bottom of the title screen, and in the menu under "What's new". + placeholder: "1.25.1" + validations: + required: true + - type: dropdown + id: device + attributes: + label: Device + options: + - Android phone + - iPhone + - Android tablet + - iPad + - Desktop or laptop + - Other + validations: + required: true + - type: input + id: browser + attributes: + label: Browser and version + placeholder: "Firefox 159 on Android 16, Safari on iOS 26.1, Chrome 141 on Windows…" + validations: + required: true + - type: dropdown + id: installed + attributes: + label: Installed as an app? + description: Did you add Series of Tubes to your home screen, or do you play in a browser tab? + options: + - In a browser tab + - Installed on the home screen + - Not sure + validations: + required: true + - type: textarea + id: save + attributes: + label: Saved game (optional, very helpful) + description: Menu → "Export save", then attach the file here. It lets us load your exact network. + - type: checkboxes + id: checks + attributes: + label: Before you submit + options: + - label: I searched the existing issues and this one is not already reported. + required: true + - label: This issue is about one bug only. + required: true diff --git a/.github/ISSUE_TEMPLATE/2-feature.yml b/.github/ISSUE_TEMPLATE/2-feature.yml new file mode 100644 index 0000000..cf46ef2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/2-feature.yml @@ -0,0 +1,54 @@ +name: Feature request +description: An idea for something new in the game. +title: "[feature] " +labels: [enhancement, triage] +body: + - type: markdown + attributes: + value: | + Ideas are welcome! The best ones describe what happens in real networks and how it could become a fun mechanic. + **One idea per issue, please.** + - type: dropdown + id: area + attributes: + label: Part of the game + options: + - Map and interface + - Phones and tablets + - Network building (POPs, links, fiber, routers) + - Peering, transit and exchanges + - Customers + - Money, banks and prices + - Incidents and events + - Scenarios, goals and badges + - Something else + validations: + required: true + - type: textarea + id: problem + attributes: + label: What problem does it solve, or what is missing? + description: For example "When I reach Tier 1 I can't find where my transit ports are." + validations: + required: true + - type: textarea + id: idea + attributes: + label: Your idea + description: How would it work in the game? + validations: + required: true + - type: textarea + id: real + attributes: + label: How does this work in real life? (optional) + description: Links, war stories and real-world numbers make an idea much easier to model well. + - type: checkboxes + id: checks + attributes: + label: Before you submit + options: + - label: I searched the existing issues and nobody suggested this yet. + required: true + - label: This issue is about one idea only. + required: true diff --git a/.github/ISSUE_TEMPLATE/3-balance.yml b/.github/ISSUE_TEMPLATE/3-balance.yml new file mode 100644 index 0000000..7a91c39 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/3-balance.yml @@ -0,0 +1,40 @@ +name: Balance or realism +description: Something works, but prices, odds or behaviour feel off compared with the real internet. +title: "[balance] " +labels: [balance, triage] +body: + - type: textarea + id: what + attributes: + label: What feels off? + description: For example "Overland waves between continents are cheaper than subsea, but in real life it's the other way round." + validations: + required: true + - type: textarea + id: real + attributes: + label: How it is in real life + description: Real prices, ratios, links or experience from your own network. + validations: + required: true + - type: textarea + id: suggestion + attributes: + label: What would you change? (optional) + - type: input + id: version + attributes: + label: Game version + description: Shown at the bottom of the title screen, and in the menu under "What's new". + placeholder: "1.25.1" + validations: + required: true + - type: checkboxes + id: checks + attributes: + label: Before you submit + options: + - label: I searched the existing issues and this is not already reported. + required: true + - label: This issue is about one topic only. + required: true diff --git a/.github/ISSUE_TEMPLATE/4-translation.yml b/.github/ISSUE_TEMPLATE/4-translation.yml new file mode 100644 index 0000000..31d261e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/4-translation.yml @@ -0,0 +1,42 @@ +name: Translation +description: A wrong, awkward or missing translation, or a new language. +title: "[translation] " +labels: [translation, triage] +body: + - type: dropdown + id: lang + attributes: + label: Language + options: + - Italiano + - A new language (say which below) + validations: + required: true + - type: textarea + id: where + attributes: + label: Where in the game? + description: Which screen, panel or message? A screenshot helps. + validations: + required: true + - type: textarea + id: current + attributes: + label: Current text + validations: + required: true + - type: textarea + id: suggested + attributes: + label: Suggested text + validations: + required: true + - type: checkboxes + id: checks + attributes: + label: Before you submit + options: + - label: I am a fluent speaker of this language. + required: true + - label: I searched the existing issues first. + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..aedb380 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Chat with other players on Signal + url: https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ + about: Screenshots, chat and peering-policy flame wars. Bugs and ideas go here as issues, so they don't scroll away. + - name: How the internet really works + url: https://tkjaer.github.io/how-the-internet-works/ + about: Curious how the real thing works? This interactive map explains it far better than any game. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..48e0a5e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,39 @@ +# Keeps what the workflows and the container image pin up to date: every GitHub Action is pinned to a commit SHA +# (Dependabot moves the SHA and its version comment together), the image's Node base to a digest, and the npm tools +# to the lockfile. Updates come as pull requests, one group per ecosystem, once a week. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + day: monday + groups: + actions: + patterns: ["*"] + commit-message: + prefix: "CI" + + - package-ecosystem: docker + directory: /docker + schedule: + interval: weekly + day: monday + # The image runs the Node major CI tests on (ci.yml); a new major comes with CI, by hand. + ignore: + - dependency-name: node + update-types: ["version-update:semver-major"] + commit-message: + prefix: "Container" + + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + day: monday + groups: + tools: + patterns: ["*"] + update-types: [minor, patch] + commit-message: + prefix: "Tools" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..b4f1a0a --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ + + +## What and why + +## How it was tested + + + +## Performance + + diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml new file mode 100644 index 0000000..765105b --- /dev/null +++ b/.github/workflows/auto-release.yml @@ -0,0 +1,117 @@ +name: Auto-release + +# Bumping "version" in package.json on main is the release button: this tags +# v, publishes a GitHub release with that version's CHANGELOG section +# as notes, and starts the deploy. Releases created with the workflow token do +# not fire the "released" event, so the deploy is started explicitly, from the +# tag, which keeps the github-pages environment's v* tag rule happy. +# +# It runs when CI finishes on main, so a release never repeats the push's tests: +# CI green on the commit that bumped the version is the go. A red CI releases +# nothing. Started by hand, it has no CI result to go by, so it tests first. +on: + workflow_run: + workflows: [CI] + types: [completed] + branches: [main] + workflow_dispatch: + +permissions: + contents: write # create the tag and the release + actions: write # start the deploy workflow + +concurrency: + group: auto-release + cancel-in-progress: false + +jobs: + check: + # After CI: only a green run of a push to main (not a PR's run, not a release's own call). + if: >- + github.event_name == 'workflow_dispatch' || + (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push') + runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ github.token }} + outputs: + skip: ${{ steps.v.outputs.skip }} + ver: ${{ steps.v.outputs.ver }} + tag: ${{ steps.v.outputs.tag }} + pre: ${{ steps.v.outputs.pre }} + # The commit CI tested (main may have moved on since); by hand, main as it is now. + sha: ${{ github.event.workflow_run.head_sha || github.sha }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.workflow_run.head_sha || github.sha }} + fetch-depth: 0 + + - name: Work out the version and whether it is new + id: v + run: | + set -euo pipefail + ver=$(node -p "require('./package.json').version") + tag="v$ver" + echo "ver=$ver" >> "$GITHUB_OUTPUT" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + if git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then + echo "$tag already exists, nothing to release." + echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0 + fi + latest=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --limit 1 --json tagName -q '.[0].tagName' || true) + latest="${latest#v}" + if [ -n "$latest" ] && [ "$(printf '%s\n%s\n' "$latest" "$ver" | sort -V | tail -n1)" != "$ver" ]; then + echo "::error::$ver is not newer than the latest release $latest"; exit 1 + fi + awk -v v="$ver" 'index($0,"## ["v"]")==1{f=1;next} /^## \[/{f=0} f' CHANGELOG.md | sed -e '/./,$!d' > notes.md + if ! grep -q '[^[:space:]]' notes.md; then + echo "::error::CHANGELOG.md has no notes under ## [$ver]"; exit 1 + fi + case "$ver" in *-*) echo "pre=true" >> "$GITHUB_OUTPUT";; *) echo "pre=false" >> "$GITHUB_OUTPUT";; esac + echo "skip=false" >> "$GITHUB_OUTPUT" + + # Only when started by hand: after a push, CI has already tested this commit. By hand the commit is main as it is + # (github.sha, what check.outputs.sha is then), named directly so CI never checks out a ref a workflow_run handed over. + tests: + needs: check + if: needs.check.outputs.skip == 'false' && github.event_name == 'workflow_dispatch' + uses: ./.github/workflows/ci.yml + with: + ref: ${{ github.sha }} + + release: + needs: [check, tests] + if: >- + always() && needs.check.result == 'success' && needs.check.outputs.skip == 'false' && + (needs.tests.result == 'success' || needs.tests.result == 'skipped') + runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.check.outputs.tag }} + VER: ${{ needs.check.outputs.ver }} + PRE: ${{ needs.check.outputs.pre }} + SHA: ${{ needs.check.outputs.sha }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.check.outputs.sha }} + + - name: Publish the release + run: | + set -euo pipefail + awk -v v="$VER" 'index($0,"## ["v"]")==1{f=1;next} /^## \[/{f=0} f' CHANGELOG.md | sed -e '/./,$!d' > notes.md + pre=(); [ "$PRE" = "true" ] && pre=(--prerelease) + gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \ + --target "$SHA" --title "$VER" --notes-file notes.md "${pre[@]}" + + - name: Deploy it + # Pre-releases are for testing and never go live. CI (or the tests above) already passed on this commit, + # so the deploy does not test it again (tested=true). + if: env.PRE == 'false' + run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" -f tested=true + + - name: Publish the Docker image + # Same pattern as the deploy above: the image is built and pushed from the + # release tag by docker.yml. Pre-releases get one too: an image tag is + # pulled on purpose, so a test image costs nothing. + run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 88089b9..a70d674 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,23 +1,142 @@ name: CI +# Every push and PR, and the releases too (auto-release.yml and release.yml call this workflow), so the tests run +# one way, split over several runners, everywhere. on: push: branches: [main] pull_request: + workflow_call: + inputs: + ref: + description: The commit or tag to test (a release tag); the caller's commit when empty + type: string + default: '' permissions: contents: read +# A newer push to the same pull request makes the older run pointless: cancel it instead of queueing behind it. +# Runs on main always finish. A release's call gets a group of its own, so it never waits behind main's push run. +concurrency: + group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ inputs.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + # Runners for the tests. Standard GitHub-hosted runners (4 cores each) are the only free ones for a public repo, + # and a run may use up to 20 at once, so more parts is how the tests get faster. Each part costs ~30 s of setup. + PARTS: 6 + jobs: - test: + # Splits the test files into parts of about equal time, once, so every part works from the same plan. The times + # come from the last run on main (the cache, see "timings" below), else from the committed tests/durations.json. + plan: runs-on: ubuntu-latest + outputs: + parts: ${{ steps.plan.outputs.parts }} steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} + restore-keys: test-durations- + - id: plan + run: echo "parts=$(node scripts/test.js --plan "$PARTS")" >> "$GITHUB_OUTPUT" + + part: + name: part ${{ strategy.job-index }} + needs: plan + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + files: ${{ fromJSON(needs.plan.outputs.parts) }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Tests + env: + FILES: ${{ matrix.files }} + # Word splitting on purpose: FILES is a space-separated list of tests/*.test.js paths. + run: npm test -- --timings "$RUNNER_TEMP/timings.json" $FILES + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: timings-${{ strategy.job-index }} + path: ${{ runner.temp }}/timings.json + retention-days: 1 + if-no-files-found: ignore + + build: + name: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm - run: npm ci - - run: npm test - name: Build (not deployed — only releases deploy) run: npm run build + + translations: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Translation coverage + run: node scripts/i18n-check.js --summary "$GITHUB_STEP_SUMMARY" + + # The one check to look at: green only when the plan, every part, the build and the translations are. + test: + needs: [plan, part, build, translations] + if: always() + runs-on: ubuntu-latest + steps: + - name: Everything passed + run: | + echo "plan: ${{ needs.plan.result }}, parts: ${{ needs.part.result }}, build: ${{ needs.build.result }}, translations: ${{ needs.translations.result }}" + test "${{ needs.plan.result }}" = success && test "${{ needs.part.result }}" = success + test "${{ needs.build.result }}" = success && test "${{ needs.translations.result }}" = success + + # After a run on main: each file's time from this run goes into the cache, so the next run (main or a PR) splits + # its parts by today's tests. Nobody has to remember to refresh tests/durations.json. + timings: + needs: part + if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.part.result != 'skipped' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} + restore-keys: test-durations- + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: timings-* + path: ${{ runner.temp }}/timings + - run: node scripts/test-timings.js --merge "$RUNNER_TEMP/timings" + - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml new file mode 100644 index 0000000..10913c4 --- /dev/null +++ b/.github/workflows/claude.yml @@ -0,0 +1,35 @@ +name: Claude + +# Comment "@claude ..." on an issue or PR (for example "@claude review this +# against CLAUDE.md") and Claude answers in the thread. Comment events run in +# this repo's context, so this also works on PRs from forks, where secrets are +# otherwise withheld. Only people with write access can trigger it. +# Needs the Claude GitHub app and a CLAUDE_CODE_OAUTH_TOKEN secret (claude setup-token). + +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + pull_request_review: + types: [submitted] + +jobs: + claude: + if: >- + (github.event_name != 'pull_request_review' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + issues: write + id-token: write + actions: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 1 + - uses: anthropics/claude-code-action@61a9c274fa7110a66dfafc1bbbced03833eb25fe # v1.0.269 + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..434307e --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,187 @@ +name: Container image + +# Publishes ghcr.io//: for releases, and nothing else: auto-release.yml dispatches this workflow +# with the new tag (pre-releases too). There is no :latest and no image per commit. Pushes and pull requests that change +# what goes into the image only build it and try both modes; they never publish. The image packages the MCP server and +# the development server; the game itself is hosted on GitHub Pages only (docs/adr/0001-github-pages-only.md). +on: + workflow_dispatch: + inputs: + tag: + description: Release tag to build and publish (e.g. v2.10.1) + required: true + push: + branches: [main] + paths: + - docker/** + - .dockerignore + - package.json + - package-lock.json + - scripts/** + - tests/harness.js + - .github/workflows/docker.yml + pull_request: + paths: + - docker/** + - .dockerignore + - package.json + - package-lock.json + - scripts/** + - tests/harness.js + - .github/workflows/docker.yml + +permissions: + contents: read + +concurrency: + group: docker-${{ github.event_name }}-${{ inputs.tag || github.ref }} + cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} + +jobs: + # A push that bumps the version is a release on its way: once CI passes, auto-release.yml starts this workflow for + # the tag, which tests the same code before it publishes. Testing the push too would be the same run twice. + gate: + runs-on: ubuntu-latest + outputs: + run: ${{ steps.g.outputs.run }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag || '' }} + persist-credentials: false + - id: g + run: | + tag="v$(jq -r .version package.json)" + if [ "$GITHUB_EVENT_NAME" = push ] && ! git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then + echo "$tag is not tagged yet: the release will test this commit when it publishes." + echo "run=false" >> "$GITHUB_OUTPUT" + else + echo "run=true" >> "$GITHUB_OUTPUT" + fi + + test: + needs: gate + if: needs.gate.outputs.run == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag || '' }} + persist-credentials: false + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build for this runner + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64 + load: true + push: false + tags: sot:test + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Try both modes + run: | + set -euo pipefail + init='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"ci","version":"1"}}}' + mcp() { curl -sS -o /tmp/out -w '%{http_code}' -X POST http://127.0.0.1:7777/mcp \ + -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' "$@" -d "$init"; } + until_up() { for i in $(seq 1 60); do curl -s -o /dev/null "$1" && return 0; sleep 1; done; docker logs "$2"; exit 1; } + + # Headless, with a token: refused without it, answered with it. + docker run -d --name sot-h -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=ci-token sot:test + until_up http://127.0.0.1:7777/ sot-h + test "$(mcp)" = 401 + test "$(mcp -H 'authorization: Bearer ci-token')" = 200 + grep -q serverInfo /tmp/out + docker rm -f sot-h + + # No token given: the container makes one, says so, and wants it. + docker run -d --name sot-t -p 127.0.0.1:7777:7777 -e MCP_MODE=headless sot:test + until_up http://127.0.0.1:7777/ sot-t + test "$(mcp)" = 401 + tok=$(docker logs sot-t 2>&1 | sed -n "s/.*this run's token is //p" | head -1) + test -n "$tok" + test "$(mcp -H "authorization: Bearer $tok")" = 200 + docker rm -f sot-t + + # Browser mode: the development page and the MCP server. + docker run -d --name sot-b -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 -e SOT_MCP_TOKEN=ci-token sot:test + until_up http://127.0.0.1:8080/ sot-b + test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/)" = 200 + until_up http://127.0.0.1:7777/ sot-b + test "$(mcp -H 'authorization: Bearer ci-token')" = 200 + docker rm -f sot-b + + # The server runs as node, not root. + test "$(docker run --rm --entrypoint id sot:test -u)" != 0 + + publish: + if: github.event_name == 'workflow_dispatch' + needs: test + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + contents: read + packages: write + steps: + - name: Check the tag + env: + TAG: ${{ inputs.tag }} + run: | + [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "::error::Not a release tag: $TAG"; exit 1; } + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag }} + persist-credentials: false + + - name: Work out the image name and version + id: meta + env: + TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + want="v$(jq -r .version package.json)" + if [ "$TAG" != "$want" ]; then echo "::error::Release tag $TAG does not match package.json ($want)"; exit 1; fi + # Named after this repository (ghcr.io//, lowercased), so forks publish their own. + echo "image=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT" + echo "version=${TAG#v}" >> "$GITHUB_OUTPUT" + echo "revision=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "created=$(git log -1 --format=%cI)" >> "$GITHUB_OUTPUT" + + - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push the release's version + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }} + labels: | + org.opencontainers.image.title=Series of Tubes MCP server + org.opencontainers.image.description=The Series of Tubes MCP server and development server, so an AI client can play the game. + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.documentation=${{ github.server_url }}/${{ github.repository }}/blob/${{ inputs.tag }}/docs/MCP.md + org.opencontainers.image.version=${{ steps.meta.outputs.version }} + org.opencontainers.image.revision=${{ steps.meta.outputs.revision }} + org.opencontainers.image.created=${{ steps.meta.outputs.created }} + org.opencontainers.image.licenses=MIT + provenance: mode=max + sbom: true + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.github/workflows/perf-comment.yml b/.github/workflows/perf-comment.yml new file mode 100644 index 0000000..a214fff --- /dev/null +++ b/.github/workflows/perf-comment.yml @@ -0,0 +1,43 @@ +name: Performance comment + +# Posts the table from the Performance workflow on its pull request, and updates the same comment on every push. +# Runs in this repository's context with write access, so it only reads the uploaded text and never runs PR code. +on: + workflow_run: + workflows: [Performance] + types: [completed] + +permissions: + pull-requests: write + issues: write + actions: read + +jobs: + comment: + if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: perf + # Outside the workspace: the files come from a PR's run and are only ever read as text. + path: ${{ runner.temp }}/perf + run-id: ${{ github.event.workflow_run.id }} + github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Post or update the comment + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + run: | + cd "$RUNNER_TEMP/perf" + pr=$(tr -cd '0-9' < pr-number.txt) + [ -n "$pr" ] || { echo "no PR number"; exit 0; } + # Trust the number only if that PR's head is the commit that was benchmarked. + head=$(gh api "repos/$REPO/pulls/$pr" --jq .head.sha) + [ "$head" = "$HEAD_SHA" ] || { echo "PR #$pr has moved on since this run"; exit 0; } + { echo ''; head -c 60000 perf.md; } > body.md + id=$(gh api "repos/$REPO/issues/$pr/comments" --paginate --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(""))) | .id' | head -n 1) + if [ -n "$id" ]; then gh api -X PATCH "repos/$REPO/issues/comments/$id" -F body=@body.md > /dev/null + else gh api -X POST "repos/$REPO/issues/$pr/comments" -F body=@body.md > /dev/null; fi + echo "Posted to #$pr" diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml new file mode 100644 index 0000000..f2657ab --- /dev/null +++ b/.github/workflows/perf.yml @@ -0,0 +1,58 @@ +name: Performance + +# Times the PR against its base on a very large network, headless and in Chrome (desktop and a throttled phone), +# and uploads the tables. A separate workflow +# (perf-comment.yml) posts it on the PR: runs for pull requests from forks have no write access. +on: + pull_request: + paths: + - 'src/**' + - 'site/**' + - 'scripts/lib/**' + - 'scripts/perf-*.js' + - 'tests/fixtures/**' + - 'tests/harness.js' + workflow_dispatch: + +permissions: + contents: read + +jobs: + bench: + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Base version of the game + if: github.event_name == 'pull_request' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + git fetch --depth=1 origin "$BASE_SHA" + # The base's page, assembled by the base's own scripts (or its site/index.html from before the split). + node scripts/lib/page.js --ref FETCH_HEAD -o "$RUNNER_TEMP/base.html" + echo "BASE_ARG=--base $RUNNER_TEMP/base.html" >> "$GITHUB_ENV" + - name: Benchmark + # The runner image ships Google Chrome; playwright-core (a dev dependency) drives it, no browser download. + run: | + export PERF_CHROME="$(command -v google-chrome || command -v google-chrome-stable || command -v chromium)" + echo "Chrome: $PERF_CHROME ($("$PERF_CHROME" --version))" + node scripts/perf-bench.js $BASE_ARG --browser --md perf.md --summary "$GITHUB_STEP_SUMMARY" + - name: Remember the PR number + if: github.event_name == 'pull_request' + env: + PR: ${{ github.event.pull_request.number }} + run: echo "$PR" > pr-number.txt + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: github.event_name == 'pull_request' + with: + name: perf + path: | + perf.md + pr-number.txt + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2bc8972..213596f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,38 +2,63 @@ name: Release to GitHub Pages # The live site at https://seriesoftub.es only ever serves a published release. # Pushes to main run CI but never deploy. To ship: bump "version" in -# package.json, add a CHANGELOG entry, merge, then publish a GitHub release -# tagged v. +# package.json and date its CHANGELOG section; auto-release.yml then tags, +# publishes the release and starts this workflow from the tag. Publishing a +# release by hand works too. Every Sunday weekly-puzzle.yml redeploys the live +# release from its tag with the new weekly puzzle added (input weekly). on: release: - types: [published] + # "released" also fires when a pre-release is promoted to a full release. + types: [released] workflow_dispatch: inputs: tag: description: Existing release tag to redeploy (e.g. v1.0.0) required: true + allow_older: + description: Allow deploying a version older than what is live (rollback) + type: boolean + default: false + weekly: + description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped + type: boolean + default: false + tested: + description: The tag's tests already passed (auto-release.yml tests it before tagging) + type: boolean + default: false +# Least privilege: only the deploy job can write to Pages. permissions: contents: read - pages: write - id-token: write concurrency: group: pages cancel-in-progress: false jobs: + # The release's tests, split over several runners like every push (ci.yml). Skipped when auto-release.yml has just + # run them on this tag, and for a weekly redeploy (the build step below tests the weekly files against the tag). + tests: + if: ${{ (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && !inputs.weekly && !inputs.tested }} + uses: ./.github/workflows/ci.yml + with: + ref: ${{ github.event.release.tag_name || inputs.tag }} + build: + needs: tests # Pre-releases are for testing and never go live. - if: ${{ github.event_name == 'workflow_dispatch' || !github.event.release.prerelease }} + if: ${{ always() && (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && (needs.tests.result == 'success' || needs.tests.result == 'skipped') }} runs-on: ubuntu-latest env: TAG: ${{ github.event.release.tag_name || inputs.tag }} + ALLOW_OLDER: ${{ inputs.allow_older || false }} + GH_TOKEN: ${{ github.token }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ env.TAG }} - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm @@ -45,28 +70,80 @@ jobs: echo "::error::Release tag $TAG does not match package.json version ($want)" exit 1 fi + - name: Never deploy pre-releases or roll the live site back by accident + run: | + set -euo pipefail + if [ "$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isPrerelease -q .isPrerelease)" = "true" ]; then + echo "::error::$TAG is a pre-release; pre-releases never deploy"; exit 1 + fi + live=$(curl -sSf https://seriesoftub.es/version.json 2>/dev/null | jq -r .version || echo "0.0.0") + new="${TAG#v}" + if [ "$ALLOW_OLDER" != "true" ] && [ "$(printf '%s\n%s\n' "$live" "$new" | sort -V | tail -n1)" != "$new" ]; then + echo "::error::$new is older than the live $live. Re-run with allow_older to roll back on purpose."; exit 1 + fi + # Weekly puzzles are published on main between releases (weekly-puzzle.yml). Every deploy ships all of them, + # so neither a release nor a weekly redeploy ever drops a week that is already out. + - name: Weekly puzzles and scenarios from main + run: | + set -euo pipefail + git fetch --no-tags --depth=1 origin main + for d in site/puzzles/weekly site/scenarios/weekly site/architect/weekly; do + if git cat-file -e "FETCH_HEAD:$d" 2>/dev/null; then + rm -rf "$d" + git checkout FETCH_HEAD -- "$d" + echo "$d: $(ls "$d" | grep -c '^[0-9].*\.json$')" + fi + done - run: npm ci - - run: npm test + # This release's prices may no longer fit a week already published: --check regenerates every week not over + # yet whose budget no longer verifies (deterministically, so main's next weekly run commits the same files), + # and fails the deploy only if that fails. Before the tests, which check the weeks too. + - name: Fit the weekly puzzles to this release + run: | + set -euo pipefail + # A release from before the weekly puzzles ships the files without reading them: nothing to check. + if [ ! -f scripts/weekly-puzzle.js ]; then echo "This release does not read weekly puzzles yet."; exit 0; fi + node scripts/weekly-puzzle.js --check + if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi + if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi + # The weekly files come from main, not the tag. When they (after fitting) are the tag's own, CI already tested + # them with it; otherwise (a newer week, a refitted one) they are tested against this release here. + - name: Are the weekly files the tag's own? + id: weekly + run: | + if [ -z "$(git status --porcelain -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly)" ]; then + echo "Same weekly files as the tag: tested with it already."; echo "same=true" >> "$GITHUB_OUTPUT" + else + git status --short -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly; echo "same=false" >> "$GITHUB_OUTPUT" + fi + - name: Test the weekly puzzles against this release + if: ${{ hashFiles('scripts/weekly-puzzle.js') != '' && (steps.weekly.outputs.same != 'true' || !(inputs.tested || needs.tests.result == 'success')) }} + run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null) - name: Build site - run: VERSION="${TAG#v}" npm run build - - uses: actions/upload-pages-artifact@v5 + run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: ./_site + # A skipped job skips everything that needs it, even through build (which runs anyway): without always() here, a + # release whose tests auto-release.yml already ran built and never deployed (v3.2.0). deploy: needs: build + if: ${{ always() && needs.build.result == 'success' }} runs-on: ubuntu-latest + permissions: + pages: write + id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - id: deployment - uses: actions/deploy-pages@v5 - - # Tell IndexNow (Bing, Yandex, Seznam, …) about the new version, only after + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 # the site is live. indexnow: needs: deploy + if: ${{ always() && needs.deploy.result == 'success' && !inputs.weekly }} runs-on: ubuntu-latest env: # IndexNow keys are public by design (also served at /.txt). diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml new file mode 100644 index 0000000..6cfa3d5 --- /dev/null +++ b/.github/workflows/weekly-puzzle.yml @@ -0,0 +1,88 @@ +name: Weekly puzzle + +# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), scenario (scripts/weekly-scenario.js) and +# Architect run (scripts/weekly-architect.js), +# commit them to main as a data-only change, and redeploy the live release with them, once. Weeks start Sunday +# 06:00 Berlin time; 03:37 UTC is 04:37 in winter and 05:37 in summer, so the files are live before the week starts. +# +# No version bump, so no release: auto-release.yml only runs when package.json changes (and pushes made with +# the workflow token start no workflows at all). The deploy itself is release.yml, still the only workflow +# that can write to Pages, started from the live release's tag with weekly=true: it rebuilds exactly that +# release with every weekly puzzle from main added, in the same "pages" concurrency group as any release. +on: + schedule: + - cron: '37 3 * * 0' + workflow_dispatch: + inputs: + key: + description: Week to make, e.g. 2026-W45 (default the week starting this Sunday) + required: false + deploy: + description: Redeploy the live release with it + type: boolean + default: true + +permissions: + contents: write # commit the puzzle to main + actions: write # start release.yml + +concurrency: + group: weekly-puzzle + cancel-in-progress: false + +jobs: + puzzle: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + GH_TOKEN: ${{ github.token }} + KEY: ${{ inputs.key }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: npm + - run: npm ci + # Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current. + - name: Fit the published weeks to main + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check + - name: Make the puzzle and the scenario + run: | + set -euo pipefail + if [ -n "$KEY" ]; then + [[ "$KEY" =~ ^[0-9]{4}-W[0-9]{2}$ ]] || { echo "::error::$KEY is not a week key"; exit 1; } + node scripts/weekly-puzzle.js --key "$KEY" + node scripts/weekly-scenario.js --key "$KEY" + node scripts/weekly-architect.js --key "$KEY" + else + node scripts/weekly-puzzle.js + node scripts/weekly-scenario.js + node scripts/weekly-architect.js + fi + - name: Check every weekly puzzle + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js tests/weekly-architect.test.js + - name: Commit it to main + run: | + set -euo pipefail + git add site/puzzles/weekly site/scenarios/weekly site/architect/weekly + # Data only: anything else changed means something is wrong. + if git status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' -e ' site/architect/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi + if git diff --cached --quiet; then echo "Nothing new to commit."; exit 0; fi + git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -m "Weekly puzzle and scenario $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')" + git push origin HEAD:main + - name: Redeploy the live release with it + if: github.event_name == 'schedule' || inputs.deploy + run: | + set -euo pipefail + tag=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --exclude-drafts --limit 1 --json tagName -q '.[0].tagName') + [ -n "$tag" ] || { echo "::error::no release to redeploy"; exit 1; } + # Releases from before the weekly puzzles cannot take them (and their game would not read them). + if ! git fetch --no-tags --depth=1 origin "refs/tags/$tag" || ! git show FETCH_HEAD:.github/workflows/release.yml | grep -q '^ weekly:'; then + echo "::notice::$tag predates weekly puzzles; the puzzle is on main and ships with the next release."; exit 0 + fi + gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$tag" -f tag="$tag" -f weekly=true + echo "Redeploying $tag with the weekly puzzles." diff --git a/.gitignore b/.gitignore index 24c9945..9027294 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ _site/ .DS_Store +mp-data/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 0066d58..01cce55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,1061 @@ All notable changes to this project are documented here. The project follows [Semantic Versioning](https://semver.org/). Each release is deployed to [seriesoftub.es](https://seriesoftub.es). +## [Unreleased] + +- Investors on a revenue share now take their cut of your IPv4 lease income too, as they already did of fiber pairs you lease out (#150). Selling a block is still a one-off that is all yours, like the up-front price of a fiber pair, and the NOC dashboard's Investor revenue share row now includes the leases. +- Island Wi-Fi: bring the internet to 18 groups of outer islands, over satellite capacity first and your own spur cable later (#83). Each group looks to an island city, like Vanua Levu to Suva or Abaco and Eleuthera to Nassau: open a POP there and its Customers tab lists them. Rent capacity at the city's teleport and about a third of the islanders sign up over GEO, three quarters over MEO and nine in ten over Starblink from a gateway there; from level 3 a spur cable from the city lets everyone sign up, with upkeep but no rent. Islanders pay island prices, their homes are IPv6-only from day one, and their traffic rides the city's routers and links. A spur can be cut and the repair ship takes weeks: a satellite circuit kept beside it carries the islands meanwhile. Investors on a revenue share take their cut of what the islands pay. +- Rent low-orbit satellite capacity from Starblink from level 5: islands near your fiber get circuits at about 30 ms round trip (#83). Host a Starblink gateway at a teleport on your fiber, then rent 5 to 50 Gbps to small islands and remote towns within 1,200 km of it. Users hardly notice the lag, and selective networks peer over it as over a cable; next to a cable it waits on standby, and a GEO or MEO circuit to the same island waits on standby beside it. Every island behind a gateway leans on that POP's routers, fiber and transit, which its teleport section now shows, and a rare solar storm puts the circuits in safe mode for a day or two. Once your own constellation carries traffic, Starblink sells you nothing new. +- A POP you mark as a micro POP, medium POP or regional hub now keeps that kind's routers when you also have a build standard (#315). Its router model and count come from its kind: "Bring everything up now" and your intern no longer swap its routers or add more to meet the build standard, while the standard's other targets still apply there. The POP's router section says so. +- Send to another device now gives a multiplayer network its session link, on copies of the game you host yourself (#263). The link carries on with the network in the session on the other device, and pasting it under From another device opens it there too; the save file stays a copy that plays on alone. +- Buy it and sign no longer spends money on an offer your IPv4 space cannot take (#150). The button only shows once the deal's address block fits. +- Linking to an island or remote town where no subsea cable lands, like Iqaluit or Adamstown, now says that a satellite can get there too. The window has a button to the order sheet from your teleports that reach it, up to four of them; without one, it says where a teleport would have to go (#83). +- IPv4 notices in the NOC's notifications now have an Open button to the bank's Address space (#150). Notices like "Your IPv4 is full" already had that button when they popped up; now they keep it. +- Red warning text and the capacity market's Hot and Cool tags now read well in dark mode (#80). The red is a lighter one on the dark panels, and the tags take the night colours instead of staying bright pastel chips. +- The build standard can now take every broadband city IPv6-only while IPv4 is scarce (#150). Its new target, Broadband: IPv6-only, swaps the home routers of every city still on dual stack for 464XLAT ones, the cities with the most dual-stack homes first. "Bring everything up now" and your intern's Keep to the build standard order start a city's swap only with all of it to spare, and the intern counts it against the order's monthly budget. What the swaps under way still owe is set aside: the button's other jobs and every one of your intern's standing orders leave it alone, above the cash floor. +- "Bring everything up now" in the build standard no longer takes a fiber dark for a day while a customer's alien or managed wave rides it. Such a fiber keeps its line system and the sheet says why; the upgrade button on the fiber itself still does it when you choose. Your intern waits for those fibers too, but no longer skips fibers that only carry leased pairs or IRUs, which a line system swap never touches. +- Broadband cities can now go IPv6-only with 464XLAT, a second way to save IPv4 next to CGNAT. Start it from a city's Home broadband, which also says what it does to your monthly IPv4 bill: its home routers are swapped over a month or more, paid as each one goes in (new homes there get one too, at the same price), and the homes then need no IPv4 address of their own, only a share of a NAT64 pool at up to 256 homes per address, with fewer refunds than CGNAT at the same ratio. The bank's Address space section shows your homes as public, behind CGNAT and IPv6-only, with the NAT64 ratio next to the CGNAT one, and says which of the two to stretch when space runs out. +- CGNAT gets a little cheaper every year as the world moves to IPv6. About two points less of your homes' traffic needs IPv4 each year, so the CGNAT and NAT64 boxes carry less of it. +- The router model and the line system your intern standardizes on are now picked in one place, the build standard. Keep routers ahead and Upgrade optical transport take them from there and say so, with a button to the sheet. With a model or line system in the standard, both orders bring everything up to it and stop there (Upgrade optical transport on every fiber, even at POPs that Keep to the build standard skips); "Keep as is" leaves them to the next one up when busy. A model or line system you had picked in an order that was running moves into your standard, so new POPs get that model too. +- Your intern no longer takes a fiber dark for the build standard just because it looks quiet. Like the optical upgrade order, it first checks that every gigabit, circuit and express gets around the fiber for the day. The two orders share one line system swap a night (two for Kevin), never work on the same fiber in one shift, and a wave the standard just upgraded is no longer handed back the same day. +- Copies of the game you host yourself can now have multiplayer, with friends building their networks next to yours in the same world. They join your session with a six-character code, and the session has a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. +- Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). +- Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58) +- Teleports bring satellites to small islands and remote towns, long before you have a cable there or a rocket company (#83). Build one at a POP from level 2 and rent GEO circuits (about 600 ms round trip, and users notice) or, with tracking antennas from level 3, MEO circuits (about 130 ms) to any island or town its satellites see. Next to an island's only cable a circuit waits on standby (whether the cable or the circuit came first) and carries the island when the cable is cut, and a city with no cable at all gets a POP and a circuit in one order. +- Set a build standard for your whole network: what every POP, connection and fiber should have, all in one sheet. It covers routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. +- IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). +- Express lightpaths now pay their share when you add a regen site, and a dirty connector on a fiber dims the expresses riding it too (#58). A regen site added to a fiber that already carries expresses needs a regen card for each of their channels, just as for the fiber's own, and the price on the fiber's button includes them. A dirty connector dims every wave in that fiber, and the express's panel says which fiber it is; an MTU mismatch, microbursts or a marginal optic stay with that fiber's own routers and optics, which an express passes by. +- Many selective networks now refuse to peer where a satellite circuit is your only way out (#83). On an island or in a remote town that only a satellite joins to the rest of your network, they would hand you traffic for your whole network to haul through orbit, so more of them turn down a GEO hop (about 600 ms there and back) than a MEO one (about 130 ms), and each says why on the exchange and PNI lists. Once a wave, fiber or cable to the island is lit they peer again. An exchange session you already had there pauses until then; a PNI you already have and the members of an exchange you run yourself keep peering. + +## [3.5.0] — 2026-11-11 + +- Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340). +- The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. (#342) +- You can now start a link by typing where it goes: open one of your POPs, go to Infra and tap Link to a city, then type a city, country or exchange and pick it. You get the same link window as dragging between the two on the map, which is much easier on a crowded phone screen (#343). +- The Connections tab of the NOC dashboard can now shrink connections as well as grow them. Next to the upgrades, transit ports, PNIs and exchange ports get a downgrade to the next smaller port and a button to drop one LAG member, and a PNI that is still on order can be chased from the list, just like from the POP panel (#336). +- Once you have made Tier 1, conferences stop sending notifications. No more 30-day reminders, reports from the hallway track or notes from your sales engineer about bookings; you can still register and sponsor from the Deals tab, and everything a conference does works as before (#101). + +## [3.4.0] — 2026-11-10 + +- A PNI can now grow past eight ports: each router at the POP takes eight members of a PNI, up to 32, so a busier interconnect costs another router and its ports. Saves keep every LAG they have, and a router a PNI still needs stays until the PNI shrinks (#323). +- Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48). +- Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61). +- RouteScript can spill early onto detours within a latency budget: `spill at 80% within 10 ms` keeps a hot link at 80% and moves the rest onto the fastest detour that adds at most 10 ms and is itself under 80%. Stack them (`spill at 90% within 20 ms`) to spill further as links get hotter (#136). +- You can now send a network to another device straight from the game: open the menu, pick Send to another device, and send the save file with AirDrop, Quick Share, a chat with yourself or email, then open it there with Import a save. You can also copy a link that carries the whole network and paste it on the other device under From another device. Nothing is uploaded anywhere (#263). +- From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137). +- From customer level 2, you can save up to three POP standards (micro POP, medium POP, regional hub), each a router model and a number of routers, and mark which POP is which. One button in a POP's Infra tab brings it up to its standard, and Utilities brings every POP of a kind up at once with the price shown first. A POP is never stepped down to a smaller model, and a busy POP with one router gets its second router before the swap, so the upgrade rolls instead of taking the POP down (#315). +- Utilities can now install the redundancy kit at every POP still missing part of it in one go, at one price shown on the button, from customer level 2. With a NOC intern you can also put the kit in the intern's new-POP template from there (#317). +- A customer asking for a backup generator, a second router or a second site at POPs you already have now shows what is missing and what it costs, with a button that buys exactly that and signs the deal. Nothing is bought unless you press it (#241). +- The NOC intern's "Light more fiber" order can now leave new fiber dark, so a fiber handed over in the night no longer pulls in traffic before you are ready for it. Fiber you light yourself still gets more optics when it runs hot (#316). +- The Transit and Peering tabs of a POP have a search box for a network's name or AS number and a "Connected only" switch, so you can find the one network you need in a long list, on phones too (#199). +- Decommissioning one of several links between the same two cities keeps the link panel open on the next one, so you can hand back a row of waves without reopening it each time (#119). +- A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329). +- A customer asking for a discount at renewal now shows how much traffic they book and get, the price per Gbps now and asked, and any latency limit or path terms they signed for, each ticked or crossed as your network stands today (#292). +- The two city names at the top of a wave, dark fiber or virtual circuit panel now open that city, for example to upgrade the router there before a bigger link (#196). + +## [3.3.0] — 2026-11-09 + +- You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Waves and leased fiber pairs move to another fiber with room for them, leaving alone what you keep back for your own traffic, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down. +- Routing a big network's day takes about half the work, with exactly the same results: on a network of 390 POPs with Auto-TE, a day's routing went from about 0.7 to 0.3 seconds on a computer. +- Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before. +- At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before. +- While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed. +- Linking to a coast where no subsea cable lands yet, like Iqaluit, now says how you can get there (overland, or with a cable of your own) instead of listing no cities to hop through (#321). +- A delay while your own subsea cable is being laid now holds the lay ship where it is, instead of sending it back to port and starting the laying over. The cable already on the seabed stays there, the build simply finishes later, and there is nothing to pay twice (#322). +- A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds. +- A low-latency boutique with a lot of its own fiber no longer stalls every day while it times its finance routes. On a big fiber network that check held the page for about a third of a second and now takes a few hundredths; checking customers who want a path without subsea or under a latency limit got quicker too. The game plays exactly as before. +- The NOC intern no longer holds a big network for more than half a second each time it weighs taking out a spare wave. Before it decides, it checks every customer promised diverse paths, no subsea or a latency limit, and on a network of 390 POPs that check now takes a few hundredths of a second. Spotting new sovereign cloud and trading offers is about ten times quicker too, and the game plays exactly as before. + +## [3.2.0] — 2026-11-07 + +- New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. +- Lambda Bazaar, a capacity market for your dark fiber, is a new tab in the NOC dashboard. Sell spectrum, managed 100G, 400G, 800G and 1.6T waves, and dark pair IRUs on every route you hold fiber on, and choose how much to keep back for your own traffic, from what demand the broker lists, and the price it never sells below. What each route wants moves all the time and grows every year: hot routes pay more, a fiber cut next door or a hyperscaler breaking ground sends demand up, buyers move from 100G to bigger waves over the years, and carriers already on your glass ask to move up a size. Short, straight routes earn more for fast waves. A Cable broker pays the broker 3% instead of 10%, and sees where each route is heading and which routes between its POPs are worth building. + +## [3.1.0] — 2026-11-07 + +- Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. +- The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary. +- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. +- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. +- France gets seven more cities: Lyon, Toulouse, Lille, Bordeaux, Strasbourg, Rennes and Nantes, all but Nantes with an exchange of their own (#288). SF-Error Telecom and Boy-Egg Telecom bring home broadband and mobile, Ov-Hatch Cloud and Scale-Away bring French clouds, Tangerine Telecom and Free as in Beer reach the new cities, Cogentle reaches Toulouse, Lille, Bordeaux and Strasbourg, and Andorable Telecom comes up to Toulouse. The Atlantic cables now come ashore where they really do: Ami-Tea at Bordeaux and Dunno-ant at Nantes, and Dunno-ant starts at Virginia Beach. +- Big networks at ×8 no longer stop for a moment when a day reroutes, after a failure, an event, the intern's shift or the sales desk's signing. Every routing a day needs now runs in the background like the day's own, a long day lets the map draw between its steps, and the check for customers afraid of sharks no longer walks every land fiber for each of them. Quiet notifications now also apply while the game is running. + +## [3.0.0] — 2026-11-06 + +**Series of Tubes 3.0: Pie in the Sky.** You have wired up the planet with fiber, cables and routers. Now take your network to orbit: start your own rocket company, fill the sky with satellites (we call them pies) and sell internet to everyone your cables will never reach. + +**How to get there.** Become Tier 1 in a game started with 3.0, whatever your charter, and Pie Control opens from the NOC tab, right next to the NOC dashboard. Want to look around first? In Sandbox the rocket company is yours from day one. Games you started before 3.0 keep the rules they began with. + +**Rockets, pies and crusts.** Build a pie factory and a launch pad on the coast (the closer to the equator, the cheaper each launch), then fly rockets that carry pies into four orbital shells, the crusts. Once a crust is 40% full it starts carrying traffic: pie dishes at your POPs land it on your backbone, and homes and boats in the remotest places, airlines, cruise lines and even a Mars mission sign up. A town no cable reaches can join your network through orbit. You watch it all on a spinning cartoon globe, launches and fireballs included. + +**Space is not quiet.** Solar storms, food fights in orbit, failed launches and spats with governments over landing rights keep you busy, and the Founder of your rocket company does something daft every few months, so the markets get the jitters until it wears off. Governments pay for space too, in a new Government money section of the bank. Run it well and a full constellation pays for itself in about seven years. + +**Three charters.** A new game now starts by asking what you are building. **Global backbone** is the classic game: grow everywhere and become Tier 1. **Low-latency boutique** lives on speed: trading firms call more often and pay more, and you win Speed of Light by beating the fastest leased latency on finance routes with your own glass. **Cable broker** is new: lay fiber on land and cables under the sea from day one, light them and sell the capacity to other carriers, and win Glass Baron when your own cables land on five continents while carriers pay you $1M a month. Every charter can still become Tier 1, and so reach orbit. + +**Sales runs the deals.** Your salesperson can now sign deals for you, orbit customers included, each in their own style, while the NOC intern sticks to running the network. + +- Pie in the Sky: become Tier 1 and you can start your own rocket company, putting your network in orbit. Win Tier 1 in a game started from this version (any charter), and Pie Control opens from the NOC tab, next to the NOC dashboard; in Sandbox it is there from day one. Build a pie factory and a launch pad on the coast (near the equator, launches are cheaper), fly rockets that carry satellites ("pies") into four orbital shells ("crusts"), and watch it all on a spinning cartoon globe with a night side, laser links between pies and launches that either spill their pies into orbit or end in a fireball. +- A new game now starts by asking what you are building, with three charters to choose from (#300). Global backbone is the classic game: grow everywhere and become Tier 1. Low-latency boutique: trading firms and other latency customers call more often and pay more, and you win Speed of Light by beating the fastest leased latency on finance routes with your own glass. Cable broker is new: lay fiber on land and cables under the sea from day one, light them and sell the capacity to other carriers, with ten goals of its own and the Glass Baron win when your own cables land on five continents while carriers pay you $1M a month. Every charter can still become Tier 1, and with it reach Pie in the Sky. +- Your pies carry real traffic and earn money once a crust is 40% full. Pie dishes (ground stations) at your POPs land the traffic on your backbone, with landing rights bought country by country. Homes and boats in the remotest places (Pitcairn, the Arctic, the outer islands), airlines, cruise lines and even a Mars mission sign up, and a town no cable reaches can join your network through orbit. Before a crust carries anything, buoys and sensors that live with gaps in the sky pay a little; when it starts carrying traffic, a grand opening brings a month of daily calls. +- Space is not quiet, and neither is your Founder. Solar storms, food fights in orbit, rain over tropical dishes, failed launches and geopolitical spats over data and landing rights keep you busy, and the Founder of your rocket company does something daft every few months, so markets get the jitters until it wears off. A full constellation pays for itself in about seven years if you run it well. +- Deals belong to Sales now: your salesperson can sign deals for you, orbit customers included. The NOC intern sticks to the network. The engineer, the shark and the CEO each sign in their own style, and each sells orbit their own way, from careful deals where a pie dish has room to Mars missions agreed with the Founder on the golf course. +- Governments pay for space too, in a new Government money section of the bank (Cash · Bank): the Rural Digital Pie Fund auctions support for remote towns only your satellites reach, the Export-Import Pie Bank lends against launches with strings attached, and the UK pays a grant when Pitcairn is served from orbit. +- Pie Control helps you plan: the Launch tab says how long each crust takes to fill at your current pace and points to a better pad when your pads are the bottleneck, the Dishes tab tells you when dishes are worth building, and the Traffic tab shows who rides your satellites, how full each crust and dish is, and why a sky is still empty. Traceroute follows packets through orbit too. +- The NOC tab is tidier: Pie Control sits in its top row next to the NOC dashboard, traceroute moved into Routing & DDoS, and All connections lives in the NOC dashboard. +- From customer level 9 you can lay your own subsea cable without being Tier 1 first (#300). +- Traffic now leaves your network at the nearest peering, so a PNI in London no longer pulls New York's traffic across the Atlantic when the New York IX reaches the same network (#298). Where a PNI and an IX port reach a network in the same city, the PNI still goes first, and RouteScript's `prefer pni` still hauls everything to your PNIs. +- Fabric (NNI) ports now grow like your other ports: buy them at 10G, 100G or 400G (as fast as your router takes), and bundle up to eight into a LAG when one is not enough (#140). A fabric customer is no longer accepted, by hand or automatically, when its bandwidth would not fit on the port as well (#307). +- Pressing Space to play again after a pause now picks up at the speed you were playing, not always at 1× (#299). +- Your own subsea cables now land right on the city's dot, also in Fujairah, Dubai, Karachi, Barcelona, Osaka and other cities the map shifts slightly so they do not overlap (#305). +- Starting a new network no longer leaves the last one's "New POP!" and money pop-ups frozen all over the map until a reload. + +## [2.10.1] — 2026-11-05 + +- "Meet halfway" on a renewal now offers the price halfway between what the customer pays and what they ask, and the button shows it before you press (#293). +- Fujairah sits on the UAE's east coast again, where its cables land, instead of on top of Muscat (#295). +- Puzzles on phones no longer scroll. A bar at the top shows the stars, the money and the one thing to do next, with a chip for every flow that turns green once it all arrives; tap a chip to jump to its city. A city or a link opens a short card at the bottom, split into tabs (links, router, traffic; size, traffic, routing), so every button is on screen at once. Architect runs get the same bar, and Reset is in the ☰ menu on phones. + +## [2.10.0] — 2026-11-05 + +**The map now runs on your graphics card.** Panning, zooming and fast play stay smooth even on huge networks. If something looks wrong or your phone gets warm, switch back to the old map in **Settings › Map drawing › Always 2D**. Older browsers stay in 2D on their own, and Settings › Diagnostic info shows which one you have. + +**Customers sign contracts now.** When one ends they renew, grow, haggle or leave, and bandwidth gets cheaper every year. To bring in more deals, hire someone to run sales: an engineer who goes to every NOG, a shark who oversells, or the CEO, who thinks he sells best. + +**Also new:** a "No POP yet" tab on the dashboard, clearer puzzles on phones, Gothenburg, Malmö, Haparanda and Bilbao on the map, and tooltips on the NOC charts. + +- The map is now drawn by your graphics card, so panning, zooming and fast play stay smooth on big networks (#281). If it looks wrong or your device runs hot, go back to the old drawing in Settings › Map drawing › Always 2D. Browsers without WebGL2 stay in 2D on their own, and Settings › Diagnostic info shows which one you are on. +- Customers sign contracts, and when one ends they renew, grow, haggle or leave (#178). Bandwidth prices fall over the years and rise when hardware is short, and the dashboard shows who you won and lost each month. +- You can hire one person to run sales: an engineer, a shark or the CEO himself. Each brings different deals and leaves their mark on the customers they sign. +- The NOC dashboard has a "No POP yet" tab listing every city you could still expand to. +- Puzzles explain their goals in plain words, with a Show me button and marks on the map, and fit phones better. +- Sweden gets Gothenburg, Malmö and Haparanda (#206). +- Bilbao joins the map, where the transatlantic cables really land; Columbus III-and-a-half now lands near Cádiz. +- NOC charts have tooltips, and their legend can hide a series. +- Leasing dark fiber costs more, alien waves are priced against the fiber, and extra crews can only halve a land build (#203). +- Clean traffic sent back by a scrubbing center no longer shows as DDoS junk on your links (#289). +- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in. +- Fixes: a link ordered by the AI tools can no longer end in a city the map does not show, and names from a save file always show as plain text. + +## [2.9.1] — 2026-11-04 + +- Jokes in the game now poke fun at networks, cables and routers, never at people, countries or beliefs. A few networks have new names (Atlas Hold-the-Line Telecom, Star-Blink, Telekom Malay-tency, Oh Yas Sénégal, Afghan Tele-Pass, Island-Hop Micronesia, Tel-One-derful, Tango Two-Step), so do three of the names for your own cables, and about forty descriptions of networks, cities, cables and events were rewritten. +- A network operators' meeting that hires you for its event network now meets only where it really does: NANOG in the United States, APRICOT in Asia Pacific and Oceania (not mainland China or Hong Kong), DENOG in Germany, UKNOF in the UK, RIPE in Europe, the Middle East and Africa, and DKNOG in Copenhagen. +- North Korea now moves well under 1 Gbps, and no customer of any kind calls from there. + +## [2.9.0] — 2026-11-04 + +- In Architect runs, a diverse second tube now takes the cheapest other route, as a new tube does, so the Euro Run's plain plan fits its budget again. A failed review also says that every site still connected after a cut needs room for its traffic, not only the mission-critical ones (#282). +- A new button next to the speed controls opens a NOC screen in a window of its own, to keep on a second display beside the map. It is a dark wallboard with a live world map of your links and POPs, traffic and money graphs, alarms, and your hottest ports with their upgrade buttons, which work on the running game; click a POP to see its ports. Details has the full dashboard, and Full screen fills the display. The new window only shows and sends clicks: your network is still played and saved in the game window. Phones do not show the button. +- Cities of one country on one piece of land can be joined by fiber over land, even where there is no road: Pevek to Anadyr or Moscow, Juneau to Seattle, Nuuk to Sisimiut. Inside one country, crossing from Europe into Asia (Moscow–Vladivostok, Istanbul–Ankara) is no longer priced as a crossing between continents. +- No circuit of any kind can be built between North and South Korea, and nothing leaves South Korea over land: every way out is a subsea cable. +- The map zooms in twice as far, for crowded regions like New England or around Washington. +- Cable ships at anchor sit a little further out from their port, and a tap on a city picks the city even with a ship close by. +- With a credit rating of AA or better you can now call a bank from the Bank window and ask for the amount you need. The better your rating, the lower the rate and the more they will lend, up to a limit based on your revenue and what you already owe, but weird conditions always apply. (#251) +- Agents playing through the Agent API can no longer start a link in a city where you have no POP, just as on the map. Before, an agent could sign a dark fiber IRU, lease a wave or lay a cable from such a city; now it is told why, and so is its dry run. +- Build POP in a small city that is off the map now says why it can't, and names a city nearby to build in instead. Founding your own exchange where you can't (mainland China, a city that already has one, a city with no POP) says why too. Before, both did nothing without a word, and an agent's dry run quoted a price. + +## [2.8.0] — 2026-11-04 + +- Every capital of the world is now on the map, with Africa's 33 capitals completing the set. They run from Porto-Novo, Bamako and Niamey to Khartoum, Juba, Mogadishu, Brazzaville, Tripoli, Rabat and Pretoria. Each country brings its real telcos, Nigeria gets its wholesale backbone up to Abuja, and the island capitals of the Comoros, São Tomé and Equatorial Guinea sit on their real cables. +- The NOC intern has a new order, Keep peering headroom, that adds capacity to your PNI and IX ports before they fill up (#234). A single port at a POP with several routers gets a second port in a LAG; any other port moves up to the smallest size that fits. It has the same Headroom and Budget dials as the transit order, and it waits out DDoS floods, link faults and PNI augments already on order. The monthly figure in the intern's log now counts IX ports too. +- An exchange port, a transit port or a PNI can now be stepped down one size from its panel, so shrinking a port no longer means leaving and rejoining (a PNI cannot while an augment is on order). +- The traceroute can follow the metrics, the lowest latency or the quietest links, like a customer circuit. +- Money now shows billions ($1.20B) and bandwidth shows petabits (1.00 Pbps) instead of running on in millions and terabits, including on the NOC graph and the fiber labels on the map. +- Latency customers only ask for a ceiling something you can build meets. Before, a Mars ground station could ask for 4.3 ms between Pevek and Anadyr, where the only sea route takes 7.7 ms at best. (#273) +- DE-Kicks ports stop getting dearer once they cost four times the list price. Before, the yearly price harmonisation kept compounding, so a long game ended up paying $100k a month for one port at Frankfurt or Mumbai. +- Your own subsea cable from Buenos Aires to Santiago now earns The Long Way Round, like a wave leased on the old ring round Cape Horn. (#272) +- Every capital in South, East and Southeast Asia and the Pacific is on the map: Thimphu, Kathmandu, Bandar Seri Begawan, Phnom Penh, Vientiane, Ulaanbaatar, Naypyidaw, Pyongyang, Dili, Hanoi and Wellington, with the island capitals Tarawa, Palikir, Yaren, Funafuti and Port Vila. Each country brings its real telcos, North Korea reaches the world only through China and Russia, and the islands hang on their real cables. +- Every capital in the Middle East, the Caucasus and Central Asia is on the map, from Yerevan and Baku to Kabul, Tehran, Baghdad, Jerusalem, Amman, Kuwait City, Beirut, Damascus, Sanaa and Manama, with Ankara and Islamabad. Each country brings its real telcos, and Bahrain is an island on the Gulf's cables. +- Every capital in Europe is on the map: Tirana, Andorra la Vella, Minsk, Sarajevo, Zagreb, Nicosia, Vaduz, Vilnius, Valletta, Chișinău, Monaco, Podgorica, Skopje, San Marino, Bratislava, Ljubljana and Bern. Each country brings its real telcos, exchanges sit only where real ones do, and Malta and Cyprus are islands on the real PEACE, MedNautilus and Blue cables. +- Every capital in the Americas is on the map: the eastern Caribbean islands, Central America, Haiti, Guyana, Suriname and Bolivia's constitutional capital Sucre. The islands land the real cables (ECFS and Southern Caribbean Fiber), Flow and Digicel serve all of them, and Belize, Guyana, Suriname and Haiti get their own national telcos. +- Every US state capital and Washington, DC are on the map, with every Canadian provincial and territorial capital and Greenland. Greenland's capital Nuuk and three towns up the coast hang on the real Greenland Connect cables; Iqaluit has only satellites, so land your own cable there. New carriers sell transit in the north and the Canadian provinces, and exchanges sit only where real ones do. +- If you run the game on your own computer, an AI agent can now play it in your browser while you watch. Turn the Agent API on in Settings (the section only appears in a copy of the game you run with npm run dev, never on seriesoftub.es) and point an AI client at the game's MCP server: every move happens live on your screen, and docs/MCP.md in the repository explains the setup. You choose the clock: a pace from one simulated day every 30 seconds to 5 minutes, which nobody can pause and which waits while no agent is connected, or the agent moves time itself. Your game, your settings and the windows you open stay yours. +## [2.7.0] — 2026-11-03 + +- Three new cities in northern Australia: Port Hedland, Townsville and Alice Springs (#255). Port Hedland lands a new cable up the coast to Darwin and a branch of Darwin's cable out to Singapore; Alice Springs has no sea at all. In the wet season, November to April, fiber cuts in the tropical north, Darwin included, take twice as long to reach. +- New keyboard shortcuts: the arrow keys and W A S D move the map, [ and ] step through your POPs, $ through the open offers, - and = zoom out and in, n opens the NOC dashboard, and ? lists every shortcut. A letter right after n opens one of the dashboard's tabs, such as n c for Connections, and Help links to the list too. +- You can pay to hurry the survey, permits and factory of your own subsea cable, 30 days at a time (#258). Money only goes so far: the cable still has to be made, about two months plus a day for every 80 km, before the lay ships sail. +- Traceroute no longer shows an "embedded cache in your rack" hop on paths that leave over transit, an exchange or a PNI. Only traffic that really ends at one of your cache boxes shows it now. + +## [2.6.0] — 2026-11-03 + +- New Best Effort mode, the gentlest way to play: rare outages, no DDoS, no chaos monkey, no conferences and no cable ships, with sea cuts that mend on their own. PNIs are up the moment you order them, customers are more patient, a rescue loan from the Ministry of Tubes replaces game over, builds take days and prices never spike. A new Quiet notifications setting, on by default in Best Effort and available in every mode, only pops up trouble and milestones; everything else goes into the NOC log. +- Backbone, Auto-TE and DDoS settings now open from a Routing & DDoS button at the top of the NOC tab. They used to sit at the very bottom, below every notification; a red dot on the button says when Auto-TE is paused. +- The Build POP button now shows the whole price of a new POP, including the routers of your standard POP (#261). Before, it showed only the site, although the standard routers were paid for on top; a note under the button now lists them, and the intern's one-tap template prices them in as well. POPs that come with a new wave, dark fiber, your own subsea cable or a consortium seat now get the standard routers too, and those offers show the price with them. +- The intern's "Light more fiber" order has a new Optics setting: light new fiber with the biggest optic it can afford, to save channels for later (#262). Once a fiber is lit, the intern still adds more of the same optic and never swaps what is in there. +- Networks you reach through an exchange's route server now stay "via RS" (#265). With an Open peering policy, the peering desk used to turn some of them into separate sessions of their own. +- The tabs above the left panel no longer run off its edge on smaller screens and tablets. Counts such as finished goals now sit on the corner of their tab. +- Gaming customers no longer warn that they attract attacks in modes without DDoS attacks, such as Change Freeze. + +## [2.5.0] — 2026-11-02 + +**Mostly a performance release.** Big networks route their traffic on about half the processor time, days no longer freeze the game, and clicks that change nothing about your traffic answer at once, so phones last longer. Same routes, same results, just faster. + +- Big networks use about half the battery they did: each day's routing takes half the processor time, and reuses what it worked out the day before when only demand has changed. Where traffic goes does not change. +- The game no longer freezes while it routes each day's traffic on big networks. A background thread of the game does the routing, so the map, panels and buttons keep responding while days go by; what the day brings is exactly what it was before. Clicks that change your network still route right away. +- On big networks, clicks that change nothing about your traffic now answer at once: dismissing an offer or renaming your network no longer works out every route again, which also saves battery on phones. +- The calendar is real now: months have 28 to 31 days and every fourth year has a 29 February (#257). Monthly prices, loan statements, the intern's budget and paydays follow calendar months, and conferences fall on the 10th of their month. +- Cache boxes are sized for the traffic each city really sends (#260): Russian and Chinese cities get boxes for the networks people there actually use, and none for networks they cannot reach. Boxes already installed stay; remove idle ones from the POP. +- A 1.6T transponder on routers with 800G ports now takes two ports at each end, one for each 800G it hands over, and the optics list says so (#256). Before, a full 1.6T fit into a single 800G port. On 1.6T routers it still takes one. +- A plug-in optic that is too short for your subsea cable no longer sends you to submarine terminals and optical engineering, which cannot stretch it (#253). The hint now names the optics that do reach, such as the Sienna WaveMagic 1.6T for Perth to Cape Town. Optics the upgrades can stretch still get the advice. + +## [2.4.0] — 2026-11-01 + +- Cable ships now sail out to fix your subsea cables, and you can watch them on the map. A cut at sea calls the nearest free ship of its region's repair club, from ports such as Cornwall, Curaçao, Cape Town, Marseille, Vancouver, Tokyo, Manila and Singapore. The cut lasts while the ship sails out (about 500 km a day), splices for 3 to 5 days in shallow water or a week or two in the deep, and in some countries waits weeks for a repair permit. A ship is busy until it is home again. +- Doitsche Telekomm and Tangerine Telecom are now Tier 1s, as in real life (#194). In new games, going transit-free means a PNI with both of them too; games you already started keep the Tier 1s they were playing for. Doitsche now sells transit at the highest price in Europe and still charges for peering, and like the other Tier 1s, Tangerine now starts its PNIs at 100G. +- Cache boxes now share router ports through an aggregation switch: one port carries as many 100G boxes as its speed holds, so 32 fit on a 3.2T port (#252). Each site gets its own. +- Pick a standard POP: in any POP's Infra tab, make its routers the standard, and every new POP gets that model and number of routers right away, while it is still empty (#240). +- Big networks run faster: the map skips links off screen without working out their shape, and the Networks tab and the zoomed-in map draw faster. Where traffic goes does not change. +- A network the game once failed to load is no longer stuck as damaged: the next version of the game tries it again, and its menu has a Try again button. Before, it could only be exported or deleted, even after the cause was fixed. +- Save files of very large networks import again: the limit went from 8 MB to 64 MB. +- 400G cache boxes: a POP whose routers have 400G or faster ports now gets 400G boxes, at $1,000 a month instead of $400 for 100G, so big caches need fewer boxes and cost less per Gbps. Boxes you already have stay as they are. +- Clarovision now peers only over paid PNIs, like the real carrier, and free only with networks at customer level 11 or above (#213). A PNI you already have with it starts paying the fee. +- Opening a link from a list now moves the map to it, zoomed so the whole line fits beside the open panel. +- Traffic for a carrier now leaves through that carrier's own transit port at the same POP, instead of being shared with every other transit port there. Networks that buy transit from the carrier get the same treatment, and a new switch on each transit port, Carry here, pulls that traffic across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win, and Prefer only does so at the POP where you set it. +- When every ship of a region's club is out, a subsea cut waits for the first one back. A private charter of the quickest free ship anywhere jumps the queue for $1M plus $200 per km it sails; the NOC intern's rush-repair order can pay it within its budget. +- Building your own subsea cable now shows the survey, permits and cable factory first, then a lay ship laying about 150 km a day. Crews can no longer speed up a cable at sea: book a second lay ship before laying starts instead, for $3M plus $150k a day, and it lays from the other end to halve that part. +- Tap a cable ship on the map to see its name, its club and what it is doing. + +## [2.3.0] — 2026-10-31 + +- Clicking a city without a POP works again while the intern's transit order is set to Already connected (#249). Before, the city panel failed to open and the map stuck to the mouse. +- The intern's Accept free caches order, and the Request caches button, now add more cache boxes as demand to a network outgrows the ones you have (#248). Before, they stopped at one box per site. +- Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Globe-Trotter Telecom now sell transit. +- Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Globe-Trotter Telecom, Diverge and RISE & Shine reach Cebu, and typhoons can hit it too. +- Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao. +- Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. GotchaFIX ports cost what the real exchange charges, about $700 a month for 10G and $2,800 for 100G. In-Vitro-IX charges about double that. +- Waves between Philippine islands now cost more than waves out of the country: Manila to Cebu costs about twice Manila to Hong Kong. +- Manila, Cebu and Davao have more people online, in line with their real populations. +- Cable names on the map no longer pile on top of each other when you zoom in. Where short cables crowd together, a name that would cover another is left out, and selecting a city shows the names of all its cables. + +## [2.2.0] — 2026-10-31 + +- DDoS attacks are realistic now: most are small, the big ones are rare, and their size no longer grows with your network, so a big network is no longer hit by floods larger than the internet's record. Attacks go after one customer (gamers and hosting attract the most) or one city's subscribers, last one to three days, and On-call sees about one a month (#242). +- A flood now arrives on every port the internet reaches you on, so more POPs and more exits spread it thinner, and a port it fills slows every customer on it. Flowspec and scrubbing behind a full port can no longer empty it (#242). +- RTBH now blackholes only the customer under attack, upstream at your transits, most exchanges and about half your private peers: everyone else is saved and the target goes dark until you withdraw it. The IX blackhole button is part of RTBH now, and RouteScript's `blackhole ddos` does the same. +- Find any city with the new 🔍 button in the top bar, or press / on a keyboard (#218). Type a city, a country (in your language or in English) or an exchange, and the map jumps there. +- Cities on the map now show how big they are: zoomed out, bigger cities are bigger dots and megacities glow; zoomed in, a city's skyline grows from a hut to a megacity's towers. When cities crowd together, the smaller ones step back to a dot until you zoom in, so the map stays readable, and exchanges you haven't joined are quieter tags. +- An engaged scrubbing center now pulls the whole flood onto its own ingress and cleans up to its size, so your ports stay clear and only the target suffers if the center is too small. On-demand scrubbing takes half the flood on its first day instead of nothing for two days. +- Each router holds a limited number of Flowspec rules, shown in its POP: every attack takes one rule on each router it enters (a carpet bomb takes four), and when they run out, junk passes that router unfiltered. Bigger routers hold more. +- The NOC's attack card reads like the flood's path: who is hit, which ports are full, what Flowspec and scrubbing do, the result and the one thing to do now. Optional Auto-RTBH and auto-engaged scrubbing switches sit in the NOC, full ports pulse on the map, and Sandbox can send a test flood. +- Flood Season starts at customer level 4, so a 10T scrubbing center is within reach for the terabit floods; a flood you blackhole to save everyone else no longer counts as held. +- The intern's transit order has a new provider choice, Already connected: it only grows the transit you already buy at each POP, the smallest port first, and never signs a new provider, so several upstreams grow together and no customer's "no Cogentle" gets a surprise (#227). +- The intern's PNI order now counts the traffic the PNI list shows at each POP, so it no longer orders a PNI where a network's own cache boxes already serve most of its traffic (#244). +## [2.1.0] — 2026-10-31 + +- Your backbone now runs a technology you choose: plain IGP, LDP/MPLS, RSVP-TE, SR-MPLS or SRv6. Each step up costs plenty and uses less router CPU: label switching makes traffic that only passes through a POP cheaper for its router, and Auto-TE and RouteScript now need RSVP-TE or higher. Routers only run what they support, so a POP with an older router stays outside the backbone, and mixing vendors at the very top of what their routers can do brings interop failures. Networks that already have Auto-TE keep it exactly as it is. +- An upgraded backbone brings new customers: L3VPNs for enterprises from LDP/MPLS, flex-algo low-latency links from SR-MPLS and network slices from SRv6. +- A seat on a consortium cable can be lit with the optics you have: add regen sites in the landing stations along the cable. Before, a seat bought at level 2 or 3 stayed dark until long-haul transponders arrived at level 4. +- List spare capacity with a capacity broker as a standing listing: pick how many alien waves (or your spare pair) to sell, and the broker sells them off over time as carriers on that route want capacity. Each route's market is sized by the eyeballs at both ends, and a busy route sells in days while a road to nowhere sells maybe once, so renting out long empty fibers is no longer a money machine (#203). +- Two new routers for RSVP-TE backbones: the refurbished Brocadabra MLX-16 with 400G ports, and the Extremely Networks SLX 9740 with 1.6T ports. +- From RSVP-TE up, fast reroute has backup paths ready, so customers lose only half as much happiness while a link is cut. +- An interop lab in the NOC tests your vendors against each other first and cuts interop incidents by 60%. +- Four new badges for your backbone: Label switcher, Bleeding edge, Single-vendor shop and Vendor zoo. +- The chaos monkey's notice in the NOC no longer has an Open button that did nothing; the monkey's own card is right above it (#226). +- The puzzle list counts each section's own stars: architect runs show theirs next to their title, and the pack total now sits right above the packs, the stars that unlock the next one (#231). +- The intern's notes now name the exchanges it peered at: a city's first exchange showed as the city, so "Apfelwein-IX, London" really meant Apfelwein-IX and LYNX (#228). +- Cancelling an IRU, giving up your own fiber or decommissioning a POP now puts the optics on its fibers back on the spares shelf, instead of throwing them away (#229). +- Big networks freeze for less on every game day and every click: working out where traffic goes skips exits whose route is already full, so a game day takes about 40% less time (#210). Traffic goes exactly where it went before. +- Premium submarine terminals and Optical engineering can no longer be bought on a cable where they would change nothing (#198). The button now says so, and an upgrade that only helps together with the other one stays available. +- A wave size that is sold out on a route can no longer be reached by upgrading a smaller wave on it (#201). The upgrade button says how long it is sold out, just like when buying. +- Choosing Both for a PNI with one member now really splits it: the second member arrives in the other building when the augment lands, instead of joining the first (#219). +- The Open button next to your intern's weekly shift report in the NOC now opens the Standing orders sheet, where the whole week is laid out (#226). Before, it did nothing. + +## [2.0.0] — 2026-10-30 + +**Series of Tubes 2.0: one game, four doors.** Some of you wanted a calmer game, some a harder one, some a quick puzzle over coffee and some a playground where nothing can go wrong. So now every network starts behind a door, and the rules you pick stay with that network for good. Your saved games carry on exactly as they were. + +**Normal** comes in three flavours. Change Freeze is the calm one: a third of the outages, no DDoS floods, and deliveries in days instead of months. On-call is the game you know. BGP at 3 a.m. is for people whose pager is a personality: more outages, longer ones, more attacks, and fiery badges to prove you survived. In your first month you also pick a charter: a global backbone, or a low-latency boutique racing the speed of light. + +**Sandbox** is a real sandbox now: everything unlocked from day one, money that never runs out, and a chaos dial from nothing ever breaks to spicy. + +**Puzzles** are small networks that carry real traffic, routed exactly like the big game. Deliver every flow for the first star, stay on budget for the second, and survive any single cut for the third. When your build earns a star, the chaos monkey runs round the map snipping every trench and cable to prove it. A new puzzle arrives every Sunday morning, the same for everyone. + +**Architect runs** grow one network brief by brief. New sites sign up, some become mission-critical, a city closes, traffic outgrows its tubes, and the chaos monkey reviews every brief before the next customer signs. Three handmade runs to start, and a fresh one every Sunday with its HQ somewhere new. + +**Scenarios** are themed crises against the clock: a cut cable, a peering spat, a flood week, a race for low latency. A new one comes out every Sunday too. + +And in On-call and BGP at 3 a.m., a **chaos monkey** sometimes moves into your network for a few months and snips tubes on purpose, the ones without a backup path first. Outlast it without a customer noticing and it pays; throw it a banana if you have had enough. + +**Also new:** Tier 1 works like the real thing, so peering with the big club brings their customers along. A NOC intern carries out your standing orders. Customers call when your network can serve them, not only when your level says so. You can buy a seat on a consortium subsea cable, see at a glance whether a PNI is worth it, keep several networks and play two side by side, and every router model has its own face. + +### One game, four doors + +- A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before. +- Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips hardware shortages, sold-out routes and de-peering at exchanges. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. +- Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. +- Pick a charter in your first month of a Normal game: Global backbone (the game as you know it, and the default) or Low-latency boutique (#187). The boutique gets more trading firms, pays them 40% more and has its own win, Speed of Light: beat the fastest leased latency on three finance routes with your own glass while two latency customers pay you. It comes with a badge and shows on your share card. +- Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge under harder rules than before upgrades it in your collection on this device, and the badge list counts how many of each kind you have. On-call games earn the standard badges; Sandbox and puzzles earn none. +- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. +- A tidier start screen: language first, then your network's name, the doors, three compact difficulty buttons with the chosen one explained below, and one drop-down for your home city with the five suggested homes at the top. +- Pick your own AS number next to your network's name when you start (#135). Leave it empty and the game picks one, and the round green arrow in the name box suggests another name. + +### Puzzles + +- Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. +- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own. +- Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. +- In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. +- When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. + +### Architect runs + +- Architect runs, under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, mission-critical sites must survive any single trench or cable cut with room on the detour, and a chaos monkey runs round the map snipping tubes before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. +- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come. + +### Scenarios + +- A new weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands in. +- Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. + +### The chaos monkey + +- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. + +### Build your network your way + +- Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. +- Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price. +- Take a seat on a new consortium subsea cable (#173). Capacity conferences offer them, and now and then a consortium calls from level 2: pay your share of the build, wait for the ship, then own one, two or four fiber pairs and light them with your own optics, your way onto your own subsea glass before Tier 1. A cut on that cable cuts your pairs too. +- Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, never breaks a customer's or a bank's transit requirement, and shows what it adds to your monthly bill. The Ops sheet opens with the intern's mood and a weekly shift report, which is also the one notice a week the intern leaves in the NOC (#98, #100, #102, #181, #185, #192, #177). +- The intern only signs a customer after a trial run shows the network can carry them without hurting anyone else, and rushes every repair that has a price, while the budget lasts (#185). The bulk peering and PNI batches live in the Ops sheet, next to the orders that repeat them (#181, #192). +- Open a new city from a template in one tap: POP, broadband, transit, an IX port and the redundancy kit, priced up front, with your standing orders taking it from there (#98, #192). +- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. A POP's Infra tab shows the redundancy kit as one line with its price, above the rows it fills in. +- Order PNIs with one network or every network at all shared POPs from the Ops sheet: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time. +- Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf. +- Every router model has its own picture: open one of your POPs and its router sits next to the city's name. + +### Peering and Tier 1 + +- Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won. +- The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. +- Every network in a POP's PNI list now shows how you reach it today and whether a PNI there is worth the cross-connect (#175, #172). A chip says PNI here (with size and load), PNI elsewhere, which exchanges you peer at, whose customer cone carries it, transit only or not reached; a value line shows how much of its traffic leaves from that POP over transit, exchanges or other PNIs, and what a PNI there would save or cost a month. The best candidates get a ⭐ Worth it tag, the list sorts them first, filters to All, Via transit, Worth it or Already PNI, and groups networks by type, with idle groups folded. The same chip shows in the Networks tab and in the bulk PNI preview. +- Only Spätzle-IX now asks for 50% reach instead of 45%, since peering with the Tier 1 club brings their customers along. Two Tier 1 PNIs and the exchange are no longer quite enough (#114). +- Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days. +- Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. + +### Prices, routing and money + +- Prices now follow how connected each city really is, based on public peering and routing data. Every city on the map now has it, from Düsseldorf and Riga to Malé, the Caribbean and the Russian Arctic. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices. +- Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. +- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. +- Links can now use a custom routing metric, set either as a multiplier or as an exact cost. Pick Custom under Routing metric to fine-tune where your traffic goes; it explains how a link's cost is worked out and what each preset comes to on that link. +- Check a selected link’s redundancy against current demand: see disconnected endpoints, additional service loss and full fallback links without changing the live network. + +### Attacks + +- Attacks are more varied: sizes and lengths change from one attack to the next, and several can hit at once, each with its own controls in the NOC. Hosting game servers or cloud gaming makes attacks more frequent, as it does in real life (#153). +- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec and require dedicated mitigation (#153). +- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation (#153). +- Game server and cloud gaming customers now carry a “Gaming attracts attacks” note on their offers and customer lists, so you can see the DDoS risk before signing them (#153). +- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through (#153). +- DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center (#153). +- Live attacks now show how much traffic Flowspec actually drops. Routers without TCAM no longer claim to filter attacks, and Flowspec drops are counted separately from other edge filters (#153). +- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency (#153). +- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels (#153). +- Flood Season keeps sending ever larger attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off (#153). +- Flood Season escalates again: ordinary floods mixed with terabit monsters, all growing through the year, and floods go for the POPs that serve customers, so empty POPs no longer hold them for free. + +### Smoother and safer + +- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner. +- The Networks list shows 100 networks at a time, with a button for the rest, so it opens quickly now that every country has its own networks. +- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside. +- The China licence follows quick lead times: about 5 days instead of 45 under Change Freeze and in Sandbox. +- Imported saves can no longer change a network's rules or slip HTML into a Flood Season attacker's name. + +## [1.37.0] — 2026-10-28 + +- Series of Tubes now speaks German. The game follows your browser's language the first time, and you can switch to German under Settings or on the title screen. Networking terms like Peering and Transit stay in English, the way network engineers say them. +- Glowball Sakura Lager joins the map: a Tier 2 carrier in the big hubs of the US, Europe and Asia-Pacific that sells transit, takes PNIs and peers openly wherever it is. It is not a Tier 1, so it buys its own transit from three of them, while 13 smaller networks in its regions buy theirs from it, and one PNI with it reaches about 3% of all traffic. Far from home, in Asia and New Zealand, it charges more than the locals, and it sells no transit in Australia. +- China Telecomet now sells its CN-Too premium crossing in Moscow too, at the same price as in Hong Kong (#195). Haul your European traffic to Moscow and it reaches China with about 3% loss; nothing else of theirs is on offer there. + +## [1.36.0] — 2026-10-28 + +- You can put a link on standby, so one of two links between the same cities sits idle as a backup (#122). It carries traffic only when the other links are full or down, so its capacity is never wasted, and the map draws it dashed while it waits. The routing metric still applies to every link between the two cities. +- Start anywhere: the new game screen lists the five suggested home cities as a compact stack, and the last entry lets you pick any city on the map that sells transit, grouped by continent. Below the big start button, How to play, Import a save and Settings are now the same size. +- Language is now a dropdown on the title screen and in Settings, with each language named in itself. On phones it opens the system picker. +- Every new network starts at ½ speed, so you can find your feet before the bills arrive (#186). Saved games still continue at the speed you left them. + +## [1.35.1] — 2026-10-28 + +- Subsea cables stay at sea: Pacific cables no longer draw a line across the whole world where the map wraps round (#183), and over 170 cable routes that cut across Africa, Arabia, India, Brazil and other coasts now follow the sea. Cables into inland cities like Paris, Dublin and Hong Kong come ashore at the nearest coast. +- Found a bug or have an idea? The menu and How to play now link straight to the forms on GitHub, where every report is tracked. The Signal group stays for chatting. + +## [1.35.0] — 2026-10-27 + +- Series of Tubes now speaks Spanish. The game follows your browser's language the first time, and you can switch to Spanish under Settings or on the title screen. +- The Caribbean joins the map: San Juan, Santo Domingo, Kingston, Havana, Nassau, Port of Spain, Bridgetown, Fort-de-France and Willemstad, with their real cables, exchanges and island networks (#125). +- Alaska, northern British Columbia and Russia's Arctic and Pacific coasts arrive, from Nome and Utqiaġvik to Petropavlovsk and Vladivostok (#145). Towns with no road in are only reachable by sea, and the towns Russia's Arctic cable never reached have a beach for your own. +- Capacity conferences arrive: PTC in Honolulu and Capacity Europe in London, once a year from customer level 3. Attend, and carriers ask for huge deals (waves, subsea capacity, whole fiber pairs) that you sign first and build afterwards, with months to deliver and a penalty if you miss the date (#168). +- Seven more American networks, from AT&Tease to GFibber (#155). New games need a PNI with AT&Tease to become a Tier 1, Spectre-um swallows Coax a year in, and a year later Final Frontear goes to Very-Zone, which charges for peering. +- More real cables in the North Sea and the Baltic, with Kristiansand, Esbjerg and Riga as new landings. The Baltic ones get cut by dragging anchors more often than most, as they do in real life. +- More real cables across the Indian Ocean and Asia-Pacific, from SJC2: Electric Boogaloo to FLAG-pole Europe-Asia, with Muscat, Malé and Fukuoka as new landings. Older cables gain the landings they were missing. +- Yellow progress bars are slim again, like the green and red ones, instead of padded boxes. +- Réunion, Mauritius, Madagascar and the Seychelles join the map in the Indian Ocean, on SAFE and the island cables, with Réunion's exchange as Rougail SAUCIX (#152). +- Pitcairn is on the map with no cable at all. Land your own, launch broadband, and the UK pays a monthly grant while the islanders are online (#124). +- Five more Australian networks, with Neptoon on every exchange in the mainland capitals (#154). Musklink now also shows up in the US. +- São Paulo's exchange is now called IX.brrr São Paulo, like every other Brazilian exchange (#166). +- Sponsor a conference: some peering meetings sell sponsorships, and while the glow lasts more customers from that region come knocking (#168). +- Big POPs can now run up to 16 routers (#157). The standard cage still holds six: each router past that costs half again to install and adds rent for a cage extension. +- Huge networks stop stuttering every few seconds when their save is too big for the browser to keep: after a failed save the game waits a minute before trying again, then longer, instead of retrying every 5 seconds and after every click. Leaving the page, exporting and new games still save at once. +- Saves of long games are much smaller: the list of customer names already used kept growing by the same names every day (half of a late-game save). Older saves shrink when loaded. +- Maps with more than a thousand lines on screen draw about twice as fast: they leave out the link labels and the dots on lit fiber, which nobody could read in such a tangle. Zoom in and they come back; the selected link keeps its label. +- The map of a huge network spends less time working out fiber capacities on every frame, and skips links above or below the screen. +- Big networks with thousands of fiber customers no longer stall: each game day and each action is about two to three times faster, and new alien-wave offers no longer freeze the game for a moment. +- The game now tells you when it cannot save: a network too big for the browser's storage, or a browser that blocks it, used to stop saving without a word (#176). Export a save from the warning to keep a backup. +- Big networks take about 40% less space to save: saves leave out customer details the game can work out again when loading (#176). +- Huge networks fit in the browser again: saves over a million characters are compressed, about ten times smaller (#176). + +## [1.34.1] — 2026-10-27 + +- The game starts faster in Italian, Portuguese and French: their translations are about 40% smaller to download. + +## [1.34.0] — 2026-10-27 + +- Choose your peering policy: Open to all, Selective or Closed. Open accepts everyone and keeps the route servers, Selective means fewer requests but you ask peers yourself, and Closed scares customers away. +- One button now raises every max-prefix limit at once. Leaks included. +- Brazil is slimmer: 15 small cities next to bigger ones are gone from new games. Saved games keep their POPs there, and Order and Progress now needs 15 IX.brrr ports. + +## [1.33.0] — 2026-10-27 + +- Australia arrives: start in Sydney on hard mode. Expensive transit, a national network that keeps 45% of every broadband bill, real Australian exchanges and carriers, Adelaide, Canberra, Hobart and the South Island of New Zealand, new cables, very Australian outages and a new scenario, Fibre to the Basement. Older saves with Australian POPs are told once what changed. +- Hardware gets dearer over the years, and shortages come and go. Routers, optics and new builds cost about 4% more each year after your first six months (up to 30%), and laser, chip or cable-ship shortages add 30 to 50% for a month or two. Stock spare optics, or lock a year of prices from the NOC tab. +- Routes can sell out of a wave size for a while. The link window shows which sizes and for how long; never in your first 90 days. +- PNIs with the big networks are quicker again: usually about a month. About one order in seven still gets stuck for 6 to 12 months. +- Crowdflare offers free Rackstar cache boxes once you send it 10 Gbps. +- Smaller fixes: one button hires enough crews to finish a build in a day, and extra crews stop once they save no time (#103). Subsea upgrades move with the cable's finish date. Alien waves from the same carrier grow one contract, keeping big saves small. The broadband panel shows what homes really pay. Crowded POP names hide until you zoom in. Exchanges named after their city no longer repeat it (#134). + +## [1.32.0] — 2026-10-27 + +- Six Atlantic stops join the map: Halifax, Bermuda, the Azores, Tenerife, Cape Verde and St Helena (#120). The cables across the Atlantic now stop where they really land, and a POP on an island splits a crossing that is just too long for 1.6T into hops that each carry 1.6T or more: Miami to Madrid via Bermuda and the Azores, Atlanta to Lisbon via Bermuda, Lisbon and London to Lagos via Tenerife, and Fortaleza to Europe via Cape Verde. Halifax sits at the start of the shortest line to England. Three new cables, Sol Survivor, Atlantis-2: The Sequel and Canary in the Cable Mine, link the islands, and older ones gain island stops. Exchanges only where one runs today, in Praia and Halifax. New island networks from One Commotion to Pretty Sure South Atlantic, cables that go quiet in the Bermuda Triangle, and a new scenario, Mid-Atlantic Accent, asks you to cross at 1.6T hop by hop. Broadband in a very small town no longer starts above what the town can use. +- Backhauling users to transit far away now makes their internet slow, and slow is bad service. Users feel the round trip to wherever their traffic leaves for transit: up to 20 ms (about 1,500 km) is fine, beyond that service suffers, and past 50 ms broadband and internet services count as bad service, which costs revenue and customers. Traffic over your own peering, PNIs and caches is not penalised. Slow cities show a 🐢 in their panel, a warning in the Transit tab and a list in the NOC. +- The NOC now keeps every notification from the last 10 minutes near the top of its tab, newest first, so nothing that popped up while you looked away is lost. Each one shows its title, a short text and how long ago it happened, repeats fold into one line with a count, and an Open button takes you to the city, link, customer, bank or goal it is about. The NOC button in the top bar and the NOC tab on phones count the ones you have not read yet. Resolved incidents now say what was fixed and where. +- Peering now comes with an inbox: every IX port brings peering requests from networks you have never heard of, and sessions drop when someone blows past the max-prefix limit their PeeringDB promised. Answer requests, decide whether a max-prefix alert is growth or a route leak, and keep your reputation up, because selective networks hear when you never answer. For $20M a year the Large Peering Model AI answers it all for you, quickly and often wrongly. +- PNIs take time: a cross-connect with a small network takes a few weeks, and the big content networks, Tier 1s and big eyeball networks quote 6 to 12 months for a new PNI or an augment. The content networks and Tier 1s no longer do 10G PNIs (100G and up), Doitsche Telekomm still sells 1G, and Microsnoft has no capacity on the US east coast at all. +- Backhauling users to transit far away now makes their internet slow, and slow is bad service. Users feel the round trip to wherever their traffic leaves for transit: up to 20 ms (about 1,500 km) is fine, beyond that service suffers, and past 50 ms broadband and internet services count as bad service, which costs revenue and customers. Traffic over your own peering, PNIs and caches is not penalised. Slow cities show a 🐢 in their panel, a warning in the Transit tab and a list in the NOC. +- RouteScript has a new “Slop it with AI” button: an AI reads your live traffic, writes you a script and tells you how great it is. A new help page explains what every rule does and how real routers do the same, with seven ready-made scripts (Penny Pincher, Peering First, Shields Up and more) filled in from your own network and loaded with one tap. +- New player-built subsea cables follow surveyed sea routes around land (#133). Their map paths, prices, optical reach and latency use the same distance, and premium designs are consistently faster. Like real cables, routes between Europe and Asia cross Egypt beside the Suez Canal and routes between the Caribbean and the Pacific cross Panama, except during the Red Sea Crisis, which shuts the canal. The low-latency design is still as fast as the fastest cable on the map: it can follow that cable’s corridor, or land a little further off and run to an inland city over land. Quotes change with the real sea distance, cheaper on some routes and dearer on others. Existing cables keep their saved characteristics. +- You can zoom in much further on the map, and a short link between two close cities can now be picked (#126). Dense regions like southern Brazil spread out properly when you zoom in, and tapping right on a link next to a city opens the link instead of the city. +- The NOC now keeps every notification from the last 10 minutes near the top of its tab, newest first, so nothing that popped up while you looked away is lost. Each one shows its title, a short text and how long ago it happened, repeats fold into one line with a count, and an Open button takes you to the city, link, customer, bank or goal it is about. The NOC button in the top bar and the NOC tab on phones count the ones you have not read yet. Resolved incidents now say what was fixed and where. + +## [1.31.0] — 2026-10-26 + +- Series of Tubes now speaks French. The game follows your browser's language the first time, and you can switch to Français under Settings or on the title screen. +- Your own subsea cables now come in three designs, from the budget route to one as fast as the fastest cable on the map, and two upgrades carry faster channels further (#65). Each design shows its latency, price and build time before you order: optimized costs three times as much and low latency seven times, and both take months longer. Premium terminals and optical engineering light longer routes at higher speeds, so a cable as long as New York to Sydney can now carry traffic, and the order screen tells you which upgrade a route needs. Calling off a cable while it is being laid refunds what you actually paid for it. +- A new Road to Tier 1 card in Goals shows what still stands between you and Tier 1 (#111, #121, #12). It counts the transit ports left to cancel, names the Tier 1s you still need a PNI with and what they want from you first, and shows how much of the internet you would still reach without transit. The Networks tab can list just the networks you reach only through transit, biggest first, each with why it is not peering with you yet and where to meet it: the cities for a PNI and the exchanges it sits on, your POPs first, then the nearest. Who your transit carries, in the NOC, names the nearest city when a network is not in yours and takes you straight to it. +- You can now run a scrubbing center in every POP, not just one (#117). An attack goes to the nearest working center and spills to the next when it is full. A center in another city means the flood rides your backbone there and back: it fills your links, adds latency, and whatever your links cannot carry is not scrubbed. DDoS protection customers mind when their attacks are hauled across an ocean, some new customers ask for a center on their own continent, and the NOC shows where each attack is being cleaned. +- Düsseldorf joins the map with the Altbier-IX (#108). It is Germany's second carrier hub, an hour from the Dutch border, and the networks you meet there are the ones really present: Voda-Phony's home market, Doitsche Telekomm, the big Tier 1s and the clouds. +- Spare capacity on your dark fiber is now easy to sell (#51). Each fiber shows its free channels and who rents alien waves or a spare pair on it, and a capacity broker can list it for you: an offer turns up at once, and the broker keeps 10%. +- Red Sea Crisis now asks you to keep 80 Gbps flowing between Asia and the rest of your network for 30 days in a row, instead of 300 Gbps served anywhere, which broadband alone could reach on day 0 (#113). The scenario card shows today's traffic to and from Asia and how many days in a row you have held it. +- Only Spätzle-IX can now be won with peering alone (#114). The goal is now 45% reach and 300 Gbps served, and the scenario card shows your reach as well as your traffic. +- PNI buttons now show the monthly port fee next to the one-off setup cost, so a $1.8k cross-connect no longer looks like a monthly bill (#110). Upgrading a PNI shows what the bigger port costs per month too. +- Luxembourg gets its own eyeball network, Poste Restante, at LU-SICK in Bettembourg, so there is a reason to peer there (#84). + +## [1.30.0] — 2026-10-26 + +- Twelve Pacific islands join the map: Honolulu, Guam, Koror, Majuro, Port Moresby, Honiara, Nouméa, Suva, Nuku’alofa, Apia, Pago Pago and Papeete. The cables across the Pacific now stop where they really land, and a POP on an island splits a long crossing into shorter hops that each carry more: California to Sydney goes from 400G to 1.6T per wave via Honolulu and Suva, Hong Kong and Manila to Los Angeles from 400G to 800G via Guam, and Santiago to Sydney from 400G to 800G via Tahiti. Twelve new cables, among them SEA-US Later, Echo-Chamber and Coral Sea Shanty, link the islands, and the old ones gain island stops. Only islands with a real exchange today get one: Honolulu, Guam, Suva, Nouméa and Honiara. Island telcos from Hawaiian Telecombo to Never Too Atoll join the networks, PacNOG meets in Suva every December, Guam, Port Moresby and Honiara have unreliable power, Tonga’s cable has a volcano for a neighbour, and a new scenario, Stepping Stones, asks you to hop the Pacific at 1.6T. +- Big networks are snappier again: working out each day's traffic takes about a third less time on phones and half on desktops, so game days and clicks pause for less. Traffic goes exactly where it went before, and the game makes far less garbage for the browser to clean up. +- Your own subsea cable can no longer be longer than any optic can light (#88). New York to Sydney now says so before you pay, instead of after the ship comes home. Calling off a cable while it is still being laid returns most of the price of the part not laid yet, and an unusable cable from an older save goes back for a full refund. +- Your own IX can now live in either building of a two-site metro, or in both with a second switch, so a dark building no longer takes your exchange down (#36). The LAG buttons that did nothing on your own IX are gone. +- Upgrading the only router in a POP that has nothing plugged in yet no longer opens a maintenance window or a NOC warning (#105). +- Declining a loan offer clears the bank badge right away, even while the game is paused (#104). +- The 3.2T transponder now falls back to 1.2T between 4,000 and 5,500 km (6,000 to 8,250 km subsea), like the 1.6T one, instead of dropping to 800G (#107). A bigger optic now carries at least as much as a smaller one at every distance. +- Parallel waves of different sizes now show each size on the map, like 800G + 400G, instead of a misleading 2 × 1.2T (#56). +- Picking a subsea route from a city without a cable landing, like Oslo, now names the nearest landing station instead of saying its cables reach "nowhere" (#50). +## [1.29.0] — 2026-10-26 + +- Big networks lag a lot less: on a network with a hundred POPs and a thousand peering ports, the NOC dashboard opens six times faster, the side panels three times faster, and each game day takes about a third less time. The map needs about a third fewer drawing steps per frame, and open panels only update what changed, which keeps them smooth and lets the traffic bars glide to their new values. The connection and customer lists in the NOC dashboard show 100 rows at a time, with a button for more. While the game is paused or animations are off, the map is only redrawn when something on it changes, which saves a lot of battery on phones. On a phone, the map also rests while the NOC dashboard fills the screen, so scrolling it stays smooth. +- Africa grows from five cities to twenty-six, across nineteen countries, and a new scenario, Cape to Cairo, asks you to cross it. New: Dakar, Abidjan, Accra, Douala, Kinshasa, Luanda, Casablanca, Algiers, Tunis, Djibouti, Addis Ababa, Mombasa, Dar es Salaam, Kampala, Kigali, Maputo, Durban, Windhoek, Lusaka, Harare and Gaborone, each with its own IX. Overland fiber across an African border costs twice as much, and Kinshasa, Lusaka and Harare have unreliable power. +- Brazil now has all forty IX.brrr locations, from Manaus to Lajeado, so you can build a real national network. Fiber into the Amazon costs twice as much and its repair crews go by boat, Oi Oi, TIM-TIM Mobile and Brisanada join Brazil's networks, and a new scenario, Order and Progress, asks you to peer on 20 IX.brrr exchanges. +- Series of Tubes now speaks Portuguese (Brazil). The game follows your browser's language the first time, and you can switch to Português under Settings or on the title screen. +- Come chat with other players in the new Series of Tubes Signal group. It's linked from the title screen, the menu and How to play: share screenshots, report bugs and argue about peering policy. +- RouteScript speaks more BGP. `prefer transit` and `avoid transit` set which upstream goes first, like local-pref, `prepend transit PROVIDER 1-3` moves part of an upstream's traffic away, the way AS-path prepending nudges the rest of the internet, and `protect customers` routes business traffic first when links are congested, so home users take the hit instead of your SLAs. A new Optimize button drafts a script from live traffic and points out networks you could reach over an IX or a PNI instead of transit. +- Twelve more Latin American cities: Montevideo, Asunción, Córdoba, La Paz, Quito, Medellín, Caracas, Guatemala City, San José, Querétaro, Monterrey and Guadalajara. Moviestar, Liberty Latte America, Antelope and Tiger Mobile join them, and Salvador and Montevideo get cable landings. +- Seven new cables around Africa (ACE of Spades, SAT-3-Legged Stool, MainOne-Track Mind, Mint Tea West Africa, Set SAIL, Sea-Comedy Hour and Dare-Devil-1), and the existing ones now stop in the new cities. Set SAIL and SACS-y Cable link Brazil to Cameroon and Angola, and Sea-Comedy Hour links Djibouti to Mumbai. Liquid Lunch Networks, Sea-Comedy Networks, Angle-a Cables, Djibouti Calling, Empty-N, Air-Tell Africa, Ethio-Tele-Calm and Atlas Hold-the-Line Telecom join the networks. +- Hamburg and Munich join the map, with the Moin-IX and the Brezn-IX. Stuttgart and Frankfurt are back where they belong on the map, with Stuttgart between Frankfurt and Zurich instead of halfway to Prague. +- Swapping router models now sells the old ones on eBuy for 30% of their price, and removing a router does too (#82). A POP takes one swap a day, so a double click no longer buys two upgrades, and optics and waves now say which port speed they need instead of naming one model. +- Fiber between nearby cities bends gently again instead of looping wide around the neighbourhood, so dense regions like Toronto, Ottawa and Montreal stay readable. +- The game no longer gets slower after a long pause. The money that floats up from your cities on payday kept piling up off-screen instead of fading, hundreds of them on a big network. + +## [1.28.0] — 2026-10-25 + +- Belgium and Luxembourg join the map: Brussels, Oostkamp and Bettembourg (#79). Belgian POPs and transit cost more, and Belgian homes stay with their two big ISPs unless you run an ad campaign there. Telenyet, Proxyminus, B.I.G.S., Citrus Belgium and CityMess join the networks, a new cable connects London to Oostkamp through some very busy fishing grounds, and Bettembourg's cooling depends on a steady supply of waste wood. +- Four new cities in North America: Kansas City, Calgary, Vancouver and Ottawa (#76). Canada gets two more big networks, Tell Us and Bodgers Communications, which you also reach through the Tier 1s they buy transit from. Ottawa's power grid is about as reliable as you would expect, and Canadian fiber has a new natural enemy. +- New waves can join any route you already have between two cities, so two waves can run on the main route and two on the diverse one (#77). Each extra route shows up as its own choice, priced like the route it joins. +- Embedded caches can now sit in either building of a two-site metro (#69). A new box goes to the building with fewer of them, you can move boxes between A and B in the Peering tab, and a dark building only takes out the boxes inside it. +- Reach in the top bar no longer rounds up to 100% when it is just short, and the Goals tab now says why you are not Tier 1 right now (#73). Tier 1 needs more than 99.9% reach, so one small network out of reach is enough to lose the title. +- Customers in Russian cities no longer get unhappy because of Goggle's throttling (#70). People there simply get, and ask for, half as much Goggle video, so a well-built network serves the whole city again and the throttled half no longer fills your links. +- Incidents now come first in the NOC, with the ones you can fix in one click at the top (#63). No more scrolling past hot ports and congested links to replace a broken optic. +- Opening a link from the NOC on mobile now closes the NOC sheet so the link details are visible. + +## [1.27.0] — 2026-10-25 + +- New "Leased lines" tab in the NOC dashboard shows which leased waves, fabric circuits and dark fiber IRUs between your POPs you could replace with cheaper capacity: leased dark fiber, your own fiber or your own subsea cable. Each option lists the up-front cost, the monthly cost, how much you would save and when it pays for itself, with a button to plan the build. +- You can now upgrade, grow and cancel transit, PNIs, IX ports, cache boxes and fabric ports straight from the Connections tab of the NOC dashboard. Each row offers the next port size and another LAG member at the same prices as the POP panel, and cancelling asks you to confirm first. +- DKNOG in Copenhagen joins the conference calendar every March. +- A PNI in the customer’s city now meets their local-breakout requirement while your network is Tier 1 (#20). +- Customers no longer ask for independent routes where the available cables cannot provide them. Impossible diversity requirements in older saves are removed. +- A deal’s “Go there” button takes you to a required city without a POP, instead of returning to a city you already serve. + +## [1.26.1] — 2026-10-25 + +- Subsea cables no longer disappear when you zoom in on the map (#49). + +## [1.26.0] — 2026-10-25 + +- Customer levels now go up to 13 instead of 4. Every new level asks for more peak traffic, POPs and continents, ending at 50 Tbps and 80 POPs on six continents, and each one unlocks new customers, gear or deals. Reaching level 13 earns a new legendary badge. +- Seven new router models arrive between levels 5 and 13, including the first 3.2T routers with 3.2T ports and 12.8T waves. The Absolute Unit 3.2T is the main upgrade; whitebox, licensed, deep-buffer, Finnish and budget side-grades sit next to it. +- Paid-peering giants now give you a free PNI once you are big enough. Doitsche Telekomm gives in at level 6, then Voda-Phony, Tel-Mess, Etis-a-lot, China Moble, Du-opoly and Ooh-redoo. +- Loans got stranger, and good ones got harder to get. Your credit rating now adds a + risk premium to the interest rate, the big banks only lend to strong ratings, and a + loan worth more than five months of revenue also takes 2–8% of your revenue until + it is repaid. +- Your own subsea cables now run much faster optics over long distances (#66). Subsea fiber is built for its whole route, so optics reach about half as far again as on land: Paris–Ashburn gets 1.2T per channel instead of 400G, and the 1.6T transponder gains a 1.2T long-haul setting on land too. +- Leased subsea waves now follow the same physics as your own cables (#68). A wave can only be as fast as its cable's length allows: transatlantic still takes 6.4T, the longest transpacific cables top out at 400G or 800G. Waves you already have keep running. +- You can lay your own subsea cable between two landing stations that also share a landmass, like Marseille–Singapore or Cairo–Palermo (#67). +- Declined PNI requests no longer repeat over and over behind an open window such as a DE-KICKS quote. Buttons hidden behind a window can no longer be pressed with the keyboard, and a declined PNI now shows why straight away instead of leaving its button there. +- New customers at the higher levels: esports world finals, sovereign cloud regions, cloud gaming platforms, metaverse platforms, AGI labs and Mars mission ground stations. +- Traffic keeps growing as you level up. Levels 5, 8, 10 and 12 each start a new era (4K everywhere, cloud gaming, VR, AI agents) that raises how many eyeballs every city wants. +- New optical gear for big networks: ROADMaster 9000 C+L line systems with 128 channels, Sienna WaveMagic 3.2T transponders, and eight fiber pairs in your own land trenches. Your own exchange gets a 102.4T fabric and scrubbing goes up to 100T. +- The "Next level" hint keeps names like Edge Lord 400 readable instead of lower-casing them. +- Your own subsea cable now runs beside the existing cable on its route instead of looping far out to sea (#64). Leased and own fiber next to a busy trench no longer swing out in giant loops either, on any route. +- New lenders: Ballooney Brothers (nothing to pay until it all comes due at once), + Stormy Weather Lending (every open incident adds 2% to your rate), Peer Pressure + Partners (you repay with 30% of your transit bill), Horoscope Holdings (the stars set + your rate each month) and Papa Pizza Capital (cheap, but every incident means pizza + for the NOC). +- New loan conditions: an odd number of POPs, no building in Bude, no diesel + generators, no new links on a Friday, no Goggle caches, a job for the CEO's nephew + and a yacht for the chairman. +- The in-app "What's new" is shorter: the first sentence of each change, at most + five, with a link to the full release notes on GitHub. + +## [1.25.2] — 2026-10-25 + +- Tier 1 networks can lay their own subsea cable (#22). Pick two cities with a + cable landing station, pay a frankly rude amount of money, wait while a cable + ship crosses the ocean, and own up to eight fiber pairs outright. It pays for + itself in a few years if it replaces enough leased waves. Whales may cause + delays. + +## [1.25.1] — 2026-10-25 + +- Once you have half a billion in the bank, the banks stop sending loan offers + (#52). They come back if your cash drops below that again. + +## [1.25.0] — 2026-10-25 + +- Your own trench can carry more than one fiber pair (#35). Once a ROADMaster + 9000 has all 64 channels lit, light the next pair: another ROADMaster and + another chain of amplifiers for 64 more channels, up to four pairs. + +## [1.24.0] — 2026-10-25 + +- New scenario: Flood Season. Amsterdam in peak botnet season: a DDoS flood + every few days, a third of them in the terabits and growing all year, on + top of everything else that breaks. Hold 20 floods, 5 of them over 1 Tbps, + with the city under attack still getting 97% of its traffic. Expect smart + toasters, sentient fridges and one very determined printer. +- Fixed: when a DDoS attack started while another was still running, the + first one ending could wipe out the new one early. + +## [1.23.0] — 2026-10-25 + +- Fixed: on a phone, a first-time player could not get past the "Play it as an + app" screen in the browser, and the Install button on the title screen did + nothing. Settings now also opens from the title screen, as promised in 1.20.0. +- Taps land where you meant them (#44): a tap only presses the button it started + on, nothing behind a menu that opened or closed mid-tap counts, a toast that + pops up under your thumb ignores taps for half a second, and panels no longer + redraw under your finger. +- The world map draws much lighter (#43). The detailed coastline is now painted + once into an image and reused, also when zoomed in, instead of being redrawn + every frame. This should fix the garbled map on Firefox for Android, and makes + zooming smoother on every phone. +- Cairo now reaches the Middle East overland across the Sinai, like Istanbul + does across the Bosporus (#47), at the same intercontinental price. +- The Tier 1 label shows what you are now (#46): buy transit again or lose a + Tier 1 PNI and it drops, with a message saying why. Your Tier 1 badge stays. +- When an update adds new networks, you get a free 60-day courtesy route to + the ones you cannot reach yet (#46), so your reach no longer drops overnight. + Saves from before this version get it too. +- Unplugged optics go on a spares shelf instead of in the bin (#45): the next + channel of that type uses a spare for free, or you can sell spares on eBuy + for 40% of their price. + +## [1.22.0] — 2026-10-25 + +- Scenarios show their goal and your progress at all times (#34): a card at the + top of the Goals tab breaks the goal into steps with progress bars and shows the + days left. The top bar on desktop, and the Goals tab on phones, show how far you + are. +- Your customer level is always visible too: a card in the Goals tab shows what + the next level unlocks and how close you are to it, and the Rank box shows + your level. +- The NOC dashboard has tabs: Overview, Customers, Connections, Traffic and + Links & routers, so you no longer scroll through everything at once. +- The share card draws links that cross the Pacific on both edges of the map + (#42). + +## [1.21.0] — 2026-10-25 + +- The world map now has real coastlines (#41, thanks @aulmaru). Greenland, the + Arctic, Indonesia, the Philippines, Japan, Madagascar, Tasmania and New + Zealand show up properly, and the Mediterranean, Black Sea, Red Sea, Gulf and + Baltic have their real shapes. Zoomed out, the tiniest islands are left off so + the map stays readable. + +## [1.20.0] — 2026-10-25 + +- A proper Settings screen, from the menu or the title screen: alerts, animations, + sound and language in one place, saved on your device. +- The game can pause when a customer turns furious, so you no longer lose + customers to a notification you missed at 8× speed (#13). It is on by + default and can be switched off in Settings, where you can also choose to + pause on outages that cost you real traffic. +- Customer happiness is easier to keep an eye on (#15). You get an early warning + when a customer drops below 60%, with the reason. A Customers box in the top bar + (on phones, a red count on Deals) shows how happy they are overall. +- A Customers list in the NOC dashboard shows everyone who pays you, unhappiest + first, with what they pay, whether they are getting happier or angrier, and + exactly what is wrong. Filter it to the unhappy ones or by city, and tap Open + to go to them (#14). + +## [1.19.0] — 2026-10-25 + +- See all your connections in one place (#31, #33, #38): a new Connections list + in the NOC dashboard shows every transit port, PNI, IX port, cache and fabric + port, with where it is, how full it is and what it costs each month. Filter it + by type, city or network, and tap Open to go straight to it. In the Networks + tab, each network now shows where you connect to it, one tap away. +- On a phone, the game now explains why it is better installed as an app before + you start a new network: full screen, offline, and on iPhone a save that + Safari won't clear. It shows exactly how to add it to your home screen, + and warns that on iPhone a game started in the browser stays there. You can + still play in the browser. + +## [1.18.4] — 2026-10-25 + +- The iPhone home-screen fix from 1.18.3 now stays in place. Before, it worked + at launch and then the empty strip under the tab bar came back. + +## [1.18.3] — 2026-10-25 + +- Installed on an iPhone home screen, the game now fills the whole screen. Before, + the tab bar floated above an empty strip at the bottom. + +## [1.18.2] — 2026-10-25 + +- A new legendary badge, A Petabit a Second, for serving a full petabit per + second (a thousand terabits) of happy traffic. + +## [1.18.1] — 2026-10-25 + +- New goal and badges for DDoS defence: a goal to stand up your first + scrubbing center, and badges for weathering an attack, holding a + multi-terabit flood, running a clean-pipe or a sacrificial PNI, blackholing + your own city, and landing a HackBack that actually works. + +## [1.18.0] — 2026-10-25 + +- Overland waves between continents (Europe to the Middle East and Asia) now cost + 45× the normal price, about ten times the subsea route or more, as in real life. + Dark fiber pairs aren't sold on those routes at all (#40). Links you already + lease keep their price. +- No more limit of four cache boxes per CDN in a POP: each box takes a router + port, and free ports are now the only limit (#39). +- Scrubbing centers now come in tiers — 100G, 1T and 10T of clean bandwidth. + A center cleans an attack only up to its capacity; a bigger flood leaks the + rest past. Centers can run always-on, or cheaper on-demand, which takes a + couple of days to engage once an attack starts. +- Transit clean-pipe add-on. Turn it on for a transit port and the provider + scrubs a flood entering there before it ever reaches you, for a monthly fee + per port. +- Sacrificial PNI. Mark a Chinese PNI as a deliberate choke point: a flood + arriving over it dies on the small port instead of flooding your core, but + legitimate traffic across it runs at half capacity. +- IX blackhole. A new mitigation on the live attack panel: announce the + victim to the exchange and about half the members drop the junk — the + customer stays up, unlike a full RTBH. +- Selling DDoS protection now carries an SLA: if a protected customer's city + is hit and still goes down, you pay out an SLA credit and they get unhappy. + +## [1.17.1] — 2026-10-25 + +- Flowspec is now a property of your router, not a licence you buy once. The + drop rules live in hardware (TCAM), and the budget differs by model: the + used Rusty Router can't do it at all, merchant-silicon and whitebox models + filter a known flood part-way, and the big chassis knock it right down. The + NOC shows how many of your POPs are Flowspec-capable, and the live attack + panel names the router doing (or not doing) the filtering. + +## [1.17.0] — 2026-10-25 + +- DDoS attacks now have a shape: a vector (DNS reflection, NTP or CLDAP + amplification, SYN or HTTP flood), a size from a few Gbps up to a + multi-terabit "botnet of toasters" monster, a target POP, a duration, and + an entry point among that city's uplinks. Most are modest spikes; the big + ones are rare. +- A DDoS toolbox in the NOC. A live attack panel shows the vector, size, + entry and what each mitigation is doing right now: + - **RTBH** — free and instant, but it blackholes the victim, so the + attack and the customer both go dark. Earns the Collateral Damage badge. + - **Flowspec** — a one-time licence that drops known UDP floods (DNS, NTP, + CLDAP, SYN) at your edge. Precise, but useless against an HTTP flood, and + the junk still fills the port it enters. + - **Scrubbing center** — cleans attacks network-wide, as before, and still + risks the GRE/MSS black hole. + - **HackBack 3000™ by Skynot AI** — a tempting red button. Sometimes it + ends the attack; more often it flattens an innocent and earns you a + regulator fine and the Vigilante badge. Hack-back is illegal in reality. + +## [1.16.0] — 2026-10-25 + +- Customers on interconnection fabrics. Companies already on Megapork, + PocketFabric or Consolation Connect ask to buy transit from you over the + fabric, or for a circuit from the fabric to one of your POPs. Both come in + through your NNI port in that city, so you need a port there with room for + them. + +## [1.15.0] — 2026-10-25 + +- The map gets cleaner as you zoom out (#37): cities turn into dots, your POPs + into small router pills, links get thinner, and only your own cities keep + their labels. Up close, a POP shows your router instead of the skyline, + and a city with a second building shows a small router B on its metro + ring, so dual-site POPs stand out. +- Parallel waves on the same cable or in the same trench draw as one line + with a combined label, like "8×6.4T · 7/8 up" (#19). +- Decommission POPs, one at a time or several at once, from the Infra tab. + Everything in them goes, and customers who depended on them are let go + with three months of their contract as an early-termination penalty. +- Dark fiber panels now list the other links between the two cities and can + add a parallel link, like waves already could. +- NLNOG Day joins the conference calendar, in Amsterdam every September (#32). + +## [1.14.0] — 2026-10-24 + +- More of Britain and Norway: Manchester, Edinburgh, the cable town of Bude + in Cornwall, and Stavanger, with British and Norwegian eyeball networks + (Bee-Tee, Sky-High Broadband, Virgin Mediocre, Tele-Nor-Way). +- Nine new cables: NO-UK-Way across the North Sea (with dark fiber for + sale), Celtic Norsemen from Ireland to Norway, Havhingsten Hoofbeat from + Blackpool to Denmark, the Shefa Sheep Line to Iceland via the Faroes, Oil + Rig Wi-Fi from Stavanger to the Netherlands, Pas de Câble under the + Channel, and Apollo 13, Yellow Brick Road and Glo-in-the-Dark into Bude. + +## [1.13.2] — 2026-10-24 + +- On phones, the "new version is out" notice is a small card above the tab + bar again instead of filling the whole screen. + +## [1.13.1] — 2026-10-24 + +- New home-screen icons. On iPhone and on Android's round and squircle + icons, the tube now sits on a full sky-blue background instead of a frame + inside a frame. + +## [1.13.0] — 2026-10-24 + +- Made for phones. A one-row status strip at the top, a tab bar at the + bottom (play, speed, goals, deals, NOC, networks), and bottom sheets you + drag up, down or away; on a phone held sideways they slide in from the + side. Notifications tap away, dialogs open as sheets, and the start button + stays in reach. +- Install it like an app: Series of Tubes now works offline and can be added + to your home screen on Android and iOS (look for "Install" on the title + screen or in Settings). It opens full screen and still updates itself. + +## [1.12.0] — 2026-10-24 + +- Korea's "sender pays" market. Transit into Seoul costs four times the + usual price, and the three incumbents, Kay-Tea, SK Broadbandit and LG + You-Pay-Plus, only peer over paid PNIs billed per gigabit you send them. + Glitch may quit Korea over the fees, Faceplant may quietly reroute Korean + users via Hong Kong, and the new Gangnam Style Peering scenario starts you + in Seoul. Collect all three PNIs for the Sender Pays badge. +- Sparkly Seabone is a Tier 1 now (#23), with a backbone across the + Mediterranean, Europe and the Americas. New games need a PNI with all six + Tier 1s to go transit-free; saves from before this release keep the five. +- Optical control plane meltdown: one bad update at your wave supplier, and + every wave you lease from it in a region goes dark at once. Your own dark + fiber carries on. +- New ways for things to go subtly wrong: LACP trouble (hash polarisation, + timer mismatches, a member in the wrong switch, min-links set a little too + keen), partial packet loss from dirty connectors, CRC errors and + microbursts (deep-buffer routers shrug those off), and PMTUD black holes + where pages to one network load halfway and stop. +- The top bar fits itself to the screen in every language: when labels get + long, the less important readouts step aside instead of wrapping over the + side panels. + +- Series of Tubes now speaks Italian. The game follows your browser's + language the first time, and you can switch between English and Italian + under Settings or on the title screen; the choice is remembered (#26, thanks @daniloctdev). +- Want the real thing? The title screen, the help page and the victory screen + now point to How the Internet Works by Thomas Kjær Aabo, an interactive, + zoomable guide to how your packets actually travel. + +## [1.11.0] — 2026-10-24 + +- Very long dark fiber works now (#17, #30). Optics drop to a slower, longer- + reaching setting past their full-rate reach: the 1.6T transponder runs at + 800G to 7,000 km and 400G to 12,000 km, and ZR+ optics halve their speed + to double their reach. Regeneration sites go further: each one turns the + light back into bits and sends it on fresh, so optics only have to reach + the next site. Existing long fibers light up without changes. +- "Quietest links" routing no longer flips between two paths every day. It + judges how busy a link is without the customer's own traffic, splits the + circuit over two paths that are about as quiet, and keeps yesterday's + choice unless a new one is clearly better (#28). +- Fewer "-ish" names. Conferences and the RIPE NCC use their real names, + data centers are named after their streets and districts, and cables, + carriers and routers got proper puns instead (Concerto in Sea Minor, + Circe du Soleil, Strait Outta Taipei, Jeddah-i Express, Kyiv Superstar, + Du-opoly and friends). +- Customers who are afraid of sharks only ask for routes that can stay on + land. No more Americas-to-Eurasia requests without a subsea cable, and + impossible asks in existing saves are dropped (#16). +- The game no longer freezes when a peer drops you at a rival exchange + (#24, thanks @daniloctdev), or when a route leak melts down one. The + messages now name the exchange and its city. +- One failing day no longer freezes the whole game: the error is caught, + you get a heads-up, and time keeps running. +- Barcelona joins the map with Catnip-IX, local transit and peering, and the + Medusa Stare cable along the coast to Lisbon and Marseille (#18, thanks + @NickBouwhuis). +- Community exchanges: FRIES-IX, Paella-NIX, KleyWrecks, LO-NAPS, JINXED-IX, + IX Strayla and Bento-IX have their own, smaller member lists and cheaper + ports. FRIES-IX 10G and 100G ports and LAG members are free. +- New networks get a random name, from Shinternet to Bogon Voyage. Click + "Another one" for more questionable branding, or type your own (#27, + thanks @NickBouwhuis). + +## [1.10.0] — 2026-10-24 + +- Router ports are finite. Every transit, IX, PNI and cache port, every wave + and every fibre channel takes a router port; 10G ports ride a breakout, + four to a port. The Infra tab shows how many are left, and plugging in more + than you have is refused. +- More routers: up to six per POP, and six new models to swap in from the + Infra tab: Mikrowtik CCR-ish, Sonic the Whitebox 32 (cheap, crashes more), + Arrrhipster 7280R-ish and 7800R-ish (lots of ports, deep buffers, boots in + minutes), Disco 8K-ish (licence keys for everything) and Knockia 7750-ish. + A swap that would not fit what is already plugged in is refused. +- New cities: Milan, Rome, Palermo, Lisbon and Athens in Europe; Atlanta, + Denver, Phoenix, Boston, Houston and Salt Lake City in the US. New cables + land with them (Lisbon to Brazil, Africa and the US Southeast; Genoa to + Sicily and Athens; Palermo to Marseille and Alexandria; Athens to Istanbul; + Boston to Dublin), along with local networks to peer with. +- Rival exchanges: 25 big metros now have a second (sometimes third) IX. + Challengers are cheaper and share many members with the incumbent, but not + all of them. Each IX is its own port, LAG and route server. +- The long tail: 60 small, odd networks with a sliver of traffic each, spread + over random exchanges. "Request all willing peers" signs them up in one go, + and they fold into one row in the network lists. +- Europe's peering market is competitive: IX ports there cost 20% less, and + price wars between rival exchanges cut your port bill further. DE-KICKS + responds with a webinar. +- Voda-Phony has ended settlement-free peering. It now peers only over a paid + PNI, through its interconnection partner. +- New US eyeballs Spectre-um Cable and Very-Zone (paid peering only). +- Pausing now freezes the map too: packet dots, waves and clouds stop + moving until you press play again (#11). +- Ports in both buildings: with a second site, any transit port, PNI or IX + port can now be set to "Both". That splits it into a LAG with members in + each building (adding a member if needed), so a dark building only takes + out half the port instead of all of it (#8). +- The top bar no longer wraps onto a second row and covers the side panels + on laptop-sized screens. +- Routers make sense now: the Chonk 800 takes 800G waves and ports (a new + 800G wave sits between 400G and 1.6T), and only the Absolute Unit has 1.6T + ports and takes 6.4T waves, handed off as 4×1.6T. Existing waves keep + their size. +- London–Amsterdam is everywhere: three more cheap North Sea cables, and dark + fiber you can lease on them (and on the Channel), since you can't dig under + the sea. +- Your own IX can grow (#10): upgrade its fabric from 400G to 1.6T, 6.4T and + 25.6T. Bigger fabrics carry more and have room for more members. +- Wave prices follow real markets: Europe is cheap, North America average, + Asia and South America pricier, and anything into Africa several times the + price. Every route has its own going rate, and new leases get about 8% + cheaper each year. The link planner tells you how a route compares. +- Cairo–Dubai over the Red Sea, plus I-ME-WE-Us to Fujairah and Mumbai. +- The Gulf: Jeddah, Riyadh and Doha. Saudi POPs need a local telecom licence, + gigaprojects want enormous demo networks, and now and then the neighbours + fall out and every link between Qatar and Saudi Arabia or the UAE goes dark + for months. Qatar is on the map as a peninsula now, too. +- Tablets in landscape: slimmer side panels, bigger touch targets, and the + left panel tucks away while a city is open (tap "Goals & NOC" to bring it + back). + +## [1.9.0] — 2026-10-23 + +- RouteScript: program your Auto-TE controller from the NOC tab with a tiny + rule language: `spill at 80%`, `prefer pni for goggle`, `avoid transit for + netchill`, `cap transit cogentle at 20 gbps`, `drain paris`, `avoid link + fra-ams` and `blackhole ddos`. Check runs a dry run against live traffic + and shows what would change; Deploy makes it real. Typos get a "did you + mean". Two new badges: Script Kiddie and Fat Finger. +- Zoom in twice as far as before, handy for crowded spots like the UAE, + Singapore or Central Europe. +- Half speed: a new ½× button, or press 0. +- NOC dashboard: a legend explains the colours in "How it arrives", the + network table sorts by any column (traffic, transit cost, loss, name), and a + new "Who your transit carries" list shows the networks you pay transit to + reach, with the cheapest way to move each one to peering (#7). +- The Transit tab shows the top destinations on each transit port, with the + same hint, so you can see who to peer with in that city (#7). +- A full code review, and about 40 fixes from it: + - Saves and imported files are checked and repaired before use, so a + damaged or hand-edited save can no longer break the game or inject + anything into the page. + - Loophole fixes: flipping crypto loans for profit, free repairs of + geopolitical cable cuts, re-rolling DE-KICKS quotes, walking out of a + failing event, and selling the same trench twice. + - The Red Sea scenario really cuts the Red Sea now, the weekly challenge + gives everyone the same world, and its "pricey" and "poor" twists work. + - China Telecomet and China Unicorn no longer act like Tier 1s. + - Metro ring cuts now alert you, overlapping site outages no longer cancel + each other, and alien waves work on unlit fiber. + - Routing is several times faster on big networks. + - The map fills wide screens at any zoom, pinch zoom goes as far as the + mouse wheel, and touch scrolling and cancelled touches behave. + - Starting a scenario from a running game asks first, and Space no longer + pauses when you meant to press a button. +- Settings for animations and sound, in the menu and on the help screen. + Animations can follow your device's reduce-motion setting (the default), + or be forced on or off. Off freezes the map: no moving packets, pulses or + floating text. + +## [1.8.0] — 2026-10-23 + +- Traceroute and looking glass: tap 🔍 Traceroute on any of your cities, or + open it from the NOC tab. See the exact path to any network or POP, hop by + hop, with latency, the exit it leaves through and the AS path, plus why + that exit won. +- Share card: an image of your network with a mini map, your stats and your + rarest badges, ready to post. Find it in the menu, after winning and after + a scenario. +- Scenarios: six hand-built challenges with a goal and a deadline (Only + Spätzle-IX, Red Sea Crisis, The Cogentle Spat, Carnaval, Mind the Gap and + Anchors Away), plus a weekly challenge where everyone gets the same world, + the same start city and the same two twists for a week. +- Sandbox mode: a billion dollars, every unlock and nothing ever breaks. + No badges, though. +- Conference season: NANOG-ish, RIPE-ish, DENOG-ish, APRICOT-ish and more + come round every year. Register in the Deals tab and selective networks in + that region need half the usual traffic to peer with you for 45 days. +- A guided first game for new players, step by step, with a skip button. +- Kyiv, with Varenyky-IX and KyivStar-ish. Blackouts are frequent, so bring + a generator. Nobody sells capacity between Kyiv and Moscow. +- 7 more badges for scenarios, the weekly challenge and conferences. + +## [1.7.0] — 2026-10-23 + +- Auto-TE: from customer level 3 you can install a traffic-engineering + controller in the NOC tab. When the shortest path is full, the overflow + spills onto up to two alternate paths with free capacity instead of being + dropped. Without it, traffic still reroutes around failures, but a full + link stays full, just like a real IGP. +- 16 more badges, mostly rare, epic and legendary: Traffic Whisperer, Same + Street, Anchors Aweigh, Samba Peering, DE-KICKS Bingo, Ring of Fire, Iron + Curtain Call, Island Hopper, Through the Wall, Darwin Award, Unbreakable, + Gigawatt Landlord, Blitz, Hundred Terabits and a few more, one of them + secret. That makes 46. + +## [1.6.0] — 2026-10-23 + +- South America is on the map properly: Fortaleza, Rio de Janeiro, Buenos + Aires, Santiago, Lima, Bogotá and Panama City, with new cables including a + ring round Cape Horn, a direct São Paulo–New York cable and the first + cable from Chile to Sydney. Nothing crosses the Darién Gap by land, transit + is pricier because so much traffic hairpins through Miami, and fiber over + the Andes costs double and breaks often. IX.brrr is run by a nonprofit + with cheap public prices, and small Brazilian provedores now buy transit + from you. +- More India: Delhi, Chennai, Bengaluru and Hyderabad, with east-coast cables + to Singapore and a lot of road widening. +- Taiwan: Taipei, with cables to Tokyo, Hong Kong, Los Angeles, Seattle and + Shanghai, and ships that keep dragging their anchors over them. +- The UAE: Abu Dhabi and Fujairah join Dubai. Only the licensed duopoly may + run fiber inside the country, so there is no dark fiber, waves cost 3×, and + POPs need a free-zone license. Most cables land in Fujairah. +- Cape Town, with Atlantic cables up the west coast of Africa and load + shedding: bring a generator. +- New local networks: Clarovision, Vivo-ish, Mercado Livre-ly, Jio-graphy, + Airtel-tale, Chunghwa Tele-calm and do-ish. +- Metro diversity: add a second data center in any POP's metro from the + Infra tab, joined by your own metro ring. A power cut, cleaner or A/C + failure then only takes out half the city. You choose which site each + transit, PNI and IX port plugs into, and metro ring cuts can cut site B + off. Some hyperscaler and AI customers now insist on two sites. +- More Asia-Pacific: Melbourne, Brisbane, Darwin, Osaka, Kuala Lumpur, + Bangkok, Ho Chi Minh City, Karachi, Dhaka and Colombo, with cables to match. + Vietnam's cables break a lot, and Darwin has crocodiles. +- Central and Eastern Europe: Warsaw, Prague, Vienna, Budapest, Bucharest, + Tallinn and Istanbul. Baltic cables meet a lot of anchors. +- The giants: at customer levels 3 and 4, hyperscalers and AI clouds bring + deals only they would ask for. Terabit AI WANs between gigawatt campuses, + training runs spread over three or four sites, week-long dataset ingests, + and hundreds of fiber pairs in a trench you dug yourself. Their campuses, + from Star-Gait Abilene to the Johor-ish Overflow, show up in each city's + "Who's here". +- Dark fiber pairs you lease out now earn even before you light your own + channels on that fiber. +- More local networks: KD-DIY, Opt-Out-Us, Mostly-True Move, Viet-tell, + PTC-hell, Telekom Ma-lazy-sia, Türk Tele-komik, Digi-tally Cheap and + UPC-You-Later. +- Badges: 30 achievements from common to legendary, shown under your goals. + Some take luck (Shark Bait), some take years (Five Nines, Speedrun), and a + couple are secret. Badges from earlier games stay on this device in a hall + of fame. +- Five new goals between Tier 2 and Tier 1: light your own dark fiber, be in + two buildings at once, five continents, sign a giant, and serve 10 Tbps. +- Tap your network's name in the top left for a menu to export or import a + save, or start a new network. + +## [1.5.0] — 2026-10-23 + +- Several transits in the same city now share the load instead of filling one + after the other. The same goes for any exits that are equally close: traffic + is spread by free capacity, and local exits still win over far ones (#4). +- Export your save to a file and import it on another device, from the help + screen or the title screen (#5). +- Full transit ports, IX ports, PNIs, caches and routers are now easy to spot. + They get red badges on the map (T, P, C, R), the IX hexagon blinks red when + its port is full, and the NOC lists everything running hot with a hint on + what to do (#6). +- Some routers take forever to boot. The Infra tab shows each chassis's boot + time and its forwarding chip, including the Junipurr PacketOinker™ in the + Chonk 800 and two of them in the Absolute Unit. On a slow booter, crashes + last a few days longer, a rush repair still needs a day of booting, and + swapping the only router takes three days. Bigger chassis are slow more + often. A second router hides all of it. + +## [1.4.0] — 2026-10-23 + +- Big peers have moods now. In some cities, large selective networks refuse + new peering for a few months, or only take PNIs there, each with a reason + ("the peering coordinator is on sabbatical", "a new VP wants to monetise + interconnection"). Now and then they also tear down a session you already + had, and traffic falls back to your next best path. Try another city or a + PNI, and ask again later. +- Remote peering is still on offer, but it is now a last resort. Ports come + through a reseller at 1.5× the price and only 80% of the port is really + yours. Goggle, Faceplant, Comecast and several other selective networks + refuse remote members outright. The route server still gets you every open + network, and building a real POP removes all of this. +- DE-KICKS Group (Frankfurt, Madrid, Marseille, Dubai, Mumbai and New York) + really hates open pricing. There is no price list, only a personalised + quote that grows with how big you look. Haggling can get you a discount, + raise the price "after consulting with management", or stall for a week + behind an NDA. Prices are "harmonised" upwards once a year. Add-ons like + Route Server Gold and Premium Port LEDs appear on your invoice until you opt + out, which takes two clicks. Trying to leave gets you a retention discount + that ends with a loyalty fee. + ## [1.3.0] — 2026-10-23 - Event networks: festivals, trade fairs and big games book a fat temporary diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..439c4a1 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,102 @@ +# Series of Tubes: notes for Claude + +A free cartoon browser game about how the internet works, live at +https://seriesoftub.es, hosted on GitHub Pages. The game is one static page with no framework. +Its source is many small files in `src/` (`src/styles/*.css`, `src/game/**/*.js`, the shell +`src/index.html`); the build pastes them together, in path order, into a single `index.html`, the +same one-file page players have always loaded. Static files (dictionaries, icons, service worker) +live in `site/`. `src/agent/` (the facade the MCP server plays through) goes into the development page only, +never into the page players get, and nothing in `src/game/` may use it (`docs/adr/0004-dev-only-code.md`). + +Read these before larger changes: + +- `docs/ARCHITECTURE.md`: where the code is, and how a day of simulation runs. +- `docs/adr/`: decisions that are settled (GitHub Pages only; one page assembled at build). +- `.claude/skills/`: step-by-step procedures (`edit-the-game`, `github-pages`, release, + translations, tests, performance). +- `.claude/skills/gameplay-rules/`: the game's design rules (W1, N3, F2…), each enforced by + `tests/gameplay-rules.test.js`; run it before changing cities, networks, cables, modes or balance. + +## Commands + +```bash +npm ci # once: installs jsdom for the tests +npm run dev # play while developing: http://localhost:8080, reloads on save (--host to share) +npm test # node:test + jsdom, every tests/*.test.js, must stay green +node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken" (and sorted dictionaries) +node scripts/i18n-add.js FILE.json # add/change/remove translations (see `add-strings`) +npm run build # builds _site/ for GitHub Pages (assembles src/, stamps version, bakes release notes) +npm run serve # build and serve the production site locally +npm run perf -- --base-ref origin/main # big-network benchmark vs main (see `performance`) +npm run perf -- --base-ref origin/main --browser # the same, also in real Chromium (desktop and phone) +npm run mcp # the game as a local MCP server for AI clients, stdio or --http (docs/MCP.md) +``` + +## Hard rules + +- **GitHub Pages, always.** The game is hosted on GitHub Pages and nowhere else. This is not up + for discussion: never propose or prepare another host, a CDN in front, a backend, server-side + rendering, redirects or custom headers. The build output stays plain static files from one + origin. If a feature seems to need a server, redesign the feature. See the `github-pages` skill + and `docs/adr/0001-github-pages-only.md`. +- **No runtime cost for structure.** The page ships as one assembled `index.html`. Organise code + into files under `src/` freely (build time is cheap), but never in a way that adds requests or + work to page load or to the game loop. +- **Git:** work on `main`, no branches. Commits are authored and committed as + `Frederic Jung `. Never add `Co-Authored-By`, `Claude-Session` + or any other attribution trailers. +- **Releases only when Frederic says so.** Never bump the version on your own: push finished + work with its CHANGELOG bullets under `## [Unreleased]` and say it is ready. When he asks + for a release, follow the `release` skill: small fixes get a patch (`x.y.Z`), features a + minor, at most one release per hour. Docs, skills, CI, tests and refactors never need one. +- **Release notes in the app are short**: only the first sentence of each CHANGELOG bullet + (and at most five bullets) shows in "What's new", with a link to the full GitHub + release. Write that first sentence so it stands on its own. +- **Names are puns.** No real company names for networks, vendors, cables, banks, + data centers or exchanges (Cogentle, Goggle, NetChill, Junipurr, Arrrhipster…). + Real conference names (NANOG, RIPE, DENOG) are fine. Avoid lazy "-ish" names: find + a real pun, or keep the plain word. +- **Easter eggs stay secret.** Never mention hidden jokes or easter eggs (for example + whatever `elephant()` does) in commit messages, release notes or the CHANGELOG. +- **Every player-facing string is translated, by label.** Code uses `tr('area.label')`, + `trn('area.label', n)` or `N_('area.label')` (anything stored in a save: `N_()`), never English text. + Add the English (`src/i18n/en.js`) and every translation (`site/i18n/*.js`) in the same change with + `scripts/i18n-add.js` (see `add-strings`). +- **Phones first.** About 70% of players are on phones. Every new panel, button and + modal must work at 360 px wide, in portrait and landscape, using the phone tab bar + and bottom sheets. Check `isPhone()` layouts, not just desktop. +- **Saves are sacred.** Old saves must keep loading. Any new state field gets a default + in `newGame()` and a check/repair in `sanitize()`; renamed fields are migrated there. +- **Performance is always demonstrated.** Every change to `src/` or `site/` is measured on the big-network + fixture against `main` (`npm run perf -- --base-ref origin/main`, see the `performance` skill), + and the numbers go into the PR and into your summary. Every PR also gets them as a comment from + CI. Anything slower needs a reason or a fix. +- **Tests come with features.** Add or extend a test in `tests/` for every feature or + fix (a new feature gets its own `tests/.test.js`). Tests are seeded, so they must not + depend on luck. +- **CHANGELOG style:** plain English, written for players, one bullet per change, + issue numbers in parentheses like `(#37)`. No internal names, no jokes explained. The CHANGELOG + is the one file every change touches; conflicts there are expected (keep both bullets). + +## Style of the code + +- Dense JavaScript in small topic files under `src/game/` (see `edit-the-game`): a new feature gets + its own `NN-name.js` in the folder of its topic, actions go in the matching + `src/game/90-actions/*.js`. All files share one top-level scope; top-level values may only use + top-level values from earlier files. Match the surrounding style: short helper names, arrow + functions, template-literal HTML, no new dependencies. +- Lists people add to (cities, cables, networks, dictionaries) are one entry per line; id-keyed + objects and dictionaries stay sorted, so additions do not collide. +- UI is rebuilt from state: change `S`, then call `after()` (recompute, check goals, + re-render, save). Buttons are `btn(label, actName, args, cls, disabled)`, which + dispatch to `ACT[actName](args)` through `data-act`/`data-args`. +- Never trust saved or imported state: anything read from `S` that came from a save + must already have been validated in `sanitize()`. +- Keep comments short and about *why*. + +## Tone + +Friendly, nerdy and accurate underneath the jokes. Mechanics should follow how +networks really work (95th-percentile billing, peering policies, LAGs, DWDM reach, +route leaks, RPKI) and then exaggerate for fun. When unsure how something works in +real life, look it up before modelling it. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..9021e8f --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,60 @@ +# Code of Conduct + +Series of Tubes is a cartoon game about how the internet works, built by people who +love networks and people who are just curious about them. Everyone is welcome here: +seasoned network engineers, students, translators, players who have never heard of BGP, +and people who just want to suggest a city with a funny data center name. + +The short version: **be excellent to each other.** + +## Where this applies + +Everywhere people meet around this project: GitHub issues, pull requests, reviews and +discussions, the Series of Tubes Signal group, and anywhere else you represent the +project, online or at a conference bar after NANOG. + +## What we want + +- **Welcome people.** Newcomers are how every community stays alive. Nobody was born + knowing what a route reflector is. Explain things kindly, and assume the question is + sincere. +- **Be patient across languages.** Many of us write in our second or third language. + Judge the idea, not the grammar. +- **Disagree about ideas, not people.** Argue about peering policy, balance and puns as + hard as you like. Criticise the change, never the person who made it. +- **Assume good intent.** Text loses tone. If something reads badly, ask before you + react. +- **Give credit.** Thank people for reports, fixes and ideas, and say where an idea came + from. +- **Own your mistakes.** We all fat-finger a config now and then. Apologise, fix it, + move on. +- **Keep the jokes kind.** This game runs on puns. The target of a joke is a network, + a cable or a router, never a person or a group of people. + +## What we don't accept + +- Harassment of any kind, in public or in private messages. +- Insults, slurs, or demeaning comments about anyone's gender, gender identity or + expression, sexual orientation, disability, appearance, body, age, race, ethnicity, + nationality, religion, experience level or anything else about who they are. +- Sexual language or imagery, and unwelcome attention of any kind. +- Threats, intimidation, stalking, or encouraging anyone else to do these things. +- Sharing someone's private information (an address, a phone number, a real name they + have not shared) without their permission. +- Trolling, deliberately derailing discussions, or flooding issues and chats. +- Continuing to contact someone after they have asked you to stop. + +## If something happens + +If someone makes you or others feel unwelcome or unsafe, tell the maintainer, Frederic, +in a private message in the Signal group. You do not need to be the person it happened +to, and you do not need proof or perfect wording. Reports are kept confidential. + +We will listen, look at what happened, and do what fits: a friendly word, a request to +edit or delete something, a warning, or removing someone from the project's spaces for a +while or for good. Whoever reports in good faith will never be punished for it. + +## Making it better + +This document is for everyone here. If something is missing or unclear, open an issue +or a pull request, like for any other part of the project. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..aaeb19f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,153 @@ +# Contributing to Series of Tubes + +Thanks for wanting to help build the cartoon internet. Bug reports, ideas, puns, +translations and code are all welcome. + +Everyone is welcome here, and everyone follows our [Code of Conduct](CODE_OF_CONDUCT.md). +The short version: be excellent to each other. + +## Reporting bugs and ideas + +Open an issue on GitHub and pick the form that fits: bug report, feature request, +balance or realism, or translation. Blank issues are turned off so every report has +what we need to triage it. For bugs, an export of your save (menu → Export save) +lets us load your exact network. One topic per issue, please. + +Ideas are best when they say what happens in real networks and how that could become +a fun mechanic. + +The [Signal group](https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ) is for hanging out with other players, not for +reports: anything meaningful (a bug, an idea, a balance problem) goes into an issue, +even if you first mentioned it in the chat. Things said only in Signal get lost. + +## Development + +The game is one static page with no framework, hosted on GitHub Pages. Its source is split into +small files under `src/` (styles in `src/styles/`, the game script in `src/game/`), which the build +joins, in path order, into a single `index.html`. Static files such as the translations live in `site/`. + +```bash +npm ci # installs jsdom for the tests +npm run dev # http://localhost:8080, reloads when you save a file +npm test # all tests must pass +node scripts/i18n-check.js # translations must be complete and sorted +npm run serve # the production build, as GitHub Pages will serve it +``` + +Where things are, and how a day of the simulation runs: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). + +### Keeping pull requests apart + +Many people work on the game at once. A few habits keep your pull request from colliding with theirs: + +- Put a new feature in its own file in the folder of its topic (for example + `src/game/70-rules/85-route-servers.js`), and its tests in their own `tests/.test.js`. + New files in `src/` and `tests/` are picked up automatically; nothing needs registering. +- Add actions to the matching file in `src/game/90-actions/`, not wherever there is room. +- Lists (cities, cables, networks) take one entry per line; keep id-keyed tables sorted. +- Text is keyed by labels (`tr('pnis.ready_in_about_n_days')`, English in `src/i18n/en.js`). Add new + text with `node scripts/i18n-add.js` rather than by hand: it writes the English and the translations + and keeps every dictionary sorted, so your new strings don't land on the same lines as everyone + else's. Fixing English wording no longer touches the translations. +- The `CHANGELOG.md` bullet is the one place everybody writes. If it conflicts, keep both bullets. + +### Your branch still edits `site/index.html`? + +Until version 1.34 the whole game was one file, `site/index.html`. If your branch was started before +the split, merge `main` and let a script move your changes into `src/`: + +```bash +git fetch origin +git merge origin/main # stops: site/index.html was deleted on main +node scripts/legacy/port-branch.js # moves your edits into the matching src/ files +git status # fix any conflict it lists, then +npm test && git commit +``` + +It splits your version of the page and the one you started from the same way `src/` was made (your +English text becomes labels too), merges each piece into `src/`, and applies your English and +dictionary changes entry by entry. It only reports conflicts +where your change and `main` touched the same lines. + +## Pull requests + +### Pick an issue labelled `implement` + +Open issues are not a to-do list. Every issue is triaged first: some are accepted, some +still need discussion, some are left for the maintainer and some won't happen at all. +**Only issues labelled [`implement`](https://github.com/fjaeckel/seriesoftubes/labels/implement) +are open for outside contributions.** Pull requests for any other issue will be closed, +however good the code is. Say in the issue that you're taking it, so two people don't +build the same thing. + +**Each account may have at most 4 open pull requests at a time, drafts included.** +GitHub won't let you open a fifth until one of them is merged or closed. + +### A note on AI agents + +AI tools are welcome as a helper, but please don't point an agent at the issue tracker +and let it open issues or pull requests on its own. We've had batches of automated +"fix all the issues" pull requests, which is why the limit above exists. Each one still +takes a human to read, check and close, and that time comes out of the game. + +So: write issues yourself, about what *you* saw. Only open a pull request you have run, +tested and can explain. Automated issues and pull requests are closed without a detailed +review, and accounts that keep sending them may be blocked. A short, honest, human-written +contribution is always welcome, even if your English or your code isn't perfect yet. + +### What every pull request needs + +- Keep pull requests small: one small feature or one fix each, targeting `main`. + Every pull request must be reviewable by a human in one sitting. Large drops, + sweeping rewrites or many unrelated changes in one PR will be asked to be split up, + and that applies just as much to AI-generated code. +- Add or update a test in `tests/` for every feature or fix. Tests are seeded and + must not depend on luck. +- Add a bullet for players under `## [Unreleased]` in `CHANGELOG.md`, in plain English. + Releases are cut by the maintainer. +- Show the performance of changes to `src/` on a big network. The Performance check posts a table + comparing your PR with `main` as a comment; to run it yourself: + `npm run perf -- --base-ref origin/main` + (add `--browser` to also time it in Chromium as a desktop and a phone, like CI does). + Anything marked slower needs an explanation. +- The game is hosted on GitHub Pages, and that will not change. Changes must work as plain static + files: no server code, no other host, no redirects or custom headers (see + [docs/adr/0001-github-pages-only.md](docs/adr/0001-github-pages-only.md)). +- Old saves must keep loading. New state needs a default for new games and a check in + `sanitize()`. +- Check your change on a phone-sized screen (about 360 px wide). Most players are on + phones. + +## House rules for content + +- **Every name is a pun.** No real company names for networks, vendors, cables, banks, + data centers or exchanges. Real conference names (NANOG, RIPE, DENOG…) are fine. + Please don't use lazy "-ish" names; find a proper pun or use a plain word. +- **Accurate underneath the jokes.** Mechanics should be recognisable to a network + engineer: exaggerated, not invented. +- **Friendly humour.** Punch at technology, bureaucracy and ourselves, not at people. + +## Translations + +Every player-facing string goes through `tr()`, `trn()` or `N_()`. Dictionaries live +in `site/i18n/` (label → translation, one entry per line, sorted; the English for each label is in +`src/i18n/en.js`). To add a language, copy `it.js`, translate the values (`en.js` lists the same labels +in the same order), register the language in the language list in `src/index.html`, and run +`node scripts/i18n-check.js ` until it reports nothing missing, unused or broken. The CI job "translations" runs the same check on every pull request, shows each language's coverage in the run summary, and also fails if a new language is not added to the language list or to the offline cache in `site/sw.js`. + +Language pull requests must be reviewed by a human who speaks the language, and +checked in the game itself, not only in the dictionary file. Passing the checker is +not enough. The reviewer plays with the language switched on and looks for anything +that got worse: + +- text overflowing buttons, panels or toasts, especially on phones +- truncated or broken layouts, missing placeholders, raw `{name}` or HTML showing +- awkward or machine-sounding phrasing, wrong networking terms +- puns and jokes that no longer land + +Note in the pull request what you checked and on which screen sizes. + +## License + +By contributing, you agree that your contributions are licensed under the +[MIT License](LICENSE). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3f4c52c --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Frederic Jung + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 8dcada4..ec085fa 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ You start with one router in one city and grow into a transit-free Tier 1: - **Interconnection:** IP transit billed on the 95th percentile, internet exchanges with route servers, open/selective/restrictive/paid peering, PNIs, embedded CDN caches, and NNI fabrics for virtual circuits and remote peering. -- **Infrastructure:** leased waves on around 40 real-ish subsea cable systems, +- **Infrastructure:** leased waves on around 40 subsea cable systems modelled on real ones, dark fiber (leased or self-built) lit with DWDM and ZR+ optics, router generations that cap your port speeds, and LAGs to bundle ports when one isn't enough. - **Traffic engineering:** see exactly what fills each link, tune link metrics and @@ -24,86 +24,63 @@ You start with one router in one city and grow into a transit-free Tier 1: Every company is a pun. No real company names are used. +## Learn how it really works + +This game simplifies a lot, and gets some things gloriously wrong on purpose. For +the real thing, go to **[How the Internet Works](https://tkjaer.github.io/how-the-internet-works/)** +by Thomas Kjær Aabo ([source](https://github.com/tkjaer/how-the-internet-works)): +an interactive, zoomable map that follows your data from Wi-Fi and copper to +undersea fiber, as the internet works today, in 2010 and in 1995, with simple or +technical explanations. If you enjoy Series of Tubes, you will learn more from +an hour there than from a year of laying cartoon fiber here. + ## Playing locally -It is a single static page with no build step for development: +It is a single static page, assembled from the files in `src/` by a small Node script: ```sh -open site/index.html # or: npm run serve +npm ci +npm run dev # http://localhost:8080 ``` Progress is saved in your browser's local storage. +The game speaks English, Italian, Portuguese, French, Spanish and German. It follows your browser's language the first time +and remembers the one you pick under Settings or on the title screen. + ## Development ```sh npm ci +npm run dev # development server on localhost (--host to share): assembles src/ on every request, reloads on save npm test # headless tests: boot, geography, a year of play, every incident, every panel -npm run build # writes the deployable site to _site/ with version and date stamped in +npm run build # writes the site for GitHub Pages to _site/, with version and date stamped in +npm run i18n:check # lists text missing from (or stale in) the translations +npm run mcp # the game as an MCP server, so an AI client can play and debug it, headless or in your tab (docs/MCP.md) ``` -``` -site/ everything that is deployed - index.html the whole game (HTML, CSS and JS in one file) - images/og-image.png social preview (1200×630) - favicon.*, icon-* favicons, app icons, manifest - robots.txt, sitemap.xml, llms.txt, 404.html, CNAME -scripts/build.sh copies site/ to _site/ and stamps __VERSION__ / __BUILD_DATE__ -tests/ node:test + jsdom -.github/workflows/ ci.yml (every push) and release.yml (Pages deploy) -``` +## Community -## Releasing +Come hang out in the **[Series of Tubes Signal group](https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ)**. Share screenshots of your +network, suggest cities, and argue about peering policy with other players. +There are fewer backhoes there than in the real thing. -Only published releases reach [seriesoftub.es](https://seriesoftub.es). Pushes to -`main` run CI and nothing else. +Signal is for chatting. Bugs, feature requests and anything else that should not get +lost go into a **[GitHub issue](https://github.com/fjaeckel/seriesoftubes/issues/new/choose)**. -1. Bump `version` in `package.json` (semver) and add a `CHANGELOG.md` entry. - Write the bullets for players: the build turns that section into the in-game - "What's new" card and into `/version.json`, which open games poll to offer a reload. -2. Merge to `main`. -3. Publish a GitHub release tagged `v`, e.g. `gh release create v1.1.0 --generate-notes`. +## Star history -The release workflow checks that the tag matches `package.json`, runs the tests, -builds, deploys to GitHub Pages and pings IndexNow. Pre-releases never deploy. -To redeploy an existing release, run the workflow manually with its tag. + + + + Star history of Series of Tubes + + -## Hosting setup +## Contributing -GitHub Pages serves the site with **Source: GitHub Actions** and the custom domain -`seriesoftub.es`. DNS for the apex domain: +Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md). Everyone taking part follows the [Code of Conduct](CODE_OF_CONDUCT.md): be excellent to each other. -``` -seriesoftub.es. A 185.199.108.153 -seriesoftub.es. A 185.199.109.153 -seriesoftub.es. A 185.199.110.153 -seriesoftub.es. A 185.199.111.153 -seriesoftub.es. AAAA 2606:50c0:8000::153 -seriesoftub.es. AAAA 2606:50c0:8001::153 -seriesoftub.es. AAAA 2606:50c0:8002::153 -seriesoftub.es. AAAA 2606:50c0:8003::153 -www.seriesoftub.es. CNAME fjaeckel.github.io. -stats.seriesoftub.es. CNAME seocho.jc-ix.net. -``` +## License -Once DNS resolves, enable **Enforce HTTPS** in the repository's Pages settings. - -## Analytics - -The game uses [Ridiculytics](https://github.com/fjaeckel/ridiculytics): cookieless, -no persistent identifiers, self-hosted at `stats.seriesoftub.es`. It only reports -from `seriesoftub.es` itself; local copies, previews and forks stay silent. The -script is pinned to `ridiculytics@1.0.1` with an SRI hash. - -Besides page views and session length, the game sends a few coarse events, all -under the collector's 50-name cap: `game_new`, `game_continue`, `play_1m` … -`play_120m` (active, unpaused play time), `goal_`, `level_2`–`level_4`, -`game_year_2/3/5`, `win_tier1` and `bankrupt`. - -The collector must allow the site, e.g. in `sites.yaml`: - -```yaml -sites: - - domain: seriesoftub.es - origins: ["https://seriesoftub.es", "https://www.seriesoftub.es"] -``` +[MIT](LICENSE) © 2026 Frederic Jung diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..1ce5130 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,28 @@ +# The MCP server and the development server in one image (docs/MCP.md, "In a container"). docker.yml builds it and +# publishes it to GHCR for releases only; nothing here is ever deployed to GitHub Pages (docs/adr/0001-github-pages-only.md). +# The base is pinned by digest and kept current by Dependabot (.github/dependabot.yml); CI tests on the same Node major. +FROM node:24-slim@sha256:01d566e8d94d8c619591d78652babfccd3c6992a3dffa9ed5ab39e11cf6c70e9 + +WORKDIR /series-of-tubes + +# Dependencies first, exactly as locked, so a change to the code reuses this layer. Every dependency is a dev one (the +# game has none), and the servers need them all. No install scripts run. +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund --ignore-scripts && npm cache clean --force + +# Only what the servers read: the game's source and static files, the scripts, and the harness the MCP server plays +# through. Owned by root and read-only to the server, which runs as node. +COPY src ./src +COPY site ./site +COPY scripts ./scripts +COPY tests/harness.js ./tests/harness.js +COPY --chmod=0755 docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh + +# --save-dir /saves needs somewhere the server may write: a volume mounted here takes this ownership. +RUN mkdir /saves && chown node:node /saves +VOLUME /saves + +USER node +ENV NPM_CONFIG_UPDATE_NOTIFIER=false +EXPOSE 8080 7777 +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh new file mode 100644 index 0000000..355af5a --- /dev/null +++ b/docker/docker-entrypoint.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Starts the container's servers (docker/Dockerfile, docs/MCP.md "In a container"). +# MCP_MODE=browser (default): the development server on :8080, with the relay a player's tab dials, and the MCP server +# on :7777 driving that tab. +# MCP_MODE=headless: only the MCP server, with a game of its own. +# Everything after the image name goes to scripts/mcp.js (node scripts/mcp.js --help lists the options). +set -uo pipefail +cd /series-of-tubes + +mode=${MCP_MODE:-browser} +case "$mode" in + browser|headless) ;; + *) echo "[entrypoint] MCP_MODE must be browser or headless, not '$mode'" >&2; exit 1 ;; +esac + +extra=("$@") +has() { local a; for a in "${extra[@]}"; do [ "$a" = "$1" ] && return 0; done; return 1; } + +# A container must listen beyond loopback to be reachable at all; --http in the arguments overrides it. +http=(--http 0.0.0.0:7777) +has --http && http=() + +# Listening beyond loopback, the MCP server would take orders from anyone who reaches the port (its Host check stops +# browsers, not other clients), so it gets a token. None given (SOT_MCP_TOKEN or --token-file): this run makes one and +# prints it. MCP_NO_TOKEN=1 turns that off, for a port published to 127.0.0.1 only. +if [ -z "${SOT_MCP_TOKEN:-}" ] && ! has --token-file && [ "${MCP_NO_TOKEN:-}" != 1 ]; then + SOT_MCP_TOKEN=$(node -e "process.stdout.write(require('node:crypto').randomBytes(24).toString('base64url'))") + export SOT_MCP_TOKEN + echo "[entrypoint] No SOT_MCP_TOKEN given: this run's token is $SOT_MCP_TOKEN" >&2 + echo "[entrypoint] claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp --header \"Authorization: Bearer $SOT_MCP_TOKEN\"" >&2 +fi + +pids=() +start() { "$@" & pids+=("$!"); } +shutdown() { + trap '' TERM INT + kill -TERM "${pids[@]}" 2>/dev/null || true + wait "${pids[@]}" 2>/dev/null || true + exit "${1:-0}" +} +trap shutdown TERM INT + +# node directly, not npm run: one process less, and signals reach the server. +if [ "$mode" = browser ]; then + start node scripts/dev.js --host 0.0.0.0 --port 8080 + start node scripts/mcp.js --browser "${http[@]}" "${extra[@]}" +else + start node scripts/mcp.js "${http[@]}" "${extra[@]}" +fi + +# One server stopping stops the container, with its status, so a restart policy can bring both back. +status=0 +wait -n || status=$? +echo "[entrypoint] a server exited with status $status; stopping the container" >&2 +shutdown "$status" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..4731c99 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,374 @@ +# Architecture + +Series of Tubes is a static web game hosted on **GitHub Pages, and only there** +([ADR 0001](adr/0001-github-pages-only.md)). Its source is split into many small files under `src/`; +the build joins them into **one self-contained `index.html`** (one inline ` - - -
-

Series of Tubes: build the internet, one tube at a time

-

A free cartoon browser game about how the internet works. Start as a tiny network in one city, launch home broadband, buy IP transit from Tier 1 and Tier 2 carriers, peer at internet exchanges, set up private interconnects and embedded CDN caches, and lay terrestrial fiber, subsea waves and your own dark fiber with DWDM and ZR optics. Sign enterprise, hosting, high-frequency trading, AI GPU and hyperscaler customers, and keep them happy while backhoes, sharks, fat fingers, route leaks, DDoS attacks and geopolitics break things.

-
- - - -
-
- -
Series of Tubes
AS —
-
- -
Traffic served
0
-
Reach
0%
-
Rank
Tier 3
- -
-
Date
Y1 · Jan 1
-
- - - - - - - - -
-
- - - - - - - -
- - - - - - - - - diff --git a/site/llms.txt b/site/llms.txt index 775d85f..853aa63 100644 --- a/site/llms.txt +++ b/site/llms.txt @@ -15,7 +15,7 @@ for every company: exchanges with route servers, peering policies (open, selective, restrictive, paid), private network interconnects (PNIs), embedded CDN caches and NNI fabrics for virtual circuits and remote peering. -- **Infrastructure:** leased waves, around 40 real-ish subsea cable systems, +- **Infrastructure:** leased waves, around 40 subsea cable systems modelled on real ones, dark fiber (leased IRU or self-built) lit with DWDM line systems, amplifiers and coherent ZR+ optics, router generations with port-speed limits. - **Traffic engineering:** per-link traffic breakdown by network, entry point and @@ -26,3 +26,9 @@ for every company: Version: __VERSION__ (__BUILD_DATE__) Source: https://github.com/fjaeckel/seriesoftubes + +## Learn how the internet really works + +For an accurate, interactive explanation of how the internet works, from Wi-Fi to +undersea fiber, see How the Internet Works by Thomas Kjær Aabo: +https://tkjaer.github.io/how-the-internet-works/ diff --git a/site/puzzles/weekly/2026-W44.json b/site/puzzles/weekly/2026-W44.json new file mode 100644 index 0000000..be7a930 --- /dev/null +++ b/site/puzzles/weekly/2026-W44.json @@ -0,0 +1 @@ +{"v":2,"key":"2026-W44","theme":"ring","cities":["ham","fra","bru","dus"],"src":["ham"],"dem":[{"t":"eye","a":"fra","g":30},{"t":"eye","a":"bru","g":60},{"t":"eye","a":"dus","g":60}],"via":[],"avoid":[],"budget":360000,"twist":{"ring":true},"name":{"l":"puzzles_weekly.name_one_ring_to_rule_reg","p":{"reg":"EU"}},"joke":{"l":"puzzles_weekly.joke_a_ring_survives_one_cut","p":{}},"ref":{"one":341708,"three":341708}} diff --git a/site/puzzles/weekly/2026-W45.json b/site/puzzles/weekly/2026-W45.json new file mode 100644 index 0000000..fc475a5 --- /dev/null +++ b/site/puzzles/weekly/2026-W45.json @@ -0,0 +1 @@ +{"v":2,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"src":["abj"],"dem":[{"t":"eye","a":"fih","g":20},{"t":"eye","a":"acc","g":10},{"t":"eye","a":"dkr","g":30}],"via":["lag"],"avoid":[],"budget":1750000,"twist":{},"name":{"l":"puzzles_weekly.name_tour_de_reg","p":{"reg":"AF"}},"joke":{"l":"puzzles_weekly.joke_a_road_trip_for_photons","p":{}},"ref":{"one":989200,"three":1657240}} diff --git a/site/puzzles/weekly/2026-W46.json b/site/puzzles/weekly/2026-W46.json new file mode 100644 index 0000000..11a7fbf --- /dev/null +++ b/site/puzzles/weekly/2026-W46.json @@ -0,0 +1 @@ +{"v":2,"key":"2026-W46","theme":"ocean","cities":["for","ssa","lad","lun"],"src":["for"],"dem":[{"t":"eye","a":"ssa","g":8},{"t":"eye","a":"lad","g":5},{"t":"eye","a":"lun","g":8}],"via":["sao","dla"],"avoid":[],"budget":4520000,"twist":{},"name":{"l":"puzzles_weekly.name_sea_you_in_b","p":{"b":"lad"}},"joke":{"l":"puzzles_weekly.joke_somewhere_between_a_and_b","p":{"a":"for","b":"lad"}},"ref":{"one":2368700,"three":4296628}} diff --git a/site/puzzles/weekly/index.json b/site/puzzles/weekly/index.json new file mode 100644 index 0000000..e112cc1 --- /dev/null +++ b/site/puzzles/weekly/index.json @@ -0,0 +1 @@ +{"v":2,"weeks":["2026-W44","2026-W45","2026-W46"]} diff --git a/site/scenarios/weekly/2026-W44.json b/site/scenarios/weekly/2026-W44.json new file mode 100644 index 0000000..ce0ba22 --- /dev/null +++ b/site/scenarios/weekly/2026-W44.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W44","rev":3,"theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":4,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":28,"big":5}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":185,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":2}} diff --git a/site/scenarios/weekly/2026-W45.json b/site/scenarios/weekly/2026-W45.json new file mode 100644 index 0000000..498ff4f --- /dev/null +++ b/site/scenarios/weekly/2026-W45.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W45","theme":"event","city":"bog","cash":900000,"days":230,"lvl":2,"rules":{},"mods":[],"goal":{"t":"event","p":{"city":"bog","g":400,"day":159,"dur":3}},"name":{"l":"wkscn.name_party_like_its_1999","p":{}},"desc":{"l":"wkscn.desc_the_whole_city_is_watching","p":{"day":159,"city":"bog","g":400}},"seed":169037385,"par":162,"ref":{"home":"bog","bb":true,"ix":true,"steps":[{"k":"hop","v":["bog","mde",1,null]},{"k":"hop","v":["bog","uio",1,null]}],"avoid":[],"tr2":false,"scrub":0,"event":{"city":"bog","day":159,"g":400}}} diff --git a/site/scenarios/weekly/2026-W46.json b/site/scenarios/weekly/2026-W46.json new file mode 100644 index 0000000..ae2a07a --- /dev/null +++ b/site/scenarios/weekly/2026-W46.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W46","theme":"spat","city":"fih","cash":750000,"days":250,"lvl":2,"rules":{"spat":true},"mods":[],"goal":{"t":"reach","p":{"r":99,"g":370}},"name":{"l":"wkscn.name_not_on_speaking_terms","p":{}},"desc":{"l":"wkscn.desc_two_giants_de_peered_over","p":{"city":"fih"}},"seed":61791269,"par":170,"ref":{"home":"fih","bb":true,"ix":true,"steps":[{"k":"hop","v":["fih","lad",1,null]},{"k":"hop","v":["fih","dla",1,null]}],"avoid":["cog"],"tr2":true,"scrub":0}} diff --git a/site/scenarios/weekly/index.json b/site/scenarios/weekly/index.json new file mode 100644 index 0000000..8955841 --- /dev/null +++ b/site/scenarios/weekly/index.json @@ -0,0 +1 @@ +{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]} diff --git a/site/site.webmanifest b/site/site.webmanifest index c0dc155..ccb3686 100644 --- a/site/site.webmanifest +++ b/site/site.webmanifest @@ -8,11 +8,38 @@ "orientation": "any", "background_color": "#57C4E5", "theme_color": "#57C4E5", - "categories": ["games", "education", "simulation"], + "categories": [ + "games", + "education", + "simulation" + ], "icons": [ - { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" }, - { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }, - { "src": "/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }, - { "src": "/favicon.svg", "sizes": "any", "type": "image/svg+xml" } - ] + { + "src": "/icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "/icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "/favicon.svg", + "sizes": "any", + "type": "image/svg+xml" + } + ], + "id": "/", + "display_override": [ + "standalone", + "fullscreen" + ], + "shortcuts": [] } diff --git a/site/sw.js b/site/sw.js new file mode 100644 index 0000000..4cf8fa4 --- /dev/null +++ b/site/sw.js @@ -0,0 +1,40 @@ +/* Series of Tubes service worker: makes the game installable and playable offline. + The page always comes from the network when there is one, so a new release shows up on the + next visit; everything else is served from the cache and refreshed in the background. */ +const CACHE = 'sot-__VERSION__'; +const CORE = ['/', '/index.html', '/site.webmanifest', '/favicon.svg', '/icon-192.png', '/icon-512.png', '/apple-touch-icon.png', '/i18n/it.js?v=__VERSION__', '/i18n/pt.js?v=__VERSION__', '/i18n/fr.js?v=__VERSION__', '/i18n/es.js?v=__VERSION__', '/i18n/de.js?v=__VERSION__']; + +self.addEventListener('install', (e) => { + e.waitUntil(caches.open(CACHE).then((c) => c.addAll(CORE)).then(() => self.skipWaiting())); +}); + +self.addEventListener('activate', (e) => { + e.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter((k) => k.startsWith('sot-') && k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim())); +}); + +self.addEventListener('fetch', (e) => { + const req = e.request; + if (req.method !== 'GET') return; + // Calls with a player's credentials, or that ask not to be cached (a self-hosted copy's multiplayer server), are never cached. + if (req.cache === 'no-store' || req.headers.has('authorization')) return; + const url = new URL(req.url); + // The update check must always ask the network. + if (url.origin === location.origin && url.pathname === '/version.json') return; + if (req.mode === 'navigate') { + e.respondWith(fetch(req).then((r) => { const copy = r.clone(); caches.open(CACHE).then((c) => c.put('/', copy)); return r; }) + .catch(() => caches.match('/').then((r) => r || caches.match('/index.html')))); + return; + } + const local = url.origin === location.origin, fonts = /fonts\.(googleapis|gstatic)\.com$/.test(url.hostname); + if (!local && !fonts) return; + // Weekly puzzles, scenarios and Architect runs are published between releases: ask the network first, and keep a copy for offline. + if (local && (url.pathname.startsWith('/puzzles/weekly/') || url.pathname.startsWith('/scenarios/weekly/') || url.pathname.startsWith('/architect/weekly/'))) { + e.respondWith(fetch(req).then((r) => { if (r.ok) { const copy = r.clone(); caches.open(CACHE).then((c) => c.put(req, copy)); } return r; }) + .catch(() => caches.match(req).then((r) => r || Response.error()))); + return; + } + e.respondWith(caches.open(CACHE).then((c) => c.match(req).then((hit) => { + const net = fetch(req).then((r) => { if (r && (r.ok || r.type === 'opaque')) c.put(req, r.clone()); return r; }).catch(() => hit); + return hit || net; + }))); +}); diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js new file mode 100644 index 0000000..5204ee1 --- /dev/null +++ b/src/agent/10-domains.js @@ -0,0 +1,130 @@ +/* ================= AGENT API: argument domains ================= + The agent facade (window.TUBES, this folder) is how tools play the game: the MCP server (scripts/mcp.js) calls it in + its own jsdom page, or in the player's tab through the agent relay (80-relay.js). It is part of the development page + only (): the page players get has none of it, so nothing in src/game/ may name anything + defined here; the game offers HOOKS instead. Nothing here runs until a tool calls it or the player switches agent + mode on: these files define tables and functions, and 99-start.js wires agent mode in. + A domain is what an argument may be: an id in a catalog table, a key, an index, a small fixed list, or a check. */ +const API_DOMAINS={ + // Tables from the catalog: an id in a list, a key in an object, or an index into a list. + cityId:{table:'CITIES',kind:'id'}, + netId:{table:'NETS',kind:'id'}, + cableId:{table:'CABLES',kind:'id'}, + fabId:{table:'FAB',kind:'key'}, + opticId:{table:'OPT',kind:'key'}, + systemId:{table:'DF_SYS',kind:'key'}, + designId:{table:'SEA_DESIGNS',kind:'key'}, + upgradeId:{table:'SUB_UPGRADES',kind:'key'}, + bizTypeId:{table:'BIZ_T',kind:'key'}, + portTier:{table:'PORT',kind:'index'}, + linkTier:{table:'LT',kind:'index'}, + nniTier:{table:'NNI',kind:'index'}, + vxcTier:{table:'VXC',kind:'index'}, + routerModel:{table:'RG',kind:'index'}, + scrubTier:{table:'SCRUB_TIERS',kind:'index'}, + satBird:{table:'SATS',kind:'key'}, + wispZone:{table:'WISP',kind:'key'}, + satG:{kind:'enum',values:()=>[...new Set(Object.values(SAT_ORB).flatMap(o=>o.g))].sort((a,b)=>a-b)}, + // Small fixed vocabularies the game itself checks by list membership. + // The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric). + metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, + egress:{table:'PREF',kind:'key'}, + routeMode:{table:'RT',kind:'key'}, + salesPersona:{table:'SALES',kind:'key'}, + site:{kind:'enum',values:['a','b','ab']}, + step:{kind:'enum',values:[1,-1]}, + connKind:{kind:'enum',values:['t','p','ix','c','nni']}, + egressKind:{kind:'enum',values:['t','p','ix','c','nni','l2']}, + peerPolicy:{table:'PPOL',kind:'enum'}, + // The intern, their orders and the new-POP template (opsHire, opsToggle, opsParam…). + internId:{table:'INTERNS',kind:'key'}, + opsKey:{table:'OPSK',kind:'key'}, + opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()}, + opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()}, + // The build standard's targets (bstdSet). + bstdKey:{kind:'enum',values:()=>BSTD.map(x=>x.k)}, + // The three POP standards (#315). + popTier:{kind:'enum',values:()=>POP_TIERS.slice()}, + // The specialist's offers: a seat on a consortium cable, the charter, a vendor demo. + seatPairs:{kind:'enum',values:()=>SEAT_N.slice()}, + callAmount:{kind:'enum',values:()=>CALL_AMTS.slice()}, + charterKey:{table:'CHARTERS',kind:'key'}, + // The link metric editor: a factor or an exact weight (metricMode, metricSet). + metricKind:{kind:'enum',values:['f','w']}, + // The NOC's auto-mitigation switches (ddosAuto). + ddosKey:{kind:'enum',values:['rtbh','scrub']}, + // Puzzle and architect builds: the tiers a puzzle may light, the router models it offers. + pztTier:{kind:'fn',ok:v=>PZ_TIERS.includes(+v)||AR_TIERS.includes(+v)}, + pzRouterModel:{table:'PZ_RG',kind:'index'}, + pzRouteMode:{kind:'enum',values:['normal','fast']}, + // The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll). + pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])}, + // The total a sheet showed (pniAll, bstdApply carry it as q): the game refuses a different one (bstdApply: more than 1% away). + shownTotal:{kind:'fn',ok:v=>typeof v==='number'&&Number.isFinite(v)}, + dashTab:{kind:'enum',values:()=>DTABS.slice()}, + dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']}, + leftTab:{kind:'enum',values:['goals','deals','noc','nets']}, + netFilter:{kind:'enum',values:['all','out']}, + pniFilter:{kind:'enum',values:['all','t','worth','pni']}, + listPage:{kind:'enum',values:['conn','cust','nets','pni','pops']}, + popsSortKey:{kind:'enum',values:['eye','cost','name']}, + custSortKey:{kind:'enum',values:['mood','mo','name','city']}, + connFilter:{kind:'enum',values:['all','k']}, + connSortKey:{kind:'enum',values:['k','city','name','use','mo']}, + dfSource:{kind:'enum',values:['lease','build','cable']}, + cityIdArray:{kind:'array',of:'cityId'}, + // Anything a panel can reach: an exchange city, a rival exchange id, one of your own exchanges. + ixId:{kind:'fn',ok:v=>isIx(v)}, + // A PNI also takes tier:-1, the 1G courtesy port a network may offer (ACT.pni). + pniTier:{kind:'fn',ok:v=>v===-1||(Number.isInteger(v)&&v>=0&&vtypeof v==='string'&&upcomingConfs(75).some(c=>c.key===v)}, + // traceroute goes to your own POPs and to networks; traceModal parses a net:/city: prefix. + traceTo:{kind:'fn',ok:v=>typeof v==='string'&&(NET[v]||isCity(v))}, + // Entity ids (uid()) cannot be validated against a table: shape only. A wrong id is the game's + // to answer, honestly, with no_effect — never a refusal invented on this side of the wall. + entityId:{kind:'string'}, + // Pie in the Sky (the rocket company, unlocked by a Tier 1 win in a new game or from day 0 in a sandbox). + rocketId:{table:'ROCKETS',kind:'key'}, + crustId:{table:'CRUSTS',kind:'key'}, + pieRdId:{table:'PIE_RD',kind:'key'}, + pieTab:{kind:'enum',values:()=>PIE_TABS.slice()}, + pieBidShare:{kind:'enum',values:()=>PIE_RDF_BIDS.slice()}, + pieSpatId:{table:'PIE_SPAT_DEF',kind:'key'}, + pieSpatChoice:{kind:'enum',values:[0,1]}, + countryCode:{kind:'enum',values:()=>[...new Set(CITIES.map(c=>c.cc))].sort()}, + // Address space: an IPv4 prefix length the market sells, and the CGNAT and NAT64 ratios. + ip4Len:{kind:'enum',values:()=>Array.from({length:IP4_MAX-IP4_MIN+1},(_,i)=>IP4_MIN+i)}, + ip4Ratio:{kind:'enum',values:()=>IP4_NAT.slice()}, + ip4Ratio64:{kind:'enum',values:()=>IP4_N64.slice()}, + scnId:{table:'SCN',kind:'id'}, + // A traceroute target in the modal's own terms. +}; + +/* Type names an arg can take instead of a domain: 'string' | 'boolean' | 'integer'. */ + +function apiDomCheck(dom,v){ + const d=API_DOMAINS[dom]; + // The game's own buttons ship truthiness as 0 and 1 (custOpen's {"sad":0}); accept the game's dialect. + if(dom==='boolean')return {ok:v===true||v===false||v===0||v===1}; + if(!d)return {ok:dom==='integer'?Number.isInteger(v):typeof v===dom}; // 'string' | 'integer' + if(d.kind==='array')return {ok:Array.isArray(v)&&v.every(x=>apiDomCheck(d.of,x).ok)}; + const t=d.table?API_CATALOG_TABLE(d.table):null; + if(d.kind==='id')return {ok:!!t&&t.some(x=>x&&x.id===v)}; + if(d.kind==='string')return {ok:typeof v==='string'}; + if(d.kind==='key'||d.kind==='enum'){ + const vs=d.kind==='key'?Object.keys(t||{}):(t||(typeof d.values==='function'?d.values():d.values)||[]); + return {ok:vs.includes(v)};} + if(d.kind==='index')return {ok:Number.isInteger(v)&&v>=0&&v<(t?t.length:0)}; + return {ok:!!d.ok&&d.ok(v)}; +} +function apiDomValues(dom){ + const d=API_DOMAINS[dom];if(!d)return null; + const t=d.table?API_CATALOG_TABLE(d.table):null; + if(d.kind==='array')return {of:d.of}; + if(d.kind==='id')return t?t.map(x=>x.id):[]; + if(d.kind==='key')return t?Object.keys(t):[]; + if(d.kind==='enum')return t||(typeof d.values==='function'?d.values():d.values)||[]; + if(d.kind==='index')return {from:0,to:(t?t.length:1)-1}; + return null; +} diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js new file mode 100644 index 0000000..5b5264e --- /dev/null +++ b/src/agent/20-commands.js @@ -0,0 +1,730 @@ +/* ================= AGENT API: the command tables ================= + Every action in ACT is in exactly one class (tests/mcp-commands.test.js fails otherwise, so a new action forces a + decision): API_CMD, a game command with typed arguments; API_VIEW, which changes only what is on screen; API_BOUND, + which only drafts an input another command reads; API_SESSION, which starts, retries or leaves a game or dismisses a + coaching screen; or API_DENY, never run by a tool. CMD fields: args [name, domain|'string'|'boolean'|'integer', + required]; bind(args) writes the UI a panel would set (bindsUI: the UI keys it touches, restored after a dry run); + open/dom: the window an input lives in and the fields that must exist before dispatch; pass(args) reshapes the args + for the action (confirmations); confirm 'arg' (passed through) or 'double' (the game arms a button first); decides + (may end in a question); reads 'modal' (the window's text is the report); watch (extra fingerprint paths, #name + filled from args); quote (the dry run, priced with the game's own helpers); doc. */ +const API_CMD={ +/* ---------- Pie in the Sky: the rocket company (Tier 1 in a new game, or a sandbox) ---------- */ + pieFound:{args:[],watch:['pie'],quote:a=>({setup:piePrice(PIE_CO),monthly:PIE_CO_MO}),doc:'Found the rocket company. Needs Tier 1 (or a sandbox).'}, + pieFactory:{args:[],watch:['pie'],quote:a=>({setup:piePrice(PIE_FAC)}),doc:'Build the pie factory: it bakes the satellites ("pies") that rockets carry.'}, + piePad:{args:[['city','cityId']],watch:['pie'],doc:'Build a launch pad in a city. Pads near the equator lift more.'}, + pieRd:{args:[['k','pieRdId']],watch:['pie'],quote:a=>({setup:piePrice(PIE_RD[a.k].cost)}),doc:'Fund rocket R&D: reuse (reusable boosters, cheaper launches) or heavy (a bigger rocket, after test flights).'}, + pieLaunch:{args:[['rk','rocketId'],['cr','crustId']],watch:['pie'],doc:'Queue a launch of a rocket into a crust (an orbital shell). Insurance and lasers follow the Launch tab toggles (pieIns, pieLas).'}, + pieDish:{args:[['city','cityId']],watch:['pie'],doc:'Build a pie dish (ground station) at one of your POPs. Needs landing rights in its country.'}, + pieAnt:{args:[['id','entityId']],watch:['pie'],quote:a=>({setup:piePrice(PIE_ANT)}),doc:'Add an antenna to a pie dish (20 Gbps each, 16 at most).'}, + pieLic:{args:[['cc','countryCode']],watch:['pie'],doc:'Buy or renew landing rights in a country, for its dishes and orbit customers.'}, + pieSafe:{args:[],watch:['pie'],doc:'Toggle safe mode: pies ride out solar storms, carrying nothing meanwhile.'}, + pieName:{args:[],watch:['pie'],doc:'Rename the rocket company to the next name on the list.'}, + pieBid:{args:[['id','entityId'],['f','pieBidShare']],watch:['pie'],doc:'Bid in a Rural Digital Pie Fund auction, asking this share of the reserve. The lower ask wins.'}, + pieExim:{args:[],watch:['pie','loans'],doc:'Take the Export-Import Pie Bank loan, with its space covenants.'}, + pieSpatPick:{args:[['id','pieSpatId'],['c','pieSpatChoice']],watch:['pie'],doc:'Answer a geopolitical spat over orbit: choice 0 or 1, as its sheet offers.'}, + downIx:{args:[['city','ixId']],watch:['ixp'],doc:'Step an exchange port down one size.'}, + downT:{args:[['id','entityId']],watch:['transit.#id'],doc:'Step a transit port down one size (a LAG steps down together).'}, + downP:{args:[['id','entityId']],watch:['pni.#id'],doc:'Step a PNI down one size. Not while an augment is on order.'}, +/* ---------- footprint: buildings, routers, POPs ---------- */ + buildPop:{args:[['city','cityId']], + quote:a=>({setup:popCost(a.city),blocked:[cityOn(a.city)?'':popOffWhy(a.city),cnCity(a.city)&&!cnOk()?tr('pops_transit_ix.you_need_a_license_first_foreign'):''].filter(Boolean)}), + doc:'Open a POP in a city you do not have one in. Costs popCost(city). Not in a retired small city (off the map in new games).'}, + launchBB:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:bbCost(a.city)}), + doc:'Launch broadband to the eyeballs of a city you have a POP in. The core revenue source; one per POP.'}, + ad:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:8000}), + doc:'A 30-day ad campaign that boosts eyeball growth in a broadband city.'}, + addRouter:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>{const p=S.pops[a.city];return {setup:p?routerCost(p.rgen||0,p.routers||1):0};}, + doc:'Add a router to a POP, up to RMAX. Cost rises with the model and the count.'}, + rmRouter:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>{const p=S.pops[a.city];return {setup:-((p&&tradeIn(p.rgen||0,1))||0),blocked:p&&portsUsed(a.city)>portsMax(a.city,undefined,p.routers-1)?[tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(a.city)),max:portsMax(a.city,undefined,p.routers-1)})]:[]};}, + doc:'Remove a router and sell it on eBuy for a trade-in. Refused while the rest cannot carry the ports.'}, + upRouter:{args:[['city','cityId'],['g','routerModel',false]],watch:['pops.#city'], + quote:a=>{const p=S.pops[a.city];if(!p)return {};const g=a.g===undefined?mainRG(RG[p.rgen||0].cls+1):+a.g; + return {setup:swapCost(a.city,g),blocked:[(!RG[g]||g===(p.rgen||0))?'no such model':modelFits(a.city,g)||''].filter(Boolean)};}, + doc:'Swap every router in a city for another model. Omit g for the next class up. One swap per day per city.'}, + addGen:{args:[['city','cityId']],watch:['pops.#city'],quote:a=>({setup:GEN_COST,monthly:GEN_MO}), + doc:'Install a generator, so a power cut does not take the POP out.'}, + addSite:{args:[['city','cityId']],watch:['pops.#city'],quote:a=>({setup:SITE2_COST,monthly:SITE2_MO}), + doc:'Add a second building in the city, so one dark data centre does not take everything down.'}, + rmSite:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'], + doc:'Remove the second building. Every port, PNI and cache there moves back to site A.'}, + decomGo:{args:[['cities','cityIdArray']],bindsUI:['decom'],bind:a=>{UI.decom=new Set((a.cities||[]).filter(c=>S.pops[c]));}, + doc:'Close POPs: cancels their ports, links, peerings and customers. Refuses to close every POP you have. Irreversible.'}, +/* ---------- upstream (transit) ---------- */ + buyTransit:{args:[['city','cityId'],['net','netId'],['tier','portTier']], + quote:a=>({setup:PORT[a.tier].setup,monthly:PORT[a.tier].tmo}), + doc:'Order a transit port from a network that sells in that city. Billed monthly on the 95th percentile. A higher tier on an existing port upgrades it.'}, + lagT:{args:[['id','entityId'],['d','step']],watch:['transit.#id'], + quote:a=>{const t=S.transit.find(x=>x.id===a.id);return {setup:a.d>0&&t?PORT[t.tier].setup:0};}, + doc:'Add or remove one LAG member on a transit port, up to LAG_MAX. Adding charges another port setup.'}, + cancelTransit:{args:[['id','entityId']],confirm:'arg',pass:a=>({id:a.id,ok:1}), + doc:'Cancel a transit port.'}, + togglePrem:{args:[['id','entityId']],watch:['transit.#id'], + doc:'Turn the premium upstream product on or off, where the network sells one in that city.'}, + cleanPipe:{args:[['id','entityId']],watch:['transit.#id'], + quote:a=>{const t=S.transit.find(x=>x.id===a.id);return t?{monthly:cleanMo(t)}:{};}, + doc:'Add or remove the upstream DDoS-scrubbing add-on. Monthly.'}, +/* ---------- exchanges ---------- */ + buyIx:{args:[['city','ixId'],['tier','portTier'],['signed','boolean',false]],decides:true, + quote:a=>({setup:ixPortMo(a.city,a.tier),monthly:ixPortMo(a.city,a.tier),blocked:[portOk(ixCity(a.city),a.tier)?'':tr('actions.your_router_can_t_take_a',{port:PORT[a.tier].n})].filter(Boolean)}), + doc:'Take a port on an internet exchange. Monthly. At a De-Kicks exchange the first order returns a personalised quote to answer. A remote port (no POP) is possible at 10G over a fabric.'}, + lagIx:{args:[['city','ixId'],['d','step']],watch:['ixn'], + doc:'Add or remove one LAG member on an IX port. Not on your own exchange.'}, + cancelIx:{args:[['city','ixId']],confirm:'arg',pass:a=>({city:a.city,ok:1}),decides:true, + doc:'Leave an exchange; drops every peering session there. De-Kicks may answer with a retention offer.'}, + rs:{args:[['city','ixId']],watch:['rs'], + doc:'Toggle the route-server session, which peers you with everyone on the server at once.'}, + foundIx:{args:[['city','cityId']],watch:['myIx.#city'],quote:a=>({setup:MYIX_COST,monthly:MYIX_MO,blocked:[foundIxWhy(a.city)].filter(Boolean)}), + doc:'Found your own exchange in a city with no IX where you have a POP. Not in mainland China. Networks join over the following days.'}, + myIxUp:{args:[['city','cityId']],watch:['myIx.#city'], + quote:a=>{const m=S.myIx[a.city];const f=m?(m.fab|0)+1:0,N=f{const t=a.tier===-1?0:a.tier,ex=S.pni.find(p=>p.city===a.city&&p.net===a.net),r=peerOk(a.net,'pni',a.city); + return {setup:a.tier===-1?PNI_G1_COST:(1500+PORT[t].setup/2)*((ex&&ex.n)||1),monthly:(a.tier===-1?Math.round(PORT[0].pni/2):PORT[t].pni)*((ex&&ex.n)||1),days:pniLead(a.net), + blocked:[r.ok?'':r.why,portOk(a.city,t)?'':tr('actions.your_router_can_t_take_a',{port:PORT[t].n}), + a.tier!==-1&&a.tier({id:a.id,ok:1}), + doc:'Cancel a PNI or its pending augment.'}, + lagP:{args:[['id','entityId'],['d','step']],watch:['pni.#id'], + doc:'Add or remove a LAG member on a PNI, up to 8 per router at the POP (pniLagMax, at most PNI_LAG_MAX). Adding is an augment with a lead time.'}, + sacrif:{args:[['id','entityId']],watch:['pni.#id'], + doc:'Mark a PNI sacrificial, so attack traffic is steered into it.'}, + peerPol:{args:[['p','peerPolicy']],watch:['ppol'], + doc:'Set your published peering policy: open, selective or closed. It answers every peering request for you: open accepts everyone, selective takes small networks on the exchange and newcomers with an up-to-date PeeringDB, closed declines them all. The NOC log sums the week up.'}, +/* ---------- caches ---------- */ + cache:{args:[['city','cityId'],['net','netId']], + quote:a=>{const n=NET[a.net];return {monthly:n&&n.cache?CACHE_MO:0, + blocked:n&&n.cache&&(R.demTo[a.net]||0){UI.pending={a:a.a,b:a.b};UI.route=a.route||'';UI.via=a.cable||'';UI.cnPrem=!!a.premiumCrossing;}, + pass:a=>({tier:a.tier}), + quote:a=>{const A=a.a,B=a.b,tier=a.tier; + if(!S.pops[A])return {blocked:[linkFromWhy(A)]}; + if(!waveOk(A,B,tier))return {blocked:[tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:waveNeed(tier)})]}; + const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); + const mult=(sib.length&&!(jn&&jn.k===(landTrenches(A,B)[0]||{}).k)?DIVERSE:1)*(border?3*((a.premiumCrossing&&(A==='hkg'||B==='hkg'))?1.6:1):1); + const wr=waveRoute(A,B,mult,border);if(!wr)return {blocked:[tr('links.no_cable_available_for_that_route')]}; + const blocked=[],so=soldOut(A,B,tier,wr.cab); + if(so)blocked.push(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)})); + const w=subWaveWhy(tier,wr.km,wr.sub);if(w)blocked.push(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:w})); + return {setup:Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm)+(S.pops[B]?0:popCost(B)),monthly:Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),blocked};}, + doc:'Lease a wave from one of your POPs (a) to any city; opens a POP in b if there is none. A second wave on a pair costs 1.4x unless it joins an existing trench; cross-border into mainland China costs 3x. premiumCrossing applies only via Hong Kong.'}, + upLink:{args:[['id','entityId'],['tier','linkTier']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {}; + const blocked=[waveOk(l.a,l.b,a.tier)?'':tr('links.a_wave_wave_needs_need_at',{wave:LT[a.tier].n,need:waveNeed(a.tier)})]; + const w=subWaveWhy(a.tier,l.km,l.sub);if(w)blocked.push(tr('links.no_wave_waves_on_this_cable',{wave:LT[a.tier].n,why:w})); + return {monthly:Math.round(waveMo(l.km,l.sub,a.tier)*(l.mult||1)),blocked:blocked.filter(Boolean)};}, + doc:'Upgrade a leased wave in place. Upward only, and only if the span and cable support it.'}, + rmLink:{args:[['id','entityId']],confirm:'double', + quote:a=>{const l=S.links.find(x=>x.id===a.id);return {setup:-((l&&cabBack(l))||0)};}, + doc:'Decommission a link. A cancelled own-cable build refunds part of the money. Irreversible.'}, + setMetric:{args:[['id','entityId'],['v','metric']],watch:['pairMet'], + doc:'Routing preference for the city pair this link belongs to (not the link): prefer, normal, avoid, backup, or custom (then metricMode and metricSet tune the number).'}, + setCarry:{args:[['id','entityId'],['on','boolean']],watch:['transit.#id'], + doc:'Turn a transit port\'s Carry here on or off: it pulls that carrier\'s traffic (and its customers\') across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win.'}, + setStandby:{args:[['id','entityId'],['on','boolean']],watch:['links.#id'], + doc:'Hold a link in reserve: its capacity fills last.'}, +/* ---------- fabrics and VXCs ---------- */ + buyNni:{args:[['city','cityId'],['prov','fabId'],['tier','nniTier']], + quote:a=>{const ex=nniPort(a.city,a.prov),n=ex?(ex.n||1):1,m=NNI[a.tier]?NNI[a.tier].mo*n:undefined;return {setup:m,monthly:m};}, + doc:'Take a port on an interconnection fabric, at any port speed the router takes. Monthly, the first month up front. A higher tier upgrades every member of the port.'}, + lagNni:{args:[['city','cityId'],['prov','fabId'],['d','step']],watch:['nni'], + quote:a=>{const pt=nniPort(a.city,a.prov),m=pt&&a.d>0&&NNI[pt.tier]?NNI[pt.tier].mo:0;return {setup:m,monthly:m};}, + doc:'Add (d:1) or remove (d:-1) a member of the fabric port\'s LAG: same speed, one more router port, up to 8. Removing is rejected while the circuits would not fit.'}, + rmNni:{args:[['city','cityId'],['prov','fabId']], + doc:'Give the fabric port back. Rejected while circuits still use it.'}, + buyVxc:{args:[['a','cityId'],['b','cityId'],['prov','fabId'],['t','vxcTier']], + quote:a=>({monthly:vxcMo(kmBetween(a.a,a.b),isSub(a.a,a.b),a.t)}), + doc:'Buy a virtual circuit between two fabric ports. Up in 59 seconds, which is the joke.'}, + upVxc:{args:[['id','entityId'],['t','vxcTier']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l&&l.kind==='vxc'?{monthly:vxcMo(l.km,l.sub,a.t)}:{};}, + doc:'Grow a circuit. Needs headroom at both ends.'}, + cancelVxc:{args:[['id','entityId']],confirm:'double', + doc:'Cancel a circuit; any remote IX ports it reached go with it.'}, + setPref:{args:[['kind','connKind'],['id','entityId'],['v','egress']],watch:['transit.#id','pni.#id'], + doc:'Egress preference for one exit: high sends more traffic that way, low keeps it for backup.'}, + siteSet:{args:[['k','connKind'],['id','entityId'],['s','site']],watch:['transit.#id','pni.#id'], + doc:'Put a transit port, PNI or IX port in building A, B or both. Choosing both with a single member adds a LAG member first, and charges for it.'}, +/* ---------- teleports and satellite capacity (#83) ---------- */ + teleBuild:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:TPORT_COST,monthly:TPORT_MO,blocked:[teleOf(a.city)?'there is a teleport here already':teleWhy(a.city)].filter(Boolean)}), + doc:'Build a teleport (a satellite gateway) at one of your POPs: it rents circuits on GEO birds to small islands and remote towns in their footprint. Refused where no satellite on sale at your level sees the city.'}, + teleTrk:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:TRK_COST,monthly:TRK_MO,blocked:[teleOf(a.city)===2?'this teleport has tracking antennas already':trkWhy(a.city)].filter(Boolean)}), + doc:'Add tracking antennas to a teleport, so it can work the MEO ring (about 130 ms round trip instead of GEO\'s 600). Only within 50 degrees of the equator, where the ring is in view.'}, + teleRm:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'], + doc:'Close a teleport (and its LEO gateway). Refused while circuits still start there.'}, + teleLeo:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:LEO_GW_COST,monthly:LEO_GW_MO,blocked:[leoGw(a.city)?'there is a LEO gateway here already':leoGwWhy(a.city)].filter(Boolean)}), + doc:'Host a Starblink LEO gateway at your teleport (level 5, a POP on your fiber or with transit, within 56 degrees of the equator): LEO circuits from it reach small islands and remote towns within 1,200 km, about 30 ms round trip. Refused once your own constellation carries traffic.'}, + teleLeoRm:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'], + doc:'Close a LEO gateway. Refused while LEO circuits still start there.'}, + buySat:{args:[['a','cityId'],['b','cityId'],['bird','satBird'],['g','satG']], + quote:a=>{const ok=own(SATS,a.bird),mo=ok?satMo(a.bird,+a.g):0;return {setup:mo+(S.pops[a.b]||!CITY[a.b]?0:popCost(a.b)),monthly:mo,days:ok?leadDays(SAT_ORB[SATS[a.bird].orb].days):0,blocked:[satWhy(a.a,a.b,a.bird,+a.g)].filter(Boolean)};}, + doc:'Rent a satellite circuit from your teleport in a to b (a small island or a remote town) on a bird that sees both: GEO 1-10 Gbps, MEO 2-20 with tracking antennas, LEO 5-50 from a LEO gateway within 1,200 km (about 30 ms round trip; it puts GEO and MEO circuits on the same pair on standby, and one ordered beside it waits on standby). The first month up front; builds a POP at b if there is none. Next to an existing link between the two it goes on standby, as backup; a link built later between the two puts it on standby too. Cancel with rmLink.'}, + satSize:{args:[['id','entityId'],['g','satG']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id&&x.kind==='sat'),g=+a.g,ok=!!l&&g!==l.g&&SAT_ORB[SATS[l.bird].orb].g.includes(g),mo=ok?satMo(l.bird,g):0; + return {setup:ok&&g>l.g?mo:0,monthly:mo,blocked:!l?['not a satellite circuit']:ok?[g>l.g&&leoLink(l)?leoGrowWhy(l):''].filter(Boolean):[tr('satellites.no_such_circuit')]};}, + doc:'Resize a satellite circuit on the same bird. A bigger one pays its new month up front; a LEO circuit grows only while its gateway is on your fiber and your own constellation carries nothing.'}, + wispSat:{args:[['z','wispZone'],['bird','satBird'],['g','satG']],watch:['pops'], + quote:a=>{const ok=own(WISP,a.z)&&own(SATS,a.bird),mo=ok?wispSatMo(a.bird,+a.g):0;return {setup:ok?mo+(wispZ(a.z)?0:wispKit(a.z)):0,monthly:mo,days:ok?leadDays(SAT_ORB[SATS[a.bird].orb].days):0,blocked:[wispSatWhy(a.z,a.bird,+a.g)].filter(Boolean)};}, + doc:'Island Wi-Fi: rent satellite capacity for an island zone (catalog WISP; its city is c) from your teleport in that city, on a bird that sees both: GEO 1-10 Gbps, MEO 2-20 with tracking antennas, LEO 5-50 from a Starblink gateway there. A contended share, 60% of a circuit\'s price. The first order of a zone also pays the island kit (towers, solar, home radios). How many homes sign up follows the link: about 35% of the pool over GEO, 75% over MEO, 90% over LEO, all over a spur. With a circuit running, one on another bird is a move: the old one carries until the new one is commissioned. The zone\'s homes join the city\'s demand.'}, + wispSatSize:{args:[['z','wispZone'],['g','satG']],watch:['pops'], + quote:a=>{const Z=own(WISP,a.z)?wispZ(a.z):null,o=Z&&Z.sat,g=+a.g,ok=!!o&&g!==o.g&&SAT_ORB[wispOrb(o)].g.includes(g),mo=ok?wispSatMo(o.bird,g):0; + return {setup:ok&&g>o.g?mo:0,monthly:mo,blocked:!o?['no circuit for that zone']:ok?[g>o.g&&wispOrb(o)==='leo'?leoGrowWhy({a:WISP[a.z].c}):''].filter(Boolean):[tr('satellites.no_such_circuit')]};}, + doc:'Resize an island zone\'s satellite circuit on the same bird. A bigger one pays its new month up front.'}, + wispSatRm:{args:[['z','wispZone']],confirm:'double',watch:['pops'], + doc:'Cancel an island zone\'s satellite circuit (and a move being commissioned). With no spur lit, its homes go offline and leave.'}, + wispSpur:{args:[['z','wispZone']],watch:['pops'], + quote:a=>{const ok=own(WISP,a.z);return {setup:ok?wispSpurCost(a.z)+(wispZ(a.z)?0:wispKit(a.z)):0,monthly:ok?wispSpurMo(a.z):0,days:ok?wispSpurDays(a.z):0,blocked:[wispSpurWhy(a.z)].filter(Boolean)};}, + doc:'Island Wi-Fi: lay a spur cable from the zone\'s city (level 3; not every zone can have one). Every home there may sign up once it is lit, and nothing is rented. A spur can be cut (weeks to mend, or a $250k repair ship): a satellite circuit kept beside it carries the islands meanwhile. A zone may start with a spur alone (with the island kit).'}, + wispRm:{args:[['z','wispZone']],confirm:'double',watch:['pops'], + doc:'Close an island Wi-Fi zone: its circuits, spur and homes go.'}, +/* ---------- dark fiber and own cable ---------- */ + orderDf:{args:[['a','cityId'],['b','cityId'],['source','dfSource'],['system','systemId']], + bindsUI:['pending','dfSrc','dfSys'],bind:a=>{UI.pending={a:a.a,b:a.b};UI.dfSrc=a.source;UI.dfSys=a.system;}, + quote:a=>{const A=a.a,B=a.b,sc=isSub(A,B)?subDfCable(A,B):null,km=sc?sc.km:kmBetween(A,B); + const building=a.source==='build'&&glassLvl()>=3&&!sc,sys=DF_SYS[a.system]&&DF_SYS[a.system].lvl<=glassLvl()?a.system:'lite'; + const amps=ampCount(km),blocked=[]; + if(!S.pops[A])blocked.push(linkFromWhy(A)); + if(isSub(A,B)&&!sc)blocked.push(tr('fiber_modals.nobody_sells_dark_fiber_on_a')); + else if(uaePair(A,B))blocked.push(tr('fiber_modals.no_dark_fiber_inside_the_uae')); + else if(landX(A,B)&&cnCity(A)===cnCity(B))blocked.push(tr('fiber_modals.nobody_sells_one_fiber_pair_across')); + else if(!dfAllowed(A,B))blocked.push(tr('fiber_modals.dark_fiber_across_the_chinese_border')); + if(glassLvl()<2)blocked.push(tr('fiber_modals.dark_fiber_unlocks_at_customer_level')); + return {setup:(building?dfBuildCost(km):0)+DF_SYS[sys].cost+amps*AMP_COST+(S.pops[B]?0:popCost(B)), + monthly:(building?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO,days:building?dfBuildDays(km):30,blocked};}, + doc:'Get dark fiber from one of your POPs (a): lease an IRU, dig your own (level 3+), or take a pair on a subsea cable; opens a POP in b if there is none. Then light it with a line system.'}, + orderCable:{args:[['a','cityId'],['b','cityId'],['design','designId',false],['terminal','boolean',false],['engineering','boolean',false]], + bindsUI:['pending','seaDesign','seaterminal','seaengineering'], + bind:a=>{UI.pending={a:a.a,b:a.b};UI.seaDesign=a.design||'standard';UI.seaterminal=!!a.terminal;UI.seaengineering=!!a.engineering;}, + quote:a=>{const why=linkFromWhy(a.a)||ownCabWhy(a.a,a.b);if(why)return {blocked:[why]}; + const design=own(SEA_DESIGNS,a.design)?a.design:'standard',up={terminal:!!a.terminal,engineering:!!a.engineering}; + const q=seaQuote(a.a,a.b,design,up),lack=seaLack(q.km,up); + return {setup:q.cost+(S.pops[a.b]?0:popCost(a.b)),monthly:ownCabMo(q.km),days:q.days, + blocked:lack.map(k=>k==='design'?tr('own_cable.this_design_s_route_is_km',{km:q.km.toLocaleString()}) + :tr('own_cable.km_km_is_too_far_for',{km:q.km.toLocaleString(),what:lack.length>1?tr('own_cable.a_and_b',{a:tr(SUB_UPGRADES[lack[0]].n),b:tr(SUB_UPGRADES[lack[1]].n)}):tr(SUB_UPGRADES[lack[0]].n)}))};}, + doc:'Commission your own submarine cable. A ship sails; it takes months. The most expensive thing in the game.'}, + subUpgrade:{args:[['id','entityId'],['k','upgradeId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:subUpgradeCost(l,a.k),days:SUB_UPGRADES[a.k].days}:{};}, + doc:'Add premium submarine terminals or extra optical engineering to your own subsea cable. Level 4+, once each.'}, + crews:{args:[['id','entityId'],['all','boolean',false]],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {};const n=a.all?crewSteps(l):Math.min(1,crewSteps(l));return {setup:n*crewCost(l),days:n?l.ready-Math.max(crewFloor(l),l.ready-30*n):0};}, + doc:'Pay for more crews on a cable build: 30 days off per step, down to half of the planned build at most.'}, + addCh:{args:[['id','entityId'],['o','opticId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:chCost(l,a.o),blocked:[chWhy(l,a.o)].filter(Boolean)}:{};}, + doc:'Light one channel on a dark-fiber span with a given optic; uses a spare from the shelf if you have one.'}, + rmCh:{args:[['id','entityId'],['o','opticId']],watch:['links.#id'], + doc:'Unplug a channel; the optic goes on the spares shelf.'}, + addPair:{args:[['id','entityId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:pairCost(l)}:{};}, + doc:'Light another fiber pair on your own cable. ROADM system, finished construction, current pair full.'}, + upSys:{args:[['id','entityId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:sysUpCost(l)}:{};}, + doc:'Upgrade the line system: Rainbow to ROADMaster to C+L. Every channel goes down for a day.'}, + regen:{args:[['id','entityId'],['d','step']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l&&a.d>0?{setup:regenAddCost(l)}:{setup:0};}, + doc:'Add or remove a regeneration site on a terrestrial span, up to REGEN_MAX. Removing is refused if the optics then cannot reach.'}, + spares:{args:[['id','entityId']],watch:['links.#id'], + doc:'Toggle keeping spare optics on site for this span, so a card failure is fixed in hours instead of days.'}, +/* ---------- hardware ---------- */ + hwLock:{args:[],quote:a=>({setup:hwLockCost()}), + doc:'Lock router, optic and build prices for a year, shortages included. Costs twice as much while a shortage runs.'}, + buySpare:{args:[['o','opticId']], + quote:a=>({setup:optCost(a.o),blocked:[OPT[a.o]&&OPT[a.o].lvl>glassLvl()?tr('action_helpers.unlocks_at_customer_level_n',{n:OPT[a.o].lvl}):''].filter(Boolean)}), + doc:'Buy a spare optic for the shelf, up to 64 of a kind. The next channel of that type is then free of optic cost.'}, + sellSpare:{args:[['o','opticId']],quote:a=>({setup:-spareValue(a.o)}), + doc:'Sell a spare on eBuy for 40% of list.'}, + /* ---------- capacity broker ---------- */ + listFiber:{args:[['id','entityId'],['w','integer'],['p','integer',false]],watch:['links.#id'], + doc:'List spare capacity on a dark-fiber span with a capacity broker as a standing listing: w alien waves, and p (own cables only) your spare fiber pair. The broker sells them off over time as carriers on that route want capacity; a busy route sells in days, a road to nowhere maybe once.'}, + mktHold:{args:[['v','integer']],watch:['cm'], + doc:'Capacity market (Lambda Bazaar): the share of every fiber (0, 10, 25 or 50%) the broker never sells, kept for your own traffic.'}, + mktCfg:{args:[['p','string'],['k','string'],['v','integer']],watch:['cm'], + doc:'Capacity market: for product p (spec = alien-wave spectrum, w100/w400 = managed 100G/400G waves carved from your lit capacity, iru = dark pairs on fiber you dug), set k: on (v 1 or 0: the broker lists it on every route by your thresholds), min (list only while the route wants at least v units; spec/w400 1,2,4,8, w100 1,4,8,16, iru 1,2) or floor (never sell below v% of list: 60, 80, 100, 120). Demand and prices move every day.'}, + mktRoute:{args:[['k','string']],watch:['cm'], + doc:'Capacity market: toggle whether the broker trades on a route (k = the two city ids sorted and joined by |, e.g. ams|fra).'}, + unlistFiber:{args:[['id','entityId']],watch:['links.#id'], + doc:'Take the listing down. What the broker already sold stays sold.'}, + setChCount:{args:[['id','entityId'],['o','opticId'],['n','integer']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:opticCountCost(l,a.o,a.n)}:{};}, + doc:'Set how many channels of one optic model a dark-fiber span carries, in one change. Added optics come from the spares shelf when you have them (regen cards still cost their share); removed ones go back to the shelf.'}, + xpBuild:{args:[['a','cityId'],['b','cityId'],['via','string'],['o','opticId']], + quote:a=>{const sp=xpParse(a.a,a.b,a.via);if(!sp||!OPT[a.o])return {setup:0,blocked:[tr('express.no_such_path')]};const old=xpFind(a.a,a.b,sp.map(s=>s.id)); + return {setup:xpCost(sp,a.o,!old),blocked:[xpWhy(a.a,a.b,sp,a.o)].filter(Boolean)};}, + doc:'Light an express lightpath from a to b straight through the ROADMs of the cities between: via is the ids of your ROADM dark fibers (land, own or IRU) in order from a, comma-separated, 2 to 6 of them. One optic, one channel slot on every fiber, ports only at a and b, and the light must reach the whole run between regen sites. The same path again adds a channel to that express. Give one up with rmLink.'}, + xpCh:{args:[['id','entityId'],['o','opticId'],['d','step']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id),sp=l&&l.kind==='xp'&&xpSpans(l);if(!sp||!OPT[a.o]||a.d<0)return {setup:0};return {setup:xpCost(sp,a.o,false),blocked:[xpWhy(l.a,l.b,sp,a.o)].filter(Boolean)};}, + doc:'Add (d:1) or unplug (d:-1) one channel of an optic on an express lightpath; unplugged optics go on the spares shelf. The last channel stays: rmLink gives the express up.'}, + /* ---------- customers ---------- */ + accept:{args:[['id','entityId']], + doc:'Sign a pending offer. Rejected without a POP in every city it needs, without the IPv4 addresses it needs (rule ip4: see the bank\'s Address space), without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, + acceptFix:{args:[['id','entityId'],['cost','integer',false]],watch:['pops','biz','offers'], + quote:a=>{const q=S?reqFix(S.offers.find(x=>x.id===a.id)):null;return q?{setup:q.cost,monthly:q.mo}:{setup:0};}, + pass:a=>({id:a.id,cost:a.cost??((reqFix(S.offers.find(x=>x.id===a.id))||{}).cost)}), + doc:'Buy what an offer asks for at POPs you already have (backup generator, a second router, a second site), then sign it. Pass the quoted setup as cost; the game checks it still matches (within 1%: hardware prices drift by the day).'}, + decline:{args:[['id','entityId']], + doc:'Throw an offer away.'}, + salesHire:{args:[['id','salesPersona']], + doc:'Put one salesperson at the sales desk: eng (engineer turned salesdroid: books every NOG at the usual ticket price, more small and mid deals, never the huge ones, customers stay longer), shark (bigger deals at higher prices plus a month of commission, oversells promises, no nerdy customers, peering desks want more traffic) or ceo (free, signs huge discounted deals on the golf course, sometimes signs what you declined, cannot be fired). One at a time; from customer level 2.'}, + salesFire:{args:[],confirm:'double', + doc:'Let the salesperson go (not the CEO: ask the board for a VP of Sales instead).'}, + salesVp:{args:[], + doc:'With the CEO running sales: pay for a board meeting that brings a VP of Sales, who frees the desk a month later.'}, + salesAuto:{args:[],watch:['slAuto'], + doc:'With someone at the sales desk: switch automatic signing on or off. Once a game day they sign the offers that fit, in their own style: eng and ceo after a routing trial (one a day; an offer that did not fit waits a week), shark every offer whose POPs are up, promises and all, while the cash covers the commission. Orbit offers sign where the landing dish has room (the shark ignores that). Nobody at the desk: nothing is signed for you.'}, + salesRen:{args:[],watch:['slAuto'], + doc:'Switch whether the sales desk answers renewal haggles for you, 3 days after each opens (only while someone runs sales). The engineer gives business customers their discount and keeps nerdy ones at the market price; the shark holds the old price (sometimes with a new promise, billing a month of the saving) but some walk; the CEO gives 10% more off for a double term, says yes, or picks a fight and loses them.'}, + salesMin:{args:[],watch:['slAuto'], + doc:'Step the minimum monthly value under which the sales desk declines offers: never, 2k, 5k, 10k, 25k, 50k. With the CEO, about one decline in three is signed anyway.'}, + renewMatch:{args:[['id','entityId']],watch:['biz.#id'], + doc:'Answer a renewal haggle (a customer with hag): renew at the price they asked. Unanswered, this happens on its own when the term ends.'}, + renewMeet:{args:[['id','entityId']],watch:['biz.#id'], + doc:'Answer a renewal haggle by meeting halfway between their price and today\'s market price. They accept about two times in three; otherwise they leave.'}, + renewLet:{args:[['id','entityId']], + doc:'Answer a renewal haggle by letting the customer go now.'}, + dropBiz:{args:[['id','entityId']],confirm:'double', + doc:'Terminate a signed customer. Rejected once an event contract\'s event has started.'}, + setRoute:{args:[['id','entityId'],['m','routeMode']],watch:['biz.#id'], + doc:'How a customer\'s traffic is routed: normal follows metrics, fast takes the lowest latency, scenic the quietest links. Clears a pinned path.'}, + pathMove:{args:[['id','entityId'],['link','entityId']],watch:['biz.#id'], + doc:'Move a fiber customer (alien wave, dark fiber pair, fiber pairs) to another working fiber between the same two cities. Free. Rejected if that fiber has no room for it.'}, + pathPin:{args:[['id','entityId'],['via','string']],watch:['biz.#id'], + doc:'Pin a circuit to a path: via is its city ids in order, comma-separated, from the customer\'s city to its city2, every hop a working link. Free. While a link on it is down the circuit follows routing.'}, + pathAuto:{args:[['id','entityId']],watch:['biz.#id'], + doc:'Unpin a circuit, so routing chooses its path again.'}, +/* ---------- traffic engineering ---------- */ + buyTE:{args:[],quote:a=>({setup:TE_COST,monthly:TE_MO,blocked:coreTE()||(S&&S.te)?[]:[tr('core.auto_te_needs_an_rsvp_te_or')]}), + doc:'Buy the Auto-TE controller, which spills overflow onto alternate paths. Level 3+, and it needs an RSVP-TE-or-higher backbone.'}, + teToggle:{args:[],watch:['te'], + doc:'Turn Auto-TE on or off.'}, + teCheck:{args:[['script','string']],open:'teEdit',dom:['teSrc'],reads:'modal', + bind:a=>{$('teSrc').value=String(a.script);}, + doc:'Parse and dry-run a RouteScript without deploying it. The parse errors, or served traffic and transit cost before and after, come back as the report. No state change.'}, + teDeploy:{args:[['script','string']],open:'teEdit',dom:['teSrc'],watch:['te'], + bind:a=>{$('teSrc').value=String(a.script).slice(0,4000);}, + quote:a=>({setup:0}), + doc:'Deploy a RouteScript, up to 4000 characters. Rejected with the parse errors. A deploy that cuts traffic by more than 10% says so in messages.'}, + teClear:{args:[],watch:['te'], + doc:'Delete the script and fall back to plain Auto-TE.'}, + traceRun:{args:[['from','cityId'],['to','traceTo']],open:'trace',dom:['trFrom','trTo'],reads:'modal', + bind:a=>{$('trFrom').value=a.from;$('trTo').value=(NET[a.to]?'net:':'city:')+a.to;}, + doc:'Run a traceroute to a network or one of your own POPs. The hops come back as report text; they are not stored in the game state.'}, +/* ---------- money ---------- */ + takeLoan:{args:[['id','entityId']], + doc:'Accept a loan offer. Terms vary wildly by bank; the crypto one pays out 55-135% of face value. Equity banks take a share of the company.'}, + callBank:{args:[['amount','callAmount']],watch:['loanOffers'], + doc:'Call a bank for a loan offer of this size, with a credit rating of AA or better (weird conditions apply). The terms follow from the rating, and the amount must fit the limit of a few months of revenue less current debt. Nothing is borrowed until you take the offer.'}, + declineLoan:{args:[['id','entityId']], + doc:'Throw a loan offer away.'}, + repayLoan:{args:[['id','entityId']],confirm:'double', + quote:a=>{const l=S.loans.find(x=>x.id===a.id);return l?{setup:repayCost(l,BANKS[l.bank])}:{};}, + doc:'Repay a loan early, or buy an equity investor out.'}, +/* ---------- address space (IPv4, rule ip4: On-call and BGP at 3 a.m.) ---------- */ + ip4Buy:{args:[['len','ip4Len']],watch:['ip4'], + quote:a=>({setup:ip4Cost(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}), + doc:'Buy an IPv4 block of this prefix length (24 = 256 addresses up to 16 = 65,536) on the transfer market at today\'s price. It can be sold again two years after this transfer. A network holds at most 256 blocks, bought, leased in and from the registry together.'}, + ip4Lease:{args:[['len','ip4Len']],watch:['ip4'], + quote:a=>({setup:0,monthly:ip4InMo(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}), + doc:'Lease an IPv4 block of this prefix length by the month, at today\'s rate (fixed for the lease). Hand it back with ip4Return. Refused at 256 blocks, like ip4Buy.'}, + ip4Sell:{args:[['id','entityId']],confirm:'double',watch:['ip4'], + doc:'Sell an owned block (not leased out) for 92% of the market price. Refused within two years of its last transfer, or when the customers signed would no longer fit with every dual-stack home behind CGNAT and the IPv6-only homes in the NAT64 pool.'}, + ip4Out:{args:[['id','entityId']],watch:['ip4'], + doc:'Lease an owned block out through a broker for a monthly income, while your own customers still fit without it.'}, + ip4Back:{args:[['id','entityId']],watch:['ip4'], + doc:'End the lease of a block you leased out; its addresses are yours to use again.'}, + ip4Return:{args:[['id','entityId']],watch:['ip4'], + doc:'Hand a leased-in block back, ending its monthly fee, when your customers still fit without it.'}, + ip4Nat:{args:[['v','ip4Ratio']],watch:['ip4'], + doc:'Set how many broadband homes share one IPv4 address behind CGNAT (8, 16, 32 or 64). More frees space for business customers but more gamers ask for refunds; fewer is refused when the customers signed would not fit.'}, + ip4Nat64:{args:[['v','ip4Ratio64']],watch:['ip4'], + doc:'Set how many IPv6-only homes share one IPv4 address in the NAT64 pool (64, 128 or 256). Their refunds are well under CGNAT\'s at the same ratio and shrink as the world moves to IPv6; fewer is refused when the customers signed would not fit.'}, + ip6Go:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:ip6Cost(a.city),days:ip6Days(a.city),monthly:Math.round(ip6Mo(a.city,ip4Eye())),blocked:[ip6Why(a.city)].filter(Boolean)}), + doc:'Take a broadband city IPv6-only (464XLAT): swap its dual-stack home routers for ones with a CLAT over the quoted days, paid day by day as they go in (setup is the whole swap; starting needs only the first day\'s share on hand, and it waits while cash is short). Those homes then need no IPv4 of their own, only a share of the NAT64 pool; new homes there get the new router too, at the swap\'s price a router, paid the day they join (even short of cash: a new home needs it). monthly is what it does to the IPv4 bill (NAT64 gateways and refunds against the CGNAT it saves; negative saves). Frees what the city panel says for new customers.'}, + ip6Stop:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Stop a city\'s swap to IPv6-only. The homes already swapped stay IPv6-only (their routers are paid for, nothing comes back); new homes come dual stack again. ip6Go resumes it for the rest.'}, +/* ---------- security, China, incidents ---------- */ + buildScrub:{args:[['city','cityId'],['tier','scrubTier',false]],watch:['scrubs'], + quote:a=>{const T=SCRUB_TIERS[a.tier||0];return {setup:T?T.cost:undefined,monthly:T?T.mo:undefined};}, + doc:'Build a scrubbing centre: 100G, 1T, 10T or 100T. Level-gated per tier; one per city.'}, + scrubUp:{args:[['city','cityId'],['tier','scrubTier']],watch:['scrubs'], + quote:a=>({setup:Math.round(SCRUB_TIERS[a.tier].cost*0.6)}), + doc:'Upgrade a scrubbing centre, at 60% of the tier price. Upward only.'}, + rmScrub:{args:[['city','cityId']],confirm:'double',watch:['scrubs'], + doc:'Tear a scrubbing centre down.'}, + scrubMode:{args:[],watch:['scrubMode'], + doc:'Switch scrubbing between always-on and on-demand.'}, + rtbh:{args:[['id','entityId',false]],watch:['ev'], + doc:'Announce a remote-triggered blackhole for the target under attack: it goes dark at your transits, most exchanges and about half your private peers, and everyone else is saved. Withdraw with unrtbh.'}, + unrtbh:{args:[['id','entityId',false]],watch:['ev'], + doc:'Withdraw the blackhole.'}, + ddosEngage:{args:[['id','entityId',false]],watch:['ev'], + doc:'Engage on-demand scrubbing now: start the diversion to the nearest active scrubbing centre instead of waiting for it to engage by itself.'}, + ddosAuto:{args:[['k','ddosKey']],watch:['ddosAuto'], + doc:'Flip a NOC auto-mitigation switch: rtbh blackholes the target of a flood on its own, scrub engages on-demand scrubbing.'}, + ddosTest:{args:[],watch:['ev'], + doc:'Sandbox only: send yourself a test flood, to try the tools on.'}, + hackback:{args:[['id','entityId',false]],watch:['ev'],quote:a=>({setup:20000}), + doc:'Fire the Hackback 3000(tm) at the botnet. 35% it ends the attack; otherwise a fine and a story.'}, + applyCn:{args:[],watch:['cnLic'],quote:a=>({setup:CN_LIC,days:45}), + doc:'File for a mainland China licence through a local partner. Required before a POP in mainland China. 45 days.'}, + fixInc:{args:[['id','entityId']],watch:['inc'], + quote:a=>{const i=S.inc.find(x=>x.id===a.id);return i&&i.cost>0?{setup:i.cost}:{};}, + doc:'Pay to rush a repair. A slow router reboot is cut to one day; anything else clears immediately.'}, +/* ---------- conferences ---------- */ + confGo:{args:[['key','confKey']],watch:['confReg'], + quote:a=>{const cf=upcomingConfs(75).find(x=>x.key===a.key);return cf?{setup:confCost(cf)}:{};}, + doc:'Register for an upcoming conference. Keys come from catalog(\'conferences\'). Peering gets easier in that region for 45 days. Capacity conferences need level 3.'}, + confSponsor:{args:[['key','confKey']],watch:['confReg'], + quote:a=>{const cf=upcomingConfs(75).find(x=>x.key===a.key);return cf&&confSp(cf)?{setup:CONF_SP-(S.confReg&&S.confReg[a.key]?CONF_COST:0)}:{};}, + doc:'Sponsor it instead: your logo on every lanyard, a bigger effect, a bigger bill. Only where sponsorships are offered; upgrades an existing registration for the difference.'}, +/* ---------- the NOC intern (standing orders) ---------- */ + opsHire:{args:[['id','internId']],quote:a=>({setup:INTERN_MO}),watch:['ops'], + doc:'Hire the NOC intern. They run your standing orders once a game day and cost a salary a month. Level 2+, and only in a game with a clock.'}, + opsFire:{args:[],confirm:'double',watch:['ops'], + doc:'Let the intern go. The standing orders stop; the rest of the month\'s salary is lost.'}, + opsToggle:{args:[['k','opsKey']],watch:['ops'], + doc:'Pause or resume one standing order. Keys come from catalog(\'OPSK\'); the sheet in the game shows what each one does.'}, + opsParam:{args:[['k','opsKey'],['p','string'],['v','string',false]],watch:['ops'], + // The routers order's model and the optup order's line system were settings once: they are the build standard's now. + pass:a=>{const b={routers:{model:'g'},optup:{sys:'sys'}}[a.k],t=b&&b[a.p]; + if(t)throw new Error(`the ${a.k} order takes its ${t==='g'?'router model':'line system'} from the build standard: set it with bstdSet (k "${t}")`);return a;}, + doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). With v (a position in the list the sheet shows, 0 first) it picks that value instead. The routers order\'s model and the optup order\'s line system are not settings: both orders take them from the build standard (bstdSet k "g" and k "sys"; "keep" leaves them to the next model or line system up, when needed).'}, + opsCap:{args:[['k','opsKey'],['v','string',false]],watch:['ops'], + doc:'Step the monthly budget of an order that has one: 10k, 50k, 250k, 1M, 5M, no limit (for caches, a cap on the rent it adds: 1k, 2.5k, 5k, 10k, 25k, no limit). With v (a position in that list, 0 first) it picks that one.'}, + opsFloor:{args:[['v','string',false]],watch:['ops'], + doc:'Step the floor under your cash that the intern keeps clear when paying for jobs: 0, 50k, 250k, 1M, 5M. With v (a position in that list, 0 first) it picks that one.'}, + opsPop:{args:[['k','opsPopKind'],['city','cityId']],watch:['ops'], + doc:'Add or remove one POP as an exception to an order: the intern never touches the POPs you except.'}, + opsTpl:{args:[['k','opsTplKey']],watch:['ops'], + doc:'Toggle a piece of the one-tap new-POP template: broadband, a transit port, an IX port, the redundancy kit.'}, + opsNewPop:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>{const q=S&&S.ops?opsTplQuote(a.city):null;return q?{setup:q.cost}:{};}, + doc:'Open a city from the template in one go: the POP, then broadband, transit, an IX port and the redundancy kit as the template says — all or nothing on the price.'}, +/* ---------- the bulk PNI order ---------- */ + pniAll:{args:[['net','pniAllNet'],['tier','pniTier'],['q','shownTotal',false]], + quote:a=>{const b=pniBatch(a.net,a.tier);return b?{setup:b.cost,monthly:b.mo,blocked:(b.blocked||[]).map(q=>q.why).filter(Boolean)}:{};}, + watch:['pni'], + doc:'Order PNIs with one network (net) or every network (net:null) at all shared POPs: missing connections are added, smaller ones upgraded, each at its own minimum size. The quote is the batch total, lead times as for one PNI. q (optional): the total you were shown; a different one now is refused and the sheet shown again.'}, +/* ---------- backbone technology ---------- */ + coreUp:{args:[],watch:['core'], + quote:a=>{const n=S&&S.core?S.core.lv+1:1;return n<=4?{setup:CORE_COST[n],blocked:[(lvl()||1)({setup:CORE_LAB}), + doc:'Build the interop lab in the NOC: it tests your vendors against each other first and cuts interop incidents by 60%.'}, + coreSet:{args:[['v','integer']],watch:['core'], + doc:'Run the backbone at any level already paid for, 0 up to the highest bought.'}, +/* ---------- the specialist's offers ---------- */ + demoAsk:{args:[['k','string'],['id','string']],watch:['demo'], + doc:'Ask a vendor for a demo unit: a router, line system or optic one level above yours, delivered in about two weeks, at 60% over list until your level catches up. k and id name the thing (as the game\'s buttons pass them).'}, + seatBuy:{args:[['n','seatPairs']],decides:true,watch:['seatOff','links'], + quote:a=>{const o=S&&S.seatOff;if(!o||!SEAT_N.includes(a.n))return {};const miss=[o.a,o.b].filter(c=>!S.pops[c]); + return {setup:seatCost(o.km,a.n)+miss.reduce((x,c)=>x+popCost(c),0),days:seatDays(o.km)};}, + doc:'Take the consortium cable offer: own 1, 2 or 4 fiber pairs on a new subsea cable for your share of the build, and light them with your own optics. POPs open at both landings if you have none.'}, + seatNo:{args:[],watch:['seatOff'], + doc:'Decline the consortium cable offer.'}, + charter:{args:[['k','charterKey']],watch:['charter'], + doc:'Sign the charter a new normal game asks for before anything else (the player sees a popup until it is signed): global backbone (the classic game), low-latency boutique (trading firms pay 40% more, and it has its own win) or broker (dark fiber, line systems, optics and own subsea cables from day one at the usual prices, its own goals and its own win, Glass Baron). One choice per network, normal games only.'}, + mkBanana:{args:[],watch:['monkey'], + quote:a=>({setup:mkBananaCost()}), + doc:'Throw the chaos monkey a banana and it leaves early. Only while it is in your network; the price scales with your revenue.'}, +/* ---------- link tools ---------- */ + metricMode:{args:[['id','entityId'],['k','metricKind']],watch:['pairMet'], + doc:'Set the custom routing metric of a link\'s city pair as a factor (k:"f", the preset way) or an exact cost weight (k:"w"). Starts from the current preset\'s value; edit the number with metricSet.'}, + metricSet:{args:[['id','entityId'],['v','string']],dom:['metIn'],watch:['pairMet'], + bind:a=>{$('metIn').value=String(a.v);}, + doc:'Write the custom metric\'s number for the link\'s city pair, in the mode metricMode set. Select the link first (view.selLink), so the panel is showing the input.'}, + seaRush:{args:[['id','entityId'],['all','boolean',false]],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {};const k=prepSteps(l),n=a.all?k:Math.min(1,k);return {setup:n*prepCost(l),days:Math.min(n*PREP_STEP,Math.max(0,l.ready-prepFloor(l)))};}, + doc:'Hurry the survey, permits and factory of your own subsea cable before laying starts: 30 days sooner per step (all: as fast as money goes), never sooner than the factory can make the cable.'}, + layShip:{args:[['id','entityId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id),q=l&&layQuote(l);return q?{setup:q.cost}:{};}, + doc:'Book a second lay ship on your own cable before laying starts: it lays from the other end and halves that part of the build.'}, +/* ---------- the build standard ---------- */ + popStdSet:{args:[['city','cityId']],watch:['popStd'], + doc:'Make a POP\'s build the standard\'s POP part: its router model, router count, second building and generator. New POPs start with them at once; the other targets are kept.'}, + popStdClear:{args:[],watch:['popStd'], + doc:'Clear the whole build standard; new POPs go back to one basic router.'}, + bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'], + doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, v6 every broadband city IPv6-only (ip6Go, only while IPv4 is scarce: rule ip4), lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. g and sys are also what the intern\'s routers and optup orders standardize on. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'}, + bstdApply:{args:[['quote','string',false],['q','shownTotal',false]],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'], + quote:a=>{const q=bstdQuote(false),nm=w=>w.split('|').map(c=>CITY[c].name).join('–');return {setup:q.cost,monthly:q.mo,key:bstdPlanKey(bstdPlan(false)), + blocked:[...q.wait.map(w=>nm(w)+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark'), + ...q.wv.map(w=>nm(w)+': its line system waits: a customer\'s wave rides it and would go dark with it for the day (upSys on the fiber still swaps it)')]};}, + doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, IPv6-only swaps (the cities with the most dual-stack homes first; each priced as its whole swap, paid as the routers go in, and started only with that much cash on top of what the swaps under way still owe), LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load, and while a customer\'s alien or managed wave rides the fiber (leased pairs and IRUs do not count: they are glass): such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill. quote and q (optional): the plan\'s key and the total you were shown; another plan, or a total more than 1% away, is refused and the sheet shown again.'}, +/* ---------- utilities ---------- */ + utilityRouteServers:{args:[['city','cityId',false]],watch:['rs'], + doc:'Join the route server at every IX you have a port at. One call does what the button does.'}, + utilityKit:{args:[['city','cityId'],['cost','integer',false]],watch:['pops.#city','caches'], + quote:a=>{const q=S?utilityKit(a.city):null;return q?{setup:q.cost,monthly:q.mo}:{};}, + pass:a=>({city:a.city,cost:a.cost??((utilityKit(a.city)||{}).cost)}), + doc:'Install the POP redundancy kit in one go: generator, second building, a second router, and the cache boxes balanced between sites. Pass the quoted setup as cost; the game checks it still matches (within 1%: hardware prices drift by the day). Nothing to do reads as no_effect.'}, + utilityKitAll:{args:[['cost','integer',false],['city','cityId',false]],watch:['pops','caches'], + quote:a=>{const q=S?utilityKitAll():null;return q?{setup:q.cost,monthly:q.mo}:{setup:0};}, + pass:a=>({city:a.city,cost:a.cost??((utilityKitAll()||{}).cost)}), + doc:'Install the redundancy kit at every POP still missing part of it, at one quoted price. From customer level 2. Pass the quoted setup as cost; the game checks it still matches (within 1%).'}, + utilityKitNew:{args:[['city','cityId',false]],watch:['ops'], + doc:'Put the redundancy kit in the intern\'s new-POP template, or take it out (the same switch as in the Ops sheet).'}, + ptSave:{args:[['city','cityId'],['k','popTier']],watch:['popTiers'], + doc:'Save a POP\'s routers (model and count) as one of three POP standards: micro, medium or hub. The POP is marked as that kind. From customer level 2.'}, + ptApply:{args:[['city','cityId'],['k','popTier'],['cost','integer',false]],watch:['pops.#city','popTiers'], + quote:a=>{const q=S?ptPlan(a.city,a.k):null;return q?{setup:q.cost,monthly:q.mo,blocked:q.why?[q.why]:[]}:{setup:0};}, + pass:a=>({city:a.city,k:a.k,cost:a.cost??((S&&ptPlan(a.city,a.k))||{cost:0}).cost}), + doc:'Mark a POP as one kind and bring its routers up to that standard: add routers, swap to the standard\'s model if it is bigger. Never a step down. Pass the quoted setup as cost; the game checks it still matches (within 1%), and 0 only marks a POP that already meets it.'}, + ptAll:{args:[['k','popTier'],['cost','integer',false],['city','cityId',false]],watch:['pops','popTiers'], + quote:a=>{const A=S?ptAll(a.k):null;return A?{setup:A.cost}:{setup:0};}, + pass:a=>({k:a.k,city:a.city,cost:a.cost??(ptAll(a.k)||{}).cost}), + doc:'Bring every POP marked as one kind up to that standard, at one quoted price. Pass the quoted setup as cost; the game checks it still matches (within 1%).'}, + utilityCaches:{args:[['city','cityId'],['quote','string',false]],watch:['caches'], + quote:a=>{const q=S?utilityCaches(a.city):null;return q?{key:q.key}:{};}, + pass:a=>({city:a.city,quote:a.quote??((utilityCaches(a.city)||{}).key)}), + doc:'Request a cache from each eligible provider at each site of the city, as many as demand asks for. Pass the quote\'s key back; the game checks the list has not moved under it.'}, + utilityPeers:{args:[['city','cityId',false]],watch:['peers'], + doc:'Request peering with every eligible peer across every IX you have joined.'}, +/* ---------- renaming ---------- */ + renameGo:{args:[['name','string']],open:'rename',dom:['rnIn'],watch:['name'], + bind:a=>{$('rnIn').value=String(a.name).slice(0,24);}, + doc:'Rename your network. act opens the menu\'s rename sheet and types the name in; it is trimmed to 24 characters.'}, +/* ---------- puzzles and architect runs ---------- */ + pzLinkTo:{args:[['a','cityId'],['b','cityId']],bindsUI:['pending'],decides:true,watch:['links'], + bind:a=>{UI.pending={a:a.a,b:a.b};}, + doc:'Puzzles only: open the link picker between two cities. Answer the decision with pzLink.'}, + pzLink:{args:[['tier','pztTier']],watch:['links'], + doc:'Puzzles only: light the pending link (from pzLinkTo) at a tier, on the picked route, in the picked trench.'}, + pzTier:{args:[['id','entityId'],['tier','pztTier']],watch:['links.#id'], + doc:'Puzzles only: change a link\'s wave size.'}, + pzRmLink:{args:[['id','entityId']],watch:['links.#id'], + doc:'Puzzles only: tear a link down.'}, + pzPop:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Puzzles only: open a POP in a puzzle city.'}, + pzRmPop:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Puzzles only: close a POP and the links that reach it.'}, + pzRtAdd:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Puzzles only: add a router to a POP, up to RMAX.'}, + pzRtRm:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Puzzles only: remove a router, if the ports still fit.'}, + pzRtModel:{args:[['city','cityId'],['g','pzRouterModel']],watch:['pops.#city'], + doc:'Puzzles only: swap every router in a POP for another model.'}, + pzRoute:{args:[['i','integer'],['m','pzRouteMode']],watch:['biz'], + doc:'Puzzles only: send one flow (index i, as state(\'biz\') lists them) along the metrics or the lowest-latency path.'}, + pzUndo:{args:[],watch:['pops','links','pairMet'], + doc:'Puzzles only: undo the last build step, up to sixty of them.'}, + pzReset:{args:[],watch:['pops','links','pairMet'], + doc:'Puzzles only: clear the whole build and start the puzzle over.'}, + pzArGo:{args:[],watch:['ar'], + doc:'Architect runs only: run the chaos monkey\'s review of this brief, every tube snipped in turn.'}, + pzArSkip:{args:[],watch:['ar'], + doc:'Architect runs only: fast-forward the review to the first cut that hurts.'}, + pzArNext:{args:[],watch:['ar'], + doc:'Architect runs only: pass the review and sign the next brief. Rejected while the current one does not pass.'}, + +/* ---------- answering decisions ---------- */ + dkAccept:{args:[],watch:['dk'], + doc:'Take the De-Kicks quote as offered and order the port.'}, + dkHaggle:{args:[],watch:['dk'], + doc:'Haggle. 45% a better price, 30% a worse one, 25% sales stops returning your calls for a few days. Three attempts.'}, + dkWalk:{args:[],watch:['dk'], + doc:'Walk away; the quote is remembered for 90 days.'}, + dkStay:{args:[['city','ixId']],watch:['dk'], + doc:'Take the retention discount instead of leaving: 40% off for six months.'}, + dkOptOut:{args:[['city','ixId'],['n','string']],confirm:'double',watch:['dk'], + doc:'Opt out of an add-on De-Kicks slipped onto the bill.'}, + closeModal:{args:[], + doc:'Close the open window, answering nothing. Always available, so you are never stuck in front of one.'}, +}; + +const API_VIEW={ + pieOpen:{args:[],doc:'Open Pie Control, the rocket company\'s panel.'}, + ip4Open:{args:[],doc:'Open the bank at its Address space section: your IPv4 blocks, who uses them, CGNAT, the NAT64 pool and the transfer market.'}, + ip4Pick:{args:[['v','ip4Len']],doc:'Pick the block size the Address space market quotes (a prefix length, 24 to 16).'}, + pieGovOpen:{args:[],doc:'Open the bank at its Government money section: the rocket company\'s fund auctions, the Pitcairn grant and the Ex-Im Pie Bank (it used to be Pie Control\'s Gov tab).'}, + pieTab:{args:[['t','pieTab']],doc:'Switch the Pie Control tab: traffic, co (the company, its books and the Founder\'s posts), fly (launches) or dish.'}, + pieCity:{args:[['v','cityId']],doc:'Pick the POP the Dishes tab works on.'}, + pieHi:{args:[['id','string']],doc:'Highlight one orbit flow on the Pie Control globe.'}, + pieIns:{args:[],doc:'Toggle launch insurance for the next launches.'}, + pieLas:{args:[],doc:'Toggle lasers (inter-satellite links) for the next launches.'}, + pieGlobeNight:{args:[],doc:'Flip the Pie Control globe between day and night.'}, + pieSpatOpen:{args:[['id','pieSpatId']],doc:'Open the sheet of a geopolitical spat over orbit.'}, + traceMode:{args:[['m','string']],doc:'Redo the open traceroute in a routing mode: normal, fast or scenic.'}, + chartToggle:{args:[['c','string'],['k','string']],doc:'Hide or show one series of a dashboard chart (a legend click); hiding every series shows them all again.'}, + help:{args:[],doc:'Open the how-to-play modal.'}, + dash:{args:[],doc:'Open the NOC dashboard.'}, + dashClose:{args:[],doc:'Close the NOC dashboard.'}, + nocWindow:{args:[],doc:'Open the NOC dashboard in a window of its own, for a second display.'}, + dashTab:{args:[['k','dashTab']],doc:'Switch the NOC dashboard tab.'}, + marketOpen:{args:[],doc:'Open the NOC dashboard at the capacity market (Lambda Bazaar).'}, + dashSort:{args:[['k','dashSortKey']],doc:'Flip a dashboard column\'s sort.'}, + dashLink:{args:[['id','entityId']],doc:'Jump from the dashboard to a link\'s panel.'}, + bank:{args:[],doc:'Open the bank.'}, + bankClose:{args:[],doc:'Close the bank.'}, + closePanel:{args:[],doc:'Close the selection panel.'}, + tab:{args:[['t','string']],doc:'Switch the city panel\'s tab.'}, + pzCity:{args:[['c','cityId']],doc:'Puzzles on a phone: open a city\'s card from its flow chip.'}, + pzTab:{args:[['k','string'],['t','string']],doc:'Puzzles on a phone: switch the city (k:"city") or link (k:"link") card\'s tab.'}, + leftTab:{args:[['t','leftTab']],doc:'Switch the left drawer and open it.'}, + toggleLeft:{args:[],doc:'Open or close the left drawer.'}, + netFocus:{args:[['id','netId']],doc:'Focus one network in the left drawer.'}, + netFilter:{args:[['f','netFilter']],doc:'All networks, or only the out-of-reach ones.'}, + meetGo:{args:[['city','cityId']],doc:'Go to a city and open where to meet networks there.'}, + phoneTab:{args:[['t','leftTab']],doc:'Phone tab bar: switch bottom-sheet tab.'}, + logOpen:{args:[['id','entityId']],doc:'Open the thing a notification refers to.'}, + logAll:{args:[],doc:'Show every notification in the drawer.'}, + focusCity:{args:[['city','cityId']],doc:'Select and centre a city.'}, + selLink:{args:[['id','entityId']],doc:'Select a link.'}, + custGo:{args:[['id','entityId']],doc:'Jump from the dashboard to a customer.'}, + pathOpen:{args:[['id','entityId']],doc:'Open the window listing the other paths a customer can move to: fibers for a fiber customer, routes for a circuit. pathMove and pathPin make the move.'}, + listMore:{args:[['k','listPage']],doc:'Show another page of the dashboard list.'}, + custF:{args:[['v','string']],doc:'Filter the customers list.'}, + custCity:{args:[['v','string']],doc:'Filter the customers list by city.'}, + custSort:{args:[['k','custSortKey']],doc:'Flip the customers list sort.'}, + custOpen:{args:[['sad','boolean',false]],doc:'Open the customers dashboard tab.'}, + popGo:{args:[['city','cityId']],doc:'Jump from the dashboard to a city with no POP yet.'}, + popsReg:{args:[['v','string']],doc:'Filter the list of cities with no POP by region.'}, + popsSort:{args:[['k','popsSortKey']],doc:'Flip the sort of the list of cities with no POP.'}, + goConn:{args:[['city','cityId'],['k','connKind']],doc:'Open a city\'s connections tab.'}, + goEgress:{args:[['city','cityId'],['k','egressKind']],doc:'Open a city\'s connections tab (l2 for the customer list).'}, + connOpen:{args:[],doc:'Open the connections tab of the NOC dashboard (also the Peering tab\'s "All connections" button).'}, + connF:{args:[['f','connFilter'],['v','string',false]],doc:'Filter the connections list.'}, + connCity:{args:[['v','string']],doc:'Filter the connections list by city.'}, + connNet:{args:[['v','string']],doc:'Filter the connections list by network.'}, + connSort:{args:[['k','connSortKey']],doc:'Flip the connections list sort.'}, + connFor:{args:[['net','netId']],doc:'Open the connections of one network.'}, + linkCheck:{args:[['id','entityId']],doc:'Open the redundancy check for a link: what a single cut would drop, without changing anything.'}, + findOpen:{args:[],doc:'Open the city finder (the 🔍 in the top bar).'}, + findGo:{args:[['city','cityId']],doc:'Close the finder and jump to a city.'}, + findLink:{args:[['city','cityId']],doc:'Open the city finder to pick where a new link from this POP goes (the "Link to a city" button in its panel).'}, + linkTo:{args:[['a','cityId'],['b','cityId']],doc:'From the link finder: open the new-link window from POP a to city b, as dragging between them would.'}, + popStep:{args:[['d','integer']],doc:'Select and centre the previous (d<0) or next (d>0) of your POPs, by name: the [ and ] keys.'}, + offerStep:{args:[],doc:'Select the next open offer (soonest to expire first), centre its city and mark it under Offers here: the $ key.'}, + zoomStep:{args:[['d','integer']],doc:'Zoom the map out (d<0) or in (d>0) around its middle: the - and = keys.'}, + keys:{args:[],doc:'Open the list of keyboard shortcuts (the ? key).'}, + routingOpen:{args:[],doc:'Open the Routing & DDoS window: the traceroute, backbone, Auto-TE and DDoS settings (the button at the top of the NOC tab).'}, + opsOpen:{args:[],doc:'Open the Ops sheet: the NOC intern\'s mood, weekly shift report and standing orders.'}, + bstdOpen:{args:[],doc:'Open the build standard sheet: every target, how many POPs, ports and links are below it, what bringing them up costs, and the intern\'s order that keeps them there.'}, + salesOpen:{args:[],doc:'Open the sales desk sheet: the three kinds of salesperson, who is at the desk and what they cost.'}, + opsCity:{args:[['v','cityId',false]],doc:'Show one POP\'s standing-order exceptions in the Ops sheet.'}, + utilities:{args:[['city','cityId',false]],doc:'Open the utilities sheet: route servers, the redundancy kit, caches and bulk peering, for one city or the whole network.'}, + pniAllOpen:{args:[['net','pniAllNet']],doc:'Open the bulk PNI order sheet for one network (or every network with null).'}, + pniFilter:{args:[['f','pniFilter']],doc:'Filter the PNI list: all, via transit, worth it, already PNI.'}, + pniGrp:{args:[['g','string'],['o','boolean',false]],doc:'Fold or unfold one group of the PNI list.'}, + pniSort:{args:[],doc:'Flip the PNI list sort between A-Z and worth-it-first.'}, + netFind:{args:[['q','string']],doc:'Filter a POP\'s transit, exchange, PNI and cache lists by network name or AS number.'}, + netOnly:{args:[],doc:'Show only the networks you are connected to in a POP\'s lists, or all of them again.'}, + netClear:{args:[],doc:'Clear the network search and the connected-only switch.'}, + puzzleMenu:{args:[],doc:'Open the puzzle list.'}, + puzzleDoor:{args:[],doc:'From the title screen: open the puzzle list (keeps the typed name).'}, + pzFinish:{args:[],doc:'Puzzles only: run the star count and show the results sheet.'}, + pzMonkey:{args:[],doc:'Puzzles only: send the chaos monkey round the build to prove the N-1 star.'}, + pzMkSkip:{args:[],doc:'Puzzles only: skip the monkey\'s tour to the verdict.'}, + pzLook:{args:[['c','cityId',false],['u','string',false]],doc:'Puzzles only: move the map to the city (c) or the cut (u, a link unit) that the sheet\'s next line names.'}, + pzArAll:{args:[],doc:'Architect runs only: show every city on the map, not just the run\'s own.'}, + tailTog:{args:[],doc:'Show or hide the long tail of small networks.'}, + teEdit:{args:[],doc:'Open the RouteScript editor.'}, + teClose:{args:[],doc:'Close the RouteScript editor.'}, + teHelp:{args:[],doc:'Open the RouteScript reference.'}, + teBack:{args:[],doc:'Back to the RouteScript editor.'}, + models:{args:[],doc:'Open the router catalogue.'}, + decomOpen:{args:[['city','cityId',false]],doc:'Open the decommissioning sheet.'}, + scenarios:{args:[],doc:'Open the scenario picker. Start one with startScn.'}, + helpClose:{args:[],doc:'Close the help modal.'}, + whatsNewShow:{args:[],doc:'Open the release notes.'}, +}; + +const API_BOUND={ + pieRename:{command:'pieName',note:'the typed company name'}, + leaseSwap:{command:'orderDf',note:'presets the dark-fiber modal on a leased pair'}, + teOpt:{command:'teDeploy',arg:'script',note:'the optimiser drafts a script'}, + teSlop:{command:'teDeploy',arg:'script',note:'the AI drafts a script'}, + teExample:{command:'teDeploy',arg:'script',note:'the worked example'}, + teRecipe:{command:'teDeploy',arg:'script',note:'a recipe from catalog(\'TE_RECIPES\')'}, + trace:{command:'traceRun',arg:'from'}, + decomToggle:{command:'decomGo',arg:'cities'}, + satOpen:{command:'buySat',note:'opens the satellite order sheet from a teleport (a) or for a city (b); buySat takes a, b, bird and g itself'}, + wispOpen:{command:'wispSat',note:'opens an island Wi-Fi zone in its city\'s Customers tab; wispSat, wispSpur and the rest take z themselves'}, + openVxc:{command:'buyVxc',note:'opens the circuit picker from a fabric port ({from, prov}); buyVxc takes a, b, prov and t itself'}, + connCancel:{command:'cancelTransit',note:'the connections list\'s cancel button: it arms, then dispatches cancelTransit, cancelPni, cancelIx, rmCache or rmNni'}, + cnPrem:{command:'buildLink',arg:'premiumCrossing'}, + addParallel:{command:'buildLink',note:'opens the link modal on the same pair',arg:'a/b'}, + via:{command:'buildLink',arg:'cable'}, + route:{command:'buildLink',arg:'route'}, + dfMode:{command:'orderDf',note:'opens the dark-fiber modal',arg:'a/b'}, + xpOpen:{command:'xpBuild',note:'opens the link window on its Express tab: the ways your ROADM fibers chain from a to b (via, fiber ids comma-separated, puts that path first)',arg:'a/b/via'}, + dfSrc:{command:'orderDf',arg:'source'}, + dfSys:{command:'orderDf',arg:'system'}, + seaDesign:{command:'orderCable',arg:'design'}, + seaPackage:{command:'orderCable',arg:'terminal/engineering'}, + ownCab:{command:'orderCable',note:'presets the own-cable flow'}, + randomName:{command:'start',note:'drafts the title-screen name; new_game starts games'}, + pickStart:{command:'start',note:'drafts the home city; new_game starts games'}, + pickHome:{command:'start',note:'drafts the home city; new_game starts games'}, + modeSet:{command:'start',note:'drafts the game mode; new_game starts games'}, + presetSet:{command:'start',note:'drafts the difficulty preset; new_game starts games'}, + chaosSet:{command:'start',note:'drafts the sandbox chaos dial; new_game starts games'}, + rename:{command:'renameGo',note:'opens the rename sheet; renameGo opens it itself'}, + pniAllSize:{command:'pniAll',arg:'tier',note:'steps the port size in the bulk sheet'}, + utilityPick:{command:'utilities',note:'the sheet\'s city picker; pass city to utilities itself'}, + pzAddPar:{command:'pzLink',note:'opens the puzzle picker on the same pair',arg:'tier'}, + pzVia:{command:'pzLink',note:'picks the route (cable or land) for the pending link'}, + pzDiv:{command:'pzLink',note:'same trench or a diverse one for the pending link'}, +}; + +/* Starting, retrying and leaving scenarios, puzzles and architect runs, and the screens a player dismisses. They run + as their buttons run them; new_game, load_save and export_save are the other half of the session, and exist only in + the MCP server's own page (scripts/lib/mcp-headless.js). In the player's tab the player owns the game, so the ones + that replace or leave it are refused there (API_PLAYER_OWNS). */ +const API_SESSION={ + startScn:{args:[['id','scnId']],doc:'Start a scenario (ids from catalog SCN), replacing the current game.'}, + startWeekly:{args:[],doc:'Start this week\'s weekly scenario, replacing the current game. The week follows the real date.'}, + pzStart:{args:[['id','string']],doc:'Start a puzzle by id (the puzzle list, view.puzzleMenu, shows them), replacing the current game.'}, + pzWeekly:{args:[],doc:'Start this week\'s weekly puzzle, replacing the current game.'}, + pzArStart:{args:[['id','string']],doc:'Start an architect run by id (view.puzzleMenu lists them), replacing the current game.'}, + pzRetry:{args:[],doc:'Puzzles and architect runs: start the same one over from scratch.'}, + pzLeave:{args:[],doc:'Leave the running puzzle or architect run.'}, + keepPlaying:{args:[],doc:'Dismiss the win screen and keep playing.'}, + pitchSkip:{args:[],doc:'Skip the opening pitch; a game waiting behind it starts.'}, + tutSkip:{args:[],doc:'Skip the tutorial coaching.'}, +}; +// Session actions that would replace or leave the game in the player's tab: refused over the relay. +const API_OWN_WHY='the game in this tab is the player\'s: only the player starts, loads or leaves one'; +const API_PLAYER_OWNS={startScn:1,startWeekly:1,pzStart:1,pzWeekly:1,pzArStart:1,pzRetry:1,pzLeave:1}; + +/* Actions no tool runs, by reason: files, storage slots, settings and the title screen are not the game's, and time + moves only through advance (or the page's own clock). */ +const API_WHY={ + time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save', + slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game', + browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', + mp:'multiplayer talks to a session server for the player: only the player starts, joins, chats in or leaves a session', +}; +const API_DENY={ + speed:'time',phonePlay:'time',phoneSpeed:'time', + start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start', + exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',xfer:'files',xferFile:'files',xferPaste:'files',xferRecv:'files', + slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', + animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',themeSet:'prefs',vpSet:'prefs', + mpDoor:'mp',mpBack:'mp',mpStart:'mp',mpJoin:'mp',mpOpen:'mp',mpShare:'mp',mpCopyLink:'mp',mpChat:'mp',mpLeaveAsk:'mp',mpLeave:'mp',mpNewer:'mp',mpKeep:'mp', + install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',xferLink:'browser',xferShare:'browser', +}; diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js new file mode 100644 index 0000000..c35908a --- /dev/null +++ b/src/agent/30-docs.js @@ -0,0 +1,171 @@ +/* ================= AGENT API: what the state and the results hold ================= + One line per field of S and of R (tests/mcp-commands.test.js fails on a field without one). */ +const API_STATE_DOC={ + v:{type:'integer',doc:'Save format version.'}, + name:{type:'string',doc:'Your network\'s name.'}, + asn:{type:'integer',doc:'Your AS number.'}, + home:{type:'string',doc:'The city you started in.'}, + day:{type:'integer',doc:'The calendar day (shared by every network of a server session); day − day0 is the network\'s age.'}, + day0:{type:'integer',doc:'The calendar day this network began: 0, or the session\'s date for a network that joined a server session late.'}, + cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'}, + priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'}, + mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'}, + rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the later rules (sea, confs, broke, moods, pnis, and ip4 for scarce IPv4, off outside On-call and BGP at 3 a.m.), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, + charter:{type:'string',doc:'The charter a normal game signed when it started: global | boutique | broker. chartSet is false until one is signed.'}, + baronWon:{type:'number',doc:'The day a broker won Glass Baron, or 0.'}, + chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'}, + solWon:{type:'integer',doc:'The day the Speed of Light win landed (boutique charter), or 0.'}, + lvl:{type:'integer',doc:'Customer level (unlocks customer types).'}, + ltv:{type:'integer',doc:'Level at which Tier 1 vendors were visible (title-screen pick).'}, + t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, + auV:{type:'integer',doc:'Australia content level gate.'}, + seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, + pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb: d, its demand in Gbps; v6, the share of its homes that are IPv6-only behind NAT64, absent for dual stack; v6e, the day a swap to IPv6-only finishes, while it runs), ad boost, downtime, routers, generator, second site, teleport (tele: 1 GEO dishes, 2 with MEO tracking antennas), a Starblink LEO gateway on it (leo: 1), island Wi-Fi zones (wisp: by zone id, {day, d: the homes\' Gbps signed up, sat: the circuit {bird, g, mo, day, ready}, nxt: a move to another bird being commissioned, sp: the spur cable {day, ready}}).'}, + links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc), express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics) and rented satellite circuits (sat: bird, g Gbps, km of radio path, ready day), each with an entity id.'}, + transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, + ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, + rs:{type:'map',doc:'Route-server sessions by exchange city.'}, + ixn:{type:'map',doc:'LAG members on IX ports by exchange city.'}, + ixSite:{type:'map',doc:'Which building each IX port sits in (a, b or ab).'}, + ixPref:{type:'map',doc:'Egress preference per IX port.'}, + myIx:{type:'map',doc:'Exchanges you founded: name, members, join schedule, fabric step.'}, + peers:{type:'map',doc:'Peering sessions, keyed "net@ix".'}, + pairMet:{type:'map',doc:'Routing metric per city pair (prefer/avoid/backup/normal), keyed by pair.'}, + pni:{type:'array',doc:'Private interconnects: city, net, tier, ready day, augments (up), LAG, sacrificial flag.'}, + caches:{type:'array',doc:'CDN cache boxes: city, net, building.'}, + nni:{type:'array',doc:'Fabric ports: city, provider, tier.'}, + biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates (te: the day the term ends, mk: the bandwidth market it was priced in, hag: an open renewal haggle {rate, until}).'}, + offers:{type:'array',doc:'Pending customer offers, each expiring on a day (mk: the bandwidth market they were priced in; refN: the customer who referred them).'}, + sales:{type:'map',doc:'The sales desk: p (eng, shark, ceo or null), hired (day), vp (the day a VP of Sales takes over from the CEO), golf and say (the CEO\'s next golf deal and opinion). Offers and customers carry by: who brought or signed them, orbit ones too (the shark\'s may carry the skyfull promise).'}, + slAuto:{type:'map',doc:'Deals the sales desk signs for you (only while someone runs sales): on (sign offers that fit), min (decline offers paying less a month; 0 never), ren (answer renewal haggles), wk (this week: w, p who was at the desk, n signed, rev their monthly revenue, x declined, y declined but signed anyway by the CEO) and rep (last week, the same).'}, + cl:{type:'map',doc:'Customer lifecycle (#178): odd (the day of the last unusual departure) and mo, one entry a month of customers won, renewed, grown, haggling and lost by reason.'}, + done:{type:'map',doc:'Goals landed, by goal id → day.'}, + ach:{type:'map',doc:'Badges earned this game, by badge id → day.'}, + inc:{type:'array',doc:'Open incidents: type, what they hit, until when, optional rush-repair price.'}, + ddosStarts:{type:'array',doc:'The days the attacks of the last week started; at most 14 a week.'}, + ev:{type:'map',doc:'Live world events: the running DDoS, route leaks, fabric failures, price shocks, a solar storm (sky: the day LEO circuits leave safe mode).'}, + stats:{type:'map',doc:'Counters: incidents survived, loans taken, sharks, conferences attended, peak traffic…'}, + log:{type:'array',doc:'The NOC notification feed, newest first, capped at 60; identical notices within a minute fold with a count.'}, + nextFail:{type:'integer',doc:'The day the next failure fires.'}, + nextEvent:{type:'integer',doc:'The day the next world event fires.'}, + rng:{type:'integer',doc:'The scenario seed; it predicts every future random draw.'}, + usedNames:{type:'array',doc:'Customer names already handed out.'}, + spares:{type:'map',doc:'Spare optics on the shelf, by optic id.'}, + scrubs:{type:'array',doc:'Scrubbing centres: city and tier.'}, + scrubMode:{type:'string',doc:'always | ondemand.'}, + cnLic:{type:'map',doc:'Mainland China licence: none | pending (with ready day) | ok.'}, + pieV:{type:'number',doc:'Pie in the Sky version stamp: 1 in games started since it shipped (only those unlock it, on a Tier 1 win).'}, + pie:{type:'map',doc:'The rocket company (Pie in the Sky), or null: company, factory, stock, pads, crusts (cohorts of pies by launch day), dishes, landing rights (lic), launch queue (q), R&D, spats, the founder (posts, promises made and broken with their due days, and his antics: jit, the market jitters 0..1 that fade over 30 days and lower orbit offer odds and happiness; next, the day of the next antic; kid, 1 + the index of PIE_KIDS once he has named his son; bill, the day orbit billing comes back (no orbit income until then); nerv, hype, leak: days a posting spree, Mars hype and a leaked launch date (dearer launch insurance) last until; mars, the due day of the Mars promise, whose slip loses a few orbit customers; all only with chaos on), books, and government money (gov: auctions, awards, Ex-Im).'}, + ppol:{type:'string',doc:'Your published peering policy: open | selective | closed.'}, + pdesk:{type:'map',doc:'This week\'s peering desk summary: sessions accepted and declined at which exchanges.'}, + pdeskRep:{type:'map',doc:'Last week\'s peering desk summary, as the NOC log reported it.'}, + ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings (network work only: deals belong to the sales desk, slAuto), the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, + core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, + ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, + ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, n64: IPv6-only homes per address in the NAT64 pool, w: which warnings were shown. What customers use is derived from their kind and size.'}, + popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen, v6 (true; v6: every broadband city goes IPv6-only, only while rule ip4 is on), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up (v6 with ip6Go, city by city). g and sys are also the model the routers order and the line system the optup order standardize on.'}, + popTiers:{type:'map',doc:'POP standards by kind: def.micro|medium|hub is {g: router model, rt: routers} or null; at maps a POP city to its kind.'}, + mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'}, + demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, + seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, + monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, + fleet:{type:'map',doc:'Cable-ship voyages by ship id: the cut it sails to, when it arrives, splices and comes home.'}, + achP:{type:'map',doc:'Which rule set each badge was earned under (oncall, freeze, bgp), by badge id.'}, + calV:{type:'integer',doc:'Calendar save-format marker: 1 once the real calendar (28-31-day months) applies.'}, + pz:{type:'map',doc:'The running puzzle: its id, cities, flows to deliver, budget and stars.'}, + ar:{type:'map',doc:'The running architect run: its HQ, brief index, gold sites, spend and the build it started from.'}, + loans:{type:'array',doc:'Active loans: bank, balance, APR, term, share (equity banks).'}, + loanOffers:{type:'array',doc:'Pending loan offers.'}, + loanStrikes:{type:'integer',doc:'How many loan offers you have let lapse.'}, + confReg:{type:'map',doc:'Conferences registered for, by key; "sp" when sponsoring.'}, + hw:{type:'map',doc:'Hardware market: price shocks and any price lock.'}, + capDeal:{type:'map',doc:'The pending capacity deal from a capacity conference.'}, + cm:{type:'map',doc:'The capacity market (Lambda Bazaar): hold (% of every fiber never sold, kept for your own traffic), p (per product spec/w100/w400/w800/w1600/iru: on, min demand, floor % of list), off (routes the broker leaves alone, by "a|b"), sh (market shocks: why, from, until, m multiplier, on a route k, a city c or every subsea route), news (the latest market news), seen (incident ids already turned into news).'}, + cam:{type:'map',doc:'Map camera position. View state that save() happens to store inside S.'}, + uiSpeed:{type:'number',doc:'The speed you left the game at. View state that save() stores inside S.'}, + won:{type:'boolean',doc:'You reached Tier 1.'}, + t1Now:{type:'boolean',doc:'Tier 1 right now, as of the last day; falling out of it is announced.'}, + lost:{type:'boolean',doc:'The bank repossessed the routers.'}, + neg:{type:'integer',doc:'Days in the red in a row.'}, + hist:{type:'array',doc:'Daily history for the graphs: demand, served, exit split, revenue, cost, cash.'}, + vol:{type:'number',doc:'Traffic carried in this game, in petabytes (each day adds a day of what was served); badges at 1 PB, 100 PB, 1 EB and 1 ZB.'}, + scn:{type:'map',doc:'The running scenario: id, rules, day limit, done/failed, and the day of the next scripted attack (nextDdos).'}, + dk:{type:'map',doc:'De-Kicks state: per-exchange multipliers, add-ons, retention, the live quote (q) and the remembered one (lastQ).'}, + grace:{type:'map',doc:'Courtesy transit after a merger wave, until a day.'}, + merged:{type:'map',doc:'Networks merged into others this game.'}, + tut:{type:'map',doc:'Tutorial progress.'}, + conf:{type:'map',doc:'The conference glow: region and until when; sp when you sponsored.'}, + phpDone:{type:'boolean',doc:'One-shot flag.'}, + krExit:{type:'map',doc:'Korea exit state.'}, + auNews:{type:'boolean',doc:'One-shot flag: the Australia news toast.'}, + richTold:{type:'boolean',doc:'One-shot flag: the cash milestone toast.'}, +}; + +const API_RESULTS_DOC={ + pie:{type:'map',doc:'Orbit this compute (only with a rocket company): revenue (rev; 0 while the founder has orbit billing down, with billOff what it would have been; including patchy: {mo, cr} from patchy-sky customers who pay from 10% coverage, before a crust carries anything, and fade out between 40% and 60%), service per orbit customer, landing dishes, flows through the sky, backhaul for cut-off POPs (bh), crust and dish load, government money (gov).'}, + nt:{type:'map',doc:'Traffic per network through transit, by net id.'}, + tNet:{type:'map',doc:'Traffic per network you hand to each upstream, by "net@upstream".'}, + reachNT:{type:'number',doc:'Networks reachable without transit.'}, + teBlack:{type:'number',doc:'Traffic blackholed by RouteScript rules.'}, + teMoved:{type:'number',doc:'Traffic Auto-TE spilled onto alternate paths.'}, + egT:{type:'map',doc:'Egress split by exit kind (c/p/ix/t/l2) in Gbps.'}, + egDesc:{type:'map',doc:'RouteScript drains per exit.'}, + netEg:{type:'map',doc:'Per-network egress split: which exit carries which network.'}, + ef:{type:'map',doc:'LAZY per-link exit breakdown: what crosses each link, per network, built only when a panel asks. What is in here depends on which panels have rendered.'}, + l2:{type:'map',doc:'Layer-2 traffic per customer (L2VPN, SD-WAN, waves).'}, + l2lat:{type:'map',doc:'Latency per L2 customer.'}, + l2route:{type:'map',doc:'Which path an L2 customer\'s traffic takes.'}, + l2split:{type:'map',doc:'L2 traffic split per path.'}, + nodeLoad:{type:'map',doc:'Router forwarding load per city.'}, + nodeCap:{type:'map',doc:'Router forwarding capacity per city.'}, + div:{type:'map',doc:'Traffic diversity per customer (how split their paths are).'}, + gfwLost:{type:'number',doc:'Traffic lost to the Great Firewall.'}, + gfwCross:{type:'number',doc:'Traffic crossing into mainland China.'}, + p95:{type:'map',doc:'95th-percentile transit readings per port.'}, + peered:{type:'number',doc:'Share of traffic that stays on peering.'}, + peerShare:{type:'number',doc:'Fraction of traffic served by peers (mood driver).'}, + load:{type:'map',doc:'Load per link in Gbps.'}, + useT:{type:'map',doc:'Transit use per port id.'}, + useIx:{type:'map',doc:'IX use per exchange city.'}, + usePni:{type:'map',doc:'PNI use per port id.'}, + useCache:{type:'map',doc:'Cache use per box id.'}, + cityDem:{type:'map',doc:'Eyeball + customer demand per city.'}, + citySrv:{type:'map',doc:'Traffic served per city.'}, + cityEye:{type:'map',doc:'Eyeballs online per city.'}, + cityWisp:{type:'map',doc:'Island Wi-Fi: the Gbps of island homes each city carries for its zones (already in cityDem; never in cityEye). Only there while you run a zone.'}, + wisp:{type:'map',doc:'Island Wi-Fi zones by zone id (catalog WISP): d, the homes\' Gbps wanted; car, what their backhaul carried; sf, how well they were served (0..1); k, how many may sign up over today\'s link (the take-up cap). Only there while you run a zone.'}, + wispL:{type:'array',doc:'Island Wi-Fi zones in this compute: z, its city c, zd wanted and car carried, in Gbps. Only there while you run a zone.'}, + latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'}, + latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'}, + satU:{type:'map',doc:'Of each city\'s served traffic, the Gbps that rode a rented satellite circuit (its users notice the orbit\'s latency on that share). Only there while you have a satellite circuit up.'}, + demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'}, + served:{type:'number',doc:'Total traffic served, in Gbps.'}, + demand:{type:'number',doc:'Total traffic demanded, in Gbps.'}, + reach:{type:'number',doc:'Fraction of the internet you can reach (0..1).'}, + sessions:{type:'number',doc:'Peering sessions up.'}, + revMo:{type:'number',doc:'Revenue per month.'}, + costMo:{type:'number',doc:'Cost per month.'}, + cost:{type:'map',doc:'Monthly cost by category (transit, pni, ix, links…).'}, + rev:{type:'map',doc:'Monthly revenue by source (late: a late joiner\'s first-year match of what its homes pay).'}, + reachable:{type:'map',doc:'Networks reachable per net id.'}, + cone:{type:'map',doc:'Which peer\'s customer cone carries each network you reach without transit of your own, by net id.'}, + ddos:{type:'array',doc:'Per live attack: the target, its size, which ports it fills, what Flowspec and each scrubbing centre cleaned, and what reaches the target.'}, + haul:{type:'array',doc:'Scrubbing detours: from the attacked city to each centre, one-way latency and how much they carry.'}, + tgtF:{type:'map',doc:'The share of a targeted customer\'s traffic that survives the attack, by customer id.'}, + bbF:{type:'map',doc:'The share of a city\'s broadband subscribers that survive an attack on them, by city id.'}, + fsUse:{type:'map',doc:'Flowspec rules in use per city: used of the routers\' rule capacity.'}, + bizDem:{type:'map',doc:'Business customers\' share of each city\'s demand, in Gbps (what RouteScript\'s protect customers serves first).'}, + bizSrv:{type:'map',doc:'Of that business demand, what was served, per city.'}, + graceNets:{type:'number',doc:'Networks reached over the courtesy route after a merger wave.'}, + cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'}, + ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'}, +}; + +/* The dice rather than the board: in the player's tab (over the relay) state never returns these, and schema says why. + The MCP server's own page returns them, for debugging. */ +const API_WITHHELD={ + rng:'the seed: it predicts every future random draw', + nextFail:'the day the next failure fires', + nextEvent:'the day the next world event fires', + 'scn.nextDdos':'the day of the next scripted attack in a scenario', +}; diff --git a/src/agent/40-read.js b/src/agent/40-read.js new file mode 100644 index 0000000..22c0082 --- /dev/null +++ b/src/agent/40-read.js @@ -0,0 +1,230 @@ +/* ================= AGENT API: reading the game ================= + Every function takes and returns plain JSON and only reads the game. */ +/* Dotted subtrees, no wildcards. An array walks by index (`biz.3`) or by entity id (`links[#id]`). */ +function apiPath(o,p){ + if(p===undefined||p===null||p==='')return o; + let v=o; + for(const k of String(p).split('.')){ + if(v==null)return undefined; + if(Array.isArray(v)){const i=Number(k); + v=(Number.isInteger(i)&&String(i)===k&&i>=0&&ix&&typeof x==='object'&&x.id===k);} + else if(v instanceof Set)v=[...v]; + else if(v instanceof Map)v=Object.fromEntries(v); + else if(typeof v==='object')v=v[k]; + else return undefined;} + return v;} + +function apiJson(v){ + if(v instanceof Set)return [...v].map(apiJson); + if(v instanceof Map)return apiJson(Object.fromEntries(v)); + if(v&&typeof v==='object')return Array.isArray(v)?v.map(apiJson):Object.fromEntries(Object.entries(v).map(([k,x])=>[k,apiJson(x)])); + if(typeof v==='function')return undefined; + return v;} + +/* The tables the argument domains point at. Everything is a static reference except three, + each computed for a reason: BADGES hides unearned secrets like the badge wall; conferences + carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders + each recipe's script, because the source is a function and some read the live network. The + recipes' relevance score is not exposed: judging which one fits is the agent's job. */ +const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SATS,SAT_ORB,SAT_PROV,WISP,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,PNI_LAG_MAX,PNI_LAG_RT,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; +const API_MADE={ + BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; + return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), + conferences:()=>!S?[]:upcomingConfs(75).map(cf=>({key:cf.key,name:cf.n,city:cf.c,day:cf.day,capacity:!!cf.cap,cost:confCost(cf),sponsorCost:confSp(cf)?CONF_SP:null})), + TE_RECIPES:()=>!S?[]:TE_RECIPES.map(r=>({id:r.id,name:tr(r.n),description:tr(r.d),script:r.src().join('\n')})), +}; +function API_CATALOG_TABLE(name){return name in API_MADE?API_MADE[name]():API_TABLES[name];} + +/* UI minus the render caches and pointer scratch, which are inputs to nothing. + Everything a command binds (pending, route, via, dfSrc, dfSys, seaDesign, cnPrem, decom, + teDraft, confirm) stays, so an agent can see what it was given. */ +const API_UI_HIDDEN={_lh:1,_ph:1,_tb:1,_layer:1,layerAt:1,hover:1,drag:1,snap:1}; + +/* ---------- text as a player reads it ---------- */ +const API_BLOCK=/^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/,API_MAX_TEXT=8000; +// One line per block, no runs of spaces. jsdom has no innerText, so this walks the nodes itself. +function apiFullText(x){ + let el=x; + if(typeof x==='string'){el=document.createElement('div');el.innerHTML=x;} + if(!el)return ''; + const out=[]; + const walk=n=>{ + if(n.nodeType===3){out.push(n.nodeValue);return;} + if(n.nodeType!==1||n.hidden||/^(SCRIPT|STYLE|SVG|CANVAS)$/i.test(n.tagName))return; + if(n.tagName==='BR'){out.push('\n');return;} + // A dropdown reads as its choice: hundreds of options would crowd out the rest (the catalog lists them). + if(n.tagName==='SELECT'){const o=n.options[n.selectedIndex];out.push(' ',o?o.text:'',' ');return;} + // Blocks get their own line; inline tags a space, so "Revenue$2k" does not read as one word. + const sep=API_BLOCK.test(n.tagName)?'\n':' '; + out.push(sep);for(const c of n.childNodes)walk(c);out.push(sep);}; + walk(el); + return out.join('').split('\n').map(l=>l.replace(/\s+/g,' ').replace(/ ([.,;:!?)])/g,'$1').replace(/\( /g,'(').trim()).filter(Boolean).join('\n');} +const apiText=(x,max=API_MAX_TEXT)=>{const s=apiFullText(x);return s.length>max?s.slice(0,max)+'\n…':s;}; +const apiR1=v=>typeof v==='number'&&isFinite(v)?Math.round(v*10)/10:v; +const apiFail=msg=>{throw new Error(msg);}; +const apiNorm=s=>String(s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').trim(); +const apiParse=s=>{try{return JSON.parse(s||'{}');}catch(e){return {};}}; + +/* ---------- finding things by id or by name ---------- */ +function apiBest(list,q,keys){const n=apiNorm(q);if(!n)return null; + for(const test of [v=>v===n,v=>v.startsWith(n),v=>v.includes(n)]){const hit=list.find(x=>keys(x).some(k=>test(apiNorm(k))));if(hit)return hit;} + return null;} +const apiNetOf=q=>NET[q]||apiBest(NETS,q,n=>[n.id,n.name,'as'+n.asn,String(n.asn)])||apiFail(`No network matches "${q}". Try find.`); +const apiCityOf=q=>CITY[q]||apiBest(CITIES,q,c=>[c.id,c.name])||apiFail(`No city matches "${q}". Try find.`); +function apiAllIx(){const o=[];for(const c of CITIES)for(const x of ixStatic(c.id))o.push(x);for(const c of Object.keys(S.myIx||{}))if(!o.includes(c))o.push(c);return o;} +const apiCityName=c=>CITY[c]?CITY[c].name:c; +const apiIncText=i=>apiText(i.msg||incTitle(i),400); +const apiMyPops=()=>Object.keys(S.pops).map(apiCityName).join(', '); + +/* ---------- the network at a glance, and the world ---------- */ +function apiStatus(){ + const goal=goals().find(g=>S.done[g.id]===undefined),t1=isTier1(),k=o=>Object.fromEntries(Object.entries(o||{}).map(([a,v])=>[a,Math.round(v)]).filter(([,v])=>v)); + return { + name:S.name,asn:S.asn,home:apiCityName(S.home),mode:S.mode,rules:S.rules&&S.rules.preset, + day:S.day,age:netAge(),date:dateStr(S.day),cash:Math.round(S.cash),level:S.lvl||0, + tier:tierLabel(),whyNotTier1:t1?null:apiText(t1Why()), + goal:goal?{title:apiText(goal.t),what:apiText(goal.d)}:null, + monthly:{revenue:Math.round(R.revMo),cost:Math.round(R.costMo),profit:Math.round(R.revMo-R.costMo),revenueBy:k(R.rev),costBy:k(R.cost)}, + traffic:{demandGbps:apiR1(R.demand),servedGbps:apiR1(R.served),reach:apiR1((R.reach||0)*100)+'%',peeringSessions:R.sessions}, + counts:{pops:Object.keys(S.pops).length,links:S.links.length,transitPorts:S.transit.length,exchangePorts:Object.keys(S.ixp).length, + pnis:S.pni.length,cacheBoxes:S.caches.length,customers:S.biz.length,offers:S.offers.length}, + pops:Object.keys(S.pops).map(apiCityName), + incidents:S.inc.map(i=>({id:i.id,type:i.type,what:apiIncText(i),until:i.until!==undefined?dateStr(i.until):undefined,rushRepairCost:i.cost||undefined})), + lost:!!S.lost,won:!!S.won, + };} + +function apiNetwork(q){ + const n=apiNetOf(q),id=n.id,eg=R.netEg&&R.netEg[id]; + return { + id,name:n.name,asn:n.asn,type:TYPE_L[n.type],policy:n.pol, + requirements:{minIxGbps:n.minIx,minPniGbps:n.minPni,paidFeePerMonth:n.paidFee,freeFromLevel:n.freeLv}, + trafficShare:apiR1(NSH[id]*100)+'%',transitPerGbps:n.price?apiR1(n.price*S.priceMul):null, + homeMarkets:n.cc?[].concat(n.cc):[],pops:n.pops.map(apiCityName), + exchanges:n.ix==='ALL'?'most exchanges where it has a PoP':(n.ix||[]).map(x=>ixName(x)), + upstreams:(n.up||[]).map(u=>NET[u]?NET[u].name:u),customerCone:(DOWN[id]||[]).length, + neededForTier1:t1Need().some(x=>x.id===id),mergedInto:merged(id)?(MERGERS.find(m=>m.id===id)||{}).into:undefined, + about:apiText(n.blurb), + you:{ + reachable:!!(R.reachable&&R.reachable[id]),demandGbps:apiR1((R.demTo&&R.demTo[id])||0), + egressGbps:eg?Object.fromEntries(Object.entries(eg).map(([k,v])=>[k,apiR1(v)])):null, + pnis:S.pni.filter(p=>p.net===id).map(p=>({id:p.id,city:apiCityName(p.city),port:pniPN(p),count:p.n||1,ready:pniOn(p)})), + exchangeSessions:Object.keys(S.ixp).filter(x=>ixSessions(x).has(id)).map(ixName), + howToPeer:apiText(offTransitHint(id,S.home)), + }, + };} + +function apiCity(q){ + const C=apiCityOf(q),c=C.id,P=S.pops[c]; + const cab=CABLE_PAIRS.filter(p=>p.a===c||p.b===c).map(p=>({cable:CAB[p.cid]?CAB[p.cid].name:p.cid,to:apiCityName(p.a===c?p.b:p.a),km:p.km})); + const here=NETS.filter(n=>n.pops.includes(c)&&!n.tail).sort((a,b)=>b.share-a.share); + return { + id:c,name:C.name,country:C.cc,region:C.reg,about:C.note?apiText(C.note):undefined,dataCenter:C.dc, + canBeHome:homeOk(c), + exchanges:ixIdsIn(c).map(x=>({id:x,name:ixName(x),members:ixMembers(x).length,yourPort:S.ixp[x]!==undefined})), + transit:NETS.filter(n=>sellsAt(n,c)).map(n=>({id:n.id,name:n.name,type:TYPE_L[n.type],perGbps:apiR1(transitPerG(n,c,false)*S.priceMul)})).sort((a,b)=>a.perGbps-b.perGbps), + networksHere:here.length,biggestNetworksHere:here.slice(0,15).map(n=>n.name),cables:cab, + you:P?{demandGbps:apiR1((R.cityDem||{})[c]||0),servedGbps:apiR1((R.citySrv||{})[c]||0),routers:P.routers,down:P.down>S.day?dateStr(P.down):false, + broadband:!!P.bb,links:S.links.filter(l=>l.a===c||l.b===c).length}:null, + };} + +function apiFind(q,kind){ + const n=apiNorm(q),hit=(...k)=>k.some(v=>apiNorm(v).includes(n)),out={}; + if(!n)apiFail('Give a word to search for.'); + if(!kind||kind==='city')out.cities=CITIES.filter(c=>hit(c.id,c.name)).slice(0,20).map(c=>({id:c.id,name:c.name,country:c.cc})); + if(!kind||kind==='network')out.networks=NETS.filter(x=>hit(x.id,x.name,String(x.asn))).slice(0,20).map(x=>({id:x.id,name:x.name,asn:x.asn,type:TYPE_L[x.type]})); + if(!kind||kind==='cable')out.cables=Object.values(CAB).filter(x=>hit(x.id,x.name)).slice(0,20).map(x=>({id:x.id,name:x.name,lands:[...new Set(x.pairs.flatMap(p=>[p[0],p[1]]))].map(apiCityName)})); + if(!kind||kind==='exchange')out.exchanges=apiAllIx().filter(x=>hit(x,ixName(x))).slice(0,20).map(x=>({id:x,name:ixName(x),city:apiCityName(ixCity(x))})); + return out;} + +function apiTrace(from,to){ + const src=apiCityOf(from).id; + if(!S.pops[src])apiFail(`You have no POP in ${apiCityName(src)}. Yours: ${apiMyPops()}.`); + let target=null; + if(typeof to==='string'&&/^city:/i.test(to))target={city:apiCityOf(to.slice(5)).id}; + else{try{target={net:apiNetOf(to).id};}catch(e){target={city:apiCityOf(to).id};}} + if(target.city&&!S.pops[target.city])apiFail(`A traceroute to a city goes to one of your POPs: ${apiMyPops()}.`); + const r=traceroute(src,target); + return {text:r.text,why:apiText(r.why||''),asPath:r.asPath||null};} + +function apiPeering(q,where,via){ + const n=apiNetOf(q),id=n.id,out=[]; + if(!via||via==='pni')for(const c of (where?[apiCityOf(where).id]:Object.keys(S.pops).filter(c=>n.pops.includes(c)))){ + const r=peerOk(id,'pni',c); + out.push({via:'pni',city:apiCityName(c),ok:!!r.ok,why:r.why?apiText(r.why):undefined,feePerMonth:r.fee,free:r.free,minimumPort:PORT[pniMin(id)].n});} + if(!via||via==='ix')for(const x of Object.keys(S.ixp).filter(x=>ixMembers(x).includes(id)&&(!where||ixCity(x)===apiCityOf(where).id))){ + const r=peerOk(id,'ix',x); + out.push({via:'ix',exchange:ixName(x),ok:!!r.ok,why:r.why?apiText(r.why):undefined,session:ixSessions(x).has(id)});} + return {network:n.name,policy:n.pol,hint:apiText(offTransitHint(id,where?apiCityOf(where).id:S.home)), + checks:out,note:out.length?undefined:'No POP or exchange port of yours is where this network is. Build one first: see network.'};} + +function apiHotSpots(limit=10){ + const top=a=>a.sort((x,y)=>y.util-x.util).slice(0,limit),pct=(u,c)=>c>0?apiR1((u/c)*100):null; + const links=S.links.map(l=>{const cap=capOf(l),u=(R.load||{})[l.id]||0;return {id:l.id,between:apiCityName(l.a)+' – '+apiCityName(l.b),kind:l.kind,capacity:capName(l),usedGbps:apiR1(u),util:pct(u,cap),down:linkDown(l)};}); + const transit=S.transit.map(t=>{const cap=lagCap(PORT[t.tier].g,t.n),u=(R.useT||{})[t.id]||0,q=(R.p95&&R.p95[t.id])||u; + return {id:t.id,city:apiCityName(t.city),carrier:NET[t.net].name,port:lagName(t.tier,t.n),usedGbps:apiR1(u),util:pct(u,cap),billPerMonth:Math.round(transitMo(t,q))};}); + const pnis=S.pni.filter(pniOn).map(p=>{const cap=pniG(p)*(p.n||1),u=(R.usePni||{})[p.id]||0;return {id:p.id,network:NET[p.net].name,city:apiCityName(p.city),port:pniPN(p),usedGbps:apiR1(u),util:pct(u,cap)};}); + const viaTransit=NETS.filter(n=>R.netEg&&R.netEg[n.id]&&R.netEg[n.id].t>0.05).sort((a,b)=>R.netEg[b.id].t-R.netEg[a.id].t).slice(0,limit) + .map(n=>({id:n.id,network:n.name,overTransitGbps:apiR1(R.netEg[n.id].t),howToPeer:apiText(offTransitHint(n.id,S.home))})); + const bill={};for(const t of transit)bill[t.carrier]=(bill[t.carrier]||0)+t.billPerMonth; + return {links:top(links),transitPorts:top(transit),pnis:top(pnis),transitBillByCarrier:bill,biggestTrafficStillOnTransit:viaTransit};} + +/* ---------- the contract: commands, arguments, reference tables, raw state ---------- */ +const apiDenied=name=>own(API_DENY,name)?API_WHY[API_DENY[name]]:null; +const apiKind=name=>API_CMD[name]?'game':API_VIEW[name]?'view':API_BOUND[name]?'draft':API_SESSION[name]?'session':null; +const apiSpec=name=>API_CMD[name]||API_VIEW[name]||API_SESSION[name]||null; +const apiClasses=()=>({game:Object.keys(API_CMD),view:Object.keys(API_VIEW),draft:Object.keys(API_BOUND),session:Object.keys(API_SESSION),denied:Object.keys(API_DENY)}); + +// One argument as the schema states it. Table domains name their catalog table rather than list every id. +function apiArgDoc([name,dom,req]){ + const a={name,required:req!==false},d=API_DOMAINS[dom]; + if(!d){a.type=dom;return a;} + a.domain=dom; + if(d.table)a.from=d.table; + else{const v=apiDomValues(dom);if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v;} + return a;} +function apiSchema(section){ + const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc}),relay=API_CTX.relay; + const doc={ + mode:apiMode(), + clock:apiClockDoc(), + commands:Object.fromEntries(Object.entries(API_CMD).map(([n,s])=>[n,{...cmd(s),dryRun:!!s.quote, + ...(s.decides?{decides:true}:{}),...(s.confirm?{confirm:s.confirm}:{}),...(s.open?{opens:s.open}:{}),...(s.reads?{report:true}:{})}])), + view:Object.fromEntries(Object.entries(API_VIEW).map(([n,s])=>[n,cmd(s)])), + session:Object.fromEntries(Object.entries(API_SESSION).map(([n,s])=>[n,{...cmd(s),...(relay&&API_PLAYER_OWNS[n]?{refused:API_OWN_WHY}:{})}])), + drafts:API_BOUND, + denied:Object.fromEntries(Object.keys(API_DENY).sort().map(n=>[n,apiDenied(n)])), + domains:Object.fromEntries(Object.entries(API_DOMAINS).map(([n,d])=>{const v=apiDomValues(n); + return [n,{kind:d.kind==='fn'?'custom':d.kind,...(d.table?{from:d.table}:{}), + ...(!d.table&&Array.isArray(v)?{values:v}:v&&v.from!==undefined?{range:v}:v&&v.of?{of:v.of}:{})}];})), + state:relay?Object.fromEntries(Object.entries(API_STATE_DOC).map(([k,d])=>[k,API_WITHHELD[k]?{...d,withheld:API_WITHHELD[k]}:d])):API_STATE_DOC, + results:API_RESULTS_DOC, + }; + if(section===undefined||section===null||section==='')return doc; + if(!(section in doc))apiFail(`No section "${section}". Sections: ${Object.keys(doc).join(', ')}.`); + return doc[section];} +function apiCatalog(name){ + if(name===undefined||name===null||name===''){ + return {tables:[...Object.keys(API_TABLES),...Object.keys(API_MADE)].sort().map(k=>{const t=k in API_MADE?API_MADE[k]():API_TABLES[k]; + return {name:k,n:Array.isArray(t)?t.length:t&&typeof t==='object'?Object.keys(t).length:1};})};} + if(name in API_MADE)return apiJson(API_MADE[name]()); + if(name in API_TABLES)return apiJson(API_TABLES[name]); + apiFail(`No table "${name}". Call catalog without a name for the list.`);} +// In the player's tab the dice are held back: a withheld field, or one inside the subtree asked for, is left out. +function apiState(path){ + if(!S)return null; + const p=path===undefined||path===null?'':String(path),v=apiJson(apiPath(S,p)); + if(v===undefined)return null; + if(!API_CTX.relay)return v; + for(const w of Object.keys(API_WITHHELD)){ + if(w===p||p.startsWith(w+'.'))return null; + if(p&&!w.startsWith(p+'.'))continue; + const ks=(p?w.slice(p.length+1):w).split('.');let o=v; + for(let i=0;i(s.args||[]).map(a=>a[0]+(a[2]===false?'?':'')).join(','),typed={}; + for(const t of [API_CMD,API_VIEW,API_SESSION])for(const [n,s] of Object.entries(t))typed[n]=sig(s); + return {typed,drafts:Object.keys(API_BOUND)};} diff --git a/src/agent/50-screen.js b/src/agent/50-screen.js new file mode 100644 index 0000000..9e754c3 --- /dev/null +++ b/src/agent/50-screen.js @@ -0,0 +1,79 @@ +/* ================= AGENT API: what is on screen ================= + The surfaces a player can read, as text with numbered buttons, by the name screen takes. The left drawer has tabs + (goals, deals, noc, nets). */ +const API_ROOT={modal:'modal',bank:'bankBox',dash:'dash',panel:'panel',left:'leftBody',puzzle:'pzBox'}; +const apiShown=w=>{const el=$(API_ROOT[w]);return !!el&&!el.hidden;}; +const apiModalOpen=()=>apiShown('modal'); +// A window the player opened by hand (API_MODAL.hand, 75-mode.js) is theirs: a tool reads it but never answers, +// closes or replaces it, and it is never a question the game is waiting on. +const apiPlayerWin=()=>apiModalOpen()&&API_MODAL.hand; +// The buttons of the last screen a tool read, for click. Set by apiScreen. +let API_LAST=[]; +function apiControls(root,player){ + const out=[]; + for(const b of root.querySelectorAll('[data-act],select[data-chg]')){ + const o=b.dataset.act?{label:apiText(b,200).replace(/\n/g,' ')||b.getAttribute('aria-label')||b.dataset.act,act:b.dataset.act,args:apiParse(b.dataset.args),disabled:!!b.disabled} + // A list the game acts on when its value changes (the change handler in 96-map/95-clicks.js): click it with a value. + :{label:b.getAttribute('aria-label')||(b.closest('label')&&apiText(b.closest('label'),120).split('\n')[0])||b.dataset.chg, + select:b.dataset.chg,args:apiParse(b.dataset.args),value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled}; + if(player)o.player=true; + out.push(o);} + return out;} +function apiScreen(where,offset=0){ + if(where===null)where=undefined; + if(where!==undefined&&!API_ROOT[where])apiFail(`where is one of ${Object.keys(API_ROOT).join(', ')}.`); + const open=Object.keys(API_ROOT).filter(w=>w!=='left'&&apiShown(w)); + const w=where||['modal','bank','dash','panel','puzzle'].find(apiShown)||'panel'; + const root=$(API_ROOT[w]),player=w==='modal'&&apiPlayerWin(); + API_LAST=root?apiControls(root,player):[]; + const all=root?apiFullText(root):'',from=Math.max(0,Math.floor(+offset)||0),more=all.length-from-API_MAX_TEXT; + const out={where:w,open,selected:UI.sel,tab:UI.tab}; + if(w==='left')out.leftTab=UI.left||'goals'; + if(w==='modal'){out.question=!!apiDecision();if(player)out.playerWindow='the player opened this window: read it, but its buttons are theirs to press';} + out.text=all.slice(from,from+API_MAX_TEXT); + if(from)out.textFrom=from; + if(more>0)out.textMore=`${more} more characters: call screen with where "${w}" and offset ${from+API_MAX_TEXT}`; + out.buttons=API_LAST.map((b,i)=>({n:i,...b})); + return out;} + +/* ---------- windows: the tool's own sheets, and the game's questions ---------- + A window the tool opened itself (a view, a draft, the link window, a sheet it clicked inside) is something to read + and click through. A window the game opened in answer to a game command, or during a day, is a question when one + of its buttons runs a game command other than closeModal (a De-Kicks quote, a retention offer); then other game + commands wait until it is answered or closed, as clicks outside an open window do in the game. */ +let API_SHEET=null; +const apiCard=()=>$('modalCard').firstChild; +const apiMarkSheet=()=>{API_SHEET=apiModalOpen()&&!apiPlayerWin()?apiCard():null;}; +const apiIsSheet=()=>apiModalOpen()&&!!API_SHEET&&apiCard()===API_SHEET; +function apiDecision(){ + if(!apiModalOpen()||apiIsSheet()||apiPlayerWin())return null; + const b=[...$('modal').querySelectorAll('[data-act]')].filter(x=>x.dataset.act!=='closeModal'&&API_CMD[x.dataset.act]); + if(!b.length)return null; + return {text:apiText($('modal'),1500),options:b.map(x=>({command:x.dataset.act,args:apiParse(x.dataset.args),label:apiText(x,120).replace(/\n/g,' ')}))};} + +/* A player's window stays where it is: its very nodes are set aside while a tool's command runs, and put back after, + so typed text survives. Only a question the game asks in answer to the tool's move takes the screen, as it would + after a click. */ +function apiHold(){const m=$('modal'),c=$('modalCard'); + return {nodes:[...c.childNodes],cls:m.className,aria:c.getAttribute('aria-modal'),setOpen:UI.setOpen,pending:UI.pending};} +function apiRestore(h){const m=$('modal'),c=$('modalCard'); + if(!m.hidden&&m.className===h.cls&&c.childNodes.length===h.nodes.length&&h.nodes.every((n,i)=>c.childNodes[i]===n)){API_MODAL.hand=true;return;} + m.className=h.cls;if(h.aria!==null)c.setAttribute('aria-modal',h.aria);c.replaceChildren(...h.nodes); + if(m.hidden)markLayer();m.hidden=false;UI.setOpen=h.setOpen;UI.pending=h.pending;API_MODAL.hand=true;API_SHEET=null;} + +function apiPanel({city:c,link,network:q,tab,left}={}){ + if(left!==undefined){if(!['goals','deals','noc','nets'].includes(left))apiFail('left is one of goals, deals, noc, nets.');ACT.leftTab({t:left});return apiScreen('left');} + if(c)UI.sel={type:'city',id:apiCityOf(c).id}; + else if(link){if(!S.links.some(l=>l.id===link))apiFail(`No link ${link}. See status or hot_spots for link ids.`);UI.sel={type:'link',id:link};} + else if(q)ACT.netFocus({id:apiNetOf(q).id}); + if(tab)UI.tab=tab; + renderAll(); + return apiScreen(q?'left':'panel');} +function apiOpenLink(a,b){ + const x=apiCityOf(a).id,y=apiCityOf(b).id; + if(!S.pops[x])apiFail(`A link starts at one of your POPs: ${apiMyPops()}.`); + if(apiPlayerWin())apiFail('The player has a window open, and the link window would replace it. Use act buildLink, orderDf or orderCable, or wait until it is closed.'); + apiTake(); + openLinkModal(x,y); + apiMarkSheet(); + return {toasts:apiToastLines(apiTake()),screen:apiScreen()};} diff --git a/src/agent/60-dispatch.js b/src/agent/60-dispatch.js new file mode 100644 index 0000000..38c3e3d --- /dev/null +++ b/src/agent/60-dispatch.js @@ -0,0 +1,123 @@ +/* ================= AGENT API: doing things ================= + One action, run as the game runs it, and reported through the game's own channels: what it said (toast), what it + charged at the money gate (spend) and whether anything changed (a fingerprint of S). The API checks shape and domain + only; whether a move is allowed is the game's to answer. */ + +// Arguments: shape and domain only. Anything beyond that is the game's to answer. +function apiValidate(spec,args){ + const problems=[],out={}; + for(const [name,dom,req] of spec.args||[]){ + const v=args[name]; + if(v===undefined){if(req!==false)problems.push(`${name} is required`);continue;} + if(apiDomCheck(dom,v).ok){out[name]=v;continue;} + const vs=apiDomValues(dom),d=API_DOMAINS[dom]; + problems.push(`${name}: ${JSON.stringify(v)} is not a ${dom}${d&&d.table&&d.kind==='id'?` (see catalog ${d.table} or find)`:Array.isArray(vs)?` (one of ${vs.slice(0,12).join(', ')}${vs.length>12?'…':''})`:vs&&typeof vs==='object'&&vs.from!==undefined?` (${vs.from}..${vs.to})`:''}`);} + for(const k of Object.keys(args))if(!(spec.args||[]).some(a=>a[0]===k))problems.push(`${k} is not an argument of this action`); + return {ok:!problems.length,problems,args:out};} + +// The fingerprint tells "did nothing" from "did something quietly": cash, day, the entity counts, the small settings +// maps, and the paths a command declares in watch. R is left out: it is rebuilt after every action. +const API_FP_LEN=['links','transit','pni','caches','biz','offers','nni','loans','loanOffers','inc','scrubs']; +const API_FP_KEYS=['pops','ixp','peers','myIx','done','ach','merged','confReg']; +const API_FP_JSON=['name','pairMet','rs','ixn','ixSite','ixPref','spares','te','cnLic','hw','scrubMode','ppol','ops','core','ddosAuto','popStd','popTiers','demo','charter','monkey','seatOff','pz','ar','dk','ev']; +function apiFp(watch,args){ + if(!S)return null; + const f={cash:S.cash,day:S.day,lvl:S.lvl||1,won:!!S.won,lost:!!S.lost}; + for(const k of API_FP_LEN)f[k]=(S[k]||[]).length; + for(const k of API_FP_KEYS)f[k]=Object.keys(S[k]||{}).length; + for(const k of API_FP_JSON)f[k]=JSON.stringify(apiJson(S[k])??null); + for(const p of watch||[])f['@'+p]=JSON.stringify(apiJson(apiPath(S,String(p).replace(/#(\w+)/g,(m,k)=>args&&args[k]!==undefined?args[k]:m)))??null); + return JSON.stringify(f);} +// spend() is the game's money gate and a top-level function, so every action reaches it by its global name. +function apiMeter(){const real=window.spend;let paid=0;window.spend=c=>{const ok=real(c);if(ok)paid+=c;return ok;};return ()=>{window.spend=real;return paid;};} + +/* typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button click + does it, with the button's own arguments. */ +function apiDispatch(name,kind,spec,args,typed){ + const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open),held=apiPlayerWin()?apiHold():null; + apiTake(); + const ref=S,cash=S?S.cash:0,f0=apiFp(spec&&spec.watch,args),paid=apiMeter(); + let threw=null,report; + try{ + if(typed&&kind==='game'){ + if(spec.open){ACT[spec.open]({});apiMarkSheet();} + // The custom metric's field lives in the link's panel. + if(name==='metricSet'&&!$('metIn')){UI.sel={type:'link',id:args.id};renderAll();} + const gone=(spec.dom||[]).filter(f=>!$(f)); + if(gone.length)throw new Error(`the field it types into (${gone.join(', ')}) is not on screen${name==='metricSet'?': set the link\'s metric to custom first (setMetric v "custom")':''}`); + if(spec.bind)spec.bind(args); + const a=spec.pass?spec.pass(args):args; + ACT[name](a); + if(spec.confirm==='double')ACT[name](a); + if(spec.reads==='modal'&&apiModalOpen()&&!apiPlayerWin()){report=apiText($('modal'));closeModal();} + }else ACT[name](args); + }catch(e){threw=e;} + const charged=paid(); + if(held&&(threw||!apiDecision())){ + // The tool's own sheet is read before the player's window goes back over it. + const shot=!threw&&apiModalOpen()&&!apiPlayerWin()?apiScreen('modal'):null; + apiRestore(held); + if(shot)shot.note='The player has a window open, so this one was shown to you and closed again.'; + held.shot=shot;} + if(threw){apiTake();apiFail(`${name} failed: ${threw&&threw.message||threw}`);} + if(!apiModalOpen()||apiPlayerWin())API_SHEET=null; + else if(mine||kind!=='game')apiMarkSheet(); + else API_SHEET=null; + const said=apiTake(),d=apiDecision(); + const outcome=d?'decision':S!==ref||apiFp(spec&&spec.watch,args)!==f0||report!==undefined?'applied' + :said.some(t=>t.kind==='bad')?'rejected':kind==='view'||kind==='draft'?'shown':'no_effect'; + return {action:name,outcome,toasts:apiToastLines(said),charged,cashChange:Math.round((S?S.cash:0)-cash), + ...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:held&&held.shot||apiScreen()};} +// While the game waits for an answer, game commands other than its options report the question instead. +function apiWaiting(name){ + const d=apiDecision(); + return d&&name!=='closeModal'&&!d.options.some(o=>o.command===name) + ?{action:name,outcome:'decision',reason:'A window is waiting for an answer: run one of its options, or closeModal.',decision:d,screen:apiScreen()}:null;} +function apiQuote(name,spec,args){ + const ui0={}; + for(const k of spec.bindsUI||[])ui0[k]=UI[k]; + const f0=apiFp(spec.watch,args); + // A dry run must not use up the dice: some helpers draw (a PNI's lead time), and a draw here would move the seeded + // game. They get the middle of the range instead, so a drawn figure in a quote is a typical one. + const dice=Math.random; + Math.random=()=>0.5; + let q={}; + try{ + if(spec.bind&&!spec.dom)spec.bind(args); + if(spec.quote)q=spec.quote(args)||{}; + }catch(e){apiFail(`${name}: the price could not be worked out: ${e&&e.message||e}`);}finally{Math.random=dice;for(const k of Object.keys(ui0))UI[k]=ui0[k];} + return {action:name,outcome:'quote',quote:{setup:0,monthly:0,...q,blocked:(q.blocked||[]).map(b=>apiText(String(b),400))},consistent:apiFp(spec.watch,args)===f0, + ...(spec.quote?{}:{note:'This command has no price of its own: it costs nothing up front.'})};} +// Checks shared by act and click: what no tool runs, and what only the player runs in their own tab. +function apiAllowed(name,what){ + const no=apiDenied(name); + if(no)apiFail(`${name} is not available here: ${no}.`); + if(API_CTX.relay&&API_PLAYER_OWNS[name])apiFail(`${name} is not available here: ${API_OWN_WHY}.`); + const kind=apiKind(name); + if(!kind||typeof ACT[name]!=='function')apiFail(what); + return kind;} +function apiRun(name,args,opts={}){ + name=String(name||''); + if(name.startsWith('view.'))name=name.slice(5); + const kind=apiAllowed(name,`There is no action "${name}". See actions or schema.`); + args=args&&typeof args==='object'&&!Array.isArray(args)?args:{}; + const spec=apiSpec(name); + if(spec){const v=apiValidate(spec,args);if(!v.ok)apiFail(`${name}: ${v.problems.join('; ')}. See schema for its arguments.`);args=v.args;} + if(kind==='game'){ + if(S&&S.lost&&name!=='closeModal')return {action:name,outcome:'stopped',reason:'The network went bankrupt: start or load another game.'}; + const w=apiWaiting(name); + if(w)return w; + if(opts.dryRun)return apiQuote(name,spec,args); + }else if(opts.dryRun)apiFail(`${name} has no price: only game commands (see schema commands) dry-run.`); + return apiDispatch(name,kind,spec,args,true);} +function apiClick(n,value){ + const b=API_LAST[n]; + if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`); + if(b.disabled)apiFail(`"${b.label}" is greyed out.`); + if(b.player&&apiPlayerWin())apiFail(`"${b.label}" is in a window the player opened: it is theirs to press.`); + // A list sends its own arguments with the value picked, as the page's change handler does (96-map/95-clicks.js). + const name=b.select||b.act,args=b.select?{...(b.args||{}),v:value===undefined?undefined:String(value)}:b.args; + if(b.select&&!b.options.some(o=>o.value===args.v))apiFail(`"${b.label}" is a list: click it with a value, one of ${b.options.map(o=>JSON.stringify(o.value)).join(', ')}.`); + const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`); + if(kind==='game'){const w=apiWaiting(name);if(w)return {clicked:b.label,...w};} + return {clicked:b.label,...apiDispatch(name,kind,apiSpec(name),args,false)};} diff --git a/src/agent/70-time.js b/src/agent/70-time.js new file mode 100644 index 0000000..fa7aee7 --- /dev/null +++ b/src/agent/70-time.js @@ -0,0 +1,67 @@ +/* ================= AGENT API: time ================= + Two clocks, in the MCP server's own page and in the player's tab alike. The agent's clock: nothing moves until a tool + asks for days with advance. A running clock: days pass at a fixed pace whatever the tool does, and the tool can only + wait and react. In the player's tab the player picks one in Settings (apiAgentMs(), 0 for the agent's clock); the MCP + server's own page is told by the server (API_CLK). */ +let API_CLK={mode:'agent',paceMs:0,running:false}; +const apiClockNow=()=>API_CTX.relay?(apiAgentMs()>0?{mode:'realtime',paceMs:apiAgentMs(),running:!!UI.speed}:{mode:'agent',paceMs:0,running:false}):API_CLK; +function apiMode(){const c=apiClockNow(); + return {backend:API_CTX.relay?'browser':'headless',clock:c.mode,...(c.mode==='realtime'?{paceMs:c.paceMs}:{}), + ...(API_CTX.relay?{withheld:API_WITHHELD,playerOwns:Object.keys(API_PLAYER_OWNS)}:{})};} +function apiClockDoc(){const c=apiClockNow(); + return c.mode==='agent'?'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.' + :`The clock runs on its own: one simulated day every ${apiR1(c.paceMs/1000)} s of real time, behind open windows too, and no tool can stop it${API_CTX.relay?' (it holds while no tool is connected)':''}. advance is not available; wait returns once days have passed.`;} +function apiClock(){const c=apiClockNow(); + return {mode:c.mode,paceMs:c.paceMs||undefined,running:c.mode==='realtime'?!!c.running:false, + day:S?S.day:null,date:S?dateStr(S.day):null,cash:S?S.cash:null,lost:!!(S&&S.lost),incidents:S?S.inc.map(i=>i.id):[],question:!!apiDecision()};} + +// What happened since a moment (the start of an advance, or a clock reading before wait): the log, new incidents, cash. +// The log keeps what mattered; toasts that only repeat a log line are left out. +function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){ + const seen=new Set(inc),entries=(S.log||[]).filter(e=>e.d>day).slice(-60),logged=entries.map(e=>apiNorm(apiText(e.t,400))); + const d=apiDecision(); + return {from:dateStr(day),to:dateStr(S.day),daysRun:S.day-day,cash:Math.round(S.cash),cashChange:Math.round(S.cash-cash), + newIncidents:S.inc.filter(i=>!seen.has(i.id)).map(apiIncText), + log:entries.map(e=>`${dateStr(e.d)}: ${apiText(e.t,400)}`), + toasts:[...new Set(apiToastLines(toasts))].filter(t=>{const f=apiNorm(t.replace(/^\w+: /,'').split('\n')[0]);return !logged.some(l=>l.startsWith(f));}).slice(-40), + ...(d?{decision:d,screen:apiScreen()}:{})};} + +function apiAdvanceStart(days){ + if(!S)apiFail('No game is running.'); + const c=apiClockNow(); + if(c.mode!=='agent')apiFail(`The clock runs on its own here, one day every ${apiR1(c.paceMs/1000)} s: use wait to let days pass.`); + if(apiModalOpen()&&!apiPlayerWin())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.'); + API_SHEET=null; + apiTake(); + return {days:Math.max(1,Math.min(3650,Math.floor(+days)||1)),start:S.day,cash:S.cash,inc:S.inc.map(i=>i.id),times:[],ran:0,stop:null};} +// One day of the run; false once it is over. +function apiAdvanceDay(a){ + if(a.ran>=a.days)return false; + if(S.lost){a.stop='bankrupt';return false;} + const t=performance.now(); + dayTick(); + a.times.push({day:S.day,ms:apiR1(performance.now()-t)});a.ran++; + if(apiModalOpen()&&!apiPlayerWin()){a.stop='a window opened';return false;} + return a.ranx+t.ms,0),out=apiSince({day:a.start,cash:a.cash,inc:a.inc},apiTake()); + if(a.stop!=='a window opened'){delete out.decision;delete out.screen;} + return {from:out.from,to:out.to,daysRun:a.ran,stoppedBecause:a.stop,cash:out.cash,cashChange:out.cashChange,newIncidents:out.newIncidents,log:out.log,toasts:out.toasts, + timing:{totalMs:apiR1(total),perDayMs:apiR1(total/(a.ran||1)),slowestDays:a.times.slice().sort((x,y)=>y.ms-x.ms).slice(0,5).map(x=>({date:dateStr(x.day),ms:x.ms}))}, + ...(out.decision?{decision:out.decision,screen:out.screen}:{})};} +function apiAdvance(days){const a=apiAdvanceStart(days);while(apiAdvanceDay(a));return apiAdvanceEnd(a);} +/* In the player's tab the days run where the player can watch them: a frame's worth of days, then the page draws. + A hidden tab draws nothing (and its timers are throttled), so there they run straight through. A day the route + worker is still routing finishes first. */ +const apiSleep=ms=>new Promise(r=>setTimeout(r,ms)); +async function apiAdvanceLive(days){ + const a=apiAdvanceStart(days);let t=performance.now(); + for(;;){ + while(RW.job)await apiSleep(20); + if(!apiAdvanceDay(a))break; + if(document.visibilityState!=='hidden'&&performance.now()-t>30){renderHUD();UI.panelsDue=true;await apiSleep(0);t=performance.now();}} + return apiAdvanceEnd(a);} + +// One day of a running clock in the MCP server's own page (the server keeps the time); the player's tab runs its own loop. +function apiTick(){if(!S||S.lost||pzOn()||!rule('clock'))return false;dayTick();renderAll();return true;} diff --git a/src/agent/75-mode.js b/src/agent/75-mode.js new file mode 100644 index 0000000..0924eb7 --- /dev/null +++ b/src/agent/75-mode.js @@ -0,0 +1,86 @@ +/* ================= AGENT MODE: the player's switch and clock ================= + In the player's own tab (the development page, served locally), the player can let an agent drive: the page dials + the agent relay (80-relay.js) and answers tool calls through TUBES.call. While it does, the clock is not the + player's (UI.clockLocked): either a fixed pace, one simulated day every 30 s to 5 min, that nobody can pause and + that holds while no tool is connected; or the agent's clock, which stands still until the agent asks for days. + The game itself knows none of this: it calls HOOKS (50-state.js), which this file fills in, and reads + UI.clockLocked. Settings of its own, in their own storage key, so the game's preferences stay as they are. */ +const API_AGENT_MS=[0,30000,60000,120000,300000],API_AGENT_KEY='sot-agent'; +const API_AGENT_PREFS=(()=>{let j={};try{j=JSON.parse(localStorage.getItem(API_AGENT_KEY)||'{}')||{};}catch(e){} + return {on:j.on===true,ms:API_AGENT_MS.includes(j.ms)?j.ms:60000};})(); +/* Only where a relay can be: plain http (an https page cannot open ws://) to an address, never a DNS name, which the + relay refuses (DNS rebinding). The public site is https and a name, so it never shows the switch. The test + harness's made-up origin opts in, and a test page loaded from the public address does not. */ +const apiAgentLocal=(p,h)=>p==='http:'&&(h==='localhost'||/\.localhost$/.test(h)||/^\[[0-9a-f:.]+\]$/i.test(h)||/^\d{1,3}(\.\d{1,3}){3}$/.test(h)); +const API_AGENT_OK=apiAgentLocal(location.protocol,location.hostname)||!!window.__TUBES_TEST__&&location.hostname==='tests.invalid'; +const apiAgentMs=()=>API_AGENT_PREFS.ms; +const apiMsLabel=ms=>ms>=60000?tr('settings.n_min',{n:Math.round(ms/60000)}):tr('settings.n_sec',{n:Math.round(ms/1000)}); +const apiAgentMsLabel=()=>apiAgentMs()>0?apiMsLabel(apiAgentMs()):tr('settings.agent_s_clock'); + +/* The speed a locked clock runs at: the pace while a tool is connected, else held (0); always 0 on the agent's clock, + where only advance moves days; and only in a game with a clock (the rule the pause buttons follow). */ +function apiAgentSpeed(){const r=API_RELAY;return r.on&&r.tools>0&&apiAgentMs()>0&&S&&rule('clock')?DAY_MS/apiAgentMs():0;} + +// k: 'on' (true/false) or 'ms' (one of API_AGENT_MS). Anything else is ignored, never coerced. +function apiAgentSet(k,v){ + if(k==='on')API_AGENT_PREFS.on=v===true||v==='1'||v===1; + else if(k==='ms'){if(!API_AGENT_MS.includes(+v))return;API_AGENT_PREFS.ms=+v;} + else return; + try{localStorage.setItem(API_AGENT_KEY,JSON.stringify(API_AGENT_PREFS));}catch(e){} + apiAgentSync();} + +/* Locks or frees the clock to match the switch, and keeps the speed where it belongs. Switching on leaves the save's + speed alone (save() does not overwrite it while the clock is locked), so switching off puts back the one the player + left the game at. Safe to run any number of times. */ +function apiAgentSync(){ + const on=!RW_IN&&API_AGENT_OK&&API_AGENT_PREFS.on; + if(on!==UI.clockLocked){ + if(on&&S&&[0,0.5,1,2,4,8].includes(UI.speed))S.uiSpeed=UI.speed; + UI.clockLocked=on; + if(!on)UI.speed=S&&[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:(UI.lastSpeed||1);} + if(on)UI.speed=apiAgentSpeed(); + apiRelaySync(); + apiTickerSync(); + renderHUD();renderTabbar();} + +/* What the game draws for a locked clock: the badge in the HUD in place of the speed buttons, and on phones the two + tab bar slots of play and speed, disabled, the second one reading the pace. */ +function apiAgentHud(){ + const p=$('spPace');if(!p)return; + p.hidden=!UI.clockLocked; + if(UI.clockLocked)p.textContent=apiAgentMs()>0?tr('settings.pace_t_per_day',{t:apiAgentMsLabel()}):apiAgentMsLabel();} +function apiAgentTabbar(){ + return ``+ + ``;} + +/* The Settings section. Its buttons are the agent's own (data-agent-set, answered below), not game actions, so no + tool can find them on a screen and switch the agent off, or on. */ +function apiAgentSettings(){ + if(!API_AGENT_OK)return ''; + const b=(v,l,on)=>``; + const line=(lab,btns,note)=>`
${lab}
${btns}

${note}

`; + return `

${tr('settings.agent_api')}

`+ + line(tr('settings.let_an_ai_agent_drive_this_game'),b('on:1',tr('common.on'),API_AGENT_PREFS.on)+b('on:0',tr('common.off'),!API_AGENT_PREFS.on),tr('settings.while_agent_mode_is_on_the'))+ + line(tr('settings.the_clock_while_an_agent_plays'),API_AGENT_MS.map(m=>b('ms:'+m,m?apiMsLabel(m):tr('settings.the_agent_moves_it'),apiAgentMs()===m)).join(''),tr('settings.a_pace_runs_one_simulated_day'));} +function apiAgentClick(e){ + const el=e.target&&e.target.closest&&e.target.closest('[data-agent-set]');if(!el||el.disabled)return; + const [k,v]=String(el.dataset.agentSet).split(':'); + apiAgentSet(k,k==='on'?v==='1':v);sfx('click');refreshSettings();} + +/* Who opened the window on screen: the player (a click, a key, a picker: window.event is the input being handled), or + the game itself (a day, a tool's call inside a relay message). A tool leaves the player's windows alone. */ +const API_MODAL={hand:false}; +const apiByHand=()=>{const e=window.event;return !!e&&/^(click|keydown|keyup|pointerup|touchend|change|input|submit)$/.test(e.type);}; + +// Wires agent mode into the page: the hooks, the badge and its style, the Settings buttons. Once, at load. +function apiAgentStart(){ + if(RW_IN)return; + Object.assign(HOOKS,{speed:apiAgentSpeed,hud:apiAgentHud,tabbar:apiAgentTabbar,settings:apiAgentSettings,modal:open=>{API_MODAL.hand=open&&apiByHand();}}); + const sp8=$('sp8'); + if(sp8&&!$('spPace')){const p=document.createElement('span');p.id='spPace';p.hidden=true;sp8.after(p);} + const st=document.createElement('style'); + st.textContent='.speed #spPace[hidden]{display:none}#spPace{border:2.5px solid var(--ink);background:var(--sun);border-radius:9px;height:32px;padding:0 8px;display:flex;align-items:center;font-family:var(--display);font-weight:800;font-size:12.5px;white-space:nowrap}'+ + '#tabbar button.pace .ic{font-size:13px;line-height:1.25}'; + document.head.appendChild(st); + document.addEventListener('click',apiAgentClick); + apiAgentSync();} diff --git a/src/agent/80-relay.js b/src/agent/80-relay.js new file mode 100644 index 0000000..b0cd1ff --- /dev/null +++ b/src/agent/80-relay.js @@ -0,0 +1,77 @@ +/* ================= AGENT RELAY: the in-page transport ================= + With agent mode on (75-mode.js), the page dials the agent relay (scripts/agent/relay.js, which npm run dev hosts on + its own port) and answers tool calls from connected tools (the MCP server, node scripts/mcp.js --browser) through + TUBES.call, so a human follows along on the real UI: toasts fire, panels render, the map moves. + + No endpoint to configure and no token: the relay rides the server that served the page, same port, path + API_RELAY_PATH, so the endpoint is where the page already is. The relay refuses a page from any other origin and a + Host that is a name, so no website can reach it through the player's browser; who else can reach it is the + operator's choice of bind address. No eval ever: a message is JSON with a tool name from TUBES.tools, a fixed list, + answered as the relay (ctx.relay): the player's game, clock, windows and settings stay theirs, and the dice stay + hidden. Nothing dials or polls while the switch is off. + + API_RELAY_HOST is a var because tests point it at their relay (under __TUBES_TEST__ nothing dials unless the test + opts in with __AGENT_RELAY_TEST__): a jsdom page is not loaded from the relay's server. */ +var API_RELAY_HOST=''; // tests: '127.0.0.1:'; live pages use their own host +const API_RELAY={ws:null,on:false,timer:null,tries:0,said:false,tools:0,host:null,queue:null}; +const API_RELAY_PATH='/agent'; +const apiRelayUrl=()=>`ws://${API_RELAY_HOST||location.host}${API_RELAY_PATH}`; + +/* The relay reports tool presence on every connect and disconnect: the clock holds while no tool is connected and + runs again the moment one arrives. A missing relay (dial failed, retry backoff) holds it too. */ +function apiRelayPresence(tools){ + API_RELAY.tools=tools|0; + if(!UI.clockLocked||!API_RELAY.on)return; + const run=apiAgentSpeed(); + if(run!==UI.speed){UI.speed=run;renderHUD();}} + +function apiRelaySync(){ + const want=!RW_IN&&UI.clockLocked&&(!window.__TUBES_TEST__||!!window.__AGENT_RELAY_TEST__); + // Nothing to do when the switch and the endpoint stand: tearing a healthy dial down for nothing drops the calls in + // flight and holds the clock for no reason. + if(API_RELAY_HOST===API_RELAY.host&&API_RELAY.on===want&&(want?!!(API_RELAY.ws||API_RELAY.timer):true))return; + clearTimeout(API_RELAY.timer);API_RELAY.timer=null;API_RELAY.tries=0; + if(API_RELAY.ws){const w=API_RELAY.ws;API_RELAY.ws=null;try{w.close();}catch(e){}} + API_RELAY.on=want;API_RELAY.host=API_RELAY_HOST; + apiRelayPresence(0); // off the relay: nobody driving, the clock holds + if(want)apiRelayDial();} + +// Dev reloads and relay restarts heal on their own, without a spinning reconnect. +function apiRelayRetry(){ + if(!API_RELAY.on)return; + const wait=Math.min(15000,500*Math.pow(2,Math.min(API_RELAY.tries++,5))); + API_RELAY.timer=setTimeout(()=>{API_RELAY.timer=null;apiRelayDial();},wait);} + +/* One call, answered in order: calls queue behind each other, so a move sent while days are still running waits for + them, as the tool sent it. A promise (days the player watches) is awaited; a throw is the tool's error. */ +function apiRelayAnswer(ws,m){ + const dayBefore=S?S.day:null,send=o=>{if(API_RELAY.ws===ws)ws.send(JSON.stringify({kind:'result',id:m.id,dayBefore,dayAfter:S?S.day:null,...o}));}; + const run=()=>Promise.resolve().then(()=>TUBES.call(m.tool,m.args||{},{relay:true})) + .then(value=>send({value}),er=>send({error:String(er&&er.message||er)})); + API_RELAY.queue=(API_RELAY.queue||Promise.resolve()).then(run);} + +function apiRelayDial(){ + if(!API_RELAY.on)return; + let ws; + try{ws=new WebSocket(apiRelayUrl());}catch(e){return apiRelayRetry();} + API_RELAY.ws=ws; + ws.onopen=()=>{ + if(API_RELAY.ws!==ws)return; + ws.send(JSON.stringify({kind:'auth',role:'page'})); + API_RELAY.tries=0; + if(!API_RELAY.said){API_RELAY.said=true;toast(tr('settings.agent_relay_connected'),'good');}}; + ws.onmessage=e=>{ + if(API_RELAY.ws!==ws)return; + let m;try{m=JSON.parse(e.data);}catch(_){return;} + if(!m||typeof m!=='object')return; + if(m.kind==='presence'){apiRelayPresence(m.tools);return;} + if(m.kind!=='call'||m.id===undefined)return; + // A call this page cannot make sense of is answered, never ignored: a silent drop would hang the tool that sent it. + if(typeof m.tool!=='string'||!TUBES.tools.includes(m.tool)){ws.send(JSON.stringify({kind:'result',id:m.id,error:`no tool "${m.tool}" here`}));return;} + apiRelayAnswer(ws,m);}; + // Replaced (4000): another tab took the relay, so this one yields instead of fighting it: redialing would just + // replace the new tab back, forever. Toggling agent mode dials again. + ws.onclose=e=>{if(API_RELAY.ws!==ws)return;API_RELAY.ws=null; + apiRelayPresence(0); // off the relay: the clock holds + if(e&&e.code===4000)API_RELAY.on=false;else apiRelayRetry();}; + ws.onerror=()=>{};} diff --git a/src/agent/85-ticker.js b/src/agent/85-ticker.js new file mode 100644 index 0000000..fca70e5 --- /dev/null +++ b/src/agent/85-ticker.js @@ -0,0 +1,24 @@ +/* ================= AGENT MODE: the clock where frames do not run ================= + A paced clock runs through the game's own loop (UI.speed is the pace, runClock() the days), but frames stop in a + hidden tab, and the frame runs no days behind an open window. Agent mode keeps time in both: a hidden tab is the + normal place for an agent to drive while the player does something else, and an agent that deliberates over a + window pays for it in days. This ticker covers exactly those moments, under the frame's other conditions, and + leaves every other moment to the frame. Hidden-tab timers are throttled (to 1 Hz, after five minutes to once a + minute in Chrome), so an unthrottled worker posts the ticks; a plain interval is the fallback without Worker. + The agent's clock (pace 0) needs no ticks: its days run when the agent asks. Never under __TUBES_TEST__: tests call + apiAgentTick() by hand. */ +const API_TICKER={on:false,worker:null,interval:null,last:0}; +// Days for the time since the last tick, if the frame is not running them now. +function apiAgentTick(now=performance.now()){ + const dt=API_TICKER.last?Math.max(0,Math.min(1000,now-API_TICKER.last)):0;API_TICKER.last=now; + const behind=document.visibilityState==='hidden'||!$('modal').hidden; + if(behind&&UI.clockLocked&&S&&!S.lost&&UI.speed&&!pzOn())runClock(dt);} +function apiTickerSync(){ + const want=UI.clockLocked&&apiAgentMs()>0&&!window.__TUBES_TEST__; + if(want===API_TICKER.on)return;API_TICKER.on=want;API_TICKER.last=0; + if(!want){if(API_TICKER.worker){try{API_TICKER.worker.terminate();}catch(e){}API_TICKER.worker=null;} + if(API_TICKER.interval){clearInterval(API_TICKER.interval);API_TICKER.interval=null;}return;} + try{const url=URL.createObjectURL(new Blob(['setInterval(()=>postMessage(0),250)'],{type:'text/javascript'})); + API_TICKER.worker=new Worker(url);URL.revokeObjectURL(url); + API_TICKER.worker.onmessage=()=>apiAgentTick();} + catch(e){API_TICKER.interval=setInterval(()=>apiAgentTick(),250);}} diff --git a/src/agent/90-facade.js b/src/agent/90-facade.js new file mode 100644 index 0000000..558d9b7 --- /dev/null +++ b/src/agent/90-facade.js @@ -0,0 +1,54 @@ +/* ================= AGENT API: the facade ================= + window.TUBES.call(tool, args) is the whole surface: one tool from API_TOOLS by name, with the MCP tool's own + arguments, answered as plain JSON (or a promise of it, for days that run where the player can watch). Nothing here + listens, polls or runs on the day loop: toast() is only listened to while a call runs. + ctx.relay: the call came over the relay into the player's tab (80-relay.js), where the player owns the game, its + clock and their windows, and the dice stay hidden. */ +let API_CTX={relay:false}; +const API_TOASTS={depth:0,list:[],real:null}; +function apiTake(){const t=API_TOASTS.list;API_TOASTS.list=[];return t;} +const apiToastLines=t=>t.map(x=>(x.kind?x.kind+': ':'')+x.text); +// toast() is a top-level function, so the game reaches it by its global name and this stands in for it. +function apiListen(on){ + if(on){if(API_TOASTS.depth++)return;const real=API_TOASTS.real=window.toast;API_TOASTS.list=[]; + window.toast=function(h,kind){API_TOASTS.list.push({kind:kind||'',text:apiText(String(h),600)});return real.apply(this,arguments);};} + else if(!--API_TOASTS.depth){window.toast=API_TOASTS.real;API_TOASTS.real=null;API_TOASTS.list=[];}} + +const API_TOOLS={ + status:()=>apiStatus(), + network:a=>apiNetwork(a.network), + city:a=>apiCity(a.city), + find:a=>apiFind(a.query,a.kind), + traceroute:a=>apiTrace(a.from,a.to), + peering_check:a=>apiPeering(a.network,a.city,a.via), + hot_spots:a=>apiHotSpots(a.limit||10), + schema:a=>apiSchema(a.section), + catalog:a=>apiCatalog(a.name), + state:a=>apiState(a.path), + results:a=>apiResults(a.path), + ui:()=>apiUi(), + actions:()=>apiActions(), + classes:()=>apiClasses(), + act:a=>{const name=a.action||a.command;if(!name)apiFail('Give action, e.g. {"action":"buildPop","args":{"city":"ams"}}.'); + return apiRun(name,a.args||{},{dryRun:!!a.dryRun});}, + screen:a=>apiScreen(a.where,a.offset), + panel:a=>apiPanel(a), + click:a=>apiClick(a.button,a.value), + open_link:a=>apiOpenLink(a.from,a.to), + advance:a=>API_CTX.relay?apiAdvanceLive(a.days):apiAdvance(a.days), + clock:()=>apiClock(), + since:a=>apiSince(a), +}; +function apiCall(tool,args,ctx){ + if(typeof tool!=='string'||!own(API_TOOLS,tool))apiFail(`No tool "${tool}".`); + if(!S&&!['schema','catalog','classes','actions','clock'].includes(tool))apiFail('No game is running.'); + const was=API_CTX;API_CTX={relay:!!(ctx&&ctx.relay)}; + apiListen(true); + let out; + try{out=API_TOOLS[tool](args&&typeof args==='object'&&!Array.isArray(args)?args:{});} + catch(e){apiListen(false);throw e;} + finally{API_CTX=was;} + if(out&&typeof out.then==='function')return out.finally(()=>apiListen(false)); + apiListen(false); + return out;} +window.TUBES={version:1,tools:Object.keys(API_TOOLS),call:apiCall}; diff --git a/src/agent/99-start.js b/src/agent/99-start.js new file mode 100644 index 0000000..7254460 --- /dev/null +++ b/src/agent/99-start.js @@ -0,0 +1,4 @@ +/* ================= AGENT API: start ================= + Last, once every file of the facade has loaded: agent mode wires itself in (75-mode.js). Everything before this only + defines tables and functions. */ +apiAgentStart(); diff --git a/src/game/00-core/10-language.js b/src/game/00-core/10-language.js new file mode 100644 index 0000000..affe784 --- /dev/null +++ b/src/game/00-core/10-language.js @@ -0,0 +1,18 @@ +/* ================= LANGUAGE ================= + Text is looked up by label: tr('pnis.delivery_2_to_6_weeks',vars) returns the player's language, or the + English from src/i18n/en.js (inlined above the game) when a translation is missing, and fills {placeholders}. + trn(label,n,vars) picks the "one" or "other" form of a plural. N_() marks a label kept in a table or a + save, translated where it is shown. A label that is not in any dictionary comes back as it is. */ +// English when the dictionary did not load (offline, or a copy without the i18n folder). +const LANGS=window.SOT_LANGS,LANG=window.I18N?.[window.SOT_LANG]?window.SOT_LANG:'en'; +document.documentElement.lang=LANG; +const EN=window.I18N.en,DICT=Object.assign(Object.create(null),EN,LANG!=='en'&&window.I18N[LANG]); +// Saves from before labels (1.34 and older) hold English text where newer ones hold a label: map it on first use. +let EN_TEXT=null; +function trKey(k){const o=DICT[k];if(o!==undefined)return o; + if(!EN_TEXT){EN_TEXT=new Map();for(const l in EN){const e=EN[l],t=DICT[l];if(typeof e==='string')EN_TEXT.set(e,t);else{EN_TEXT.set(e.one,t.one||e.one);EN_TEXT.set(e.other,t.other||e.other);}}} + return EN_TEXT.get(k)??k;} +const fillIn=(o,v)=>v?o.replace(/\{(\w+)\}/g,(m,k)=>k in v?v[k]:m):o; +function tr(k,v){const o=trKey(k);return fillIn(typeof o==='string'?o:o.other,v);} +function trn(k,n,v){const o=trKey(k);return fillIn(typeof o==='string'?o:n===1?o.one:o.other,{n,...v});} +function N_(s){return s;} diff --git a/src/game/00-core/20-analytics.js b/src/game/00-core/20-analytics.js new file mode 100644 index 0000000..0984ea9 --- /dev/null +++ b/src/game/00-core/20-analytics.js @@ -0,0 +1,28 @@ +/* ================= ANALYTICS (ridiculytics) ================= + Off unless ANALYTICS.host is set. Fill in your collector when you self-host the game. + Inside the claude.ai viewer outside requests are blocked, so it only reports from your own domain. */ +const APP_VERSION='__VERSION__'; +// Filled in by scripts/build.sh from CHANGELOG.md for this version. +const RELEASE_NOTES=/*__RELEASE_NOTES__*/[]; +// A big release's story, shown in full in "What's new" (paragraphs; **bold** allowed). Empty for most releases. +const RELEASE_STORY=/*__RELEASE_STORY__*/[]; +const IS_DEV=APP_VERSION.startsWith('__'); +// Multiplayer (docs/MULTIPLAYER.md): the path of a self-hosted copy's session server, stamped by MP_API=/api/mp npm run build. +// Empty, as in every plain build (and on seriesoftub.es), multiplayer stays off: no door, no requests. +const MP_API=/*__MP_API__*/''; +// Server-run play's build id (scripts/lib/page.js simId()), stamped next to MP_API; the session server refuses a page of another build. +const SIM_ID=/*__SIM_ID__*/''; +// Only report from the real site; previews, localhost and the Claude viewer stay silent. +const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'}; +(function(){ + try{ + window.ridiculytics=window.ridiculytics||function(){const q=window.ridiculytics.q=window.ridiculytics.q||[];if(q.length<100)q.push(arguments);}; + if(!ANALYTICS.host)return; + const sc=document.createElement('script');sc.defer=true;sc.src='https://cdn.jsdelivr.net/npm/ridiculytics@1.0.1/web/counter.min.js'; + sc.setAttribute('data-host',ANALYTICS.host);if(ANALYTICS.site)sc.setAttribute('data-site',ANALYTICS.site);sc.setAttribute('data-spa','false');sc.integrity='sha384-uNCU8e2RB7Yn6lVNut2gupQsJwKwXPZu2i4t/Eg6Q59ki0kchBR4L4yoS3ZxxjEX';sc.crossOrigin='anonymous';sc.referrerPolicy='no-referrer'; + document.head.appendChild(sc); + }catch(e){} +})(); +const TRACKED=new Set(); +function track(name,once){if(!ANALYTICS.host)return;if(once){if(TRACKED.has(name))return;TRACKED.add(name);}try{window.ridiculytics(name);}catch(e){}} +const PLAY_MARKS=[1,5,15,30,60,120]; diff --git a/src/game/10-catalog/10-economy.js b/src/game/10-catalog/10-economy.js new file mode 100644 index 0000000..465ff59 --- /dev/null +++ b/src/game/10-catalog/10-economy.js @@ -0,0 +1,68 @@ +/* ================= CONSTANTS ================= */ +const W=2000, H=1000, KM=14; +const POP_COST=20000, POP_MO=1500, EYE_RATE=150, CACHE_CAP=100, CACHE_MO=400, CACHE_BIG=400, CACHE_BIG_MO=1000; +const DAY_MS=2500, ROUTER_COST=15000, ROUTER_MO=1500, GEN_COST=12000, GEN_MO=600, DIVERSE=1.4; +const RU_BOX=40000, RU_BOX_MO=2000; +const UAE_LIC=15000,KSA_LIC=25000; +// Korea: "sender pays" interconnection makes transit into Seoul about four times the usual price. +const KR_TRANSIT=4; +/* Gangnam Style Peering (scenario rule `sender`) turns sender pays all the way up: every Gbps a carrier delivers into + Korea is billed again as a sender-pays fee, the incumbents take traffic only over a paid PNI, home gigabit is cheap, + and users notice every millisecond of a haul to Tokyo or Hong Kong. */ +const KR_FEE=180,KR_ARPU=0.85,KR_LAT_OK=8,KR_LAT_BAD=40; +/* Australia: a long way from everywhere. Every gigabit out of the country rides a long, thin subsea + cable, so transit and waves cost more than almost anywhere else. IX ports are the exception: a + nonprofit exchange sells 10G for about AUD 350 a month. Retail broadband is dear, but the national + wholesale network keeps roughly half of every home bill (about AUD 50 a month per home). */ +const AU_TRANSIT=3,AU_WAVE={land:1.8,sub:2.6,ew:1.3},AU_IX=0.8,AU_ARPU=1.8,AU_WHOLESALE=0.45; +// Fibre to the Basement: on your own fibre you skip the wholesale cut, but competing networks pay the +// Regional Broadband Scheme levy instead (about $7 a month on a ~$90 bill). +const AU_LEVY=0.08; +/* The Philippines: few, thin routes out and an incumbent that owns most of them. 100 GigE transit in Manila + costs about 1.9 times Jakarta's (TeleGeography, 2026: $2.25 against $1.21 per Mbps), so the islands pay + 1.9 times the Asian rate. Homes pay about ₱1,450 (US$25) a month, the incumbent's own figure (PLDT, 2025). + Between the islands capacity is dearer than out of the country: a Manila–Cebu wave costs about what + Manila–Singapore does, twice Manila–Hong Kong. */ +const PH_TRANSIT=4.7,PH_ARPU=0.7,PH_WAVE=3.7; +const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000; +const SITE2_N=[tr('economy.the_other_building'),tr('economy.campus_b_the_one_with_parking'),tr('economy.across_the_river_dc'),tr('common.the_annex'),tr('economy.suburban_mega_shed'),tr('economy.the_cheaper_one'),tr('economy.formerly_a_shopping_mall'),tr('common.bunker_two')]; +// A city's buildings: '#' becomes a site number from 1 to dcN (dc2N for the second building) that stays put for this network. +const siteNo=(name,n)=>name.replace('#',1+((S&&S.asn)|0)%(n||1)); +const siteName=(c,s)=>s==='b'?CITY[c].dc2?siteNo(CITY[c].dc2,CITY[c].dc2N):SITE2_N[hstr(c)%SITE2_N.length]:siteNo(CITY[c].dc,CITY[c].dcN); +const BE_TAPE=30000; +const popCost=c=>Math.round(POP_COST*colo(c))+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); +const CN_LIC=150000, CN_JV_MO=6000; +// Scrubbing centers come in tiers by clean bandwidth, and each brings its own dirty-side ingress of that size: when +// engaged it announces the target's prefix more specifically, so the flood comes to it instead of your ports (a +// magnet) and it cleans up to its tier (a sponge). Always-on is engaged from the first minute; on-demand is cheaper +// and pulls half the flood on the first day while the diversion starts. A clean-pipe add-on scrubs upstream, per port. +const SCRUB_TIERS=[{n:'100G',g:100,cost:60000,mo:5000,lvl:1},{n:'1T',g:1000,cost:180000,mo:15000,lvl:3},{n:'10T',g:10000,cost:500000,mo:40000,lvl:4},{n:'100T',g:100000,cost:1500000,mo:110000,lvl:10}]; +const SLA_PEN=20000; +const scrubMo1=x=>Math.round(SCRUB_TIERS[x.tier||0].mo*(S.scrubMode==='ondemand'?0.6:1)),scrubMo=()=>S.scrubs.reduce((a,x)=>a+scrubMo1(x),0); +const hasScrub=()=>!!(S&&S.scrubs&&S.scrubs.length),SCRUB_FAR_MS=30; +const cleanMo=t=>Math.round(PORT[t.tier].g*(t.n||1)*5); +/* DDoS (see docs: sizes come from the world, a flood enters on every port it can reach, each tool acts where it does in + real networks). A vector's `fs` is whether Flowspec has a signature for it: the known volumetric floods, not ACK or + application floods. Flowspec lives in each router's TCAM: RG[].fsN is how many rules one POP's routers hold; a live + attack takes one per vector on every router it enters, four for a carpet bomb spread over a whole prefix. */ +const FS_DROP=0.95,FS_CARPET=4; +// Upstream blackholing (RTBH): what still arrives on a port after the victim /32 is tagged. Transit honours it, an IX +// route server mostly does, a private peer about half the time (by network). +const RTBH_LEFT={t:0,ix:0.3}; +const DDOS_VEC={ + dns:{n:tr('common.dns_reflection'),fs:true}, + ntp:{n:tr('common.ntp_amplification'),fs:true}, + memcached:{n:tr('common.memcached_amplification'),fs:true}, + ack:{n:tr('common.ack_flood'),fs:false}, + cldap:{n:tr('common.cldap_flood'),fs:true}, + syn:{n:tr('common.syn_flood'),fs:true}, + http:{n:tr('common.http_flood'),fs:false}, + racknet:{n:tr('common.racknet'),fs:false,gaming:true}, + teamspooked:{n:tr('common.teamspooked'),fs:false,gaming:true}, +}; +const MYIX_COST=80000, MYIX_MO=3000, MYIX_FEE=1500, START_CASH=200000; +// Your own exchange's switching fabric. Bigger fabrics carry more and attract more members. +const MYIX_FAB=[{n:'400G',g:400,cost:0,mo:3000,max:12},{n:'1.6T',g:1600,cost:60000,mo:6000,max:20,lvl:2},{n:'6.4T',g:6400,cost:200000,mo:12000,max:30,lvl:3},{n:'25.6T',g:25600,cost:600000,mo:25000,max:45,lvl:4},{n:'102.4T',g:102400,cost:1800000,mo:60000,max:60,lvl:9}]; +const myFab=c=>MYIX_FAB[Math.min(MYIX_FAB.length-1,Math.max(0,(S.myIx[c]&&S.myIx[c].fab)|0))]; +const LT=[{n:'10G',g:10,m:1},{n:'100G',g:100,m:2.8},{n:'400G',g:400,m:6},{n:'800G',g:800,m:9},{n:'1.6T',g:1600,m:13},{n:'6.4T',g:6400,m:28,car:1600,note:tr('economy.handed_off_as_4_1_6t')},{n:'12.8T',g:12800,m:45,car:3200,note:tr('economy.handed_off_as_4_3_2t')}]; +const PORT=[{n:'10G',g:10,setup:500,tmo:150,ix:400,pni:200},{n:'100G',g:100,setup:1500,tmo:400,ix:1500,pni:350},{n:'400G',g:400,setup:4000,tmo:900,ix:4000,pni:600},{n:'800G',g:800,setup:8000,tmo:1600,ix:7000,pni:1000},{n:'1.6T',g:1600,setup:16000,tmo:2800,ix:12000,pni:1600},{n:'3.2T',g:3200,setup:32000,tmo:5000,ix:20000,pni:2600}]; diff --git a/src/game/10-catalog/20-routers.js b/src/game/10-catalog/20-routers.js new file mode 100644 index 0000000..1ce9685 --- /dev/null +++ b/src/game/10-catalog/20-routers.js @@ -0,0 +1,31 @@ +/* Router models, by index: saves keep a POP's model as its index, so new models go at the end. bb is the highest + core each one can run (cr, CORE_LV: 0 plain IGP, 1 LDP, 2 RSVP-TE, 3 SR-MPLS, 4 SRv6) and it runs every one below + that too, except noMpls (SRv6 natively, no label stack). v is the vendor: mixing vendors is where interop fails. */ +const RG=[ + {n:'Rusty Router 9000',cr:0,v:'rusty',pn:'100G',cap:400,cost:0,mo:0,maxLT:1,maxP:1,ports:8,cls:0,lvl:1,boot:6,slowP:10,fs:0,fsN:0,chip:tr('routers.a_mystery_asic'),blurb:tr('routers.bought_used_on_ebuy_the_fans')}, + {n:'Edge Lord 400',cr:0,v:'edge',pn:'400G',cap:3200,cost:30000,mo:1000,maxLT:2,maxP:2,ports:24,cls:1,lvl:2,boot:11,slowP:20,fs:1,fsN:4,chip:tr('common.merchant_silicon'),blurb:tr('routers.sharp_edgy_and_finally_speaks_400g')}, + {n:'Chonk 800',cr:2,v:'junipurr',pn:'800G',cap:12800,cost:90000,mo:3000,maxLT:3,maxP:3,ports:36,cls:2,lvl:3,boot:25,slowP:45,fs:2,fsN:12,chip:'Junipurr PacketOinker™',blurb:tr('routers.an_absolute_unit_with_800g_ports')}, + {n:'Absolute Unit 1.6T',cr:3,v:'junipurr',pn:'1.6T',cap:51200,cost:250000,mo:8000,maxLT:5,maxP:4,ports:40,cls:3,lvl:4,boot:40,slowP:60,fs:2,fsN:16,chip:tr('routers.packetoinker2_two_pigs_one_chassis'),blurb:tr('routers.1_6t_ports_its_own_weather')}, + {n:'Mikrowtik CCR',cr:1,v:'mikrowtik',pn:'100G',cap:300,cost:4000,mo:150,maxLT:1,maxP:1,ports:16,cls:0,lvl:1,boot:2,slowP:5,badge:'M',fs:1,fsN:2,chip:tr('routers.a_few_dozen_arm_cores'),blurb:tr('routers.costs_less_than_lunch_and_has')}, + {n:'Sonic the Whitebox 32',cr:0,v:'whitebox',pn:'400G',cap:3200,cost:14000,mo:400,maxLT:2,maxP:2,ports:32,cls:1,lvl:2,boot:9,slowP:25,flaky:true,badge:'W',fs:1,fsN:4,chip:tr('routers.tomahack_merchant_silicon'),blurb:tr('routers.a_bare_metal_switch_running_open')}, + {n:'Arrrhipster 7280R',cr:3,v:'arrrhipster',pn:'400G',cap:4800,cost:42000,mo:1300,maxLT:2,maxP:2,ports:48,cls:1,lvl:2,boot:3,slowP:2,badge:'A',fs:2,fsN:8,chip:tr('routers.jerry_cho_deep_buffer_silicon'),blurb:tr('routers.fixed_config_deep_buffers_a_well')}, + {n:'Arrrhipster 7800R',cr:3,v:'arrrhipster',pn:'800G',cap:16000,cost:130000,mo:4200,maxLT:3,maxP:3,ports:96,cls:2,lvl:3,boot:7,slowP:4,badge:'A',fs:2,fsN:12,chip:tr('routers.jerry_cho3_deep_buffer_silicon'),blurb:tr('routers.the_modular_one_ninety_six_800g')}, + {n:'Disco 8K',cr:4,v:'disco',pn:'800G',cap:12800,cost:80000,mo:4800,maxLT:3,maxP:3,ports:64,cls:2,lvl:3,boot:20,slowP:35,badge:'D',fs:2,fsN:12,chip:'Silly-con One',blurb:tr('routers.cheap_to_buy_expensive_to_own')}, + {n:'Knockia 7750',cr:4,v:'knockia',pn:'1.6T',cap:40000,cost:200000,mo:7000,maxLT:5,maxP:4,ports:56,cls:3,lvl:4,boot:30,slowP:15,badge:'K',fs:2,fsN:16,chip:tr('routers.fin_p_network_processor'),blurb:tr('routers.finnish_engineering_indestructible')}, + {n:'Sonic the Whitebox 64',cr:4,v:'whitebox',noMpls:true,pn:'1.6T',cap:25600,cost:60000,mo:1500,maxLT:5,maxP:4,ports:64,cls:3,lvl:5,boot:9,slowP:25,flaky:true,badge:'W',fs:1,fsN:8,chip:tr('routers.tomahack_5_merchant_silicon'),blurb:tr('routers.sixty_four_1_6t_ports_on')}, + {n:'Disco 8K Ultra',cr:4,v:'disco',pn:'1.6T',cap:51200,cost:140000,mo:11000,maxLT:5,maxP:4,ports:72,cls:3,lvl:6,boot:22,slowP:35,badge:'D',fs:2,fsN:16,chip:'Silly-con One G3',blurb:tr('routers.cheap_chassis_eternal_subscription')}, + {n:'Absolute Unit 3.2T',cr:4,v:'junipurr',pn:'3.2T',cap:204800,cost:600000,mo:18000,maxLT:6,maxP:5,ports:48,cls:4,lvl:7,boot:50,slowP:60,fs:2,fsN:24,chip:tr('routers.packetoinker3_a_whole_litter'),blurb:tr('routers.3_2t_ports_and_12_8t')}, + {n:'Arrrhipster 7800R5',cr:3,v:'arrrhipster',pn:'3.2T',cap:160000,cost:450000,mo:14000,maxLT:6,maxP:5,ports:144,cls:4,lvl:9,boot:8,slowP:4,badge:'A',fs:2,fsN:24,chip:tr('routers.jerry_cho5_deep_buffer_silicon'),blurb:tr('routers.a_hundred_and_forty_four_3')}, + {n:'Knockia 7950 XRS',cr:4,v:'knockia',pn:'3.2T',cap:180000,cost:520000,mo:15000,maxLT:6,maxP:5,ports:96,cls:4,lvl:10,boot:32,slowP:15,badge:'K',fs:2,fsN:24,chip:tr('routers.fin_p6_network_processor'),blurb:tr('routers.built_like_a_sauna_door_heavy')}, + {n:'Mikrowtik CCR 3.2T',cr:1,v:'mikrowtik',pn:'3.2T',cap:51200,cost:45000,mo:900,maxLT:6,maxP:5,ports:32,cls:4,lvl:11,boot:3,slowP:5,flaky:true,badge:'M',fs:1,fsN:4,chip:tr('routers.several_hundred_arm_cores_and_a'),blurb:tr('routers.a_3_2t_router_for_the')}, + {n:'The Router at the End of the Universe',cr:4,v:'universe',pn:'3.2T',cap:819200,cost:3000000,mo:60000,maxLT:6,maxP:5,ports:256,cls:4,lvl:13,boot:42,slowP:42,badge:'U',fs:2,fsN:42,chip:tr('routers.forty_two_of_them'),blurb:tr('routers.two_hundred_and_fifty_six_3')}, + {n:'Brocadabra MLX-16',cr:2,v:'brocadabra',pn:'400G',cap:4000,cost:26000,mo:900,maxLT:2,maxP:2,ports:32,cls:1,lvl:2,boot:14,slowP:20,flaky:true,badge:'B',fs:1,fsN:4,noPz:true,chip:tr('routers.a_refurbished_network_processor'),blurb:tr('routers.pulls_rsvp_tunnels_out_of_a')}, + {n:'Extremely Networks SLX 9740',cr:2,v:'extremely',pn:'1.6T',cap:36000,cost:170000,mo:5500,maxLT:5,maxP:4,ports:48,cls:3,lvl:4,boot:18,slowP:15,badge:'X',fs:2,fsN:12,noPz:true,chip:tr('routers.tridont_merchant_silicon'),blurb:tr('routers.bought_the_magician_s_hat')} +]; +// The biggest model, which is no longer simply the last one. +const RG_TOP=RG.reduce((b,r,i)=>r.cap>RG[b].cap?i:b,0); +/* Some routers take forever to boot. Each POP's chassis has a personality per model: most come + back in minutes, a few sit through every line card self-test known to the vendor. */ +const SLOW_BOOT=[tr('routers.is_oinking_through_the_self_test'),tr('routers.is_running_fsck_on_a_compact'),tr('routers.found_a_newer_firmware_on_the'),tr('routers.is_counting_to_2_million_routes'),tr('routers.is_waiting_for_the_line_cards'),tr('routers.booted_panicked_about_a_missing_fan'),tr('routers.is_synchronising_the_routing_engines')]; +function slowBoot(c){const p=S.pops[c];if(!p)return false;const g=p.rgen||0;return hstr(c+'|boot|'+g+'|'+S.asn)%100{ +const O='#1E2640',W=4; +const st=(f,w=W)=>`fill="${f}" stroke="${O}" stroke-width="${w}" stroke-linejoin="round" stroke-linecap="round"`; +const P=(d,f='none',w=W)=>``; +const R=(x,y,w,h,f,r=10,sw=W)=>``; +const C=(x,y,r,f,sw=W)=>``; +const E=(x,y,rx,ry,f,sw=W,rot=0)=>``; +const T=(x,y,t,s=10,f=O)=>`${t}`; +const sh=(w=70,x=100,y=146)=>``; +const bob=s=>`${s}`; +const ports=(x,y,w,n,c='#7FD8EE')=>{let s=R(x,y,w,16,O,4,2);const g=(w-8)/n;for(let i=0;i`;return s;}; +const leds=(x,y,cs,r=4)=>cs.map((c,i)=>C(x+i*(r*3),y,r,c,2)).join(''); +// faces: eyes at (x,y), d apart from the middle +const glint=(x,y)=>``; +const EY={ + happy:(x,y,d=14)=>P(`M${x-d-6} ${y} q6 -8 12 0 M${x+d-6} ${y} q6 -8 12 0`), + sleepy:(x,y,d=14)=>P(`M${x-d-6} ${y} q6 6 12 0 M${x+d-6} ${y} q6 6 12 0`), + dots:(x,y,d=14)=>``, + angry:(x,y,d=14)=>P(`M${x-d-9} ${y-8} L${x-d+7} ${y-3} M${x+d+9} ${y-8} L${x+d-7} ${y-3}`,'none',5)+``, + shades:(x,y,d=14)=>``+P(`M${x-d+11} ${y-3} H${x+d-11}`,'none',3)+glint(x-d,y)+glint(x+d,y), + sad:(x,y,d=14)=>EY.dots(x,y+2,d)+P(`M${x-d-7} ${y-9} L${x-d+5} ${y-6} M${x+d+7} ${y-9} L${x+d-5} ${y-6}`,'none',3), + dizzy:(x,y,d=14)=>P(`M${x-d-5} ${y-5} l10 10 m0 -10 l-10 10 M${x+d-5} ${y-5} l10 10 m0 -10 l-10 10`,'none',3.5), + worried:(x,y,d=14)=>EY.dots(x,y,d)+P(`M${x-d-6} ${y-10} L${x-d+6} ${y-12} M${x+d+6} ${y-10} L${x+d-6} ${y-12}`,'none',3), +}; +EY.wink=(x,y,d=14)=>``+P(`M${x+d-6} ${y} q6 -8 12 0`); +const MO={ + smile:(x,y,w=9)=>P(`M${x-w} ${y} q${w} ${w*.8} ${2*w} 0`), + grin:(x,y,w=10)=>P(`M${x-w} ${y} q${w} ${w*1.2} ${2*w} 0z`,'#7A2633',3), + flat:(x,y,w=8)=>P(`M${x-w} ${y} h${2*w}`), + frown:(x,y,w=8)=>P(`M${x-w} ${y+4} q${w} ${-w*.8} ${2*w} 0`), + o:(x,y)=>E(x,y+2,4,5,'#7A2633',3), + smirk:(x,y,w=9)=>P(`M${x-w} ${y+1} q${w*1.2} ${w*.5} ${2*w} -4`), + w:(x,y)=>P(`M${x-8} ${y} q4 5 8 0 q4 5 8 0`), + teeth:(x,y,w=12)=>R(x-w,y-4,2*w,9,'#fff',3,3)+P(`M${x-w/3} ${y-4} v9 M${x+w/3} ${y-4} v9`,'none',2), +}; +const face=(x,y,e,m,d=14,my=14)=>EY[e](x,y,d)+(m?MO[m](x,y+my):''); +const cheeks=(x,y,d=26)=>``; +// props +const antenna=(x,y,dx,dy,tip='#FFD23F')=>P(`M${x} ${y} l${dx} ${dy}`)+C(x+dx,y+dy,5,tip,3); +const bent=(x,y)=>P(`M${x} ${y} q4 -14 18 -22 q6 4 2 10`); +const tapeX=(x,y,w,h)=>P(`M${x} ${y} L${x+w} ${y+h} M${x+w} ${y} L${x} ${y+h}`,'none',13).replace(`stroke="${O}"`,'stroke="#C9D1E6"')+P(`M${x} ${y} L${x+w} ${y+h} M${x+w} ${y} L${x} ${y+h}`,'none',2).replace('stroke-linecap','stroke-dasharray="2 5" stroke-linecap'); +const cobweb=(x,y)=>P(`M${x} ${y} q10 -10 20 0 M${x+6} ${y} q4 -6 8 0 M${x+10} ${y} v-9`,'none',1.5); +const sticker=(x,y,w,h,t,f='#fff',s=8)=>P(`M${x} ${y} h${w} l3 ${h} h${-w}z`,f,2.5)+T(x+w/2+1.5,y+h/2+3,t,s); +const spots=(a)=>a.map(([x,y,s])=>P(`M${x} ${y} q${s} ${-s*.6} ${s*1.8} ${s*.2} q${-s*.2} ${s} ${-s*1.2} ${s*.8}z`,'#9A5226',3)).join(''); +const flames=(x,y,s=1)=>P(`M${x} ${y} q${-14*s} ${-6*s} ${-6*s} ${-24*s} q${4*s} ${8*s} ${10*s} ${8*s} q${-2*s} ${-12*s} ${8*s} ${-20*s} q${2*s} ${14*s} ${10*s} ${16*s} q${2*s} ${-6*s} ${-2*s} ${-12*s} q${14*s} ${8*s} ${8*s} ${32*s}z`,'#FF8A3D',3)+P(`M${x+2*s} ${y-2*s} q${-6*s} ${-4*s} ${-1*s} ${-12*s} q${4*s} ${6*s} ${8*s} ${4*s} q${2*s} ${6*s} ${-1*s} ${8*s}z`,'#FFD23F',2); +const feet=(xs,y,f)=>xs.map(x=>P(`M${x-8} ${y} q-2 10 8 10 h6 q8 0 4 -10`,f)).join(''); +const legs=(xs,y,f='#1E2640',h=12)=>xs.map(x=>P(`M${x} ${y} v${h} h8`,'none',5)).join(''); +const cloud=(x,y,s=1,f='#fff')=>P(`M${x-22*s} ${y} q-8 -14 8 -14 q4 -12 18 -6 q12 -8 18 6 q14 0 8 14z`,f,3); +const rain=(x,y)=>P(`M${x-14} ${y+6} l-3 8 M${x} ${y+6} l-3 8 M${x+14} ${y+6} l-3 8`,'none',3).replace(`stroke="${O}"`,'stroke="#2F8CFF"'); +const sun=(x,y,r=10)=>C(x,y,r,'#FFD23F',3)+P(`M${x} ${y-r-4} v-6 M${x} ${y+r+4} v6 M${x-r-4} ${y} h-6 M${x+r+4} ${y} h6 M${x-r} ${y-r} l-4 -4 M${x+r} ${y+r} l4 4 M${x+r} ${y-r} l4 -4 M${x-r} ${y+r} l-4 4`,'none',3); +const bolt=(x,y,s=1,f='#FFD23F')=>P(`M${x} ${y} l${-10*s} ${18*s} h${8*s} l${-6*s} ${18*s} l${18*s} ${-24*s} h${-9*s} l${7*s} ${-12*s}z`,f,3); +const smoke=(x,y)=>C(x,y,6,'#C9D1E6',2.5)+C(x+8,y-10,8,'#C9D1E6',2.5)+C(x+2,y-24,10,'#E8EDF7',2.5); +const steam=(x,y)=>P(`M${x} ${y} q-6 -8 0 -16 q6 -8 0 -16 M${x+12} ${y} q-6 -8 0 -16 q6 -8 0 -16`,'none',3).replace(`stroke="${O}"`,'stroke="#fff"').replace('stroke-width="3"','stroke-width="4"'); +const speed=(x,y)=>P(`M${x} ${y} h-26 M${x-6} ${y+14} h-30 M${x} ${y+28} h-22`,'none',4).replace(`stroke="${O}"`,'stroke="#fff"'); +const tag=(x,y,l1,l2)=>P(`M${x-24} ${y-20} q-12 2 -12 14`,'none',2.5)+R(x-12,y-6,30,26,'#FFD23F',4,3)+T(x+3,y+5,l1,8)+(l2?T(x+3,y+15,l2,8):''); +const disco=(x,y,r=16)=>P(`M${x} ${y-r-12} v12`)+C(x,y,r,'#C9D1E6')+P(`M${x-r+2} ${y-6} h${2*r-4} M${x-r} ${y+2} h${2*r} M${x-r+3} ${y+9} h${2*r-6} M${x} ${y-r} v${2*r} M${x-9} ${y-r+3} q-4 ${r-3} 0 ${2*r-6} M${x+9} ${y-r+3} q4 ${r-3} 0 ${2*r-6}`,'none',2); +const beams=(x,y)=>``; +const coinslot=(x,y)=>R(x,y,24,10,'#FFD23F',3,3)+R(x+6,y+3,12,3,O,1,1); +const coins=(x,y,n)=>Array.from({length:n},(_,i)=>E(x,y-i*6,12,5,'#FFD23F',3)).join(''); +const eyepatch=(x,y)=>C(x,y,8,O,2)+P(`M${x-24} ${y-16} L${x+30} ${y+6}`,'none',2.5); +const beanie=(x,y,w,f='#FF8A3D')=>P(`M${x-w/2} ${y} q0 ${-w*.5} ${w/2} ${-w*.5} q${w/2} 0 ${w/2} ${w*.5}z`,f)+R(x-w/2-3,y-6,w+6,12,f,5,3)+C(x,y-w*.5-5,6,f,3); +const beard=(x,y,w=30,f='#8A4B22')=>P(`M${x-w/2} ${y} q${w/2} ${w*.9} ${w} 0 q-6 6 ${-w/2} 6 q${-w/2+6} 0 ${-w/2} -6z`,f,3); +const capHat=(x,y,w=70)=>P(`M${x-w/2} ${y} q${w/2} -40 ${w} 0 q${-w/2} 12 ${-w} 0z`,'#1E2640',3)+C(x,y-14,5,'#FFD23F',2)+P(`M${x-5} ${y-14} l10 0`,'none',2).replace(`stroke="${O}"`,'stroke="#FFF"'); +const bandana=(x,y,w)=>P(`M${x-w/2} ${y} q${w/2} -26 ${w} 0z`,'#FF4D5E',3)+P(`M${x+w/2} ${y-2} l14 4 l-6 8z`,'#FF4D5E',3)+``; +const parrot=(x,y)=>E(x,y,10,14,'#22C47A',3)+C(x+2,y-14,8,'#22C47A',3)+P(`M${x+9} ${y-15} q8 2 2 8z`,'#FFD23F',2.5)+``+P(`M${x-6} ${y+10} l-8 10 M${x+2} ${y+12} l2 8`,'none',3).replace(`stroke="${O}"`,'stroke="#FF4D5E"'); +const chest=(x,y)=>R(x,y,40,26,'#C9B27C',4,3)+P(`M${x} ${y} q20 -18 40 0`,'#C9B27C',3)+R(x+16,y-2,8,8,'#FFD23F',2,2)+coins(x+20,y-12,1); +const mast=(x,y,h=70)=>P(`M${x} ${y} v${-h}`)+P(`M${x} ${y-h+4} l34 10 l-34 14z`,'#1E2640',3)+C(x+14,y-h+15,4,'#fff',1.5); +const wheel=(x,y,r=16)=>C(x,y,r,'#C9B27C',3)+C(x,y,5,'#FFD23F',2.5)+P(`M${x-r-6} ${y} h${2*r+12} M${x} ${y-r-6} v${2*r+12} M${x-r} ${y-r} l${2*r} ${2*r} M${x+r} ${y-r} l${-2*r} ${2*r}`,'none',3); +const anchor=(x,y)=>P(`M${x} ${y} v26 M${x-12} ${y+18} q12 16 24 0 M${x-6} ${y+6} h12`,'none',4)+C(x,y-4,4,'#fff',3); +const rivets=(x,y,w,h)=>[[x+8,y+8],[x+w-8,y+8],[x+8,y+h-8],[x+w-8,y+h-8]].map(([a,b])=>C(a,b,3,'#E8EDF7',2)).join(''); +const pine=(x,y,w,h)=>{let s='';for(let i=1;i<6;i++)s+=P(`M${x+i*w/6} ${y+4} v${h-8}`,'none',2);return s;}; +const thermo=(x,y,f='#FF4D5E')=>R(x-4,y-26,8,30,'#fff',4,2.5)+C(x,y+6,7,f,2.5)+``; +const stars=(pts)=>pts.map(([x,y,r])=>``).join(''); +const planet=(x,y,r,f,ring)=>C(x,y,r,f,3)+(ring?E(x,y,r+8,4,'none',3,-20):''); +const towel=(x,y)=>P(`M${x} ${y} q22 -6 20 26 l-8 36 q-4 -28 -12 -40z`,'#FFD23F',3)+P(`M${x+8} ${y+6} l6 40 M${x+16} ${y+10} l2 20`,'none',3).replace(`stroke="${O}"`,'stroke="#FF4F9A"'); +const screen=(x,y,w,h,t,s=20)=>R(x,y,w,h,'#0B0F1C',4,3).replace(`stroke="${O}"`,'stroke="#7FD8EE"')+T(x+w/2,y+h/2+s*.35,t,s,'#7FD8EE'); +const bricks=(x,y,n)=>Array.from({length:n},(_,i)=>R(x+i*36,y,34,16,'#E07A5F',2,3)).join(''); +const bandaid=(x,y,rot=-30)=>`${R(x-14,y-5,28,10,'#F4CFA0',4,2.5)}`; +const knob=(x,y)=>C(x,y,8,'#C9B27C',3)+P(`M${x} ${y} l4 -5`,'none',3); +const mustache=(x,y)=>P(`M${x} ${y} q-8 -6 -18 2 q8 2 18 -2 q8 -6 18 2 q-8 2 -18 -2z`,'#8A4B22',2.5); +const hood=(x,y,w,h)=>P(`M${x} ${y+h} V${y+24} q0 -30 ${w/2} -30 q${w/2} 0 ${w/2} 30 V${y+h}`,'#3A4266'); +const katana=(x1,y1,x2,y2)=>P(`M${x1} ${y1} L${x2} ${y2}`,'none',7).replace(`stroke="${O}"`,'stroke="#C9D1E6"')+P(`M${x1} ${y1} L${x2} ${y2}`,'none',2)+P(`M${x2} ${y2} l10 -10`,'none',6).replace(`stroke="${O}"`,'stroke="#7A2633"'); +const ears=(x,y,d,f)=>P(`M${x-d-14} ${y} l8 -22 l16 16z M${x+d+14} ${y} l-8 -22 l-16 16z`,f); +const tail=(x,y,f)=>P(`M${x} ${y} q30 -6 22 -34 q-2 -8 -8 -4`,'none',9).replace(`stroke="${O}"`,`stroke="${O}"`)+P(`M${x} ${y} q30 -6 22 -34 q-2 -8 -8 -4`,'none',5).replace(`stroke="${O}"`,`stroke="${f}"`); +const sweat=(x,y)=>P(`M${x} ${y} q-6 8 0 10 q6 -2 0 -10z`,'#7FD8EE',2.5); +const arm=(x,y,s)=>P(`M${x} ${y} q${s*22} 4 ${s*26} -18 q${s*-2} -10 ${s*-12} -6`,'none',10)+P(`M${x} ${y} q${s*22} 4 ${s*26} -18 q${s*-2} -10 ${s*-12} -6`,'none',6).replace(`stroke="${O}"`,'stroke="#FF8FBE"')+C(x+s*22,y-8,7,'#FF8FBE',3); +const dumbbell=(y)=>P(`M30 ${y} H170`,'none',5)+R(18,y-14,12,28,'#5D6788',3,3)+R(170,y-14,12,28,'#5D6788',3,3)+R(8,y-10,10,20,'#5D6788',3,3)+R(182,y-10,10,20,'#5D6788',3,3); +const headband=(x,y,w)=>R(x,y,w,10,'#FF4D5E',3,3); +const notes=(x,y)=>P(`M${x} ${y} v-14 l10 -3 v14`,'none',3)+C(x-3,y,3.5,O,0)+C(x+7,y-3,3.5,O,0); +const tiles=(y)=>{const cs=['#FF4F9A','#FFD23F','#22C47A','#7FD8EE','#7B61FF'];let s='';for(let i=0;i<8;i++)s+=P(`M${20+i*20} ${y} h20 l-4 14 h-20z`,cs[i%5],2.5);return s;}; +const headphones=(x,y,w)=>P(`M${x-w/2} ${y} q0 ${-w*.55} ${w/2} ${-w*.55} q${w/2} 0 ${w/2} ${w*.55}`,'none',5)+R(x-w/2-8,y-6,12,18,'#FF4F9A',4,3)+R(x+w/2-4,y-6,12,18,'#FF4F9A',4,3); +const afro=(x,y,w)=>{let s='';for(let i=0;i<7;i++){const a=Math.PI*(i/6),r=w/2;s+=C(x-Math.cos(a)*r*.9,y-Math.sin(a)*r*.6,14,'#3A2A20',3);}return s+E(x,y-10,w/2,18,'#3A2A20',0);}; +const bells=(xs,y)=>xs.map(x=>P(`M${x-5} ${y} l-6 18 h18 l-6 -18z`,'#FF8A3D',3)).join(''); +const hammer=(x,y)=>P(`M${x} ${y} l26 -8`,'none',6).replace(`stroke="${O}"`,'stroke="#C9B27C"')+P(`M${x} ${y} l26 -8`,'none',2)+R(x+32,y-30,12,22,'#9AA3BE',2,3)+P(`M${x+30} ${y-6} l4 -4 M${x+28} ${y-12} l4 2`,'none',2); +const anvil=(x,y)=>P(`M${x-24} ${y} h48 l-6 8 h-10 l4 12 h-24 l4 -12 h-10z M${x-24} ${y} q-14 0 -16 -6 h16z`,'#5D6788',3); +const dizzyStars=(x,y)=>stars([[x-12,y,3],[x,y-6,3.5],[x+12,y,3]])+P(`M${x-18} ${y+4} q18 -14 36 0`,'none',2); +const icicles=(x,y,w)=>{let s='';for(let i=0;i<5;i++)s+=P(`M${x+i*w/5+4} ${y} l4 ${10+(i%2)*6} l4 ${-10-(i%2)*6}`,'#E8F6FF',2);return s;}; +const snowcap=(x,y,w)=>P(`M${x-4} ${y+4} q${w/4} -14 ${w/2} -4 q${w/4} -12 ${w/2+8} 4 q-6 8 -14 2 q-10 8 -20 0 q-12 8 -24 0 q-10 8 ${-w/2+22} -2z`,'#fff',3); +const racing=(x,y,w)=>``; +const roundel=(x,y,t)=>C(x,y,15,'#fff',3)+T(x,y+6,t,16); +const fire=(x,y)=>flames(x,y,.55); +const extinguisher=(x,y)=>R(x,y,14,34,'#FF4D5E',6,3)+P(`M${x+4} ${y} v-6 h10 l6 6`,'none',3)+P(`M${x-2} ${y+12} h18`,'none',6).replace(`stroke="${O}"`,'stroke="#C9D1E6"'); +const rope=(x1,x2,y)=>R(x1-4,y-34,8,40,'#FFD23F',3,3)+R(x2-4,y-34,8,40,'#FFD23F',3,3)+P(`M${x1} ${y-26} q${(x2-x1)/2} 18 ${x2-x1} 0`,'none',6).replace(`stroke="${O}"`,'stroke="#C0154F"'); +const receipt=(x,y)=>P(`M${x} ${y} h18 v34 q-2 10 14 12 h40 v10 h-56 q-16 0 -16 -14z`,'#fff',3)+P(`M${x+4} ${y+8} h10 M${x+4} ${y+16} h10 M${x+4} ${y+24} h10 M${x+26} ${y+52} h30`,'none',2)+T(x+9,y+-2,'€',10); +const piglet=(x,y)=>C(x,y,10,'#FF8FBE',3)+E(x,y+3,5,3.5,'#FF4F9A',2)+``+P(`M${x-9} ${y-7} l-3 -6 l6 3 M${x+9} ${y-7} l3 -6 l-6 3`,'#FF8FBE',2); +const ladder=(x,y,h)=>P(`M${x} ${y} l10 ${-h} M${x+16} ${y} l10 ${-h}`,'none',3)+Array.from({length:Math.floor(h/12)},(_,i)=>P(`M${x+2+i*1.2*10/h*12} ${y-8-i*12} h16`,'none',2.5)).join(''); +const rainbow=(x,y,r)=>['#FF4D5E','#FF8A3D','#FFD23F','#22C47A','#2F8CFF'].map((c,i)=>``).join(''); +const nest=(x,y)=>P(`M${x-18} ${y} h36 l-4 14 h-28z`,'#C9B27C',3)+P(`M${x} ${y+14} v24`,'none',4); +const scope=(x,y)=>P(`M${x} ${y} l26 -10`,'none',8)+P(`M${x} ${y} l26 -10`,'none',4).replace(`stroke="${O}"`,'stroke="#FFD23F"'); +const bench=(y)=>R(24,y,152,12,'#C9B27C',3,3)+P(`M40 ${y+12} v14 M160 ${y+12} v14`,'none',5); +const vihta=(x,y)=>P(`M${x} ${y} l-6 30`,'none',4).replace(`stroke="${O}"`,'stroke="#8A4B22"')+[[0,0],[-8,6],[8,6],[-4,14],[6,14],[0,-8]].map(([a,b])=>E(x+a,y+b-6,6,9,'#22C47A',2,a*4)).join(''); +const bucket=(x,y)=>P(`M${x-16} ${y-22} h32 l-4 26 h-24z`,'#C9B27C',3)+P(`M${x-16} ${y-14} h32 M${x-16} ${y-4} h32`,'none',2)+P(`M${x+10} ${y-24} q12 -24 28 -18`,'none',4)+E(x+40,y-40,7,4,'#C9B27C',2.5); +const rocks=(x,y)=>[[0,0,9],[14,2,8],[-14,3,7],[6,-9,7],[-6,-8,6]].map(([a,b,r])=>C(x+a,y+b,r,'#9AA3BE',2.5)).join(''); +const springs=(x,y,dir)=>P(`M${x} ${y} l${8*dir} -6 l${-6*dir} -6 l${8*dir} -6 l${-6*dir} -6 l${8*dir} -6`,'none',3)+R(x+dir*6-5,y-38,10,8,'#FFD23F',2,2.5); +const propeller=(x,y)=>beanie(x,y,40,'#22C47A')+P(`M${x} ${y-26} v-8`,'none',3)+E(x-14,y-36,14,4,'#FF4F9A',2.5)+E(x+14,y-36,14,4,'#FFD23F',2.5); +const band=(x,y,w,h)=>P(`M${x+w*.3} ${y-2} v${h+4}`,'none',6).replace(`stroke="${O}"`,'stroke="#C0154F"'); +const awning=(x,y,w)=>{let s='';const n=6,g=w/n;for(let i=0;iE(x,y,18,5,'#fff',3)+P(`M${x} ${y+4} v20 M${x-10} ${y+24} h20`,'none',3)+R(x-2,y-14,4,10,'#fff',1,2)+P(`M${x} ${y-14} q-3 -4 0 -8 q3 4 0 8z`,'#FFD23F',1.5)+P(`M${x-34} ${y+24} v-26 h10 v10 M${x+34} ${y+24} v-26 h-10 v10`,'none',3); +const swirl=(x,y)=>`${[56,42,28,14].map((r,i)=>``).join('')}`; +const box=(x,y,w,h,f,r=10)=>R(x,y,w,h,f,r); +const tower=(x,y,w,h,f)=>R(x,y,w,h,f,10); +const raft=(y)=>{let s='';for(let i=0;i<6;i++)s+=R(28+i*24,y,24,12,'#C9B27C',3,3);return s+P(`M14 ${y+18} q14 -8 28 0 q14 8 28 0 q14 -8 28 0 q14 8 28 0 q14 -8 28 0 q14 8 28 0`,'none',4).replace(`stroke="${O}"`,'stroke="#2F8CFF"');}; +const sail=(x,y)=>P(`M${x} ${y} v-62`)+P(`M${x+3} ${y-58} q30 20 2 48z`,'#fff',3); +const hook=(x,y)=>P(`M${x} ${y} h14`,'none',6)+P(`M${x+14} ${y} q14 2 10 16 q-4 8 -12 2`,'none',4).replace(`stroke="${O}"`,'stroke="#C9D1E6"'); +const glasses=(x,y)=>C(x,y,9,'rgba(255,255,255,.4)',3); +const mug=(x,y)=>R(x,y,20,22,'#fff',4,3)+P(`M${x+20} ${y+6} q10 0 10 6 q0 6 -10 6`,'none',3)+P(`M${x+5} ${y-4} q-3 -6 0 -10 M${x+13} ${y-4} q-3 -6 0 -10`,'none',2).replace(`stroke="${O}"`,'stroke="#9AA3BE"'); +const skates=(xs,y)=>xs.map(x=>R(x-14,y,30,10,'#FF4F9A',4,3)+C(x-6,y+14,5,'#FFD23F',2.5)+C(x+8,y+14,5,'#FFD23F',2.5)).join(''); +const tray=(y)=>R(18,y,164,12,'#C9D1E6',4,3); +const juice=(x,y)=>R(x,y,18,28,'#FFD23F',2,3)+P(`M${x+12} ${y} l6 -14`,'none',3)+T(x+9,y+18,'OJ',8); +const apple=(x,y)=>C(x,y,10,'#FF4D5E',3)+P(`M${x} ${y-10} q2 -6 6 -6`,'none',3)+E(x+6,y-12,4,2,'#22C47A',1.5,-20); +const sandwich=(x,y)=>P(`M${x} ${y} h50 l-10 -24 q-15 -10 -30 0z`,'#F4CFA0',4)+P(`M${x+4} ${y-12} q10 -6 20 0 q10 6 22 0`,'none',5).replace(`stroke="${O}"`,'stroke="#22C47A"')+P(`M${x+8} ${y-4} h36`,'none',5).replace(`stroke="${O}"`,'stroke="#FF4D5E"'); +const handle=(x,y,w)=>P(`M${x} ${y} q0 -22 ${w/2} -22 q${w/2} 0 ${w/2} 22`,'none',7); +const stickers=(pts)=>pts.map(([x,y,f,k])=>k?R(x-8,y-6,16,12,f,3,2):C(x,y,7,f,2)).join(''); +const wood=(x,y,w,h)=>{let s='';for(let i=1;i<4;i++)s+=P(`M${x+6} ${y+i*h/4} q${w/2} -4 ${w-12} 0`,'none',1.5);return s;}; +// magic and extreme sports (Brocadabra, Extremely Networks) +const tophat=(x,y,w=56,h=34,band='#FF4F9A')=>R(x-w/2,y-h,w,h,O,4,3)+R(x-w/2-12,y-4,w+24,9,O,4,3)+``; +const rabbit=(x,y,f='#fff')=>E(x-7,y-22,5,14,f,3,-8)+E(x+7,y-22,5,14,f,3,8)+E(x-7,y-21,1.8,8,'#FF8FBE',0,-8)+E(x+7,y-21,1.8,8,'#FF8FBE',0,8)+C(x,y,13,f,3)+``+E(x,y+4,2.5,2,'#FF4F9A',0); +const wand=(x,y,dx=34,dy=-24)=>P(`M${x} ${y} l${dx} ${dy}`,'none',6)+P(`M${x+dx*.8} ${y+dy*.8} l${dx*.2} ${dy*.2}`,'none',6).replace(`stroke="${O}"`,'stroke="#fff"'); +const sparkle=(x,y,s=7,f='#FFD23F')=>P(`M${x} ${y-s} q${s*.25} ${s*.75} ${s} ${s} q${-s*.75} ${s*.25} ${-s} ${s} q${-s*.25} ${-s*.75} ${-s} ${-s} q${s*.75} ${-s*.25} ${s} ${-s}z`,f,2); +const cape=(x,y,w,h,f='#C0154F')=>P(`M${x} ${y} q${-18} ${h*.6} ${-8} ${h} h${w+16} q10 ${-h*.4} ${-8} ${-h}z`,f,3); +const helmet=(x,y,w,f='#FF8A3D')=>P(`M${x-w/2} ${y} q0 ${-w*.44} ${w/2} ${-w*.44} q${w/2} 0 ${w/2} ${w*.44}z`,f,3)+P(`M${x-w*.18} ${y-w*.4} v${w*.34} M${x+w*.18} ${y-w*.4} v${w*.34}`,'none',2.5)+R(x-w/2-4,y-4,w+8,9,f,4,3); +const goggles=(x,y,d=16)=>R(x-d-12,y-8,24,16,'#7FD8EE',8,3)+R(x+d-12,y-8,24,16,'#7FD8EE',8,3)+P(`M${x-d+12} ${y} H${x+d-12}`,'none',3)+glint(x-d,y-1)+glint(x+d,y-1); +const can=(x,y)=>R(x,y,18,32,'#7B61FF',4,3)+R(x+2,y-4,14,6,'#C9D1E6',2,2)+bolt(x+12,y+5,.45,'#FFD23F'); +const bungee=(x,y1,y2)=>P(`M${x} ${y1} q10 ${(y2-y1)*.25} 0 ${(y2-y1)*.5} q-10 ${(y2-y1)*.25} 0 ${(y2-y1)*.5}`,'none',5).replace(`stroke="${O}"`,'stroke="#22C47A"'); + return [ + /* rusty: Vintage set */ ()=>sh()+bob(P('M84 58 L62 18 M116 58 L138 18')+C(62,18,5,'#C9D1E6',3)+C(138,18,5,'#C9D1E6',3)+box(32,56,136,78,'#E8D9B0',14)+wood(32,56,136,78)+R(46,68,72,46,'#5D6788',8,3)+face(82,86,'dots',null,12)+mustache(82,104)+knob(140,78)+knob(140,106)+cobweb(146,56)), + /* edgelord: All spikes */ ()=>sh(72)+bob(P('M26 128 L40 52 L58 36 L70 50 L86 30 L100 48 L114 28 L130 48 L144 34 L160 52 L174 128Z','#2E3550')+face(100,80,'angry',null,22)+ports(54,100,92,6,'#FF4D5E')+legs([46,146],128)), + /* chonk: Round and content */ ()=>sh(76)+bob(feet([68,128],132,'#FF8FBE')+E(100,82,78,56,'#FF8FBE')+P('M30 92 Q100 116 170 92 L168 108 Q100 128 32 108Z','#1E2640',3)+leds(56,106,['#FFD23F','#FFD23F','#FFD23F','#FFD23F','#FFD23F','#FFD23F','#FFD23F'],3)+face(100,62,'happy','smile',18,14)+cheeks(100,76,34)+C(164,40,3,'#C9B27C',2)+C(172,50,2,'#C9B27C',2)), + /* unit16: Flexing */ ()=>sh(78)+bob(arm(46,88,-1)+arm(154,88,1)+box(46,46,108,88,'#FF8FBE',12)+face(100,72,'dots','grin',18,16)+ports(58,108,84,6)+cloud(150,26,.8,'#E8EDF7')+rain(146,26)), + /* mikro: Lunchbox */ ()=>sh(74)+bob(handle(64,72,44)+box(40,70,92,64,'#22C47A')+ports(50,104,72,6)+leds(58,86,['#FFD23F'])+T(96,92,'CCR',11)+sandwich(136,128)), + /* wb32: Roller skates */ ()=>sh(66)+speed(36,74)+bob(box(46,56,108,64,'#F4F6FB')+face(100,80,'wink','grin',16,14)+ports(58,98,84,7)+skates([70,130],120)), + /* ar7280: Flat white */ ()=>sh()+bob(box(40,54,108,80,'#2F8CFF')+beanie(94,56,84,'#22C47A')+eyepatch(78,84)+glasses(112,84)+``+MO.smirk(94,104)+ports(50,116,88,7)+mug(150,96)), + /* ar7800: The captain */ ()=>sh(70)+bob(box(46,46,108,90,'#2F8CFF',8)+capHat(100,48,96)+face(100,66,'dots','smirk',16,10)+[86,100,114].map(y=>R(56,y,88,10,'#1E2640',3,2)+[0,1,2,3,4].map(i=>C(68+i*16,y+5,3,'#FFD23F',0)).join('')).join('')), + /* disco8k: Disco ball */ ()=>sh()+beams(100,38)+bob(disco(100,38)+box(34,60,132,74,'#7B61FF')+leds(54,80,['#FF4F9A','#FFD23F','#22C47A','#7FD8EE','#FF8A3D'],5)+ports(46,98,108,8,'#fff')+tag(178,104,'€/mo','∞')), + /* knockia7750: Minus forty */ ()=>sh()+bob(box(38,58,124,76,'#9AA3BE',6)+snowcap(38,58,124)+icicles(44,134,112)+face(96,86,'dots','smile',14,12)+thermo(144,108,'#2F8CFF')+ports(48,108,80,6))+R(140,30,42,18,'#fff',5,2.5)+T(161,43,'−40°',11,'#2F8CFF'), + /* wb64: Race car */ ()=>sh(84)+bob(box(26,62,148,62,'#F4F6FB',14)+racing(26,70,148)+roundel(60,104,'64')+face(124,100,'shades',null,14)+ports(88,108,30,2)+smoke(178,96)), + /* disco8ku: Double disco */ ()=>sh()+beams(70,36)+bob(disco(70,36,13)+disco(130,36,13)+box(30,56,140,78,'#7B61FF')+coinslot(88,72)+ports(42,102,116,9,'#fff')+tag(180,108,'€/mo','∞∞')), + /* unit32: Litter of pigs */ ()=>sh(84)+bob(box(24,36,152,100,'#FF8FBE',14)+face(100,64,'happy','smile',22,14)+R(38,90,124,30,'#1E2640',6,3)+piglet(58,105)+piglet(100,105)+piglet(142,105)), + /* ar7800r5: Ship of the line */ ()=>sh(84)+bob(mast(100,72,62)+P('M20 72 H180 L164 132 H36Z','#2F8CFF')+[0,1,2,3,4,5,6,7].map(i=>C(44+i*16,92,5,'#1E2640',2)+``).join('')+ports(48,108,104,8)), + /* knockia7950: Sauna door */ ()=>sh()+steam(70,46)+bob(box(40,50,120,86,'#E6C48E',8)+pine(40,50,120,86)+thermo(68,98)+R(132,78,8,26,'#8A4B22',3,2.5)+face(100,74,'sleepy',null,12))+ports(52,116,96,7), + /* mikro32: Propeller hat */ ()=>sh(66)+bob(propeller(100,64)+box(50,66,100,66,'#22C47A')+face(100,88,'happy','grin',16,14)+sweat(154,78)+ports(60,112,80,6,'#FF4F9A')), + /* universe: 42 and a towel */ ()=>bob(tower(62,12,76,132,'#1E2640')+stars([[76,28,1.8],[122,40,1.5],[90,112,1.6],[126,96,2],[72,88,1.3],[110,128,1.4]])+screen(74,44,52,30,'42',20)+P('M74 84 H126 M74 92 H126 M74 100 H126','none',2).replace(`stroke="${O}"`,'stroke="#7FD8EE"')+towel(138,30))+``+planet(22,100,11,'#FF8A3D',1)+planet(178,52,7,'#22C47A') +, + /* brocadabra: Rabbit out of the hat */ ()=>sh()+bob(box(38,76,124,60,'#2F8CFF')+face(100,98,'happy','smile',16,12)+ports(48,116,104,7)+rabbit(100,46)+tophat(100,76,58,28)+wand(150,104))+sparkle(170,60)+sparkle(30,52,5)+sparkle(176,32,4), + /* extremely: Energy drink */ ()=>sh()+bob(box(40,56,120,78,'#FF8A3D')+helmet(100,58,104,'#7B61FF')+goggles(100,80,18)+MO.teeth(100,104,12)+ports(50,118,100,7)+can(160,86))+bolt(28,40,.8)+sweat(42,64) + ];})(); +const RG_ART_C=[]; +// The picture for model g, as inline SVG ('' for a model without one). +function rgArt(g){const f=RG_ART[g];if(!f)return '';return RG_ART_C[g]||(RG_ART_C[g]=``);} diff --git a/src/game/10-catalog/30-supply-chain.js b/src/game/10-catalog/30-supply-chain.js new file mode 100644 index 0000000..87f904a --- /dev/null +++ b/src/game/10-catalog/30-supply-chain.js @@ -0,0 +1,35 @@ +/* ---------- Supply chain: hardware gets dearer over the years, with shortages that come and go ---------- + Transit keeps getting cheaper (it really does), but routers, optics and new builds drift the other way: free for + the first six months, then +4% a year, capped at +30%. Only new purchases pay it; what you own costs what it cost. + Now and then a shortage hits one kind of hardware for a month or two. Spares on the shelf and a yearly price lock + with your vendor are the ways around it. */ +const HW_YR=0.04,HW_CAP=1.3,HW_FREE=180,HW_LOCK_DAYS=365; +const HW_SHOCK={opt:{mul:1.5,n:N_('common.optics'),msg:N_('supply_chain.laser_shortage_the_factory_that')}, + rt:{mul:1.4,n:N_('common.routers'),msg:N_('supply_chain.chip_shortage_every_router_vendor_is')}, + build:{mul:1.3,n:N_('supply_chain.new_fiber_and_cable_builds'),msg:N_('supply_chain.every_cable_ship_is_booked')}}; +const hwTrend=d=>Math.min(HW_CAP,1+HW_YR*Math.max(0,(d-HW_FREE)/365)); +const hwShock=()=>{const s=S&&S.hw&&S.hw.shock;return s&&s.until>S.day?s:null;},hwLock=()=>{const l=S&&S.hw&&S.hw.lock;return l&&l.until>S.day?l:null;}; +function hwMul(k){if(!S||!rule('market'))return 1;const l=hwLock();if(l)return l.mul;const s=hwShock();return hwTrend(S.day)*(s&&s.k===k?s.mul:1);} +// A lock costs a little more for a bigger network, and twice as much in the middle of a shortage. +const hwLockCost=()=>Math.round((80000+30000*Object.keys(S.pops).length)*(hwShock()?2:1)/1000)*1000; +function hwShockStart(){const k=pick(Object.keys(HW_SHOCK)),n=45+Math.floor(Math.random()*31);S.hw=S.hw||{};S.hw.shock={k,until:S.day+n,mul:HW_SHOCK[k].mul}; + toast(tr(HW_SHOCK[k].msg,{n})+(hwLock()?'
'+tr('supply_chain.your_price_lock_covers_you_until',{date:dateStr(hwLock().until)}):''),hwLock()?'':'bad');sfx('alert');} +function hwCard(){if(!S||!rule('market')||(S.day<=HW_FREE&&!hwShock()&&!hwLock()))return '';const t=hwTrend(S.day)/hwTrend(S.day0|0),s=hwShock(),l=hwLock(); + return `
📦 ${tr('common.supply_chain')}
+
${tr('common.hardware_prices')}${t>1.005?tr('supply_chain.p_since_you_started',{p:pct(t-1)}):tr('supply_chain.as_when_you_started')}
+
${tr('lifecycle.bandwidth_prices')}${mktTxt()}
+ ${s?`
${tr('common.shortage')}${tr('supply_chain.what_p_n_days_left',{what:tr(HW_SHOCK[s.k].n),p:pct(s.mul-1),n:s.until-S.day})}
`:''} + ${l?`
${tr('common.price_lock')}${tr('supply_chain.until_date_at_p',{date:dateStr(l.until),p:pct(l.mul-1)})}
` + :`

${tr('supply_chain.routers_optics_and_new_builds_at')}

${btn(tr('supply_chain.lock_prices_for_a_year_cost',{cost:fmt$(hwLockCost())}),'hwLock',{},'sm',S.cash`}
`;} +// Routers past the standard cage (#157) need a cage extension: pricier to install, and rent on top. +const RCAGE=6,CAGE_MUL=1.5,CAGE_MO=2000; +const routerCost=(g,rt)=>Math.round((ROUTER_COST+RG[g].cost*0.8)*((rt||1)>=RCAGE?CAGE_MUL:1)*hwMul('rt')*techMul(RG[g].lvl)); +const routerMo=g=>ROUTER_MO+RG[g].mo,cageMo=rt=>Math.max(0,(rt||1)-RCAGE)*CAGE_MO; +// Old routers go on eBuy when you swap models or remove one (#82), like spare optics (#45). Chassis age faster. +// swapCostOf: the same price for a POP on model old with rt routers (the build standard plans a few steps ahead). +const ROUTER_RESALE=0.3,tradeIn=(g,n)=>Math.round(RG[g].cost*n*ROUTER_RESALE),swapCostOf=(g,old,rt)=>Math.max(0,Math.round(RG[g].cost*rt*hwMul('rt')*techMul(RG[g].lvl))-tradeIn(old,rt)),swapCost=(c,g)=>{const p=S.pops[c];return swapCostOf(g,p.rgen||0,p.routers||1);}; +const RMAX=16; +// The plain, badge-less model of each class is the default upgrade path; the others are side-grades. +const mainRG=k=>RG.findIndex(r=>r.cls===k&&!r.badge); +// Ports and waves beyond 1.6T / 6.4T only show once a router that takes them is unlocked. +const portShown=i=>i<=4||RG.some((r,g)=>rgOpen(g)&&r.maxP>=i),waveShown=i=>i<=5||RG.some((r,g)=>rgOpen(g)&&r.maxLT>=i); diff --git a/src/game/10-catalog/40-ports.js b/src/game/10-catalog/40-ports.js new file mode 100644 index 0000000..945b534 --- /dev/null +++ b/src/game/10-catalog/40-ports.js @@ -0,0 +1,46 @@ +/* Ports are finite. Every transit, IX, PNI, fabric and cache port, every wave and every fibre channel + takes a router port. 10G ports ride a breakout cable, four to a port. */ +const PORT_SLOT=i=>i===0?0.25:1; +// Cache boxes sit behind an aggregation switch: one router port carries as many 100G boxes as its speed holds +// (a 3.2T port takes 32), per site (#252). +const portG=g=>{const s=RG[g].pn;return parseFloat(s)*(s.endsWith('T')?1000:1);}; +const cachePerPort=(c,g)=>{const p=S.pops[c];return p?Math.max(1,Math.floor(portG(g===undefined?(p.rgen||0):g)/CACHE_CAP)):1;}; +// Boxes come in 100G and, behind 400G or faster router ports, 400G: cheaper per Gbps. +const cacheG=x=>x.g===CACHE_BIG?CACHE_BIG:CACHE_CAP,cacheMo=x=>x.g===CACHE_BIG?CACHE_BIG_MO:CACHE_MO,cachesMo=()=>S.caches.reduce((a,x)=>a+cacheMo(x),0); +const cacheBox=c=>{const p=S.pops[c];return p&&portG(p.rgen||0)>=CACHE_BIG?{g:CACHE_BIG}:{};}; +function cachePorts(c,extra=[],g){const n={a:0,b:0};for(const x of S.caches)if(x.city===c)n[x.site==='b'?'b':'a']+=cacheG(x);for(const x of extra)n[x.site==='b'?'b':'a']+=cacheG(x); + return cachePortsOf(c,n,g);} +// n: the Gbps of boxes per site. +function cachePortsOf(c,n,g){const p=S.pops[c],k=p?portG(g===undefined?(p.rgen||0):g):CACHE_CAP;return Math.ceil(n.a/k-1e-9)+Math.ceil(n.b/k-1e-9);} +const cachePortsAdd=(c,adds)=>cachePorts(c,adds)-cachePorts(c); +/* A dark fiber channel takes as many router ports at each end as the optic's speed needs (#256): a pluggable sits + in one port, but a 1.6T transponder shelf hands off to an 800G router as two 800G clients. */ +const chPorts=(o,c,g)=>{const p=S.pops[c];return p&&OPT[o]?Math.max(1,Math.ceil(OPT[o].g/portG(g===undefined?(p.rgen||0):g)-1e-9)):1;}; +function portsUsed(c,g){return portsAt([c],g).get(c);} +/* The router ports in use at each of the cities cs, in one pass over the network: the intern sizes every POP each day, + and a pass per POP was a pass over every link, PNI and cache box for each. Each city's count adds the same things in + the same order as on its own. g: another router model at those cities (what would fit). */ +function portsAt(cs,g){const u=new Map(),box=new Map();for(const c of cs){u.set(c,0);box.set(c,{a:0,b:0});} + const add=(c,v)=>{const x=u.get(c);if(x!==undefined)u.set(c,x+v);}; + for(const l of S.links){if(l.kind==='vxc')continue;for(const c of l.a===l.b?[l.a]:[l.a,l.b]){if(!u.has(c))continue; + if(l.kind!=='df'&&l.kind!=='xp'){add(c,1);continue;}for(const o of l.ch||[])add(c,chPorts(o,c,g));}} + // A puzzle's content origin (t.pz) hands off on a port of its own: it takes none of yours. + for(const t of S.transit)if(!t.pz)add(t.city,PORT_SLOT(t.tier)*(t.n||1)); + for(const x of S.pni)add(x.city,PORT_SLOT(x.tier)*(x.n||1)); + for(const c of u.keys()){for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])add(c,PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1)); + if(S.myIx[c])add(c,1);} + for(const x of S.caches){const n=box.get(x.city);if(n)n[x.site==='b'?'b':'a']+=cacheG(x);} + for(const x of S.nni||[])add(x.city,PORT_SLOT(x.tier)*(x.n||1)); + for(const c of u.keys())add(c,cachePortsOf(c,box.get(c),g)); + return u;} +function portsMax(c,g,rt){const p=S.pops[c];if(!p)return 0;return RG[g===undefined?(p.rgen||0):g].ports*(rt||p.routers||1);} +function portGate(c,add){if(!S.pops[c]||add<=0)return true;const u=portsUsed(c),m=portsMax(c);if(u+add<=m+1e-9)return true; + toast(tr('ports.no_free_router_ports_in_city',{city:esc(CITY[c].name),u:fmtPorts(u),m}),'bad');sfx('err');return false;} +// Nothing depends on this POP yet: no broadband, nothing plugged in, no customer. Work here bothers nobody (#105). +const popIdle=c=>{const p=S.pops[c];return !!p&&!p.bb&&portsUsed(c)===0&&!S.biz.some(b=>b.city===c||b.city2===c||(b.sites||[]).includes(c));}; +const fmtPorts=u=>Number.isInteger(u)?String(u):u.toFixed(2).replace(/0+$/,''); +function modelFits(c,g){const G=RG[g],p=S.pops[c];if(!p)return ''; + if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='wave'&&l.tier>G.maxLT))return tr('ports.a_wave_here_is_faster_than',{pn:G.pn}); + if([...S.transit,...S.pni,...(S.nni||[])].some(t=>t.city===c&&!t.pz&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn}); + if(S.links.some(l=>(l.a===c||l.b===c)&&(l.kind==='df'||l.kind==='xp')&&(l.ch||[]).some(o=>OPT[o]&&OPT[o].rg>G.cls)))return tr('ports.a_fibre_here_uses_optics_this'); + if(portsUsed(c,g)>portsMax(c,g))return tr('ports.you_use_u_ports_here_and',{u:fmtPorts(portsUsed(c,g)),r:p.routers||1,model:G.n,max:portsMax(c,g)});return '';} diff --git a/src/game/10-catalog/50-dark-fiber.js b/src/game/10-catalog/50-dark-fiber.js new file mode 100644 index 0000000..3bd9c12 --- /dev/null +++ b/src/game/10-catalog/50-dark-fiber.js @@ -0,0 +1,54 @@ +// dark fiber & optical gear +const DF_SYS={ + lite:{n:'Rainbow-in-a-Box DWDM',max:16,cost:25000,lvl:2,blurb:tr('dark_fiber.fixed_mux_plus_amplifiers_up_to')}, + roadm:{n:'ROADMaster 9000',max:64,cost:60000,lvl:3,blurb:tr('dark_fiber.full_c_band_remotely_reconfigurable')}, + cl:{n:'ROADMaster 9000 C+L',max:128,cost:140000,lvl:6,blurb:tr('dark_fiber.lights_the_l_band_as_well')}, +}; +const AMP_EVERY=100, AMP_COST=8000, AMP_MO=300; +/* Your own trench holds more than one fiber pair (#35). Once a ROADMaster is full you can light the next pair: + another ROADMaster and another chain of amplifiers, 64 more channels. Regen huts are shared. */ +const isRdm=y=>y==='roadm'||y==='cl'; +const PAIRS_MAX=4,PAIRS_BIG=8,PAIRS_LV=12,SUB_PAIRS_MAX=8,SUB_PAIR_UP=1500000,pairsMax=l=>l.seat?Math.max(1,l.pairs|0):l.sub?SUB_PAIRS_MAX:glassLvl()>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,chMax=l=>DF_SYS[l.sys].max*(isRdm(l.sys)&&l.own?Math.max(1,l.pairs|0):1), + pairCost=l=>DF_SYS[isRdm(l.sys)?l.sys:'roadm'].cost+(l.sub?SUB_PAIR_UP:ampCount(l.km)*AMP_COST); +const OPT={ + zr4:{n:'Ackackia 400ZR+',g:400,cost:12000,reach:1500,modes:[[400,1500],[200,3000]],rg:1,lvl:2,sys:'lite',blurb:tr('dark_fiber.coherent_pluggable_in_the_router_no')}, + zr8:{n:'Sizzle 800ZR+',g:800,cost:22000,reach:900,modes:[[800,900],[400,1800],[200,3600]],rg:2,lvl:3,sys:'lite',blurb:tr('dark_fiber.twice_the_speed_shorter_reach')}, + tp16:{n:'Sienna WaveMagic 1.6T',g:1600,cost:70000,reach:4000,modes:[[1600,4000],[1200,5500],[800,7000],[400,12000]],rg:2,lvl:4,sys:'roadm',blurb:tr('dark_fiber.big_shelf_big_reach_big_invoice')}, + tp32:{n:'Sienna WaveMagic 3.2T',g:3200,cost:130000,reach:1500,modes:[[3200,1500],[1600,4000],[1200,5500],[800,7000],[400,12000]],rg:4,lvl:8,sys:'roadm',blurb:tr('dark_fiber.twice_the_wavemagic_full_speed_only')}, +}; +// A leased fiber pair, per month. Dear enough that it pays off at a couple of 400G waves, as dark fiber does (#203); +// a lease already signed keeps its price (l.mo). +const dfLeaseMo=km=>Math.round(600+km*1.5); +const dfBuildCost=km=>Math.round((25000+km*120)*hwMul('build')); +const dfBuildDays=km=>leadDays(Math.round(120+km*0.25)),IRU_DAYS=30; +const ampCount=km=>Math.max(0,Math.floor(km/AMP_EVERY)); +const fmtCap=g=>g>=999950?(+(g/1e6).toFixed(g>=9.995e6?0:1))+'P':g>=1000?(+(g/1000).toFixed(1))+'T':g+'G'; +const WAVECO=['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','Bolt Technology','youNetworks','G&T (Gin and Transit)']; +const MONTHS=[tr('common.jan'),tr('common.feb'),tr('common.mar'),tr('common.apr'),tr('common.may'),tr('common.jun'),tr('common.jul'),tr('common.aug'),tr('common.sep'),tr('common.oct'),tr('common.nov'),tr('common.dec')]; +const REG={AM:tr('common.americas'),SA:tr('common.south_america'),EU:tr('common.europe'),AF:tr('common.africa'),AS:tr('common.asia'),OC:tr('common.oceania')}; +const waveMo=(km,sub,tier)=>Math.round((300+km*1.2)*LT[tier].m*(sub?1.8:1)); +const FABS=[ + {id:'mgp',name:'Megapork',col:'#FF5A1F',cities:['mel','bne','per','adl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','mrs','sto','mad','sin','hkg','tok','syd','jnb'],blurb:tr('dark_fiber.elastic_interconnection_now_with')}, + {id:'pkf',name:'PocketFabric',col:'#00A896',cities:['sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra'],blurb:tr('dark_fiber.a_whole_network_fabric_that_fits')}, + {id:'ccn',name:'Consolation Connect',col:'#8E44AD',cities:['icn','lon','fra','ams','mrs','bom','sin','hkg','tok','syd','lag','jnb'],blurb:tr('dark_fiber.strong_in_asia_and_africa_every')}, +]; +const FAB=Object.fromEntries(FABS.map(f=>[f.id,f])); +/* A fabric port (NNI) comes in 10G, 100G or 400G, as fast as the router takes (portOk), and bundles into a LAG like + any other port (#140): more than 400G is more members. Fabrics sell nothing faster. Monthly, the first month up + front; cheaper per Gbps the faster it is. 10G and 100G keep the prices they always had. */ +const NNI_MO=[500,1200,3000]; +const NNI=NNI_MO.map((mo,i)=>({n:PORT[i].n,g:PORT[i].g,mo})); +const VXC=[{n:'10G',g:10,m:1},{n:'50G',g:50,m:2.4},{n:'100G',g:100,m:3.6}]; +const vxcMo=(km,sub,t)=>Math.round((150+km*0.12)*VXC[t].m*(sub?2:1)); +const MET={prefer:{l:tr('common.prefer'),f:0.5},normal:{l:tr('common.normal'),f:1},avoid:{l:tr('common.avoid'),f:4},backup:{l:tr('common.backup_only'),f:60}}; +// Custom metrics: a multiplier on the distance cost (f) or an absolute IGP cost (w), capped like an OSPF metric. +const MET_LIM={f:[0.1,100],w:[1,65535]}; +const clampM=(k,v)=>{const [lo,hi]=MET_LIM[k];v=Math.min(hi,Math.max(lo,v));return k==='w'?Math.round(v):Math.round(v*100)/100;}; +const PREF={high:tr('common.prefer'),normal:tr('common.normal'),low:tr('common.backup_only')}; +const edgeKey=l=>l.aMath.ceil(l.km/((l.regen|0)+1)); +/* Subsea glass is engineered end to end for one route: ultra-low-loss, large-area fiber and a repeater every + ~70 km, no regens in the middle of the sea (#66, #68). A consortium cable lands in several countries on its way, so a + seat on one can regenerate in those landing stations; your own point-to-point cable cannot. Optics reach about half as far again as on land, and the same physics caps + every wave on a cable, leased or your own: transatlantic gets 1.6T, transpacific 800G. */ +const SUB_REACH=1.5,reachOn=(r,sub)=>sub?Math.round(r*SUB_REACH):r; +const SUB_MAXKM=()=>subReach(1,1); +// Upgrades improve long-haul modes, not the nominal 1.6T/3.2T rate. +const SUB_UPGRADES={terminal:{n:N_('reach_and_subsea.premium_submarine_terminals'),cost:5000000,days:30},engineering:{n:N_('common.optical_engineering'),cost:12000000,days:180}}; +const subUpgradeReady=(l,k)=>l.kind==='df'&&l.sub&&l.own&&Number.isFinite(l['sub'+k])&&l['sub'+k]<=S.day; +const subUpgradeCost=(l,k)=>SUB_UPGRADES[k].cost+(k==='engineering'?Math.round(l.km*1000):0); +// Pending transmission work follows the construction schedule. Keep the actual +// shift (the last crew purchase can save fewer than 30 days) and completed work. +function setCableReady(l,ready,day=S.day){const shift=ready-l.ready;layHold(l,shift,day); + if(l.kind==='df'&&l.own&&l.sub)for(const k of Object.keys(SUB_UPGRADES)){ + const f='sub'+k;if(Number.isFinite(l[f])&&l[f]>day)l[f]=Math.max(day+1,l[f]+shift); + }l.ready=ready; +} +// Crews hurry a build on land. At sea only a cable ship does (85-incidents/50-cable-ships.js). +const crewCost=l=>Math.round(15000+l.km*6); +// Permits and rights of way set the pace: crews cut at most half of the planned build (#203). +const crewFloor=l=>Math.max(S.day+1,Number.isFinite(l.day)?l.day+Math.ceil(dfBuildDays(l.km)/2):0); +const crewSteps=l=>Math.max(0,Math.ceil((l.ready-crewFloor(l))/30)); +// Old saves lack purchase dates. Only shorten dates beyond any valid remaining +// commissioning window. Credit elapsed time since the actual cable finish; +// recent purchases and installed upgrades stay untouched. +function repairSubUpgradeDates(l,day){if(l.kind!=='df'||!l.own||!l.sub)return; + for(const [k,U] of Object.entries(SUB_UPGRADES)){const f='sub'+k; + if(Number.isFinite(l[f])&&l[f]>Math.max(day,l.ready)+U.days)l[f]=l.ready+U.days; + } +} +function optModes(o,l){return (OPT[o].modes||[[OPT[o].g,OPT[o].reach]]).map(([g,r])=>{ + let reach=reachOn(r,l.sub); + if(l.sub&&['tp16','tp32'].includes(o)&&g<=1200){ + if(subUpgradeReady(l,'terminal'))reach=Math.max(reach,({1200:9000,800:13500,400:20000})[g]||reach); + if(subUpgradeReady(l,'engineering'))reach=Math.round(reach*1.25); + } + return [g,reach];});} +function optMode(o,l){const km=spanKm(l);for(const [g,r] of optModes(o,l))if(km<=r)return {g,reach:r,full:g===OPT[o].g};return null;} +// The same cable with both subsea upgrades in service: if an optic still falls short, no upgrade can stretch it. +const withSubUps=l=>({...l,subterminal:0,subengineering:0}); +// The longest subsea span any optic lights with these upgrades in service, and the cheapest upgrades a length needs +// (null: nothing can light it). The length limit, the order screen and refunds all use these, so they agree. +const SUBR=[],subReach=(t,e)=>SUBR[(t?1:0)+(e?2:0)]??(SUBR[(t?1:0)+(e?2:0)]=Math.max(...Object.keys(OPT).flatMap(o=>optModes(o,{kind:'df',own:true,sub:true,subterminal:t?0:undefined,subengineering:e?0:undefined}).map(m=>m[1])))), + subNeed=km=>km<=subReach(0,0)?[]:km<=subReach(1,0)?['terminal']:km<=subReach(0,1)?['engineering']:km<=subReach(1,1)?['terminal','engineering']:null; +// Upgrades a cable of this length still needs on top of the chosen ones; ['design'] when nothing can light it. +const seaLack=(km,up)=>{const n=subNeed(km);return n?n.filter(k=>!up[k]):['design'];}; +const submarineRate=l=>Math.max(0,...Object.keys(OPT).filter(o=>OPT[o].lvl<=glassLvl()&&(OPT[o].sys!=='roadm'||isRdm(l.sys||'roadm'))).map(o=>optG(o,l))); +// The fastest single carrier any optic can run over this much subsea cable. +const subCarrier=km=>Math.max(0,...Object.values(OPT).map(O=>{const m=(O.modes||[[O.g,O.reach]]).find(([,r])=>km<=reachOn(r,true));return m?m[0]:0;})); +// A big leased wave is several carriers (6.4T = 4×1.6T), so each carrier has to make it across on its own. +const waveCar=i=>LT[i].car||LT[i].g; +function subWaveWhy(i,km,sub){if(!sub)return '';const c=subCarrier(km);return waveCar(i)>c?tr('common.km_km_of_cable_carries_at',{km:Math.round(km).toLocaleString(),g:fmtCap(c)}):'';} +const subMaxTier=km=>{let t=0;LT.forEach((T,i)=>{if(!subWaveWhy(i,km,true))t=i;});return t;}; +// What an optic carries depends only on the optic, the span length and subsea or not; the map and compute() ask a lot. +// Cached per optic, span and cable state: subsea, and which submarine upgrades are in service (#78). +const OPTG={};const optG=(o,l)=>{const km=spanKm(l),fl=l.sub?1+(subUpgradeReady(l,'terminal')?2:0)+(subUpgradeReady(l,'engineering')?4:0):0,c=OPTG[o]||(OPTG[o]=[]),m=c[fl]||(c[fl]=new Map());let g=m.get(km);if(g===undefined){const x=optMode(o,l);m.set(km,g=x?x.g:0);}return g;}; +// Whether upgrade k changes what any optic carries on a subsea cable this long (#198). has: the other upgrade is +// already in; otherwise k also counts when it only helps together with the other one. +const subOther=k=>k==='terminal'?'engineering':'terminal',subHelps=(km,k,has)=>{const j=subOther(k),c=(on,o)=>({kind:'df',own:true,sub:true,km,['sub'+k]:on?0:undefined,['sub'+j]:o?0:undefined}); + return (has?[1]:[0,1]).some(o=>Object.keys(OPT).some(x=>optG(x,c(1,o))!==optG(x,c(0,o))));}; +const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1); +// The map asks for every fiber's capacity several times per frame (width, colour, label, up or down), each time over +// all its channels. Nothing changes while a frame is drawn, so draw() keeps the answers in DFC for that frame. +let DFC=null; +const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;}; +// dfLit: everything the optics carry; dfCap0: what is left for your own traffic once managed waves sold on it (mwG(), +// the capacity market) are carved out. A fiber's channels come in runs of one optic (a big one: a thousand of them): +// optG() once per run, added up in order. +const dfLit=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0,o=null,x=0;for(const c of ch){if(c!==o){o=c;x=optG(c,l);}g+=x;}const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; +const dfCap0=l=>Math.max(0,dfLit(l)-mwG(l)); +// Whether a fiber carries anything for you (linkDown() asks of every fiber, often): dfCap(l)>0 without adding up every +// channel. An optic out of service, or managed waves sold on it, take the sum. +const dfOn=l=>{if(l.ready>S.day||l.eqDown>S.day)return false;if(l.chFail&&l.chFail.until>S.day||mwG(l)>0)return dfCap(l)>0;let o=null;for(const c of l.ch||[])if(c!==o){o=c;if(optG(c,l)>0)return true;}return false;}; +const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):l.kind==='xp'?xpG(l)*xpGlassF(l):l.kind==='sat'?l.g:LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); +// A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears. +const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]}); +const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc'||l.kind==='sat')return 0;const g=l.kind==='xp'?xpG(l):dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; +const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='sat'?fmtCap(l.g)+' '+SAT_ORB[SATS[l.bird].orb].n:l.kind==='xp'?(g=>g?tr('express.cap',{cap:fmtCap(g)}):tr('common.dark'))(xpG(l)):l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; + diff --git a/src/game/10-catalog/70-pie.js b/src/game/10-catalog/70-pie.js new file mode 100644 index 0000000..adb07dc --- /dev/null +++ b/src/game/10-catalog/70-pie.js @@ -0,0 +1,84 @@ +/* ---------- Pie in the Sky: the rocket-company endgame (docs/plans/pie-in-the-sky.md) ---------- + The catalog: rockets, crusts (orbital shells of pies), prices and the small helpers everything else asks. + Hardware is list price x PIE_MUL x hwMul(); running costs, fees and landing rights are not inflated, like the rest + of the game. The economy and the daily tick are in 60-features/99-pie-in-the-sky.js. */ +const PIE_MUL=1; +const PIE_CO=250e6,PIE_CO_MO=5e6,PIE_FAC=1e9,PIE_FAC_MO=8e6,PIE_FAC_MONTH=120,PIE_STOCK_MAX=480, + PIE_PIE=0.5e6,PIE_LAS=0.25e6,PIE_PAD=400e6,PIE_PAD_MO=2e6,PIE_PAD_MAX=6,PIE_EQ=0.15, + PIE_REUSE=500e6,PIE_HEAVY=3e9,PIE_HEAVY_TESTS=3,PIE_BOOST=40e6,PIE_BOOST_MAX=20,PIE_BOOSTERS=6,PIE_INS=0.08, + PIE_DISH=25e6,PIE_ANT=2e6,PIE_ANT_MAX=16,PIE_ANT_G=20,PIE_DISH_MO=3e5,PIE_DISH_MAX=200, + PIE_LIC_MIN=10e6,PIE_LIC_MAX=100e6,PIE_LIC_P=12000,PIE_LIC_DAYS=360,PIE_LEOIX=50e6,PIE_LEOIX_MO=1e6,PIE_PARTY=2e6, + PIE_QUIET=90,PIE_PREP=7,PIE_Q_MAX=40,PIE_COHORTS=240,PIE_POSTS=20,PIE_RAW=0.4,PIE_BAKED=0.6,PIE_SPARE=1.1,PIE_WEAR=0.3; +// In generation order. fail: chance a launch is lost (x chaos); land: chance a reused booster does not come back. +const ROCKETS={ + falcon:{n:N_('pie.rk_falcon_punch'),cost:60e6,pies:20,fail:0.05,gap:14}, + again:{n:N_('pie.rk_falcon_punch_again'),cost:30e6,pies:20,fail:0.04,land:0.06,gap:10,rd:'reuse'}, + heavy:{n:N_('pie.rk_starshipping_and_handling'),cost:100e6,pies:100,fail:0.08,gap:30,rd:'heavy'}, +}; +const PIE_RD={reuse:{n:N_('pie.rd_reuse'),cost:PIE_REUSE},heavy:{n:N_('pie.rd_heavy'),cost:PIE_HEAVY}}; +// alt km, full: pies for 100% coverage, inc: the orbit's inclination (a pad can launch to it from |lat| <= inc), +// life in game days (a year is 360), g: Gbps the whole crust carries when full. +const CRUSTS={ + short:{n:N_('pie.cr_shortcrust'),alt:550,full:1584,inc:53,life:1800,g:40000}, + frozen:{n:N_('pie.cr_frozen'),alt:560,full:520,inc:97.6,life:1800,g:10000,polar:true}, + upper:{n:N_('pie.cr_upper'),alt:1100,full:1200,inc:60,life:1800,g:24000}, + flaky:{n:N_('pie.cr_flaky'),alt:340,full:2500,inc:53,life:1080,g:60000,dense:true}, +}; +// Company names: the first is the default; saves keep the label, or the player's own text after a rename. +const PIE_NAMES=[ + N_('pie.co_mid_life_crisis_aerospace'), + N_('pie.co_hubris_heavy_industries'), + N_('pie.co_spacexpensive'), + N_('pie.co_thrust_issues'), + N_('pie.co_payload_bearing'), + N_('pie.co_compensation_dynamics'), + N_('pie.co_escape_velocity_partners'), + N_('pie.co_gravity_is_optional'), +]; +// What the Founder posts. Saves keep the label and at most a number and a crust id. +const FOUNDER_POSTS=[ + N_('pie.fp_baked'), + N_('pie.fp_booster'), + N_('pie.fp_dish'), + N_('pie.fp_fail'), + N_('pie.fp_found'), + N_('pie.fp_launch'), + N_('pie.fp_promise'), + N_('pie.fp_rename'), + N_('pie.fp_slip'), + N_('pie.fp_test'), + N_('pie.fp_tour'), +]; +const PIE_LIC_STATES=['ok','refused','sus']; +/* Hooks for the parts built later, so they live in their own files: push functions here. + day: f(d) once a day; launch: f(L,ok) after every launch; fail: f(L) after a lost one. + PIE_SPATS[id] = {fix:(o,s)=>o|null}: a geopolitical spat kept in S.pie.spat[id], repaired by sanitize. */ +const PIE_ON={day:[],launch:[],fail:[]},PIE_SPATS={}; +const piePrice=(v,k='build')=>Math.round(v*PIE_MUL*hwMul(k)); +// A pad goes on the coast: a beach city, or within 80 km of the drawn coastline (cached; cable hubs inland do not count). +const PIE_COAST=new Map(); +function pieCoast(c){if(!isCity(c))return false;if(PIE_COAST.has(c))return PIE_COAST.get(c);const C=CITY[c],cl=Math.cos(C.lat*Math.PI/180);let m=1e9; + if(!C.beach)for(const p of COAST_LL)for(const q of p){const dx=(q[0]-C.lon)*cl,dy=q[1]-C.lat,d=dx*dx+dy*dy;if(dPIE_EQ*clamp((45-Math.abs(CITY[c].lat))/35,0,1); +// Landing rights by market size: the eyeballs of every city in the country. +const pieLicPrice=cc=>Math.round(clamp(PIE_LIC_MIN+CITIES.reduce((a,c)=>a+(c.cc===cc?c.P:0),0)*PIE_LIC_P,PIE_LIC_MIN,PIE_LIC_MAX)/1e6)*1e6; +// The feature is here: unlocked by becoming Tier 1 in a save of this version, or open gates (sandbox). Never in puzzles, +// the Architect or scenarios. +function pieOn(){return !!S&&!S.scn&&S.mode!=='puzzle'&&(!!S.pie||gatesOpen());} +const pieT1=()=>!!S.won&&isTier1(); +// New things (company, factory, pads, R&D, launches, dishes) need you to be Tier 1 now, or a sandbox. +function pieCanBuild(){return pieOn()&&(gatesOpen()||pieT1());} +// Pies wear out over the last PIE_WEAR of their life, a few every day, so a launch month never falls out of the sky at once: +// a cohort counts in full until then, then less every day, and nothing at its life's end (no dice, nothing saved). +function pieAlive(k,life){const left=life-(S.day-k.day),w=life*PIE_WEAR;return left>=w?k.n:left>0?k.n*left/w:0;} +function pieLive(id){const c=S&&S.pie&&S.pie.crusts[id];if(!c)return 0;let n=0;const life=CRUSTS[id].life;for(const k of c.cohorts)n+=pieAlive(k,life);return Math.round(n);} +function pieCov(id){return own(CRUSTS,id)?Math.min(1,pieLive(id)/CRUSTS[id].full):0;} +// A crust is baked from 60%. Under that it is half-baked: from 40% (PIE_RAW) it carries a share of its traffic that grows +// to all of it at 60% (pieCarry), under 40% nothing; too many gaps. +function pieBaked(id){return pieCov(id)>=PIE_BAKED;} +function pieCarry(id){return clamp((pieCov(id)-PIE_RAW)/(PIE_BAKED-PIE_RAW),0,1);} +function pieUp(id){const P=S&&S.pie;return !!P&&!P.safe&&pieCarry(id)>0&&!(P.crusts[id].down>S.day);} +// Gbps a crust carries today: its capacity at its coverage, times the share a half-baked one manages. +const pieCap=id=>CRUSTS[id].g*pieCov(id)*pieCarry(id); diff --git a/src/game/10-catalog/75-satellites.js b/src/game/10-catalog/75-satellites.js new file mode 100644 index 0000000..cc3e66c --- /dev/null +++ b/src/game/10-catalog/75-satellites.js @@ -0,0 +1,90 @@ +/* ---------- Satellites (#83): capacity rented on someone else's birds ---------- + A teleport (a satellite gateway at one of your POPs) links to a small island or a remote town over rented capacity: + the early answer to "no cable lands there", and the warm backup for an island hanging on one cable. Geostationary + birds (GEO, 35,786 km up) see a whole ocean from one dish: no build, dear per Gbps, about 600 ms there and back. A + medium-orbit ring over the equator (MEO, 8,062 km up) gets that down to about 130 ms, but a teleport needs tracking + antennas to follow its satellites across the sky. A rented low-orbit constellation (LEO, 550 km up, from level 5) is + a bent pipe: one satellite sees a gateway at your teleport and an island at once, so it reaches only the region round + the gateway, at about 30 ms. Your own constellation (Pie in the Sky) comes later still. + The providers are vendors, like the fabrics: they sell you capacity, they are not networks you route to. */ +// h: km up; proc: ms of modems and error correction each way; loss: the share of a city's service its users stop counting +// once their traffic rides it (half for GEO, like any haul past 50 ms; MEO feels almost like fiber); days: to point and +// commission a new circuit; lv: the level it unlocks at; g: the sizes sold (Gbps). A MEO ring or LEO shell covers +// |lat| <= lat (LEO's 53 degree shell reaches a few degrees past its inclination, as pieCovers does), and a circuit's two +// ends must see the same satellite at once: at most km apart (LEO: a bent pipe, no lasers on a rented tier), and at least +// el degrees above both horizons (what a ground terminal needs to clear the trees; far north, two ends 7,000 km apart lose +// a MEO satellite below the horizon). loss is also how satEdges/satAfter tell the orbits apart, so no two may share one. +// wisp: how many of an island zone's homes sign up when this orbit is their only link (46-wisp-zones.js). +const SAT_ORB={ + geo:{n:'GEO',h:35786,proc:25,loss:0.5,days:10,lv:2,g:[1,2,5,10],wisp:0.35}, + meo:{n:'MEO',h:8062,proc:7,loss:0.08,days:21,lv:3,g:[2,5,10,20],lat:50,km:7500,el:5,wisp:0.75}, + leo:{n:'LEO',h:550,proc:10,loss:0.03,days:14,lv:5,g:[5,10,20,50],lat:56,km:1200,el:25,wisp:0.9}, +}; +// pg: dollars a month for the first Gbps; bigger circuits cost less per Gbps (satMo). +const SAT_PROV={ + its:{n:'Intelsplat',col:'#2F8CFF',pg:2500,blurb:tr('satellites.its_blurb')}, + kac:{n:'Kacophony',col:'#FF8A3D',pg:1400,blurb:tr('satellites.kac_blurb')}, + sbk:{n:'Starblink',col:'#7C5CFF',pg:1000,blurb:tr('satellites.sbk_blurb')}, + sesa:{n:'SESame',col:'#16A866',pg:2000,blurb:tr('satellites.sesa_blurb')}, +}; +// The birds. A GEO sits over the equator at lon; r is how far its beams reach, in degrees of arc from the point under it +// (72: a global beam, down to about 5 degrees above the horizon; Kacophony's Ka-band spot beams cover less, for less). +const SATS={ + is18:{n:'Intelsplat 18',p:'its',orb:'geo',lon:180,r:72,sea:N_('satellites.sea_pacific')}, + is20:{n:'Intelsplat 20',p:'its',orb:'geo',lon:68.5,r:72,sea:N_('satellites.sea_indian')}, + is37:{n:'Intelsplat 37e',p:'its',orb:'geo',lon:-18,r:72,sea:N_('satellites.sea_atlantic')}, + kac1:{n:'Kacophony-1',p:'kac',orb:'geo',lon:150,r:50,sea:N_('satellites.sea_west_pacific')}, + gx19:{n:'Intelsplat 19',p:'its',orb:'geo',lon:-97,r:72,sea:N_('satellites.sea_americas')}, + o3b:{n:'O3bservant',p:'sesa',orb:'meo',sea:N_('satellites.sea_tropics')}, + sb53:{n:'Starblink Shell 53',p:'sbk',orb:'leo',sea:N_('satellites.sea_leo')}, +}; +// The teleport itself (dishes, a building, the licences), and the MEO tracking antennas it may add. +const TPORT_COST=90000,TPORT_MO=2500,TRK_COST=250000,TRK_MO=3000; +// The rented LEO tier: its one bird, the gateway Starblink puts on your teleport's roof, and its solar storms (a weight +// among the failures, and the most days one may last). +const LEO_BIRD='sb53',LEO_GW_COST=400000,LEO_GW_MO=8000,LEO_STORM_W=1,LEO_STORM_MAX=3; +// Who a satellite serves: a small island off the big continents, or a remote town anywhere, never a big city's market. +const SAT_MAIN=['af','am','eu','oc','sa'],SAT_ISLE_P=150,SAT_TOWN_P=5; +const SAT_RE=6371,SAT_C=300; +// The arc between two points on the globe, in degrees. +function satArc(la1,lo1,la2,lo2){const r=Math.PI/180,c=Math.sin(la1*r)*Math.sin(la2*r)+Math.cos(la1*r)*Math.cos(la2*r)*Math.cos((lo2-lo1)*r);return Math.acos(Math.max(-1,Math.min(1,c)))/r;} +// From a dish to a satellite h km up over a point arc degrees away, in a straight line. +function satSlant(arc,h){const Q=SAT_RE+h,a=arc*Math.PI/180;return Math.sqrt(SAT_RE*SAT_RE+Q*Q-2*SAT_RE*Q*Math.cos(a));} +// How high above a dish's horizon that satellite stands, in degrees (negative: below it, behind the Earth). +function satElev(arc,h){const a=arc*Math.PI/180;return Math.atan2(Math.cos(a)-SAT_RE/(SAT_RE+h),Math.sin(a))*180/Math.PI;} +/* The geometry works on points ({lat, lon}: a city, or an island zone that is no city), and the city versions wrap it. + The longitude the bird sits over for a circuit between P and Q: a GEO's slot; a MEO ring's satellite halfway between + the two ends. LEO does not use it: its satellite flies over the midpoint of the two ends, not over the equator. */ +function satLonAt(id,P,Q){const B=SATS[id];if(B.orb==='geo')return B.lon;const r=Math.PI/180; + return Math.atan2(Math.sin(P.lon*r)+Math.sin(Q.lon*r),Math.cos(P.lon*r)+Math.cos(Q.lon*r))/r;} +function satLon(id,a,b){return satLonAt(id,CITY[a],CITY[b]);} +// Whether bird id sees point P, and city c. +function satSeesAt(id,P){const B=SATS[id];if(!B||!P)return false;return B.orb==='geo'?satArc(0,B.lon,P.lat,P.lon)<=B.r:Math.abs(P.lat)<=SAT_ORB[B.orb].lat;} +function satSees(id,c){return satSeesAt(id,CITY[c]);} +// Whether one satellite of bird id sees both ends at once: a GEO sees them from its slot; a MEO or LEO satellite has to +// be within km of both and high enough above both horizons (LEO's flies over the midpoint). km as kmBetween counts it. +function satPairAt(id,P,Q){if(!satSeesAt(id,P)||!satSeesAt(id,Q))return false;const B=SATS[id];if(B.orb==='geo')return true;const O=SAT_ORB[B.orb]; + if(Math.max(20,Math.round(hav(P.lon,P.lat,Q.lon,Q.lat)))>O.km)return false; + if(B.orb==='leo')return satElev(satArc(P.lat,P.lon,Q.lat,Q.lon)/2,O.h)>=O.el; + const lon=satLonAt(id,P,Q);return [P,Q].every(X=>satElev(satArc(0,lon,X.lat,X.lon),O.h)>=O.el);} +function satPairOk(id,a,b){return a!==b&&satPairAt(id,CITY[a],CITY[b]);} +// The radio path: up from one dish and down to the other, the km the signal really travels. It is the link's km, so the +// routers' metric (pairW) sees a satellite as the long way round it is, and a cable wins whenever there is one. +function satKmAt(id,P,Q){const h=SAT_ORB[SATS[id].orb].h; + if(SATS[id].orb==='leo')return Math.round(2*satSlant(satArc(P.lat,P.lon,Q.lat,Q.lon)/2,h)); + const lon=satLonAt(id,P,Q);return Math.round(satSlant(satArc(0,lon,P.lat,P.lon),h)+satSlant(satArc(0,lon,Q.lat,Q.lon),h));} +function satKm(id,a,b){return satKmAt(id,CITY[a],CITY[b]);} +/* LEO from a gateway to any point on the globe (a zone of islands, not a city): pure, they read only the catalog and + CITY. c: the gateway's city id; lat, lon: the far end in degrees. leoArcLL: the arc between them in degrees; leoKmLL: + the radio path in km (up to the satellite over the midpoint and down again); leoMsLL: one way in ms, the modems + included. Whether a gateway may serve that point today is leoReachLL (60-features/45-teleports.js). */ +const leoArcLL=(c,lat,lon)=>satArc(CITY[c].lat,CITY[c].lon,lat,lon); +const leoKmLL=(c,lat,lon)=>Math.round(2*satSlant(leoArcLL(c,lat,lon)/2,SAT_ORB.leo.h)); +const leoMsLL=(c,lat,lon)=>leoKmLL(c,lat,lon)/SAT_C+SAT_ORB.leo.proc; +// One way: the radio path at the speed of light in vacuum, plus the modems at both ends. +const satLat=l=>l.km/SAT_C+SAT_ORB[SATS[l.bird].orb].proc; +const satMo=(id,g)=>Math.round(SAT_PROV[SATS[id].p].pg*Math.pow(g,0.85)/10)*10; +const satRemote=c=>{const C=CITY[c];return !!C&&(C.P<=SAT_TOWN_P||C.P<=SAT_ISLE_P&&!SAT_MAIN.includes(C.land));}; +const satName=l=>SATS[l.bird]?SATS[l.bird].n:'?'; +// A subsea cable: a satellite circuit is stored as sub (never a land route) but is no cable on the seabed. +const seaLink=l=>!!l.sub&&l.kind!=='sat'; diff --git a/src/game/10-catalog/76-wisp-zones.js b/src/game/10-catalog/76-wisp-zones.js new file mode 100644 index 0000000..b81d956 --- /dev/null +++ b/src/game/10-catalog/76-wisp-zones.js @@ -0,0 +1,38 @@ +/* ---------- Island Wi-Fi zones (#83): the outer islands no cable reaches ---------- + Each zone is a pool of island homes looking to one island city (c, always one a satellite serves), at the point lat, + lon: no city on the map and no link, only homes your POP in c brings online (60-features/46-wisp-zones.js). + n: real place names, as in CITIES, joined by "&". P: Gbps of homes at full take-up in era 1 (about the islands' share + of their country, half again for being the only internet there; scaled by eraMul() like eyeP). km: the spur cable from + c, 0 where none can be laid (too far, or sea ice). v: volcanic, so an eruption can cut the spur. Zones under 3 G are + left out: pie terminals and a satellite circuit to the island itself serve those. + The zones beyond 56 degrees (Nunavut, Southeast Alaska) are past Starblink's shell and MEO's ring: GEO only there. */ +const WISP={ + anjouan:{n:'Anjouan & Mohéli',c:'hah',lat:-12.25,lon:44.1,P:6,km:200}, + capeverde:{n:'Sal, Boa Vista & São Vicente',c:'rai',lat:16.6,lon:-23.8,P:6,km:450}, + chuuk:{n:'Chuuk, Yap & Kosrae',c:'pni',lat:7.4,lon:151.85,P:5,km:800}, + leeward:{n:'Bora Bora & Raiatea',c:'ppt',lat:-16.8,lon:-151.45,P:4,km:250}, + malaita:{n:'Malaita & Gizo',c:'hir',lat:-8.5,lon:159.5,P:8,km:350}, + marianas:{n:'Saipan, Tinian & Rota',c:'gum',lat:15.2,lon:145.75,P:6,km:230,v:1}, + ngi:{n:'New Britain, New Ireland & Bougainville',c:'pom',lat:-5,lon:152.5,P:12,km:900,v:1}, + nunavut:{n:'Rankin Inlet, Cambridge Bay & Pond Inlet',c:'yfb',lat:66.5,lon:-88,P:5,km:0}, + outislands:{n:'Abaco, Eleuthera & Exuma',c:'nas',lat:25.1,lon:-76.4,P:8,km:400}, + rangiroa:{n:'Rangiroa & Nuku Hiva',c:'ppt',lat:-12,lon:-144,P:3,km:1400}, + santo:{n:'Espiritu Santo & Tanna',c:'vli',lat:-16.5,lon:167.8,P:8,km:400,v:1}, + savaii:{n:'Savai’i',c:'apw',lat:-13.6,lon:-172.4,P:3,km:80}, + seak:{n:'Sitka, Ketchikan & Petersburg',c:'jnu',lat:56.4,lon:-133.3,P:5,km:450}, + southatolls:{n:'Addu, Fuvahmulah & Huvadhoo',c:'mle',lat:0,lon:73.3,P:6,km:500}, + tobago:{n:'Tobago',c:'pos',lat:11.25,lon:-60.7,P:3,km:120}, + vanualevu:{n:'Vanua Levu & Taveuni',c:'suv',lat:-16.6,lon:179.2,P:10,km:220}, + vavau:{n:'Vava’u & Ha’apai',c:'tbu',lat:-19.2,lon:-174.2,P:3,km:300,v:1}, + vi:{n:'St Thomas, St Croix & Tortola',c:'sju',lat:18.2,lon:-64.8,P:6,km:160}, +}; +/* The money. ARPU: islanders pay island prices (times EYE_RATE). SHARE: a zone's satellite capacity is a contended share + of a high-throughput beam, cheaper than a trunk circuit of the same size. KIT(+G per Gbps of pool): towers, solar + panels and home radios, with the first order; MO(+G): their upkeep. SPUR: a subsea branch cable with small beach + landings (repeatered past a few hundred km, as real ones are), mostly paid by development banks (this is your share), + plus KM a km; MO + MO_KM a km to run; G: what it carries; D0 + DKM a km: days to lay it. LV: the level spurs come at. + GROW: daily take-up growth; START: the pool share that signs up at once and never leaves. RUSH: chartering a repair + ship for a cut spur; CUT_W: a lit spur's weight among the failures. */ +const WISP_ARPU=14,WISP_SHARE=0.6,WISP_KIT=30000,WISP_KIT_G=4000,WISP_MO=500,WISP_MO_G=50, + WISP_SPUR=150000,WISP_SPUR_KM=600,WISP_SPUR_MO=400,WISP_SPUR_MO_KM=1.5,WISP_SPUR_G=100,WISP_SPUR_D0=90,WISP_SPUR_DKM=0.15, + WISP_SPUR_LV=3,WISP_GROW=0.02,WISP_START=0.05,WISP_RUSH=250000,WISP_CUT_W=1.5; diff --git a/src/game/20-world/10-projection.js b/src/game/20-world/10-projection.js new file mode 100644 index 0000000..f47fa68 --- /dev/null +++ b/src/game/20-world/10-projection.js @@ -0,0 +1,7 @@ +/* ================= WORLD ================= */ +// Simplified real geography: lon/lat outlines, equirectangular, with gentle "magnifying lenses" over the busy regions. +const LENSES=[{lon:102.5,lat:2.6,r:22,m:1.1},{lon:52.5,lat:25.3,r:45,m:1.5},{lon:78.5,lat:15,r:48,m:1.1},{lon:-44.5,lat:-23.5,r:30,m:1.2},{lon:9,lat:49,r:170,m:1.25},{lon:121,lat:32,r:120,m:0.45},{lon:-80,lat:40,r:110,m:0.5}]; +function proj0(lon,lat){return [(lon+180)/360*W,(84-lat)*6.4];} +for(const L of LENSES){const q=proj0(L.lon,L.lat);L.x=q[0];L.y=q[1];} +function proj(lon,lat){const q=proj0(lon,lat);let dx=0,dy=0;for(const L of LENSES){let ex=q[0]-L.x;ex-=W*Math.round(ex/W);const ey=q[1]-L.y,f=L.m*Math.exp(-(ex*ex+ey*ey)/(L.r*L.r));dx+=ex*f;dy+=ey*f;}return [q[0]+dx,q[1]+dy];} +function hav(lo1,la1,lo2,la2){const r=Math.PI/180,dLa=(la2-la1)*r,dLo=(lo2-lo1)*r,a=Math.sin(dLa/2)**2+Math.cos(la1*r)*Math.cos(la2*r)*Math.sin(dLo/2)**2;return 2*6371*Math.asin(Math.min(1,Math.sqrt(a)));} diff --git a/src/game/20-world/20-landmasses.js b/src/game/20-world/20-landmasses.js new file mode 100644 index 0000000..f9e58be --- /dev/null +++ b/src/game/20-world/20-landmasses.js @@ -0,0 +1,131 @@ +const LANDS_LL=[ + {id:'am',ll:[[-166,68],[-156.7,71.5],[-141,69.8],[-128,70],[-115,68.5],[-97,68],[-94,62],[-92.5,57.5],[-85,55.2],[-80,51.5],[-78.5,58],[-77,62],[-70,61],[-64.5,60],[-61.5,56.5],[-57,52],[-55.6,49.5],[-53.4,49.7],[-52.5,48.4],[-52.5,47.3],[-53.2,46.6],[-59,46.5],[-61,45.2],[-63.2,44.4],[-66,44.5],[-70,43.3],[-70,42],[-74,40.6],[-76,38],[-75.8,35.5],[-77.5,34.5],[-79,33],[-81,31],[-80.05,27],[-80.1,25.3],[-81.5,25],[-82.7,27.5],[-84,30],[-89,30.2],[-94,29.5],[-97,28],[-97.5,25],[-97.7,22],[-96,19],[-94,18.3],[-91,18.5],[-90.4,21],[-87,21.5],[-88,17],[-88.5,15.8],[-84,15.8],[-83.4,12],[-83.7,10.5],[-81.5,9],[-79.5,9.5],[-77.5,8.6],[-75,10.8],[-71.5,12.3],[-68,10.6],[-62,10.5],[-60,8.6],[-58.2,7.3],[-55.2,6.3],[-52,5.3],[-50,1.5],[-48,-1],[-44,-2.5],[-39,-3.5],[-35,-5.5],[-35,-9],[-37.5,-12.5],[-39,-15],[-39.7,-19],[-41,-22],[-44,-23],[-48,-26],[-48.6,-28.5],[-51,-31],[-53,-34],[-58,-34.5],[-57,-37],[-62,-39],[-65,-41],[-64,-43],[-67.5,-46],[-66,-48],[-69,-51],[-68.5,-53],[-70,-55],[-73,-53],[-75,-48],[-73.5,-43],[-73.5,-37],[-71.5,-32],[-71.3,-27],[-70.5,-20],[-71.5,-17],[-76,-14],[-78,-10],[-81,-6],[-80.5,-3],[-80,0],[-79,1.5],[-77.5,4],[-77.4,7.5],[-80,7.3],[-82.5,8.2],[-85.7,10],[-87,12.5],[-91,14],[-94,16],[-96.5,15.7],[-100,17],[-105.5,20],[-105.5,22.5],[-108,25.5],[-110.8,27.9],[-113,31.3],[-114.7,31.7],[-113.5,29],[-112,26.5],[-110,24],[-109.5,23],[-112,24.8],[-114,27.5],[-115.5,29.8],[-117,32.5],[-118.5,34],[-120.6,34.6],[-122.5,37.5],[-124,40.5],[-124.5,43],[-124,46.2],[-124.7,48.4],[-123,49],[-126,50.5],[-131,54.5],[-133,57.5],[-137,58.5],[-141,60],[-146,61],[-150,59.5],[-152,58.5],[-156,57.5],[-158,56.8],[-162,55.5],[-164.5,54.5],[-158,58.5],[-162,60],[-165,61.5],[-166,64],[-166.6,64.7],[-164,65.5]]}, + {id:'eu',ll:[[-9,39],[-9.5,43],[-8,43.7],[-1.8,43.4],[-1.2,46],[-2.5,47.3],[-4.5,48],[-1.6,48.6],[1.5,50.2],[3,51.2],[4.5,52.5],[5,53.4],[7,53.6],[8.6,54],[8.2,55.5],[8.1,57],[10.5,57.7],[10.5,56.5],[11.2,56],[12.6,56.1],[12.7,55.6],[12.1,54.9],[11,54.3],[14,54],[18.5,54.8],[21,55.3],[21,57],[24,57.5],[24,59.2],[28,59.5],[30,60],[28,60.5],[25,60.1],[22.5,60.3],[21.5,61.5],[21.5,63],[25,65],[25.5,65.6],[22,65.8],[20.5,63.5],[18,62.5],[17.4,61],[19,59.8],[18,59],[16.5,57],[16,56.2],[14.2,55.4],[13,55.4],[12.9,56.5],[11.5,58],[10.5,59.3],[8,58],[5.5,58.5],[5,60],[5,62],[7,63],[10,64],[12.5,66],[15,68.5],[18,69.8],[21.5,70.2],[26,71],[30,70],[33,69.3],[41,67],[44,68.5],[53,68.5],[58,69],[68,69],[69,72.8],[73,72.5],[80,73.5],[87,74.8],[100,76],[104,77.7],[112,74],[113.5,73.5],[127,73.5],[132,71.5],[140,72.5],[150,71.5],[160,70],[170,70],[180,69],[190,66.5],[186,64.5],[182,65],[178,62.5],[173,61],[170,60],[164,60],[164,57],[162,55],[159,52],[156.7,51],[156,55.5],[157,58],[155,59.5],[150,59.5],[143,59.3],[137,54.5],[141,53],[140,48.5],[135,43.5],[131,42.7],[129.5,41],[129.4,37],[129.4,35.5],[127.5,34.6],[126.3,34.8],[126.5,37],[125,37.8],[124.5,39.7],[121.5,39],[121.7,40.8],[119,39.3],[117.8,38.5],[119,37.2],[122.5,37.3],[120.5,36],[119.2,35],[121,32],[121.9,30.8],[121.5,28],[119.5,25.5],[116.5,23],[114.3,22.1],[111,21.5],[109.7,20.5],[108.5,21.6],[106.5,20],[106,18],[108.5,15],[109.3,12],[107,10.5],[105,8.6],[104.8,10.3],[103,11],[100.9,12.6],[100,13.4],[99.3,10.5],[100.3,7],[101,6.8],[103.4,4],[104.3,1.4],[103.6,1.25],[101.3,2.8],[100.2,5.3],[98.3,8],[98.6,13],[97.7,16.5],[94.4,16.2],[94.2,18.8],[92.3,20.6],[91.8,22.6],[90,22],[88.3,21.6],[86.9,20.6],[85,19.5],[82.3,16.6],[80.3,15.8],[80.3,13.5],[79.8,10.3],[78.3,8.9],[77.5,8.1],[76.5,8.9],[75.8,11.5],[74.8,12.9],[73.5,16],[72.8,19],[72.7,21.2],[70,22.5],[68.5,23.5],[66.6,25.4],[61.6,25.2],[57.3,25.8],[56.4,27.1],[54.7,26.5],[51.5,27.9],[50,30],[48,30],[48.4,28.5],[49.5,26.7],[50.8,24.8],[50.85,25.6],[51.2,26.15],[51.62,25.9],[51.62,24.6],[52.6,24.2],[54.3,24.6],[55.3,25.3],[55.9,25.75],[56.1,26.1],[56.35,26.38],[56.42,25.8],[56.38,25.0],[56.5,24.6],[57.8,23.8],[58.7,23.75],[58.8,22.5],[59.8,22.4],[58.5,20.5],[57.7,19],[55.4,17.7],[52.2,15.7],[48.7,14],[45,12.8],[43.4,12.6],[42.7,15.7],[42.5,17.2],[41,19.5],[39.1,21.6],[38.4,23.6],[37,25.5],[35.2,28],[34.9,29.5],[34.3,27.8],[33,28.8],[32.6,30],[32.3,31.2],[34.2,31.3],[34.9,32.8],[35.6,34.5],[36,35.8],[36.2,36.7],[34.5,36.8],[32.5,36.1],[30.5,36.4],[29,36.6],[27.3,37.4],[26.3,38.6],[26.5,40],[26.2,40.6],[24,40.8],[22.6,40.4],[24.1,38.2],[24,37.6],[23.2,37.5],[22.3,36.5],[21.7,36.8],[21.2,38.4],[19.5,40],[19.5,41.8],[18.5,42.5],[16,43.5],[13.7,45.6],[12.3,45.3],[12.4,44.2],[13.6,43.5],[15.9,41.6],[18.5,40.2],[17,39],[16.6,38],[15.6,38],[15.3,37],[15.1,36.65],[12.4,37.8],[13.3,38.25],[15.55,38.3],[16.1,39],[15.6,40.1],[14.3,40.6],[12.5,41.6],[11,42.5],[10.2,43.9],[8.8,44.4],[7.5,43.8],[6,43.1],[4,43.5],[3.1,43.1],[3.2,41.9],[0.8,41],[0,39.5],[-0.3,38.4],[-0.8,37.6],[-2.1,36.7],[-4.4,36.7],[-5.6,36],[-6.3,36.8],[-7.4,37.2],[-8.9,37],[-8.8,38.4],[-9.5,38.6]]}, + {id:'af',ll:[[-17.5,14.7],[-17,21],[-16,24],[-13,27.5],[-9.8,30],[-9.2,32.5],[-6.9,34.2],[-5.9,35.8],[-2,35.1],[1,36.5],[5,36.8],[9.8,37.3],[11,36.9],[10.2,35.2],[11.1,33.3],[13.2,33.1],[15.2,32.3],[19,30.3],[20.1,32],[23,32.6],[25,31.7],[29,30.9],[32.2,31.3],[32.6,30],[33.5,28],[35.5,24],[37.2,21],[38.5,18],[39.6,15.5],[41.6,13.5],[43.3,12.4],[44,10.4],[47,11.1],[51.2,11.8],[51,10.4],[49.5,7],[47.8,4.5],[45,1.6],[42,-1],[40.2,-2.8],[39.3,-4.8],[38.8,-6.5],[39.6,-10],[40.5,-11],[40.6,-14.6],[37,-17.5],[35.4,-22],[35.5,-24],[32.9,-25.9],[32.5,-28.6],[31,-29.9],[28,-32.7],[25.6,-33.9],[22.5,-34],[20,-34.8],[18.4,-34],[17.9,-32.5],[16.5,-28.6],[15.2,-27],[14.4,-23],[12.8,-19],[11.8,-16.8],[12.2,-14.5],[13.6,-12.2],[13.2,-8.8],[12.3,-6],[11.8,-3.5],[9.5,-1],[9.4,1],[9.8,3.2],[8.9,4.5],[6,4.3],[4.3,6.3],[1.6,6.2],[-2,4.8],[-4.6,5.2],[-7.5,4.4],[-9.6,5.1],[-11.6,6.5],[-13.4,8.3],[-13.3,8.8],[-15,10.9],[-16.7,12.4]]}, + {id:'uk',ll:[[-5.7,50.1],[-3,50.6],[1.4,51.2],[1.7,52.7],[0.3,53.4],[-0.2,54.3],[-1.6,55.6],[-2,56.4],[-1.8,57.6],[-3.4,58.6],[-5,58.6],[-6.2,57.5],[-5.6,56.3],[-5,55],[-3.2,54.9],[-3.4,54],[-3,53.4],[-4.6,53.3],[-4.2,52.2],[-5.2,51.7],[-3.2,51.4],[-4.6,51]]}, + {id:'ie',ll:[[-6,52.2],[-6.2,53.5],[-5.6,54.6],[-6.4,55.2],[-7.4,55.4],[-8.5,54.5],[-10,54.2],[-9.6,53.2],[-10.2,51.9],[-9.6,51.5],[-8.2,51.8]]}, + {id:'is',ll:[[-22.5,63.9],[-24,65.5],[-22,66.4],[-16,66.5],[-14.5,65.3],[-14.6,64.4],[-18,63.4]]}, + {id:'jp',ll:[[129.6,33.3],[130.2,31.3],[131.4,31.5],[132,33],[133.5,33.4],[135.2,33.6],[136.8,34.3],[138.8,34.6],[140,35],[140.8,35.7],[141,38.2],[141.9,39.5],[141.4,41.4],[140,41.4],[139.9,40.3],[139.8,38.5],[138.8,37.8],[137.3,36.9],[136,36],[135.4,35.6],[133,35.5],[131.5,34.6],[130.9,34]]}, + {id:'oc',ll:[[113.5,-22],[114,-26.5],[115,-30],[115.7,-33.6],[115,-34.3],[117.9,-35.1],[123.5,-33.9],[126,-32.3],[131,-31.5],[134,-32.8],[135.6,-34.8],[137.6,-35.6],[138.3,-34.5],[139.6,-36.9],[141.5,-38.4],[144.9,-37.9],[146.4,-39.1],[150,-37.5],[150.8,-34.5],[152.5,-32.4],[153.6,-28.5],[153,-25],[150.8,-22.5],[149,-20.6],[146.3,-18.9],[145.4,-16],[145.3,-14.9],[143.5,-12.3],[142.5,-10.7],[141.6,-12.8],[141.6,-16],[140.6,-17.6],[139.3,-17.4],[137,-15.9],[135.8,-15],[136.8,-12.2],[135,-12],[132.6,-11.5],[131,-12.2],[129.5,-14.9],[128,-15.4],[126.5,-13.9],[124.5,-16.5],[122.2,-18.2],[121,-19.7],[118.5,-20.3],[116.7,-20.6],[114.6,-21.8]]}, + {id:'tas',ll:[[144.6,-40.7],[146.5,-41.1],[148.3,-40.9],[148.3,-42.2],[147.9,-43.2],[146.9,-43.6],[146,-43.5],[145.2,-42.2],[144.7,-41.2]]}, + {id:'nz',ll:[[172.7,-34.4],[174.5,-36],[175.9,-37.5],[178.5,-37.7],[177.9,-39.2],[176.9,-39.6],[175.2,-41.6],[174.6,-41.2],[174.9,-39.9],[173.8,-39.3],[174.6,-38.1],[174.5,-37.3],[173.1,-35.3]]}, + {id:'nzs',ll:[[172.6,-40.5],[174.3,-41.0],[174.2,-41.7],[173.3,-42.9],[172.8,-43.9],[171.3,-44.4],[170.7,-45.8],[169.3,-46.6],[168.3,-46.6],[166.5,-46.0],[166.8,-45.3],[168.2,-44.0],[170.6,-43.0],[171.4,-41.8],[172.1,-40.9]]}, + {id:'idn',ll:[[105.2,-6.8],[106.8,-6.1],[108.5,-6.4],[110.5,-6.9],[112.6,-6.9],[114.6,-7.7],[114.4,-8.7],[111,-8.3],[108,-7.8],[105.5,-7]]}, + {id:'ph',ll:[[120.6,18.5],[122.2,18.5],[122,16.5],[121.6,14.2],[124,13.8],[124,12.5],[123.3,13],[121,13.6],[120.6,14.5],[119.8,16.2]]}, +]; +// South America is drawn as part of 'am' but counts as its own landmass: nothing crosses the Darién Gap. +// Atlantic islands, each its own landmass too. +LANDS_LL.push( + {id:'bm',ll:[[-65.18,32.59],[-64.38,32.59],[-64.38,31.99],[-65.18,31.99]]}, + {id:'az',ll:[[-26.07,38.04],[-25.27,38.04],[-25.27,37.44],[-26.07,37.44]]}, + {id:'ic',ll:[[-16.65,28.76],[-15.85,28.76],[-15.85,28.16],[-16.65,28.16]]}, + {id:'cv',ll:[[-23.91,15.22],[-23.11,15.22],[-23.11,14.62],[-23.91,14.62]]}, + {id:'sh',ll:[[-6.12,-15.63],[-5.32,-15.63],[-5.32,-16.23],[-6.12,-16.23]]}, +); +// Pacific islands, each its own landmass. +LANDS_LL.push( + {id:'hi',ll:[[-158.26,21.61],[-157.46,21.61],[-157.46,21.01],[-158.26,21.01]]}, + {id:'gu',ll:[[144.35,13.77],[145.15,13.77],[145.15,13.17],[144.35,13.17]]}, + {id:'pw',ll:[[134.08,7.64],[134.88,7.64],[134.88,7.04],[134.08,7.04]]}, + {id:'mh',ll:[[170.98,7.39],[171.78,7.39],[171.78,6.79],[170.98,6.79]]}, + {id:'pg',ll:[[146.78,-9.14],[147.58,-9.14],[147.58,-9.74],[146.78,-9.74]]}, + {id:'sb',ll:[[159.55,-9.13],[160.35,-9.13],[160.35,-9.73],[159.55,-9.73]]}, + {id:'nc',ll:[[166.06,-21.97],[166.86,-21.97],[166.86,-22.57],[166.06,-22.57]]}, + {id:'fj',ll:[[178.04,-17.84],[178.84,-17.84],[178.84,-18.44],[178.04,-18.44]]}, + {id:'to',ll:[[-175.60,-20.84],[-174.80,-20.84],[-174.80,-21.44],[-175.60,-21.44]]}, + {id:'ws',ll:[[-172.16,-13.53],[-171.36,-13.53],[-171.36,-14.13],[-172.16,-14.13]]}, + {id:'as',ll:[[-171.10,-13.98],[-170.30,-13.98],[-170.30,-14.58],[-171.10,-14.58]]}, + {id:'pf',ll:[[-149.97,-17.23],[-149.17,-17.23],[-149.17,-17.83],[-149.97,-17.83]]}, +); +LANDS_LL.push( + {id:'lk',ll:[[79.9, 9.8], [80.6, 9.6], [81.4, 8.5], [81.9, 7.4], [81.6, 6.4], [80.6, 5.9], [80.0, 6.2], [79.75, 7.2], [79.75, 8.3]]}, + {id:'sa',hide:true,ll:[[-77.5, 8.6], [-75, 10.8], [-71.5, 12.3], [-68, 10.6], [-62, 10.5], [-60, 8.6], [-58.2, 7.3], [-55.2, 6.3], [-52, 5.3], [-50, 1.5], [-48, -1], [-44, -2.5], [-39, -3.5], [-35, -5.5], [-35, -9], [-37.5, -12.5], [-39, -15], [-39.7, -19], [-41, -22], [-44, -23], [-48, -26], [-48.6, -28.5], [-51, -31], [-53, -34], [-58, -34.5], [-57, -37], [-62, -39], [-65, -41], [-64, -43], [-67.5, -46], [-66, -48], [-69, -51], [-68.5, -53], [-70, -55], [-73, -53], [-75, -48], [-73.5, -43], [-73.5, -37], [-71.5, -32], [-71.3, -27], [-70.5, -20], [-71.5, -17], [-76, -14], [-78, -10], [-81, -6], [-80.5, -3], [-80, 0], [-79, 1.5], [-77.5, 4], [-77.4, 7.5]]}, + {id:'tw',ll:[[121.5, 25.35], [122.05, 25.0], [121.85, 24.3], [121.4, 23.0], [120.85, 21.9], [120.6, 22.3], [120.15, 22.9], [120.1, 23.6], [120.55, 24.5], [121.0, 25.1]]}, +); +// Caribbean islands, each its own landmass (#125). +LANDS_LL.push( + {id:'pr',ll:[[-66.50,18.70],[-65.70,18.70],[-65.70,18.10],[-66.50,18.10]]}, + {id:'hs',ll:[[-74.5,18.45],[-72.8,19.95],[-71,19.95],[-69.9,19.75],[-68.3,18.6],[-69,18.15],[-71,17.55],[-72.8,18.05],[-74.5,18.05]]}, + {id:'jm',ll:[[-77.18,18.35],[-76.38,18.35],[-76.38,17.75],[-77.18,17.75]]}, + {id:'cu',ll:[[-82.77,23.39],[-81.97,23.39],[-81.97,22.79],[-82.77,22.79]]}, + {id:'bs',ll:[[-77.75,25.34],[-76.95,25.34],[-76.95,24.74],[-77.75,24.74]]}, + {id:'tt',ll:[[-61.88,10.96],[-61.08,10.96],[-61.08,10.36],[-61.88,10.36]]}, + {id:'bb',ll:[[-59.98,13.42],[-59.18,13.42],[-59.18,12.82],[-59.98,12.82]]}, + {id:'mq',ll:[[-61.43,14.94],[-60.63,14.94],[-60.63,14.34],[-61.43,14.34]]}, + {id:'cw',ll:[[-69.32,12.43],[-68.52,12.43],[-68.52,11.83],[-69.32,11.83]]}, +); +// Indian Ocean islands (#152), Pitcairn (#124), the Aleutians and Sakhalin (#145). +LANDS_LL.push( + {id:'re',ll:[[55.06,-20.62],[55.86,-20.62],[55.86,-21.22],[55.06,-21.22]]}, + {id:'mu',ll:[[57.12,-19.88],[57.92,-19.88],[57.92,-20.48],[57.12,-20.48]]}, + {id:'mg',ll:[[47.12,-18.58],[47.92,-18.58],[47.92,-19.18],[47.12,-19.18]]}, + {id:'sc',ll:[[55.07,-4.35],[55.87,-4.35],[55.87,-4.95],[55.07,-4.95]]}, + {id:'pn',ll:[[-130.50,-24.77],[-129.70,-24.77],[-129.70,-25.37],[-130.50,-25.37]]}, + {id:'al',ll:[[-166.93,54.18],[-166.13,54.18],[-166.13,53.58],[-166.93,53.58]]}, + {id:'sak',ll:[[142.34,47.26],[143.14,47.26],[143.14,46.66],[142.34,46.66]]}, +); +// Places on a continent with no road or fiber in, only the sea: Juneau, Alaska's Arctic coast and Russia's Arctic and Kamchatka (#145). +// `on` is the land they are really part of: your own country may still dig to them over land (isSub()), nobody else's can. +LANDS_LL.push( + {id:'aks',hide:true,on:'am',ll:[[-134.76,58.61],[-133.96,58.61],[-133.96,58.01],[-134.76,58.01]]}, + {id:'swd',hide:true,on:'am',ll:[[-165.78,64.82],[-164.98,64.82],[-164.98,64.22],[-165.78,64.22]]}, + {id:'nsl',hide:true,on:'am',ll:[[-157.15,71.58],[-156.35,71.58],[-156.35,70.98],[-157.15,70.98]]}, + {id:'tay',hide:true,on:'eu',ll:[[80.25,73.81],[81.05,73.81],[81.05,73.21],[80.25,73.21]]}, + {id:'lap',hide:true,on:'eu',ll:[[128.47,71.94],[129.27,71.94],[129.27,71.34],[128.47,71.34]]}, + {id:'pvk',hide:true,on:'eu',ll:[[169.91,70.00],[170.71,70.00],[170.71,69.40],[169.91,69.40]]}, + {id:'chu',hide:true,on:'eu',ll:[[177.05,65.05],[177.85,65.05],[177.85,64.45],[177.05,64.45]]}, + {id:'kam',hide:true,on:'eu',ll:[[158.25,53.32],[159.05,53.32],[159.05,52.72],[158.25,52.72]]}, +); +// The Maldives. +LANDS_LL.push( + {id:'mv',ll:[[73.11,4.48],[73.91,4.48],[73.91,3.88],[73.11,3.88]]}, +); +// The Visayas and Mindanao: Cebu and Davao are islands of their own, reached from Luzon only by cable. +LANDS_LL.push( + {id:'ceb',ll:[[123.3,11.3],[124.1,11.3],[124.1,9.4],[123.3,9.4]]}, + {id:'mdn',ll:[[121.9,7],[123,8.4],[125.4,9.8],[126.6,7.5],[126.2,5.6],[125,5.6],[122,6.6]]}, +); +// Greenland's towns and Iqaluit: no road between them, and no fiber over the ice, only the sea. Greenland's towns share one +// island ('grl'), so Greenland may dig between them; Iqaluit is on Baffin Island. +LANDS_LL.push( + {id:'baf',hide:true,ll:[[-68.92,64.05],[-68.12,64.05],[-68.12,63.45],[-68.92,63.45]]}, + {id:'gln',hide:true,on:'grl',ll:[[-52.12,64.48],[-51.32,64.48],[-51.32,63.88],[-52.12,63.88]]}, + {id:'glq',hide:true,on:'grl',ll:[[-46.44,61.02],[-45.64,61.02],[-45.64,60.42],[-46.44,60.42]]}, + {id:'gls',hide:true,on:'grl',ll:[[-54.07,67.24],[-53.27,67.24],[-53.27,66.64],[-54.07,66.64]]}, + {id:'gla',hide:true,on:'grl',ll:[[-53.27,69.01],[-52.47,69.01],[-52.47,68.41],[-53.27,68.41]]}, +); +// The eastern Caribbean capitals, each its own island, on ECFS and Southern Caribbean Fiber +LANDS_LL.push( + {id:'anu',hide:true,ll:[[-62.25,17.42],[-61.45,17.42],[-61.45,16.82],[-62.25,16.82]]}, + {id:'kna',hide:true,ll:[[-63.12,17.60],[-62.32,17.60],[-62.32,17.00],[-63.12,17.00]]}, + {id:'dma',hide:true,ll:[[-61.79,15.60],[-60.99,15.60],[-60.99,15.00],[-61.79,15.00]]}, + {id:'lca',hide:true,ll:[[-61.39,14.31],[-60.59,14.31],[-60.59,13.71],[-61.39,13.71]]}, + {id:'vct',hide:true,ll:[[-61.62,13.46],[-60.82,13.46],[-60.82,12.86],[-61.62,12.86]]}, + {id:'grd',hide:true,ll:[[-62.15,12.35],[-61.35,12.35],[-61.35,11.75],[-62.15,11.75]]}, +); +// Malta and Cyprus, islands reached only by their cables +LANDS_LL.push( + {id:'cyp',hide:true,ll:[[32.98,35.49],[33.78,35.49],[33.78,34.89],[32.98,34.89]]}, + {id:'mlt',hide:true,ll:[[14.11,36.20],[14.91,36.20],[14.91,35.60],[14.11,35.60]]}, +); +// Bahrain, an island of its own: reached by its cables (and the causeway's fibre, which the game leaves out). +LANDS_LL.push( + {id:'bhr',hide:true,ll:[[50.19,26.53],[50.99,26.53],[50.99,25.93],[50.19,25.93]]}, +); +// Brunei, Timor-Leste and the Pacific capitals, each its own island +LANDS_LL.push( + {id:'brn',hide:true,ll:[[114.54,5.20],[115.34,5.20],[115.34,4.60],[114.54,4.60]]}, + {id:'tim',hide:true,ll:[[125.17,-8.26],[125.97,-8.26],[125.97,-8.86],[125.17,-8.86]]}, + {id:'kir',hide:true,ll:[[172.58,1.63],[173.38,1.63],[173.38,1.03],[172.58,1.03]]}, + {id:'pnp',hide:true,ll:[[157.76,7.22],[158.56,7.22],[158.56,6.62],[157.76,6.62]]}, + {id:'nru',hide:true,ll:[[166.52,-0.25],[167.32,-0.25],[167.32,-0.85],[166.52,-0.85]]}, + {id:'tuv',hide:true,ll:[[178.80,-8.22],[179.60,-8.22],[179.60,-8.82],[178.80,-8.82]]}, + {id:'vut',hide:true,ll:[[167.92,-17.43],[168.72,-17.43],[168.72,-18.03],[167.92,-18.03]]}, +); +// Moroni, São Tomé and Malabo, island capitals on their cables +LANDS_LL.push( + {id:'com',hide:true,ll:[[42.86,-11.40],[43.66,-11.40],[43.66,-12.00],[42.86,-12.00]]}, + {id:'stp',hide:true,ll:[[6.33,0.64],[7.13,0.64],[7.13,0.04],[6.33,0.04]]}, + {id:'bio',hide:true,ll:[[8.38,4.05],[9.18,4.05],[9.18,3.45],[8.38,3.45]]}, +); +const LANDS=LANDS_LL.map(l=>({id:l.id,hide:true,pts:l.ll.map(q=>proj(q[0],q[1]))})); diff --git a/src/game/20-world/30-coastline.js b/src/game/20-world/30-coastline.js new file mode 100644 index 0000000..f6c8516 --- /dev/null +++ b/src/game/20-world/30-coastline.js @@ -0,0 +1,23 @@ +// Drawn coastline: Natural Earth 1:50m land, simplified (tight around cities, looser elsewhere), lon/lat rings. Built by scripts/build-land.mjs. +// LANDS above is only the coarse landmass test that decides which landmass a city sits on (subsea vs overland); it is not drawn. +const COAST_LL=[[[86.89,73.89],[85.79,73.44],[86.68,73.11],[85.91,73.39],[87.57,73.81],[86,74.32],[87.23,74.36],[85.79,74.65],[87.47,75.01],[87.01,75.17],[94.16,75.96],[92.86,75.98],[93.26,76.1],[95.58,76.14],[96.08,76.08],[95.65,75.89],[96.5,75.89],[98.66,76.24],[99.77,76.03],[99.54,75.8],[99.82,76.14],[98.8,76.48],[101.6,76.44],[100.93,76.56],[101.1,76.7],[100.91,76.9],[104.01,77.73],[106.06,77.39],[104.2,77.1],[107.43,76.93],[106.42,76.51],[111.11,76.72],[112.62,76.38],[112.66,76.05],[113.27,76.25],[113.56,75.89],[113.86,75.92],[113.57,75.57],[112.45,75.83],[113.73,75.45],[112.92,75.02],[107.27,73.62],[105.14,72.78],[110.87,73.73],[109.67,73.8],[110.26,74.02],[111.55,74.03],[111.23,73.97],[112.15,73.71],[113.03,73.91],[113.42,73.65],[113.16,73.46],[113.49,73.35],[113.16,72.77],[113.67,72.64],[113.22,72.81],[113.89,73.35],[113.51,73.5],[114.06,73.58],[118.45,73.59],[118.94,73.48],[118.46,73.46],[118.43,73.25],[119.75,72.98],[122.54,72.88],[123.62,73.19],[123.32,73.43],[123.41,73.64],[124.54,73.75],[126.55,73.33],[127.74,73.48],[129.1,73.11],[128.6,72.9],[129.25,72.7],[128.42,72.53],[129.28,72.44],[129.28,72.09],[127.73,72.41],[128.91,71.75],[129.21,71.92],[129.46,71.74],[128.84,71.66],[129.76,71.12],[131.02,70.75],[132.04,71.24],[132.65,71.93],[133.69,71.43],[136.09,71.62],[137.94,71.13],[138.32,71.33],[137.92,71.38],[138.23,71.6],[139.99,71.49],[139.72,71.89],[139.36,71.95],[140.19,72.19],[139.18,72.16],[139.14,72.33],[141.08,72.59],[140.65,72.84],[140.81,72.89],[146.25,72.44],[144.29,72.19],[146.83,72.29],[146.11,71.95],[146.23,72.14],[145.76,72.23],[145.76,71.94],[145.07,71.93],[145.19,71.7],[147.26,72.33],[149.5,72.16],[150.02,71.9],[148.92,71.71],[150.67,71.45],[150.1,71.23],[151.58,71.29],[152.09,71.02],[151.76,70.98],[152.51,70.83],[155.89,71.1],[158.7,70.94],[159.91,70.51],[159.83,69.78],[160.91,69.61],[161.34,68.9],[160.86,68.54],[161.56,68.9],[161.54,69.38],[163.2,69.72],[166.89,69.5],[167.86,69.73],[168.3,69.27],[169.31,69.08],[169.61,68.79],[170.54,68.83],[171,69.14],[170.58,69.58],[170.16,69.63],[170.49,70.11],[173.28,69.82],[175.92,69.9],[179.87,69.01],[180,68.98],[181.13,68.75],[181.94,68.27],[182.2,68.34],[181.63,68.57],[184.65,67.68],[184.63,67.36],[185.15,67.35],[185.08,66.62],[185.61,66.34],[185.91,66.47],[185.94,66.23],[186.22,66.43],[185.77,66.63],[185.91,66.94],[185.45,67.09],[186.84,67.07],[186.74,66.84],[187.48,66.95],[186.99,67.06],[188.2,66.93],[189.4,66.25],[190.27,66.06],[189.6,65.93],[189.33,65.62],[188.55,65.79],[188.83,65.5],[187.22,65.68],[187.77,65.45],[187.34,65.25],[187.79,65.05],[186.93,64.85],[187.62,64.43],[187.1,64.53],[186.84,64.28],[186.67,64.54],[186.27,64.36],[184.56,64.82],[183.91,65.47],[181.59,65.49],[181.06,66.03],[181.47,66.4],[181.08,66.18],[180.86,66.37],[180.22,66.02],[180.65,65.52],[179.45,64.82],[178.52,64.6],[176.41,65.07],[177.22,64.86],[176.06,64.96],[174.55,64.68],[175.68,64.78],[176.06,64.9],[176.25,64.84],[176.35,64.71],[176.14,64.59],[176.51,64.68],[176.84,64.63],[177.05,64.72],[177.39,64.77],[177.47,64.74],[177.41,64.57],[177.43,64.44],[177.95,64.22],[178.13,64.24],[178.23,64.36],[178.38,64.26],[178.48,64.13],[178.45,64.01],[178.65,63.97],[178.69,63.84],[178.47,63.57],[179.33,63.19],[179.57,62.77],[179.12,62.32],[177.02,62.78],[177.16,62.56],[172.86,61.47],[172.39,61.06],[170.61,60.43],[170.35,59.97],[169.23,60.6],[167.23,60.41],[166.27,59.86],[166.35,60.48],[165.09,60.1],[164.96,59.84],[163.74,60.03],[161.96,58.08],[162.39,57.72],[162.66,57.95],[163.23,57.79],[162.76,57.24],[162.8,56.81],[163.26,56.69],[163.34,56.23],[162.84,56.06],[162.63,56.23],[163.04,56.52],[162.67,56.49],[162.09,56.09],[161.72,55.5],[162.1,54.75],[160.07,54.19],[159.84,53.78],[159.96,53.55],[159.9,53.38],[160,53.27],[160.03,53.13],[159.95,53.13],[159.77,53.23],[159.59,53.24],[158.95,53.05],[158.75,52.91],[158.56,53.05],[158.47,53.03],[158.43,52.96],[158.61,52.87],[158.48,52.63],[158.49,52.38],[158.33,52.09],[158.1,51.81],[156.75,50.97],[155.56,55.2],[156.02,56.75],[156.85,57.29],[156.87,57.8],[158.27,58.01],[162.07,60.47],[163.71,60.92],[163.56,61.03],[164.01,61.34],[163.8,61.46],[164.21,62.29],[165.4,62.49],[164.42,62.71],[163.33,62.55],[163.09,61.57],[162.39,61.66],[160.17,60.64],[160.38,61.02],[159.79,60.96],[160.31,61.89],[157.09,61.68],[154.29,59.83],[154.15,59.53],[154.97,59.45],[155.16,59.19],[153.36,59.21],[152.82,58.93],[151.33,58.88],[151.12,59.08],[152.26,59.22],[149.64,59.77],[148.8,59.53],[148.96,59.37],[148.73,59.26],[146.54,59.46],[146.05,59.17],[145.55,59.41],[142.58,59.24],[140.79,58.3],[140.45,57.81],[138.66,56.97],[137.69,56.14],[135.26,54.94],[135.26,54.73],[135.85,54.58],[136.8,54.62],[136.72,53.8],[137.16,53.82],[137.14,54.18],[137.67,54.28],[137.34,54.1],[137.84,53.95],[137.25,53.55],[137.95,53.6],[138.53,53.96],[138.25,53.52],[138.45,53.54],[138.66,54.3],[139.71,54.28],[141.38,53.29],[141.18,53.01],[140.84,53.09],[141.26,52.84],[141.13,52.43],[141.49,52.18],[140.52,50.8],[140.38,48.96],[138.11,46.25],[135.13,43.53],[133.16,42.7],[133.06,42.72],[133,42.81],[132.86,42.79],[132.71,42.88],[132.3,42.88],[132.31,43.31],[132.03,43.12],[131.87,43.1],[132.01,43.28],[131.94,43.3],[131.72,43.2],[131.39,42.82],[131.16,42.63],[130.71,42.66],[130.83,42.52],[130.73,42.33],[129.76,41.71],[129.71,40.86],[127.57,39.78],[127.4,39.21],[128.33,38.68],[129.42,37.06],[129.56,35.95],[129.21,35.18],[128.51,35.1],[128.44,34.87],[127.71,34.96],[127.72,34.72],[127.4,34.82],[127.32,34.46],[127.25,34.76],[126.53,34.31],[126.27,34.67],[126.59,34.82],[126.29,35.15],[126.69,36.01],[126.54,36.17],[126.55,36.48],[126.49,36.69],[126.39,36.65],[126.18,36.69],[126.16,36.77],[126.22,36.87],[126.49,37.01],[126.78,36.95],[126.87,36.82],[126.98,36.94],[126.87,36.98],[126.74,37.19],[126.79,37.3],[126.65,37.45],[126.66,37.55],[126.56,37.72],[126.63,37.78],[126.37,37.88],[126.12,37.74],[126.05,37.87],[125.94,37.87],[125.77,37.99],[125.41,37.72],[124.99,37.93],[125.21,38.08],[124.69,38.13],[125.55,38.69],[125.17,38.81],[125.36,39.53],[124.64,39.61],[124.35,40.01],[122.84,39.6],[121.16,38.73],[121.11,38.92],[121.82,39.39],[121.27,39.55],[122.26,40.5],[121.83,40.97],[121.18,40.9],[120.48,40.23],[119.39,39.75],[118.98,39.18],[117.78,39.13],[117.65,38.42],[118.94,38.04],[119.11,37.2],[119.76,37.15],[120.75,37.83],[121.64,37.46],[122.67,37.4],[122.34,36.83],[121.93,36.96],[120.81,36.63],[120.64,36.13],[120.18,36.2],[120.29,35.98],[119.22,35.01],[119.2,34.75],[120.27,34.27],[120.86,32.66],[121.34,32.43],[121.4,32.37],[121.45,32.15],[121.68,32.05],[121.83,31.9],[121.87,31.7],[121.76,31.7],[121.35,31.86],[120.97,31.87],[120.79,32.03],[120.52,32.11],[120.07,31.96],[120.19,31.91],[120.5,32.02],[120.71,31.98],[120.79,31.82],[121.06,31.72],[121.66,31.32],[121.79,31.16],[121.88,30.92],[121.42,30.79],[121,30.56],[120.82,30.35],[120.45,30.39],[120.23,30.25],[120.5,30.3],[120.63,30.13],[120.91,30.16],[121.16,30.3],[121.26,30.3],[121.43,30.23],[121.68,29.98],[122.08,29.87],[121.91,29.78],[121.51,29.48],[121.97,29.49],[121.92,29.13],[121.45,29.13],[121.68,28.95],[121.47,28.64],[121.61,28.29],[121.15,28.33],[120.75,28.01],[120.09,26.67],[119.59,26.79],[119.88,26.33],[119.14,26.12],[119.62,26],[119.62,25.39],[119.18,25.45],[119.29,25.23],[118.98,25.21],[118.66,24.62],[117.84,24.47],[118.06,24.25],[117.37,23.59],[116.91,23.65],[116.47,22.95],[115.64,22.85],[115.5,22.72],[115.38,22.72],[115.2,22.82],[114.85,22.62],[114.75,22.63],[114.71,22.74],[114.65,22.75],[114.54,22.62],[114.55,22.53],[114.34,22.59],[114.27,22.54],[114.34,22.4],[114.27,22.3],[113.9,22.4],[114.01,22.51],[113.83,22.61],[113.62,22.86],[113.62,23.13],[113.45,23.05],[113.44,22.94],[113.33,22.91],[113.55,22.59],[113.59,22.35],[113.55,22.22],[113.15,22.08],[113.09,22.21],[113.01,22.12],[112.99,21.94],[112.9,21.88],[112.81,21.95],[112.66,21.86],[112.36,21.98],[112.3,21.74],[111.94,21.85],[111.6,21.56],[110.41,21.34],[110.16,20.94],[110.52,20.46],[110.12,20.26],[109.66,20.92],[109.93,21.48],[109.52,21.69],[109.08,21.44],[108.48,21.9],[108.5,21.63],[107.81,21.5],[107.16,20.95],[106.68,21],[106.52,20.29],[105.98,19.94],[105.62,18.97],[106.5,17.95],[106.35,17.77],[108.82,15.38],[109.3,13.86],[109.45,12.6],[109.22,12.65],[109.2,11.73],[108.99,11.34],[108.18,10.92],[108.1,10.9],[108,10.72],[107.84,10.7],[107.26,10.4],[107.09,10.5],[107.01,10.66],[106.95,10.4],[106.81,10.43],[106.73,10.54],[106.61,10.47],[106.74,10.44],[106.76,10.3],[106.47,10.3],[106.73,10.19],[106.79,10.12],[106.6,9.86],[106.14,10.22],[106.51,9.82],[106.57,9.64],[106.48,9.56],[106.38,9.56],[105.83,10],[106.16,9.59],[106.21,9.5],[106.17,9.4],[104.77,8.6],[105.03,10.07],[104.26,10.54],[103.59,10.55],[103.65,11.06],[103.15,10.91],[103.12,11.46],[102.65,12.15],[101.72,12.69],[101.44,12.62],[100.9,12.65],[100.86,12.72],[100.96,13.43],[100.6,13.57],[100.54,13.51],[100.23,13.48],[100.02,13.35],[99.99,13.24],[100.09,13.04],[99.96,12.69],[100.01,12.35],[99.16,10.32],[99.25,9.27],[99.83,9.29],[100.42,7.19],[101.5,6.86],[103.2,5.26],[103.45,4.67],[103.48,2.84],[103.81,2.58],[104.22,1.72],[104.28,1.42],[104.18,1.37],[103.98,1.62],[103.99,1.46],[103.69,1.45],[103.48,1.33],[103.36,1.55],[102.73,1.86],[102.55,2.04],[102.15,2.25],[101.78,2.57],[101.52,2.68],[101.3,2.89],[101.35,3.01],[101.3,3.25],[100.72,3.97],[100.8,4.02],[100.66,4.23],[100.26,6.18],[99.6,7.36],[98.24,8.42],[98.7,10.19],[98.56,10.03],[98.47,10.68],[98.88,11.72],[98.64,11.74],[98.57,13.16],[98.2,13.98],[98.11,13.71],[97.81,14.86],[97.58,16.02],[97.72,16.57],[97.38,16.52],[96.85,17.4],[96.77,16.71],[96.43,16.5],[96.19,16.77],[96.32,16.44],[95.39,15.72],[95.35,16.1],[95.18,15.83],[94.94,15.82],[94.89,16.18],[94.66,15.9],[94.7,16.51],[94.23,16.02],[94.59,17.57],[94.05,19.29],[93.93,18.9],[93.49,19.37],[93.83,19.24],[94,19.44],[93.71,19.91],[93.25,20.07],[93.13,19.86],[93.07,20.38],[92.83,20.18],[92.74,20.56],[92.72,20.3],[92.31,20.79],[91.86,22.35],[91.53,22.71],[91.48,22.88],[91.22,22.64],[90.95,22.6],[90.63,23.09],[90.6,23.59],[90.56,23.42],[90.27,23.46],[90.59,23.27],[90.6,23.13],[90.47,23.05],[90.55,22.91],[90.46,22.88],[90.43,22.75],[90.61,22.36],[90.55,22.22],[90.16,21.82],[90.21,22.16],[89.96,22.02],[89.89,22.31],[89.98,22.47],[89.88,22.39],[89.57,21.77],[89.48,22.28],[89.35,21.72],[89.05,22.09],[89.05,21.65],[88.75,21.58],[88.64,22.12],[88.58,21.66],[88.06,21.69],[88.2,22.14],[87.94,22.37],[88.16,22.12],[87.95,21.83],[86.86,21.24],[86.98,20.7],[86.75,20.31],[86.22,19.9],[85.25,19.76],[85.18,19.59],[85.44,19.63],[84.11,18.29],[82.36,17.1],[82.26,16.56],[81.29,16.34],[80.98,15.76],[80.38,15.79],[80.1,14.8],[80.18,14.48],[80.11,14.21],[80.31,13.49],[80.16,13.71],[80.06,13.61],[80.34,13.36],[80.23,12.69],[80.14,12.45],[79.86,11.99],[79.84,10.32],[79.31,10.26],[78.92,9.45],[79.41,9.19],[78.42,9.1],[78.06,8.38],[77.3,8.15],[76.4,9.24],[76.35,9.92],[74.94,12.56],[74.38,14.49],[73.47,16.05],[73.15,17.53],[72.87,18.64],[73.01,19.02],[72.97,19.15],[72.83,18.98],[72.8,19.08],[72.81,19.3],[72.99,19.28],[72.79,19.36],[72.75,19.45],[72.8,19.52],[72.73,19.58],[72.67,19.83],[72.9,20.67],[72.61,21.46],[73.11,21.75],[72.54,21.7],[72.7,21.97],[72.52,21.98],[72.81,22.23],[72.18,22.27],[72.04,21.82],[72.25,21.53],[72.02,21.16],[70.72,20.74],[68.97,22.29],[70.18,22.57],[70.49,23.09],[69.67,22.76],[69.24,22.85],[68.42,23.57],[68.78,23.85],[68.23,23.6],[68.16,23.86],[68.11,23.75],[68.04,23.85],[67.95,23.83],[67.86,23.9],[67.82,23.83],[67.67,23.81],[67.65,23.92],[67.56,23.88],[67.31,24.17],[67.17,24.76],[66.7,24.86],[66.7,25.23],[66.43,25.58],[66.22,25.59],[66.13,25.49],[66.36,25.51],[66.47,25.45],[66.24,25.46],[65.68,25.35],[61.41,25.1],[60.51,25.44],[59.05,25.42],[57.34,25.79],[57.21,26.04],[57.2,26.16],[56.73,27.13],[56.28,27.19],[55.42,26.77],[55.29,26.79],[54.9,26.56],[54.64,26.51],[54.52,26.59],[53.71,26.73],[52.48,27.62],[51.52,27.91],[50.07,30.2],[49.56,30.03],[49,30.51],[48.83,30.04],[47.98,30.01],[48.15,29.57],[47.72,29.39],[48.05,29.35],[48.8,27.72],[50.15,26.66],[50.15,26.1],[50.1,26.12],[50.08,25.96],[50.24,25.62],[50.46,25.42],[50.56,25.09],[50.81,24.79],[50.85,24.89],[50.76,25.45],[51,25.98],[51.26,26.15],[51.54,25.9],[51.57,25.78],[51.49,25.53],[51.61,25.05],[51.43,24.67],[51.27,24.61],[51.42,24.53],[51.31,24.34],[51.54,24.29],[51.6,24.34],[51.67,24.25],[51.77,24.25],[51.84,24.01],[52.12,23.97],[52.51,24.11],[53.03,24.15],[53.89,24.08],[54.4,24.28],[54.75,24.81],[55.1,25.04],[55.52,25.5],[55.94,25.79],[56.17,26.21],[56.31,26.24],[56.41,26.35],[56.37,25.8],[56.3,25.65],[56.36,25.57],[56.37,25.02],[56.64,24.47],[56.91,24.15],[57.22,23.92],[58.58,23.64],[59.84,22.42],[58.47,20.41],[58.17,20.59],[57.86,20.24],[57.81,19.02],[56.82,18.75],[56.38,17.99],[55.48,17.84],[55.06,17.04],[54.07,17],[52.45,16.39],[52.22,15.66],[51.6,15.34],[49.35,14.64],[48.67,14.05],[45.66,13.34],[45.04,12.82],[44.26,12.64],[43.49,12.7],[42.94,14.94],[42.66,15.23],[42.7,16.74],[41.66,18.01],[40.76,19.75],[40.08,20.27],[39.88,20.29],[39.73,20.39],[39.27,20.97],[39.09,21.31],[39.15,21.52],[38.99,21.88],[39.09,22.39],[39.01,22.77],[38.88,22.88],[38.94,22.88],[38.29,23.91],[37.54,24.29],[37.15,25.29],[35.18,28.04],[34.62,28.06],[34.97,29.55],[34.22,27.76],[33.25,28.57],[32.72,29.52],[32.56,29.97],[32.47,29.93],[32.49,29.85],[32.36,29.63],[32.4,29.53],[32.56,29.39],[32.66,28.93],[33.55,27.9],[33.96,26.65],[35.2,24.47],[35.78,23.94],[35.51,23.78],[35.7,22.95],[36.83,22.1],[37.26,21.11],[37.47,18.82],[38.57,18.07],[39.5,15.53],[39.79,15.12],[39.86,15.47],[40.2,15.01],[41.18,14.62],[43.3,12.46],[43.34,12.03],[42.54,11.51],[43.16,11.57],[44.28,10.47],[44.94,10.44],[45.82,10.84],[46.56,10.75],[47.4,11.17],[50.11,11.53],[50.79,11.98],[51.26,11.83],[51.03,10.44],[51.39,10.39],[50.93,10.34],[50.82,9.43],[47.98,4.5],[46.05,2.47],[43.72,0.86],[41.39,-1.87],[40.22,-2.69],[39.23,-4.67],[38.8,-6.07],[39.54,-7.02],[39.29,-7.52],[39.3,-8.44],[39.72,-10],[40.61,-10.66],[40.43,-12.94],[40.83,-14.79],[39.84,-16.44],[37.51,-17.57],[36.41,-18.77],[34.95,-19.81],[34.65,-19.7],[35.31,-22.4],[35.45,-22.12],[35.54,-22.3],[35.44,-24.17],[34.99,-24.65],[32.79,-25.64],[32.59,-26],[32.85,-26.27],[32.96,-26.08],[32.89,-26.83],[32.38,-28.5],[31.34,-29.38],[29.97,-31.32],[27.86,-33.05],[26.61,-33.71],[25.81,-33.74],[25.57,-34.04],[22.55,-34.01],[21.79,-34.37],[19.64,-34.75],[19.39,-34.6],[19.3,-34.62],[19.33,-34.49],[19.24,-34.41],[19.15,-34.42],[19.1,-34.35],[18.83,-34.36],[18.81,-34.11],[18.75,-34.08],[18.53,-34.09],[18.46,-34.17],[18.46,-34.35],[18.41,-34.3],[18.33,-34.07],[18.35,-33.94],[18.47,-33.89],[18.43,-33.72],[18.26,-33.42],[18.16,-33.36],[17.88,-32.96],[17.85,-32.83],[17.89,-32.75],[17.97,-32.71],[18.04,-32.78],[18.12,-32.75],[18.25,-32.65],[18.33,-32.5],[18.21,-31.74],[16.74,-29.01],[15.29,-27.28],[14.5,-24.2],[14.46,-22.45],[11.78,-18],[11.75,-15.83],[12.55,-13.44],[13.79,-11.81],[13.83,-10.93],[13,-9.05],[13.38,-8.37],[12.28,-6.12],[13.07,-5.87],[12.45,-6],[12.24,-5.81],[11.78,-4.57],[9.72,-2.47],[10.06,-2.55],[9.62,-2.37],[9.04,-1.31],[9.5,-1.55],[9.06,-1.3],[8.7,-0.59],[8.95,-0.69],[9.3,-0.35],[9.35,0.34],[9.8,0.04],[10,0.2],[9.33,0.55],[9.62,0.58],[9.6,1.05],[9.39,1.14],[9.81,1.93],[9.95,3.08],[9.56,3.8],[9.69,4.06],[9,4.09],[8.92,4.55],[8.57,4.53],[8.25,4.92],[8.29,4.56],[7.08,4.72],[6.92,4.39],[6.77,4.72],[6.86,4.37],[6.08,4.29],[5.49,4.84],[5.37,5.34],[5.55,5.47],[5.2,5.53],[5.46,5.61],[5.11,5.64],[4.86,6.03],[4.43,6.35],[4.13,6.41],[3.45,6.43],[3.75,6.58],[3.72,6.6],[3.43,6.52],[3.34,6.4],[1.82,6.26],[-2,4.76],[-3.25,5.11],[-3.02,5.13],[-3.2,5.35],[-3.35,5.13],[-5.28,5.21],[-5.06,5.13],[-7.54,4.35],[-8.26,4.59],[-11.73,7.09],[-12.49,7.39],[-12.48,7.75],[-12.85,7.82],[-13.27,8.43],[-12.89,8.63],[-13.18,8.58],[-13.06,8.88],[-13.69,9.54],[-13.69,9.93],[-14.43,10.25],[-14.59,10.77],[-14.89,10.97],[-15.01,10.8],[-15.05,11.14],[-15.39,11.22],[-15.43,11.5],[-15.07,11.6],[-15.5,11.78],[-15.08,11.97],[-15.94,11.79],[-16.79,12.47],[-16.44,12.61],[-16.77,12.63],[-16.75,13.43],[-16.41,13.27],[-15.43,13.47],[-16.44,13.35],[-16.77,13.9],[-16.62,14.04],[-17.53,14.75],[-16.57,15.73],[-16.08,17.55],[-16.09,18.52],[-16.52,19.36],[-16.21,20.23],[-16.88,21.09],[-17.1,20.86],[-16.93,21.9],[-16.36,22.59],[-15.9,23.84],[-14.91,24.72],[-14.47,26.16],[-13.58,26.74],[-12.95,27.91],[-11.55,28.31],[-10.2,29.38],[-9.67,30.11],[-9.81,31.42],[-9.25,32.57],[-8.51,33.25],[-6.9,33.97],[-5.92,35.79],[-5.28,35.9],[-5.25,35.61],[-4.63,35.21],[-2.97,35.41],[-2.84,35.13],[-1.91,35.09],[1.26,36.52],[3.78,36.9],[5.29,36.65],[6.49,37.09],[7.91,36.86],[9.69,37.34],[9.83,37.14],[10.2,37.21],[10.41,36.73],[10.95,37.06],[11.13,36.87],[10.49,36.26],[11.12,35.24],[10.06,34.21],[10.31,33.73],[10.96,33.63],[11.2,33.25],[12.28,32.86],[13.28,32.92],[15.18,32.39],[15.71,31.43],[17.83,30.93],[18.94,30.29],[19.59,30.41],[20.01,30.8],[19.93,31.82],[20.12,32.22],[21.63,32.94],[23.09,32.62],[23.29,32.21],[24.88,31.98],[25.23,31.53],[26.77,31.47],[29.07,30.83],[30.22,31.26],[30.57,31.47],[30.92,31.57],[30.56,31.42],[31,31.46],[31.08,31.6],[32.14,31.34],[31.89,31.48],[31.77,31.29],[32.01,31.22],[32.1,31.09],[32.28,31.2],[32.21,31.29],[32.6,31.07],[33.67,31.13],[34.48,31.59],[35.98,34.55],[35.81,36.31],[36.18,36.81],[35.39,36.57],[34.7,36.82],[33.69,36.18],[32.79,36.04],[31.24,36.82],[30.65,36.87],[30.45,36.27],[29.69,36.16],[28.97,36.72],[27.46,36.71],[28.24,37.03],[27.26,36.98],[27.53,37.16],[27.07,37.66],[27.23,37.98],[26.29,38.28],[26.44,38.64],[26.67,38.34],[27.14,38.45],[26.76,38.71],[27.01,38.89],[26.68,39.29],[26.9,39.55],[26.09,39.52],[26.18,39.99],[26.74,40.4],[27.73,40.33],[27.85,40.38],[27.73,40.48],[27.99,40.49],[27.93,40.38],[27.96,40.37],[29.01,40.39],[29.05,40.42],[28.79,40.53],[29.05,40.65],[29.85,40.74],[29.36,40.81],[29.12,40.94],[29.05,41.01],[29.15,41.22],[29.92,41.15],[30.35,41.2],[31.25,41.11],[33.28,42],[35,42.06],[35.3,41.73],[36.05,41.68],[36.41,41.27],[38.38,40.93],[39.43,41.11],[40.13,40.94],[41.41,41.42],[41.76,41.97],[41.42,42.74],[38.72,44.29],[36.63,45.15],[36.87,45.43],[37.65,45.38],[37.93,46],[38.49,46.09],[37.77,46.64],[38.5,46.66],[38.44,46.81],[39.27,47.04],[39.02,47.27],[35.83,46.62],[35.02,46.11],[35.23,46.44],[34.85,46.19],[35.02,45.7],[35.46,45.32],[36.57,45.39],[36.39,45.07],[35.47,45.1],[33.91,44.39],[33.45,44.55],[33.55,45.1],[32.51,45.4],[33.67,45.95],[33.59,46.1],[31.83,46.28],[32.01,46.43],[31.56,46.56],[32.58,46.62],[32.05,46.64],[31.76,47.21],[31.87,46.65],[30.8,46.55],[30.22,45.87],[29.63,45.72],[29.56,44.84],[28.89,44.92],[28.56,43.5],[28.13,43.4],[27.89,42.75],[27.48,42.47],[27.98,42.05],[27.99,41.86],[28.2,41.56],[29.06,41.23],[28.96,41.01],[28.78,40.97],[28.17,41.08],[27.92,40.99],[27.5,40.97],[27.43,40.84],[26.2,40.07],[26.79,40.63],[24.48,40.95],[23.76,40.75],[24.34,40.15],[23.73,40.33],[23.95,39.97],[23.43,40.26],[23.63,39.92],[22.81,40.58],[22.59,40.04],[23.23,39.36],[23.33,39.18],[23.22,39.1],[23.12,39.13],[23.16,39.26],[22.99,39.33],[22.84,39.26],[22.97,39.03],[23.07,39.04],[22.8,38.9],[22.57,38.87],[23.25,38.66],[23.37,38.53],[23.57,38.49],[23.68,38.35],[23.97,38.27],[24.06,37.82],[24.05,37.71],[23.97,37.68],[23.5,38.03],[23.03,37.88],[23.15,37.8],[23.2,37.62],[23.39,37.58],[23.49,37.44],[23.16,37.33],[23.1,37.36],[23.1,37.44],[22.94,37.52],[22.78,37.59],[22.73,37.54],[23.06,36.85],[23.04,36.64],[23.11,36.55],[22.83,36.69],[22.78,36.79],[22.72,36.79],[22.49,36.45],[22.08,37.03],[21.89,36.74],[21.58,37.08],[21.68,37.39],[21.12,37.89],[21.83,38.33],[22.24,38.19],[22.92,37.96],[22.89,38.05],[23.12,38.07],[23.18,38.13],[23.15,38.18],[22.83,38.23],[22.42,38.44],[22.23,38.35],[21.11,38.39],[20.77,38.87],[21.12,39.03],[20.3,39.33],[19.85,40.04],[19.4,40.28],[19.58,41.79],[18.65,42.44],[17.04,43.02],[17.72,42.85],[16.9,43.39],[15.99,43.52],[15.19,44.17],[15.47,44.27],[14.55,45.3],[14.31,45.34],[13.86,44.84],[13.52,45.48],[13.78,45.63],[13.63,45.77],[12.27,45.45],[12.52,44.97],[12.25,44.72],[12.4,44.22],[13.56,43.57],[14.01,42.69],[14.54,42.24],[15.17,41.93],[16.17,41.9],[15.9,41.51],[17.96,40.65],[18.48,40.1],[18.34,39.82],[17.87,40.28],[16.93,40.46],[16.52,39.75],[17.11,39.38],[17.17,39],[16.62,38.8],[16.06,37.94],[15.72,37.94],[15.64,38.18],[16.21,38.94],[15.69,39.99],[14.95,40.24],[14.77,40.67],[14.34,40.6],[14.46,40.73],[14.05,40.81],[13.86,41.13],[13.67,41.26],[13.25,41.29],[13.09,41.24],[12.85,41.41],[12.63,41.47],[12.08,41.94],[11.81,42.08],[11.64,42.29],[11.3,42.42],[11.1,42.42],[11.18,42.46],[11.17,42.53],[10.51,42.97],[10.19,43.95],[9.73,44.1],[9.29,44.32],[8.76,44.42],[8.55,44.35],[8.29,44.14],[6.72,43.37],[6.57,43.2],[6.11,43.07],[5.81,43.1],[5.41,43.23],[5.32,43.35],[5.07,43.37],[5.06,43.44],[4.71,43.37],[4.22,43.48],[4.05,43.59],[3.91,43.56],[3.16,43.08],[3.09,42.59],[3.31,42.29],[3.17,42.26],[3.15,42.16],[3.24,42.08],[3.25,41.94],[3,41.77],[2.31,41.47],[2.08,41.29],[1.03,41.06],[0.71,40.82],[0.89,40.72],[-0.33,39.52],[0.2,38.76],[-0.52,38.32],[-0.72,37.63],[-1.64,37.39],[-2.19,36.74],[-4.37,36.72],[-5.63,36.03],[-6.38,36.64],[-6.22,36.91],[-6.86,37.28],[-7.84,37.01],[-8.93,37.17],[-8.81,37.43],[-8.79,37.73],[-8.88,37.96],[-8.8,38.18],[-8.88,38.45],[-8.67,38.42],[-8.8,38.52],[-9.21,38.45],[-9.25,38.66],[-9.02,38.75],[-8.94,39],[-8.79,39.08],[-8.96,39.02],[-9.14,38.74],[-9.36,38.7],[-9.47,38.73],[-9.48,38.8],[-9.35,39.25],[-9.38,39.34],[-9.15,39.54],[-8.84,40.12],[-8.87,40.26],[-8.66,41.03],[-8.89,42.11],[-8.69,42.27],[-9.18,43.17],[-7.7,43.77],[-7.06,43.55],[-1.99,43.35],[-1.49,43.56],[-1.08,44.69],[-1.24,44.67],[-1.08,45.53],[-0.55,45],[-1.2,45.71],[-1.03,45.74],[-1.15,46.31],[-2.09,46.87],[-2.11,47.26],[-1.74,47.22],[-4.31,47.82],[-4.68,48.04],[-4.33,48.17],[-4.58,48.29],[-4.24,48.3],[-4.72,48.54],[-3.23,48.84],[-2.69,48.54],[-1.38,48.65],[-1.86,49.68],[-0.16,49.3],[0.44,49.47],[0.13,49.51],[0.19,49.7],[1.24,50],[1.59,50.25],[1.67,50.88],[3.72,51.37],[4.22,51.39],[4.01,51.44],[3.82,51.41],[3.69,51.45],[3.55,51.59],[3.89,51.57],[4.14,51.46],[4.28,51.47],[4.01,51.6],[4.18,51.61],[3.95,51.81],[4.08,51.99],[4.48,52.31],[4.77,52.94],[4.89,52.91],[5.06,52.96],[5.36,53.1],[5.53,53.27],[6.06,53.41],[7.2,53.28],[7.21,53.66],[7.63,53.7],[8.49,53.39],[8.62,53.88],[9.78,53.55],[8.65,54.29],[8.96,54.54],[8.68,54.79],[8.62,55.42],[8.13,55.6],[8.16,56.61],[9.2,56.7],[9.11,57.04],[8.77,56.72],[8.27,56.81],[10.53,57.73],[10.28,56.62],[10.9,56.36],[9.91,55.84],[9.46,55.04],[10.02,54.67],[9.87,54.47],[11.01,54.38],[10.86,54.01],[12.11,54.17],[12.58,54.47],[13.03,54.41],[13.15,54.28],[13.82,54.02],[13.87,53.85],[13.95,53.8],[14.49,53.67],[14.56,53.82],[14.17,53.87],[13.93,53.88],[13.92,54],[13.83,54.06],[14.38,53.92],[18.08,54.84],[18.76,54.68],[18.44,54.75],[18.84,54.37],[19.41,54.39],[19.97,54.92],[20.68,55.1],[21.12,55.62],[20.59,54.98],[21.19,54.93],[21.03,56.64],[21.73,57.57],[22.56,57.72],[23.65,56.97],[24.4,57.33],[24.3,57.78],[24.49,58.26],[24.55,58.3],[24.53,58.35],[24.34,58.38],[24.11,58.27],[23.77,58.36],[23.69,58.51],[23.51,58.66],[23.68,58.79],[23.5,58.79],[23.43,58.92],[23.51,59],[23.47,59.03],[23.52,59.11],[23.5,59.19],[24.08,59.29],[24.05,59.37],[24.38,59.47],[25.44,59.52],[25.52,59.56],[25.51,59.64],[27.89,59.41],[28.06,59.78],[30.17,59.96],[28.64,60.38],[28.51,60.68],[26.45,60.47],[26.21,60.41],[25.95,60.47],[26.04,60.34],[25.76,60.27],[25.66,60.33],[24.6,60.11],[24.45,60.02],[23.46,59.99],[23.18,59.84],[22.96,59.83],[23.2,60.02],[22.91,60.21],[22.46,60.03],[22.58,60.38],[21.44,60.6],[21.61,61.59],[21.12,62.69],[21.65,63.04],[21.54,63.21],[22.32,63.31],[22.53,63.65],[23.6,64.04],[24.56,64.8],[25.29,64.86],[25.35,65.48],[24.63,65.86],[22.4,65.86],[22.25,65.6],[21.41,65.32],[21.57,65.13],[21.14,64.81],[21.52,64.46],[20.76,63.87],[18.61,63.18],[18.17,62.79],[17.88,62.87],[18.04,62.6],[17.38,62.46],[17.63,62.23],[17.47,61.68],[17.13,61.57],[17.25,60.7],[17.36,60.64],[17.56,60.64],[17.66,60.54],[17.96,60.59],[18.16,60.41],[18.56,60.25],[18.53,60.15],[18.79,60.08],[18.93,59.94],[18.97,59.76],[18.28,59.44],[17.97,59.36],[18.13,59.32],[18.51,59.41],[18.62,59.33],[18.42,59.29],[18.29,59.11],[17.76,58.97],[16.98,58.65],[16.64,58.65],[16.21,58.64],[16.79,58.59],[16.93,58.49],[16.82,58.46],[16.65,58.43],[16.53,57.07],[16,56.22],[14.72,56.13],[14.26,55.89],[14.34,55.53],[14.08,55.39],[13.81,55.43],[13.32,55.35],[12.89,55.41],[12.94,55.48],[12.97,55.75],[12.47,56.29],[12.71,56.23],[12.8,56.26],[12.66,56.44],[12.86,56.45],[12.92,56.52],[12.88,56.62],[12.72,56.66],[12.42,56.91],[11.25,58.42],[11.21,58.87],[11.15,58.99],[11.19,59.08],[11.39,59.04],[11.37,59.1],[10.83,59.18],[10.64,59.39],[10.6,59.76],[10.54,59.7],[10.57,59.59],[10.4,59.52],[10.46,59.38],[10.43,59.28],[10.18,59.01],[9.84,58.96],[9.64,59.12],[9.56,59.11],[9.7,59.01],[9.62,58.95],[8.17,58.14],[7,58.02],[6.9,58.07],[6.88,58.15],[6.8,58.16],[6.73,58.07],[6.59,58.1],[6.55,58.12],[6.69,58.22],[6.66,58.26],[6.39,58.27],[6.05,58.38],[5.71,58.52],[5.52,58.73],[5.56,58.97],[5.61,59.01],[6.1,58.87],[6.36,59],[6.1,58.95],[5.89,59.1],[5.97,59.19],[5.95,59.3],[6.4,59.56],[5.56,59.29],[5.36,59.17],[5.17,59.16],[5.13,59.23],[5.19,59.45],[5.3,59.64],[5.47,59.71],[5.77,59.66],[5.87,59.73],[6.22,59.82],[5.83,59.8],[5.73,59.86],[6.07,60.08],[6.14,60.23],[6.35,60.35],[6.53,60.21],[6.53,60.15],[7,60.51],[6.35,60.42],[6.15,60.35],[5.91,60.15],[5.88,60.07],[5.7,60.01],[5.5,59.83],[5.15,59.64],[5.12,59.83],[5.22,59.98],[5.18,60.05],[5.21,60.09],[5.5,60.07],[5.69,60.12],[5.29,60.21],[5.14,60.44],[5.65,60.69],[5.12,60.64],[5.1,61.07],[6.78,61.14],[7.04,60.95],[7.61,61.21],[7.44,61.43],[7.17,61.17],[5.11,61.19],[5,61.43],[5.34,61.48],[4.93,61.88],[6.73,61.87],[5.27,61.94],[5.14,62.16],[6.69,62.47],[6.14,62.41],[6.35,62.61],[8.09,62.73],[6.73,62.72],[7.57,63.1],[8.62,62.85],[8.16,63.16],[8.63,63.34],[8.36,63.5],[8.58,63.6],[9.7,63.63],[10.02,63.39],[11.37,63.81],[11.18,63.9],[11.31,64.05],[10.06,63.51],[9.57,63.71],[11.63,64.81],[11.3,64.76],[11.49,64.98],[12.92,65.34],[12.42,65.18],[12.12,65.36],[13.03,65.96],[12.79,66.1],[14.03,66.3],[13.12,66.23],[13.21,66.64],[13.96,66.8],[13.65,66.91],[15.42,67.2],[14.44,67.27],[14.96,67.57],[15.59,67.35],[15.69,67.52],[15.25,67.6],[15.31,67.77],[14.78,67.68],[15.05,67.96],[15.62,67.95],[15.29,68.04],[16.01,68.23],[16.31,67.88],[16.21,68.32],[17.57,68.45],[16.58,68.59],[18.1,69.16],[18.26,69.47],[18.92,69.33],[18.61,69.49],[19.2,69.75],[19.72,69.78],[19.64,69.42],[20.32,69.95],[20.05,69.33],[20.74,69.52],[20.62,69.91],[21.98,69.83],[21.36,70.23],[22.69,70.37],[23.36,69.98],[23.38,70.25],[24.66,71],[25.77,70.85],[25.04,70.11],[26.51,70.91],[26.74,70.85],[26.58,70.41],[27.55,70.8],[27.33,71],[28.14,71.04],[28.38,70.87],[27.9,70.68],[28.27,70.67],[28.19,70.25],[28.83,70.86],[30.96,70.34],[28.78,70.15],[29.6,69.98],[29.69,69.74],[31.45,69.69],[31.98,69.95],[33.01,69.72],[32.09,69.63],[32.38,69.48],[33.45,69.43],[33.14,69.07],[33.68,69.31],[35.86,69.19],[40.97,67.71],[41.36,67.21],[41.19,66.83],[40.1,66.3],[38.66,66.07],[34.48,66.55],[32.93,67.09],[31.89,67.16],[33.65,66.44],[33.36,66.33],[34.69,65.95],[34.41,65.4],[35.03,64.44],[37.44,63.81],[38.06,64.09],[37.95,64.32],[37.18,64.41],[36.58,64.79],[36.88,65.17],[39.76,64.58],[40.44,64.78],[39.8,65.35],[39.82,65.6],[42.21,66.52],[43.23,66.41],[44.11,66.01],[44.43,66.94],[43.78,67.26],[44.2,68.25],[43.33,68.67],[45.89,68.48],[46.69,67.85],[45.53,67.76],[44.9,67.41],[46.49,66.8],[47.66,66.98],[47.88,67.58],[48.83,67.68],[48.75,67.9],[51.99,68.54],[52.4,68.35],[52.72,68.48],[52.34,68.61],[53.8,69],[54.49,68.99],[53.8,68.91],[53.93,68.44],[53.26,68.27],[54.86,68.2],[55.42,68.57],[57.13,68.55],[59.06,69.01],[59.37,68.74],[59.1,68.44],[59.73,68.35],[59.9,68.71],[60.93,68.99],[60.17,69.59],[60.91,69.85],[64.19,69.53],[68.5,68.35],[69.14,68.95],[68.54,68.97],[67.62,69.58],[66.9,69.55],[67.29,70.74],[66.7,70.82],[66.85,71.06],[66.64,71.08],[68.27,71.68],[69.39,72.96],[71.5,72.91],[72.81,72.69],[72.57,72.01],[71.87,71.46],[72.7,70.96],[72.47,70.28],[72.58,68.97],[73.59,68.48],[73.14,68.18],[73.07,67.77],[71.85,67.01],[71.37,66.96],[71.54,66.68],[70.72,66.52],[70.38,66.6],[70.69,66.74],[69.01,66.79],[69.98,66.4],[72.07,66.25],[73.79,66.99],[74.77,67.77],[74.39,68.42],[74.58,68.75],[75.12,68.86],[76.46,68.98],[77.24,68.47],[77.18,67.78],[78.92,67.59],[77.59,67.75],[77.67,68.19],[78,68.26],[77.65,68.9],[76,69.24],[73.78,69.2],[73.89,69.42],[73.58,69.8],[74.34,70.58],[73.09,71.44],[73.67,71.85],[74.99,72.15],[75.1,72.42],[74.79,72.81],[75.6,72.58],[75.74,72.3],[75.27,71.96],[75.5,71.65],[75.28,71.43],[75.73,71.27],[79.02,70.95],[76.43,71.55],[76.03,71.91],[78.19,71.91],[77.41,72.11],[78.48,72.4],[79.42,72.38],[81.66,71.72],[83.11,71.72],[82.98,71.45],[82.32,71.26],[82.16,70.6],[82.22,70.4],[82.59,70.89],[83.01,70.9],[82.68,70.22],[83.08,70.09],[83.74,70.55],[83.15,71.1],[83.53,71.68],[82.09,72.27],[81.1,72.39],[80.83,72.49],[80.66,72.71],[80.84,72.95],[80.76,73.03],[80.51,73.09],[80.42,73.23],[80.4,73.36],[80.6,73.47],[80.58,73.57]],[[-152.47,70.65],[-151.77,70.56],[-151.94,70.45],[-149.27,70.5],[-144.62,69.98],[-143.22,70.12],[-135.26,68.68],[-135.91,69.11],[-134.46,69.48],[-134.41,69.68],[-133.88,69.51],[-134.18,69.25],[-130.67,70.13],[-129.54,70.11],[-131.94,69.53],[-133.42,68.84],[-132.71,68.81],[-132.53,68.87],[-132.72,69.08],[-131.79,69.43],[-131.06,69.45],[-130.97,69.21],[-130.12,69.72],[-128.9,69.97],[-129.16,69.8],[-128.85,69.75],[-127.68,70.26],[-128.17,70.42],[-127.99,70.57],[-125.73,69.38],[-125.17,69.43],[-125.34,69.66],[-124.56,70.15],[-124.12,69.69],[-124.34,69.36],[-123.53,69.39],[-123.03,69.81],[-121.74,69.8],[-117.23,68.91],[-115.44,68.94],[-113.96,68.4],[-115.43,67.9],[-115.13,67.82],[-112.43,67.68],[-110.07,67.99],[-107.99,67.26],[-108.5,67.09],[-107.26,66.4],[-107.75,66.96],[-107.16,66.88],[-107.96,67.82],[-105.75,68.59],[-107.73,68.17],[-108.72,68.3],[-108.34,68.6],[-106.16,68.92],[-104.49,68.06],[-103.47,68.11],[-102.32,67.74],[-98.41,67.81],[-98.63,68.07],[-97.61,67.63],[-97.16,67.73],[-98.19,67.92],[-98.65,68.36],[-97.83,68.53],[-96.43,68.31],[-96.72,68.04],[-95.97,68.25],[-96.37,67.51],[-95.42,67.01],[-96.42,67.04],[-95.79,66.62],[-96.04,66.94],[-95.4,66.95],[-95.26,67.26],[-95.65,67.74],[-95.46,68.02],[-93.45,68.62],[-93.85,69],[-94.6,68.8],[-94.09,69.12],[-94.25,69.31],[-93.43,69.37],[-96.05,69.83],[-96.54,70.33],[-95.89,70.69],[-96.36,70.68],[-96.53,71.13],[-96.06,71.41],[-95.56,71.34],[-95.41,71.49],[-95.87,71.57],[-95.2,71.9],[-94.61,71.99],[-94.48,71.85],[-94.31,71.77],[-93.03,71.34],[-92.98,70.85],[-91.57,70.18],[-92.32,70.24],[-92.51,70.1],[-91.98,70.04],[-92.89,69.67],[-90.42,69.46],[-91.24,69.29],[-90.48,68.88],[-90.58,68.48],[-90.25,68.27],[-89.28,69.26],[-88.04,68.81],[-87.81,68.35],[-88.35,68.29],[-88.31,67.95],[-87.36,67.18],[-86.56,67.48],[-85.69,68.67],[-84.87,68.77],[-85.11,68.84],[-84.86,69.07],[-85.39,69.23],[-85.51,69.85],[-82.62,69.69],[-82.37,69.64],[-82.76,69.49],[-82.23,69.25],[-81.32,69.14],[-81.96,68.88],[-81.28,68.66],[-82.55,68.45],[-81.29,67.5],[-81.39,67.19],[-82.64,66.59],[-83.52,66.37],[-84.85,67.03],[-85.11,66.89],[-84.64,66.9],[-83.8,66.24],[-86.71,66.52],[-85.96,66.12],[-87.45,65.34],[-89.75,65.94],[-91.43,65.95],[-87,65.11],[-88.11,64.18],[-89.13,63.97],[-90.04,64.14],[-89.86,63.96],[-90.17,63.98],[-90.01,63.8],[-90.24,63.64],[-93.7,64.15],[-93.56,63.86],[-92.16,63.69],[-92.47,63.56],[-91.84,63.7],[-90.97,63.44],[-90.7,63.06],[-92.36,62.82],[-91.94,62.59],[-92.55,62.55],[-92.77,62.35],[-92.53,62.17],[-93.21,62.36],[-92.9,62.22],[-93.58,61.94],[-93.31,61.77],[-93.91,61.48],[-94.76,60.5],[-94.96,59.07],[-94.29,58.72],[-94.33,58.3],[-94.12,58.74],[-93.18,58.73],[-92.43,57.32],[-92.8,56.92],[-90.59,57.22],[-88.83,56.81],[-87.48,56.02],[-85.68,55.6],[-85.22,55.35],[-85.37,55.08],[-83.91,55.31],[-82.39,55.07],[-82.22,54.81],[-82.42,54.24],[-82.14,53.82],[-82.29,53.03],[-81.6,52.43],[-81.83,52.22],[-80.59,51.67],[-80.44,51.39],[-80.85,51.12],[-80.1,51.28],[-79.35,50.76],[-79.74,51.19],[-79.34,51.63],[-78.9,51.2],[-78.73,51.5],[-78.98,51.78],[-78.45,52.26],[-79.1,53.66],[-79.01,54.02],[-79.71,54.67],[-77.78,55.29],[-76.55,56.36],[-76.57,57.18],[-76.89,57.76],[-78.51,58.68],[-77.73,59.68],[-77.35,59.58],[-77.29,60.02],[-77.59,60.09],[-77.68,60.43],[-77.5,60.54],[-77.79,60.64],[-77.59,60.81],[-78.18,60.82],[-77.51,61.56],[-78.02,61.83],[-78.13,62.28],[-77.37,62.57],[-74.63,62.11],[-73.71,62.47],[-72.69,62.13],[-72.77,61.84],[-72.23,61.83],[-72.04,61.68],[-72.21,61.59],[-71.64,61.62],[-71.85,61.44],[-71.42,61.16],[-69.99,60.86],[-69.5,61.04],[-69.67,60.08],[-70.66,60.03],[-69.73,59.92],[-69.68,59.34],[-69.35,59.3],[-69.53,58.87],[-70.16,58.76],[-68.38,58.74],[-68.36,58.16],[-69.04,57.9],[-68.41,58.05],[-68.02,58.48],[-68.06,58.14],[-67.75,58.4],[-67.68,57.99],[-66.36,58.79],[-66,58.43],[-66.04,58.82],[-65.38,59.06],[-65.7,59.21],[-65.48,59.47],[-65.04,59.39],[-65.43,59.78],[-65.03,59.77],[-65.17,59.91],[-64.82,60.33],[-64.5,60.27],[-64.77,60.01],[-64.28,60.06],[-64.23,59.74],[-63.75,59.51],[-63.95,59.38],[-63.42,59.19],[-63.97,59.05],[-63.25,59.07],[-63.28,58.87],[-62.87,58.67],[-63.54,58.33],[-62.61,58.5],[-63.26,58.01],[-62.49,58.15],[-61.96,57.91],[-61.97,57.61],[-62.49,57.49],[-61.33,57.01],[-61.37,56.68],[-62.5,56.8],[-61.43,56.36],[-61.71,56.23],[-61.36,56.22],[-61.45,56],[-60.34,55.79],[-60.19,55.48],[-60.62,55.06],[-59.76,55.31],[-59.44,55.18],[-59.84,54.81],[-59.26,55.2],[-58.78,54.84],[-57.96,54.88],[-57.4,54.59],[-60.4,53.65],[-60.1,53.49],[-60.33,53.27],[-57.93,54.1],[-58.36,54.16],[-58.19,54.23],[-57.42,54.16],[-57.13,53.79],[-57.52,53.61],[-57.33,53.47],[-56.46,53.76],[-55.86,53.34],[-55.8,52.64],[-56.32,52.54],[-55.74,52.47],[-56.01,52.39],[-55.69,52.14],[-56.98,51.46],[-58.51,51.29],[-59.88,50.32],[-61.72,50.1],[-62.71,50.3],[-66.41,50.22],[-66.94,49.99],[-67.37,49.35],[-68.28,49.2],[-69.67,48.2],[-71.02,48.46],[-69.77,48.1],[-70.71,47.14],[-72.68,46.29],[-72.98,46.21],[-73.02,46.12],[-73.14,46.07],[-73.47,45.74],[-73.71,45.71],[-74.04,45.5],[-74.31,45.53],[-74,45.43],[-73.98,45.35],[-74.36,45.21],[-74.71,45],[-73.76,45.4],[-73.56,45.42],[-73.46,45.63],[-73.16,46.01],[-72.73,46.18],[-72.37,46.4],[-70.52,47.03],[-69.47,47.97],[-68.24,48.63],[-65.4,49.26],[-64.26,48.92],[-64.51,48.84],[-64.26,48.55],[-65.26,48.02],[-65.93,48.19],[-66.7,48.02],[-65.61,47.67],[-64.7,47.73],[-65.32,47.1],[-64.83,47.06],[-64.54,46.24],[-62.75,45.65],[-61.95,45.87],[-61.35,45.57],[-61.46,45.37],[-61.03,45.29],[-63.6,44.68],[-63.61,44.48],[-64.29,44.55],[-64.86,43.87],[-65.74,43.56],[-66.13,43.81],[-66.02,44.56],[-64.45,45.34],[-64.14,45.02],[-63.37,45.36],[-64.87,45.36],[-64.32,45.84],[-64.63,45.95],[-64.78,45.64],[-65.89,45.22],[-66.03,45.42],[-66.44,45.1],[-67.12,45.17],[-66.99,44.83],[-68.06,44.39],[-68.45,44.51],[-68.53,44.26],[-68.81,44.34],[-68.76,44.57],[-69.14,44.04],[-70.27,43.67],[-70.2,43.63],[-70.52,43.35],[-70.73,43.07],[-70.83,42.83],[-70.74,42.67],[-70.62,42.67],[-70.61,42.62],[-70.83,42.55],[-71.04,42.33],[-70.74,42.23],[-70.62,42.04],[-70.66,41.99],[-70.55,41.94],[-70.52,41.8],[-70.43,41.76],[-70.3,41.73],[-70,41.83],[-70.11,42.03],[-70.24,42.09],[-70.11,42.08],[-69.98,41.96],[-69.93,41.71],[-70.66,41.53],[-70.7,41.72],[-71.17,41.49],[-71.2,41.64],[-71.15,41.75],[-71.27,41.68],[-71.39,41.79],[-71.37,41.7],[-71.43,41.63],[-71.44,41.45],[-71.52,41.38],[-72.92,41.28],[-73.58,41.02],[-73.99,40.75],[-73.87,41.06],[-73.88,41.17],[-73.97,41.25],[-73.92,41.14],[-73.93,40.91],[-74.26,40.53],[-74.24,40.46],[-74,40.45],[-73.97,40.4],[-74.08,39.79],[-74.07,39.99],[-74.26,39.61],[-74.33,39.54],[-74.41,39.55],[-74.39,39.49],[-74.48,39.34],[-74.58,39.32],[-74.61,39.25],[-74.92,38.94],[-74.9,39.15],[-75.52,39.49],[-75.07,39.98],[-75.17,39.89],[-75.32,39.86],[-75.57,39.48],[-75.04,38.43],[-75.93,37.15],[-75.66,37.95],[-75.85,37.97],[-75.86,38.36],[-76.12,38.32],[-76.26,38.44],[-76.26,38.6],[-76,38.6],[-76.21,38.76],[-76.28,38.77],[-76.34,38.71],[-76.3,38.82],[-76.17,38.85],[-76.19,38.91],[-76.33,38.91],[-76.33,38.95],[-76.31,39.01],[-76.19,38.99],[-76.13,39.12],[-76.22,39.06],[-76.24,39.19],[-76.15,39.32],[-75.94,39.4],[-76,39.41],[-75.97,39.51],[-76.01,39.57],[-76.06,39.56],[-76.1,39.43],[-76.21,39.38],[-76.25,39.44],[-76.28,39.32],[-76.33,39.4],[-76.42,39.23],[-76.57,39.27],[-76.43,39.13],[-76.47,39.03],[-76.56,39.07],[-76.5,38.94],[-76.54,38.74],[-76.5,38.53],[-76.39,38.37],[-76.57,38.44],[-76.68,38.61],[-76.67,38.54],[-76.64,38.45],[-76.41,38.27],[-76.34,38.09],[-76.46,38.17],[-76.77,38.26],[-76.87,38.39],[-76.89,38.29],[-77,38.44],[-77.23,38.41],[-77.22,38.54],[-77.02,38.78],[-77.03,38.89],[-77.05,38.78],[-77.26,38.6],[-77.31,38.4],[-77.27,38.35],[-77.05,38.36],[-76.91,38.2],[-76.55,38.09],[-76.35,37.96],[-76.34,37.68],[-76.79,37.94],[-76.94,38.1],[-77.11,38.16],[-76.62,37.76],[-76.27,37.49],[-76.45,37.27],[-76.76,37.51],[-76.34,37.01],[-77.25,37.33],[-76.49,36.9],[-76,36.91],[-75.53,35.82],[-75.95,36.66],[-75.82,36.11],[-76.15,36.28],[-76.56,36.02],[-76.73,36.23],[-76.73,35.96],[-76.07,35.97],[-76.08,35.69],[-75.76,35.84],[-76.17,35.35],[-77.04,35.53],[-76.51,35.27],[-76.78,34.99],[-77.07,35.15],[-76.97,35.02],[-76.44,34.84],[-77.41,34.73],[-77.93,33.94],[-77.95,34.17],[-78.01,33.91],[-78.84,33.72],[-79.94,32.67],[-80.64,32.51],[-80.58,32.29],[-80.8,32.45],[-80.69,32.22],[-81.44,31.2],[-81.25,29.79],[-80.52,28.49],[-80.46,27.9],[-80.84,28.76],[-80.05,26.81],[-80.13,25.83],[-80.16,25.88],[-80.3,25.62],[-80.37,25.33],[-80.48,25.23],[-80.74,25.16],[-81.11,25.14],[-81.17,25.23],[-81.14,25.31],[-80.97,25.22],[-80.94,25.26],[-81.11,25.37],[-81.37,25.83],[-81.72,25.98],[-81.96,26.49],[-81.83,26.69],[-82.04,26.55],[-82.01,26.96],[-82.29,26.87],[-82.72,27.5],[-82.41,27.86],[-82.84,27.85],[-82.65,28.89],[-84.04,30.1],[-85.32,29.68],[-85.6,30.29],[-86.45,30.4],[-86.26,30.49],[-87.2,30.34],[-87,30.57],[-88,30.23],[-87.79,30.29],[-88.01,30.69],[-88.13,30.37],[-89.59,30.17],[-90.23,30.38],[-90.28,30.06],[-89.4,30.05],[-89.35,29.82],[-89.72,29.62],[-89.02,29.2],[-89.38,28.98],[-90.16,29.54],[-90.21,29.1],[-91.29,29.29],[-91.25,29.56],[-91.89,29.84],[-92.26,29.56],[-93.83,29.72],[-93.88,29.81],[-93.81,29.85],[-93.79,29.98],[-93.84,29.98],[-93.94,29.81],[-93.89,29.69],[-94.1,29.67],[-94.76,29.38],[-94.53,29.55],[-94.78,29.55],[-94.74,29.75],[-94.83,29.75],[-94.89,29.68],[-95.02,29.7],[-94.99,29.53],[-94.89,29.37],[-95.14,29.17],[-95.15,29.08],[-95.27,28.96],[-95.85,28.64],[-96.23,28.49],[-96.01,28.63],[-96.37,28.66],[-96.45,28.59],[-96.58,28.72],[-96.42,28.46],[-97.16,28.14],[-97.07,27.99],[-97.43,27.84],[-97.44,27.33],[-97.77,27.46],[-97.48,27.24],[-97.14,26.03],[-97.67,24.39],[-97.86,22.62],[-97.31,21.56],[-97.41,21.27],[-97.75,22.03],[-97.64,21.6],[-95.92,18.82],[-95.18,18.7],[-94.46,18.17],[-92.44,18.67],[-91.53,18.46],[-91.27,18.62],[-91.44,18.89],[-90.74,19.35],[-90.35,21.01],[-88.47,21.57],[-87.04,21.59],[-86.82,21],[-87.69,19.64],[-87.43,19.58],[-87.85,18.27],[-88.03,18.84],[-88.35,18.36],[-88.08,18.23],[-88.31,16.63],[-88.89,15.89],[-88.13,15.7],[-87.7,15.91],[-86.91,15.76],[-84.97,15.99],[-84.26,15.82],[-83.76,15.22],[-83.37,15.24],[-83.19,14.34],[-83.57,13.32],[-83.51,12.41],[-83.59,12.71],[-83.75,12.5],[-83.83,11.13],[-82.24,9.03],[-81.78,8.96],[-81.9,9.14],[-81.55,8.83],[-81.06,8.81],[-80.84,8.89],[-80.55,9.08],[-80.13,9.21],[-79.58,9.6],[-79.11,9.54],[-78.93,9.43],[-78.5,9.41],[-78.08,9.24],[-76.79,7.93],[-76.92,8.57],[-75.64,9.45],[-75.54,10.2],[-75.71,10.14],[-75.45,10.61],[-74.84,11.11],[-74.33,11],[-74.4,10.77],[-74.14,11.32],[-73.31,11.3],[-71.6,12.43],[-71.14,12.05],[-71.96,11.57],[-71.6,10.66],[-72.11,9.82],[-71.62,9.05],[-71.24,9.16],[-71.05,9.71],[-71.47,10.96],[-69.81,11.47],[-70.29,11.89],[-70,12.18],[-69.63,11.48],[-68.4,11.16],[-68.14,10.49],[-66.25,10.63],[-65.13,10.07],[-63.73,10.5],[-64.3,10.64],[-61.88,10.74],[-62.91,10.53],[-62.74,10.06],[-62.55,10.2],[-62.32,9.78],[-62.08,9.98],[-61.74,9.63],[-61.59,9.89],[-60.79,9.36],[-61.25,8.6],[-61.62,8.6],[-61.3,8.41],[-60.17,8.62],[-58.81,7.74],[-58.48,7.33],[-58.67,6.39],[-58.42,6.85],[-57.98,6.79],[-57.23,6.18],[-57.18,5.53],[-56.97,5.99],[-55.9,5.7],[-55.83,5.96],[-54.36,5.91],[-54.05,5.81],[-54.16,5.36],[-53.85,5.78],[-52.9,5.43],[-52.06,4.72],[-52,4.35],[-51.83,4.64],[-51.65,4.06],[-51.55,4.31],[-51.22,4.09],[-50.72,2.13],[-49.96,1.66],[-49.9,1.16],[-51.28,-0.08],[-51.98,-1.37],[-52.66,-1.55],[-51.95,-1.59],[-50.9,-0.94],[-50.4,-2.01],[-49.32,-1.73],[-49.64,-2.66],[-49.21,-1.92],[-48.35,-1.48],[-48.45,-1.15],[-48.12,-0.74],[-47.4,-0.63],[-45.46,-1.36],[-45.33,-1.72],[-45.08,-1.47],[-44.65,-1.75],[-44.54,-2.05],[-44.76,-2.26],[-44.44,-2.17],[-44.38,-2.37],[-44.72,-3.2],[-44.23,-2.47],[-44.19,-2.81],[-43.38,-2.38],[-42.25,-2.79],[-39.77,-2.99],[-39.02,-3.39],[-38.69,-3.65],[-38.48,-3.72],[-38.05,-4.22],[-37.63,-4.59],[-37.3,-4.71],[-36.59,-5.1],[-35.39,-5.25],[-34.83,-7.02],[-34.84,-7.97],[-35.34,-9.23],[-37.36,-11.25],[-38.02,-12.59],[-38.4,-12.97],[-38.69,-12.62],[-38.85,-12.79],[-39.09,-13.59],[-38.88,-15.86],[-39.16,-17.7],[-39.65,-18.25],[-39.78,-19.57],[-40.96,-21.24],[-41,-22],[-41.58,-22.24],[-41.98,-22.58],[-41.94,-22.79],[-42.04,-22.95],[-42.96,-22.97],[-43.08,-22.9],[-43.09,-22.72],[-43.23,-22.75],[-43.22,-22.99],[-43.9,-23.1],[-43.97,-23.06],[-43.68,-23.01],[-43.86,-22.91],[-44.15,-23.01],[-44.37,-23],[-45.21,-23.58],[-45.33,-23.6],[-45.46,-23.8],[-45.97,-23.79],[-46.87,-24.24],[-47.14,-24.49],[-47.59,-24.78],[-48.2,-25.42],[-48.73,-25.37],[-48.4,-25.6],[-48.75,-26.27],[-48.56,-27.2],[-48.8,-28.58],[-49.75,-29.36],[-50.92,-31.26],[-52.04,-32.12],[-52.06,-31.83],[-51.27,-31.48],[-50.58,-30.44],[-50.56,-30.25],[-51.03,-30.37],[-51.3,-30.04],[-51.28,-30.75],[-51.97,-31.38],[-52.65,-33.14],[-53.79,-34.38],[-54.9,-34.93],[-56.85,-34.68],[-57.17,-34.45],[-57.87,-34.45],[-58.4,-33.91],[-58.44,-33.72],[-58.36,-33.18],[-58.15,-33.07],[-58.2,-32.47],[-58.2,-33.01],[-58.25,-33.08],[-58.42,-33.11],[-58.55,-33.66],[-58.39,-34.19],[-58.52,-34.3],[-58.47,-34.46],[-58.28,-34.68],[-57.76,-34.89],[-57.3,-35.19],[-57.17,-35.36],[-57.16,-35.51],[-57.35,-35.72],[-57.26,-36.14],[-56.72,-36.39],[-56.67,-36.85],[-57.65,-38.17],[-59.83,-38.84],[-61.6,-39],[-62.34,-38.8],[-62.3,-39.24],[-62.05,-39.37],[-62.39,-40.89],[-63.62,-41.16],[-64.87,-40.74],[-65.13,-40.88],[-64.99,-42.1],[-64.42,-42.43],[-63.79,-42.11],[-63.62,-42.7],[-64.04,-42.88],[-64.49,-42.51],[-64.97,-42.67],[-64.32,-42.97],[-65.25,-43.57],[-65.29,-44.36],[-65.65,-44.66],[-65.64,-45.01],[-66.94,-45.26],[-67.6,-46.05],[-67.51,-46.44],[-66.78,-47.01],[-65.85,-47.16],[-65.77,-47.57],[-66.22,-47.83],[-65.81,-47.94],[-67.47,-48.95],[-67.91,-49.98],[-68.26,-50.1],[-68.67,-49.75],[-68.98,-50],[-68.42,-50.16],[-68.94,-50.38],[-69.36,-51.03],[-69.06,-51.55],[-69.46,-51.58],[-68.96,-51.68],[-68.4,-52.31],[-69.24,-52.21],[-70.8,-52.77],[-70.99,-53.78],[-71.3,-53.88],[-72.41,-53.35],[-71.94,-53.23],[-71.79,-53.48],[-71.23,-52.81],[-72.28,-53.13],[-72.55,-53.46],[-73.05,-53.24],[-72.73,-52.76],[-71.51,-52.61],[-72.71,-52.54],[-73.12,-53.07],[-73.64,-52.84],[-73.12,-52.49],[-74.01,-52.64],[-74.3,-52.12],[-73.83,-52.23],[-72.79,-51.95],[-72.57,-52.2],[-72.72,-52.36],[-72.52,-52.25],[-72.54,-51.71],[-73.17,-51.45],[-72.6,-51.8],[-73.52,-52.04],[-74.19,-51.68],[-73.93,-51.62],[-73.94,-51.27],[-74.81,-51.06],[-75.09,-50.68],[-74.68,-50.66],[-74.64,-50.36],[-73.81,-50.94],[-73.65,-50.49],[-73.98,-50.83],[-74.2,-50.61],[-73.95,-50.51],[-74.63,-50.19],[-73.96,-49.99],[-74.29,-49.6],[-73.83,-49.61],[-74.09,-49.43],[-73.94,-49.02],[-74.22,-49.5],[-74.37,-49.4],[-74.34,-48.6],[-74.01,-48.48],[-74.48,-48.46],[-74.58,-48],[-73.39,-48.15],[-73.72,-47.66],[-74.23,-47.97],[-74.66,-47.7],[-74.13,-47.59],[-74.48,-47.43],[-74.16,-47.18],[-74.31,-46.79],[-75,-46.74],[-75.02,-46.51],[-75.54,-46.7],[-75.43,-46.93],[-75.71,-46.77],[-74.93,-46.16],[-75.07,-45.88],[-74.16,-45.77],[-73.96,-45.4],[-74.02,-46.06],[-74.39,-46.22],[-73.97,-46.15],[-73.73,-45.81],[-73.85,-46.57],[-73.59,-45.9],[-73.73,-45.48],[-72.93,-45.45],[-73.45,-45.24],[-72.68,-44.59],[-73.27,-44.17],[-73.08,-43.32],[-72.76,-43.04],[-72.77,-42.26],[-72.41,-42.39],[-72.5,-41.98],[-72.82,-41.91],[-72.32,-41.5],[-73.73,-41.74],[-73.98,-40.97],[-73.23,-39.22],[-73.66,-37.34],[-73.22,-37.17],[-71.99,-34.29],[-72,-34.17],[-71.83,-33.82],[-71.66,-33.65],[-71.64,-33.52],[-71.7,-33.43],[-71.74,-33.09],[-71.59,-32.97],[-71.45,-32.66],[-71.42,-32.39],[-71.51,-32.21],[-71.71,-30.63],[-71.31,-29.65],[-71.52,-28.93],[-70.65,-26.33],[-70.39,-23.57],[-70.59,-23.25],[-70.09,-21.49],[-70.36,-18.4],[-71.53,-17.3],[-75.11,-15.41],[-76.29,-14.13],[-76.23,-13.37],[-76.5,-12.98],[-76.83,-12.35],[-77.15,-12.06],[-77.22,-11.66],[-77.31,-11.53],[-77.63,-11.29],[-77.74,-10.84],[-79.76,-7.07],[-81.14,-6.06],[-80.88,-5.63],[-81.34,-4.67],[-81.23,-4.23],[-79.96,-3.16],[-79.73,-2.58],[-79.84,-2.07],[-79.93,-2.55],[-80.01,-2.35],[-80.29,-2.71],[-80.96,-2.19],[-80.77,-2.08],[-80.9,-1.08],[-80.28,-0.62],[-80.48,-0.37],[-80.05,0.16],[-80.09,0.79],[-78.9,1.21],[-79.03,1.62],[-78.58,1.77],[-78.59,2.36],[-77.81,2.72],[-77.08,3.91],[-77.52,4.21],[-77.29,4.72],[-77.54,5.54],[-77.25,5.78],[-77.47,6.18],[-77.37,6.57],[-78.38,7.9],[-78.42,8.06],[-78.29,8.09],[-78.28,8.25],[-78.14,8.39],[-77.76,8.13],[-78.06,8.4],[-78.1,8.5],[-78.22,8.4],[-78.4,8.51],[-78.37,8.4],[-78.41,8.36],[-78.51,8.63],[-78.95,8.93],[-79.25,9.02],[-79.51,8.97],[-79.69,8.85],[-79.81,8.64],[-79.75,8.6],[-80.12,8.35],[-80.37,8.29],[-80.46,8.21],[-80.46,8.08],[-80.07,7.67],[-80.01,7.5],[-80.84,7.22],[-81.06,7.9],[-81.27,7.63],[-82.23,8.31],[-82.78,8.3],[-82.88,8.07],[-83.29,8.67],[-83.47,8.71],[-83.29,8.41],[-83.61,8.48],[-83.74,9.15],[-84.58,9.57],[-85.02,10.12],[-85.26,10.26],[-84.89,9.82],[-85.11,9.58],[-85.63,9.9],[-85.85,10.29],[-85.67,10.74],[-85.91,10.9],[-85.74,11.09],[-87.67,12.9],[-87.34,12.95],[-87.49,13.35],[-88.69,13.28],[-88.51,13.18],[-91.38,13.99],[-93.92,16.05],[-94.86,16.42],[-95.02,16.28],[-94.8,16.21],[-96.21,15.69],[-97.75,15.97],[-100.85,17.2],[-101.92,17.96],[-103.44,18.33],[-103.91,18.83],[-104.94,19.31],[-105.67,20.38],[-105.26,20.58],[-105.51,20.81],[-105.21,21.49],[-105.65,21.99],[-105.79,22.63],[-107.77,24.47],[-107.51,24.49],[-107.95,24.62],[-108.28,25.08],[-108.05,25.07],[-109.03,25.48],[-108.88,25.73],[-109.31,25.63],[-109.42,26.03],[-109.12,26.25],[-109.28,26.53],[-110.38,27.23],[-110.53,27.86],[-111.12,27.97],[-112.16,29.02],[-113.06,30.65],[-113.05,31.18],[-114.93,31.9],[-114.55,30.02],[-112.87,28.42],[-112.73,27.83],[-111.86,26.68],[-111.7,26.58],[-111.79,26.88],[-111.57,26.71],[-110.69,24.87],[-110.66,24.34],[-110.37,24.1],[-110.26,24.34],[-109.42,23.48],[-109.5,23.16],[-110,22.89],[-110.36,23.61],[-112.07,24.84],[-112.38,26.21],[-113.02,26.58],[-113.15,26.95],[-113.6,26.72],[-114.99,27.74],[-114.3,27.87],[-114.07,27.68],[-114.27,27.93],[-114.05,28.43],[-115.67,29.76],[-117.27,32.81],[-117.32,33.1],[-117.47,33.3],[-118.08,33.72],[-118.41,33.74],[-118.39,33.86],[-118.51,34.02],[-118.83,34.02],[-119.14,34.11],[-119.41,34.34],[-119.61,34.42],[-119.71,34.4],[-120.65,34.58],[-120.63,35.08],[-121.46,35.93],[-121.88,36.33],[-121.92,36.57],[-121.79,36.73],[-121.81,36.85],[-121.88,36.94],[-122.17,36.99],[-122.4,37.21],[-122.51,37.77],[-122.39,37.79],[-122.37,37.66],[-122.07,37.48],[-122.39,37.96],[-122.22,38.04],[-121.52,38.06],[-122.03,38.12],[-122.15,38.07],[-122.39,38.14],[-122.48,38.11],[-122.47,37.84],[-122.52,37.83],[-122.93,38.06],[-123,37.99],[-122.98,38.23],[-122.88,38.12],[-122.99,38.28],[-123.7,38.91],[-123.83,39.78],[-124.33,40.25],[-124.07,41.46],[-124.54,42.81],[-124.15,43.69],[-123.99,46.22],[-123.22,46.15],[-124.07,46.28],[-123.89,46.66],[-124.11,46.86],[-123.84,46.96],[-124.14,46.95],[-124.71,48.38],[-123.3,48.12],[-123.12,48.15],[-122.98,48.07],[-122.78,48.14],[-122.66,47.88],[-122.78,47.74],[-122.82,47.79],[-123.05,47.55],[-123.14,47.36],[-122.92,47.41],[-123.07,47.4],[-123.06,47.45],[-122.59,47.86],[-122.59,47.93],[-122.53,47.92],[-122.53,47.77],[-122.62,47.71],[-122.61,47.62],[-122.68,47.61],[-122.56,47.46],[-122.58,47.29],[-122.71,47.32],[-122.77,47.22],[-122.83,47.34],[-123.03,47.14],[-122.7,47.11],[-122.54,47.28],[-122.35,47.37],[-122.4,47.78],[-122.24,48.01],[-122.42,48.18],[-122.4,48.08],[-122.52,48.16],[-122.52,48.23],[-122.41,48.29],[-122.67,48.46],[-122.5,48.51],[-122.54,48.76],[-122.69,48.79],[-122.83,49.03],[-122.96,49.07],[-123.08,48.98],[-123.23,49.26],[-122.88,49.4],[-123.28,49.34],[-123.19,49.68],[-123.53,49.4],[-124.03,49.6],[-123.58,49.68],[-123.88,49.74],[-123.83,50.15],[-124.28,49.77],[-124.78,50.02],[-125.06,50.42],[-124.86,50.87],[-125.06,50.51],[-126.09,50.5],[-126.45,50.59],[-125.91,50.7],[-126.51,50.68],[-126.52,51.06],[-127.06,50.87],[-127.71,51.15],[-127.42,51.61],[-126.69,51.7],[-127.64,51.48],[-127.85,51.67],[-127.8,52.19],[-127.44,52.36],[-126.71,52.06],[-127.19,52.46],[-127.01,52.84],[-128.1,51.79],[-128.36,52.16],[-127.94,52.55],[-128.27,52.36],[-128.05,52.91],[-128.36,52.83],[-129.17,53.53],[-128.85,53.7],[-127.93,53.28],[-128.67,53.55],[-128.76,53.75],[-128.71,53.81],[-128.53,53.86],[-128.7,53.92],[-128.89,53.83],[-128.96,53.84],[-129.21,53.64],[-129.26,53.42],[-129.46,53.35],[-129.56,53.25],[-129.82,53.41],[-129.91,53.55],[-130.07,53.58],[-130.34,53.72],[-130.09,53.98],[-130.04,54.13],[-129.63,54.23],[-130.08,54.18],[-130.29,54.27],[-130.43,54.42],[-130.35,54.66],[-130.22,54.73],[-129.89,55.16],[-129.56,55.46],[-129.79,55.56],[-130.05,55.06],[-130.02,55.89],[-130.04,55.3],[-130.54,54.75],[-131.05,55.16],[-130.75,55.32],[-131.03,56.09],[-132.12,55.57],[-132.21,55.75],[-131.55,56.21],[-132.18,56.42],[-132.82,57.06],[-133.47,57.17],[-133.44,57.34],[-133.54,57.55],[-133.65,57.64],[-133.55,57.7],[-133.12,57.57],[-133.52,57.78],[-133.54,57.83],[-133.51,57.88],[-133.19,57.88],[-133.56,57.92],[-133.66,57.84],[-133.72,57.84],[-134.03,58.07],[-134.05,58.29],[-133.88,58.52],[-134.21,58.23],[-134.78,58.45],[-134.94,58.65],[-134.99,58.77],[-135.13,58.84],[-135.33,59.24],[-135.36,59.42],[-135.41,59.32],[-135.48,59.31],[-135.4,59.21],[-135.5,59.2],[-135.39,59.09],[-135.06,58.34],[-135.06,58.28],[-135.14,58.23],[-135.3,58.26],[-135.45,58.38],[-135.57,58.41],[-135.9,58.4],[-135.86,58.58],[-136.04,58.82],[-135.83,58.9],[-136.02,58.87],[-136.15,59.05],[-136.12,58.82],[-136.23,58.77],[-136.45,58.85],[-136.57,58.94],[-136.99,59.04],[-137.06,58.87],[-136.06,58.45],[-136.61,58.24],[-139.77,59.53],[-139.51,59.95],[-139.29,59.61],[-138.99,59.84],[-139.43,60.01],[-140.42,59.71],[-141.41,59.9],[-141.41,60.12],[-144.15,60.02],[-144.9,60.34],[-144.69,60.67],[-145.25,60.38],[-146.57,60.73],[-146.39,60.81],[-146.63,60.99],[-146.38,61.14],[-147.81,60.89],[-148.01,60.97],[-147.75,61.22],[-148.34,61.06],[-148.56,60.8],[-148.28,60.61],[-148.64,60.49],[-147.96,60.48],[-148.43,59.99],[-149.4,60.11],[-149.6,59.77],[-149.71,59.92],[-150.93,59.25],[-151.74,59.19],[-151.93,59.34],[-151.04,59.77],[-151.85,59.78],[-151.4,60.27],[-151.36,60.72],[-150.44,61.02],[-149.07,60.89],[-150.05,61.17],[-149.33,61.5],[-151.59,60.98],[-152.37,60.34],[-153.02,60.3],[-152.63,60.04],[-153.21,59.84],[-153.05,59.73],[-154.09,59.36],[-154.13,59.12],[-153.33,58.88],[-154.25,58.16],[-158.41,56.44],[-158.55,56.31],[-158.28,56.2],[-159.66,55.63],[-159.77,55.84],[-161.38,55.37],[-161.2,55.54],[-161.52,55.62],[-162.08,55.14],[-162.63,55.25],[-162.67,55],[-163.12,55.06],[-163.34,54.84],[-163.28,55.12],[-161.7,55.91],[-160.29,55.8],[-160.54,56.01],[-160.3,56.31],[-158.67,56.8],[-158.32,57.3],[-157.46,57.51],[-157.7,57.68],[-157.61,58.05],[-157.19,58.19],[-157.52,58.42],[-156.97,58.74],[-156.81,59.13],[-158.19,58.62],[-158.5,58.85],[-158.08,58.98],[-158.81,58.97],[-158.95,58.4],[-159.67,58.91],[-160.36,59.05],[-162.14,58.64],[-161.72,58.79],[-161.64,59.11],[-161.98,59.15],[-161.83,59.59],[-162.42,60.28],[-161.96,60.69],[-162.68,60.27],[-162.57,59.99],[-163.68,59.8],[-165.36,60.54],[-164.8,60.89],[-164.32,60.77],[-164.37,60.59],[-163.42,60.76],[-163.91,60.85],[-163.59,60.9],[-163.75,60.97],[-165.11,60.93],[-164.87,61.11],[-165.27,61.27],[-165.57,61.1],[-165.84,61.54],[-166.15,61.55],[-165.81,61.7],[-166.08,61.8],[-165.61,61.87],[-165.71,62.1],[-165.19,62.47],[-164.76,62.5],[-164.59,62.71],[-164.79,62.62],[-164.8,62.92],[-164.38,63.03],[-164.41,63.22],[-163.29,63.05],[-162.28,63.53],[-161.1,63.56],[-160.78,63.82],[-160.99,64.25],[-161.49,64.43],[-160.86,64.76],[-161.76,64.82],[-162.33,64.61],[-162.71,64.38],[-162.81,64.37],[-162.88,64.52],[-163.2,64.65],[-163.3,64.61],[-163.05,64.52],[-163.14,64.42],[-163.71,64.59],[-164.3,64.58],[-164.69,64.51],[-164.76,64.53],[-164.98,64.45],[-166.14,64.58],[-166.33,64.63],[-166.48,64.73],[-166.48,64.8],[-166.41,64.83],[-166.42,64.93],[-166.55,64.95],[-166.93,65.16],[-166.53,65.15],[-166.45,65.25],[-166.16,65.29],[-167.4,65.42],[-168.09,65.66],[-164.46,66.59],[-163.64,66.57],[-163.89,66.58],[-164.03,66.22],[-163.7,66.08],[-161.04,66.19],[-162.61,66.89],[-162.36,66.95],[-161.59,66.46],[-160.23,66.51],[-161.57,66.59],[-161.86,66.7],[-161.72,67.02],[-163.53,67.1],[-164.12,67.61],[-166.79,68.36],[-166.38,68.43],[-166.21,68.89],[-163.87,69.04],[-161.88,70.33],[-162.08,70.16],[-160.12,70.59],[-159.96,70.57],[-160.11,70.47],[-160.01,70.45],[-160.1,70.33],[-159.91,70.33],[-159.87,70.28],[-159.81,70.5],[-159.39,70.52],[-159.75,70.53],[-159.96,70.63],[-160.08,70.63],[-159.68,70.79],[-159.31,70.88],[-159.19,70.86],[-159.34,70.78],[-159.25,70.75],[-159,70.8],[-157.91,70.86],[-157.32,71.04],[-156.78,71.32],[-156.47,71.41],[-156.4,71.4],[-156.57,71.34],[-156.47,71.29],[-155.65,71.18],[-155.58,71.12],[-155.8,71],[-156.15,70.93],[-155.97,70.84],[-155.58,70.89],[-155.17,71.1],[-154.94,71.08],[-154.67,70.99],[-154.79,70.89],[-154.2,70.8],[-153.92,70.88],[-153.23,70.93],[-152.49,70.88],[-152.23,70.81],[-152.44,70.73]],[[143.18,-11.96],[143.75,-14.35],[144.47,-14.23],[145.29,-14.94],[145.43,-16.41],[145.91,-16.91],[146.03,-18.27],[146.38,-18.98],[148.76,-20.29],[148.88,-20.48],[148.68,-20.58],[149.21,-21.12],[149.71,-22.44],[149.98,-22.55],[150.08,-22.16],[150.54,-22.56],[150.67,-22.42],[150.84,-23.46],[151.83,-24.12],[153.03,-25.87],[153.17,-25.96],[153.08,-26.3],[153.16,-26.98],[153.12,-27.19],[153.38,-27.77],[153.45,-28.05],[153.58,-28.24],[153.6,-28.86],[152.95,-31.43],[152.21,-32.68],[152.14,-32.68],[152.19,-32.72],[152.16,-32.76],[151.81,-32.9],[151.48,-33.35],[151.43,-33.52],[151.29,-33.58],[151.28,-33.93],[151.24,-33.99],[151.12,-34.01],[151.23,-34.03],[150.96,-34.3],[150.78,-34.89],[150.81,-34.99],[150.68,-35.08],[150.71,-35.16],[150.57,-35.21],[150.2,-35.83],[149.93,-37.53],[147.88,-37.93],[146.86,-38.66],[146.22,-38.73],[146.45,-39.11],[146.16,-38.87],[146.07,-38.83],[145.94,-38.9],[145.79,-38.67],[145.61,-38.66],[145.4,-38.54],[145.46,-38.42],[145.54,-38.39],[145.48,-38.24],[145.29,-38.24],[145.19,-38.38],[144.96,-38.5],[144.72,-38.34],[144.91,-38.34],[145.12,-38.09],[144.89,-37.9],[144.4,-38.14],[144.67,-38.21],[144.1,-38.46],[143.69,-38.77],[141.93,-38.28],[141.43,-38.36],[140.39,-37.9],[139.78,-37.25],[139.73,-36.37],[138.98,-35.62],[139.29,-35.61],[139.28,-35.38],[138.19,-35.61],[138.51,-35.02],[138.09,-34.17],[137.69,-35.14],[136.88,-35.24],[137.02,-34.92],[137.39,-34.91],[137.49,-34.16],[137.93,-33.58],[137.78,-32.58],[137.24,-33.63],[136.43,-34.03],[135.89,-34.66],[135.97,-34.98],[135.65,-34.94],[135.12,-34.59],[135.45,-34.58],[135.22,-33.96],[134.72,-33.26],[134.3,-33.17],[134.23,-32.55],[131.14,-31.5],[128.95,-31.7],[127.32,-32.26],[125.92,-32.3],[124.24,-33.01],[123.51,-33.92],[119.85,-33.97],[117.86,-35.05],[116.52,-34.99],[115.01,-34.26],[114.99,-33.51],[115.36,-33.64],[115.61,-33.37],[115.68,-33.19],[115.62,-32.67],[115.71,-32.57],[115.74,-31.89],[115.7,-31.7],[115.08,-30.56],[114.86,-29.14],[114.17,-28.08],[114.03,-27.35],[113.18,-26.18],[113.36,-26.08],[113.58,-26.56],[113.83,-26.5],[113.45,-25.6],[113.72,-26.13],[114.22,-26.29],[114.21,-25.85],[113.42,-24.44],[113.96,-21.94],[114.12,-21.83],[114.14,-22.48],[114.71,-21.82],[116.71,-20.65],[117.41,-20.72],[119.11,-19.99],[121,-19.6],[122.35,-18.11],[122.14,-17.43],[122.33,-17.06],[122.97,-16.44],[123.56,-17.52],[123.59,-17.03],[123.83,-17.12],[123.88,-16.92],[123.49,-16.49],[123.61,-16.22],[124.77,-16.4],[124.4,-16.3],[124.65,-15.87],[124.38,-15.76],[124.44,-15.49],[124.69,-15.27],[125.06,-15.44],[124.84,-15.16],[125.36,-15.12],[125.18,-14.72],[125.63,-14.26],[125.66,-14.53],[126.02,-14.5],[126.05,-13.98],[126.57,-14.16],[126.9,-13.74],[127.46,-14.03],[128.18,-14.71],[128.07,-15.33],[128.58,-14.77],[129.64,-15.14],[129.64,-14.85],[129.85,-14.83],[129.38,-14.39],[129.94,-13.5],[130.14,-13.45],[130.26,-13.3],[130.14,-13.15],[130.17,-12.96],[130.32,-12.88],[130.4,-12.69],[130.62,-12.65],[130.62,-12.43],[130.74,-12.43],[130.87,-12.56],[130.87,-12.37],[131.03,-12.34],[131.05,-12.19],[131.22,-12.18],[131.29,-12.07],[131.34,-12.21],[131.44,-12.28],[131.89,-12.23],[132.07,-12.28],[132.25,-12.19],[132.41,-12.3],[132.44,-12.18],[132.58,-12.11],[132.67,-11.65],[132.28,-11.47],[132.13,-11.5],[131.81,-11.27],[131.96,-11.18],[132.16,-11.31],[135.03,-12.19],[135.92,-11.83],[135.71,-12.21],[135.94,-12.15],[136.08,-12.42],[136.54,-11.96],[136.95,-12.35],[136.46,-13.23],[135.93,-13.3],[135.95,-13.93],[135.45,-14.92],[140.04,-17.7],[140.83,-17.41],[141.29,-16.46],[141.63,-15.06],[141.61,-12.94],[141.93,-12.74],[141.69,-12.35],[142.46,-10.71],[142.78,-11.12],[142.87,-11.82],[143.07,-11.92]],[[-29.95,83.56],[-25.8,83.26],[-32.03,82.98],[-25.12,83.16],[-24.47,82.88],[-21.52,82.6],[-23.12,82.33],[-29.89,82.05],[-25.15,82],[-24.29,81.7],[-22.94,82.03],[-21.13,81.93],[-21.5,81.44],[-23.12,80.78],[-19.63,81.64],[-17.45,81.4],[-15.45,81.84],[-11.42,81.48],[-14.45,80.99],[-14.23,80.87],[-14.5,80.76],[-16.76,80.57],[-15.94,80.43],[-16.49,80.25],[-19.43,80.26],[-20.15,80.01],[-20.07,79.77],[-19.35,79.73],[-19.41,79.35],[-18.99,79.18],[-21.13,78.66],[-20.95,78.55],[-21.73,77.71],[-20.86,77.91],[-19.49,77.72],[-19.29,77.59],[-20.68,77.62],[-20.23,77.37],[-18.44,77.26],[-18.34,76.92],[-22.61,76.68],[-21.49,76.27],[-19.86,76.12],[-19.4,75.49],[-19.52,75.18],[-22.23,75.12],[-20.99,75.07],[-20.78,74.89],[-21.04,74.65],[-20.86,74.64],[-19.99,74.98],[-19.27,74.34],[-21.13,74.11],[-21.95,74.24],[-21.76,74.48],[-21.98,74.57],[-22.33,74.29],[-22.13,73.99],[-20.37,73.85],[-20.64,73.46],[-22.35,73.27],[-24.16,73.77],[-24.68,73.6],[-25.52,73.85],[-24.78,73.54],[-26.06,73.25],[-27.27,73.44],[-26.54,73.25],[-27.56,73.14],[-24.13,73.41],[-22.04,72.92],[-22.29,72.12],[-24.07,72.5],[-24.63,73.04],[-26.66,72.72],[-24.81,72.9],[-24.7,72.51],[-25.2,72.39],[-21.96,71.74],[-22.48,71.38],[-21.75,71.48],[-21.52,70.53],[-22.38,70.46],[-22.44,70.86],[-22.69,70.44],[-23.33,70.45],[-23.97,70.65],[-24.56,71.22],[-27.09,71.63],[-25.84,71.48],[-25.67,71.27],[-26.72,70.95],[-28.4,70.99],[-27.98,70.84],[-29.07,70.44],[-26.51,70.4],[-27.63,70.03],[-27.38,69.99],[-25.53,70.35],[-22.21,70.11],[-23.87,69.74],[-23.74,69.59],[-24.3,69.58],[-26.48,68.68],[-30.98,68.06],[-32.33,68.44],[-32.16,67.99],[-33.16,67.63],[-34.63,66.43],[-35.19,66.25],[-35.87,66.44],[-35.63,66.14],[-37.76,65.59],[-38,65.71],[-37.28,66.3],[-38.15,66.39],[-37.75,66.26],[-38.14,65.9],[-38.52,66.01],[-38.2,65.71],[-40.17,65.56],[-39.58,65.34],[-41.09,65.03],[-40.18,64.48],[-40.78,64.22],[-41.58,64.3],[-40.62,64.13],[-40.55,63.73],[-41.39,63.06],[-42.18,63.21],[-41.64,62.97],[-41.91,62.74],[-42.94,62.72],[-42.15,62.57],[-42.32,62.15],[-42.11,61.86],[-42.59,61.72],[-42.32,61.68],[-43.04,60.52],[-43.92,60.6],[-43.21,60.39],[-43.12,60.06],[-43.95,60.02],[-43.66,59.86],[-43.91,59.81],[-44.41,59.92],[-44.22,60.27],[-44.61,60.02],[-45.38,60.2],[-44.76,60.67],[-45.38,60.44],[-46.05,60.61],[-45.87,61.22],[-46.87,60.82],[-48.18,60.77],[-47.77,61],[-48.39,61.01],[-49.29,61.59],[-49.38,61.89],[-48.83,62.08],[-49.62,62],[-49.55,62.23],[-50.32,62.47],[-49.79,63.05],[-50.39,62.82],[-51.47,63.64],[-51.55,64.01],[-50.26,64.21],[-51.71,64.2],[-50.68,64.68],[-50.01,64.45],[-50.12,64.7],[-50.96,65.2],[-50.72,64.8],[-51.26,64.76],[-51.92,64.22],[-52.54,65.33],[-51.09,65.78],[-52.55,65.46],[-53.2,65.59],[-53.11,65.98],[-53.39,66.05],[-51.23,66.88],[-53.61,66.15],[-53.42,66.65],[-52.39,66.88],[-53.69,66.99],[-53.8,67.42],[-52.51,67.76],[-50.61,67.53],[-51.17,67.69],[-50.97,67.81],[-52.35,67.84],[-53.74,67.55],[-53.15,68.21],[-51.6,68.06],[-51.17,68.39],[-53.38,68.3],[-53.04,68.61],[-51.13,68.6],[-50.8,68.79],[-51.25,68.74],[-51.09,69.13],[-50.3,69.17],[-51.08,69.21],[-50.32,70.03],[-52.26,70.06],[-54.53,70.7],[-52.8,70.75],[-50.68,70.4],[-51.77,71.01],[-51.02,71],[-53.12,71.31],[-51.78,71.68],[-53.44,71.58],[-53.15,71.81],[-53.81,72.29],[-53.65,72.36],[-53.93,72.32],[-53.48,71.85],[-54.02,71.66],[-53.96,71.46],[-55.59,71.55],[-55.32,72.11],[-54.84,72.38],[-55.58,72.18],[-55.29,72.35],[-55.6,72.45],[-54.92,72.57],[-54.74,72.87],[-55.67,73.01],[-55.29,73.33],[-56.1,73.56],[-55.84,73.76],[-56.23,74.13],[-57.23,74.12],[-56.26,74.53],[-58.57,75.35],[-58.25,75.51],[-58.52,75.69],[-63.29,76.35],[-67.08,76.2],[-66.83,75.97],[-68.32,76.09],[-69.48,76.4],[-68.11,76.65],[-69.89,76.83],[-69.69,76.99],[-70.61,76.82],[-71.16,77.07],[-68.14,77.38],[-66.39,77.28],[-66.27,77.51],[-66.82,77.69],[-69.35,77.47],[-70.56,77.72],[-70.12,77.84],[-71.27,77.81],[-72.82,78.19],[-71.65,78.62],[-65.82,79.17],[-64.79,80],[-64.18,80.1],[-66.84,80.08],[-67.19,80.28],[-64.51,81],[-63.06,80.89],[-63.24,81.08],[-62.99,81.21],[-61.44,81.13],[-61.1,81.4],[-61.2,81.75],[-60.43,81.92],[-56.62,81.36],[-59.27,81.98],[-54.55,82.35],[-53.67,82.16],[-53.56,81.65],[-53.04,81.87],[-53.02,82.32],[-50.9,81.89],[-49.54,81.92],[-50.99,82.46],[-50.04,82.47],[-44.73,81.78],[-44.33,82.47],[-45.56,82.75],[-41.37,82.75],[-46.48,82.95],[-43.01,83.26],[-41.3,83.1],[-40.36,83.33],[-38.15,83],[-37.94,83.16],[-38.75,83.37],[-30.7,83.59]],[[-86.59,71.01],[-84.82,71.03],[-84.7,71.63],[-85.91,71.99],[-85.32,72.23],[-84.28,72.04],[-85.65,72.72],[-85.26,72.95],[-84.26,72.8],[-85.46,73.11],[-83.41,73.63],[-81.6,73.7],[-80.28,72.77],[-81.23,72.31],[-80.61,72.45],[-80.95,71.92],[-79.88,72.18],[-80.11,72.33],[-79.83,72.45],[-79,72.27],[-79.01,72.04],[-78.58,71.88],[-78.86,72.1],[-78.7,72.35],[-77.52,72.18],[-78.42,72.57],[-77.25,72.74],[-75.07,72.32],[-75.92,71.72],[-75.15,72.06],[-74.27,72.04],[-74.32,71.84],[-75.21,71.71],[-74.7,71.68],[-75,71.22],[-74.49,71.65],[-73.87,71.77],[-73.71,71.72],[-74.2,71.4],[-73.71,71.59],[-73.18,71.28],[-73.28,71.54],[-72.9,71.68],[-71.64,71.52],[-71.19,71.28],[-72.63,70.83],[-70.67,71.05],[-70.76,70.79],[-71.89,70.43],[-71.28,70.5],[-71.43,70.13],[-70.98,70.58],[-70.08,70.83],[-68.5,70.61],[-68.48,70.41],[-70.06,70.04],[-68.78,70.2],[-69.01,69.98],[-68.74,69.94],[-67.86,70.28],[-67.19,69.76],[-69.25,69.51],[-66.68,69.26],[-69.04,69.1],[-67.75,69.04],[-67.88,68.78],[-69.32,68.86],[-66.71,68.45],[-67.03,68.33],[-66.92,68.07],[-66.21,68.28],[-66.53,67.85],[-65.94,68.07],[-65.51,67.97],[-65.4,67.68],[-65.41,67.88],[-64.98,68.04],[-65.02,67.79],[-63.85,67.57],[-64.59,67.32],[-63.04,67.23],[-63.7,66.82],[-62.12,67.05],[-61.3,66.65],[-62.12,66.64],[-61.58,66.41],[-61.86,66.31],[-62.55,66.41],[-61.99,66.03],[-62.59,66.03],[-62.38,65.83],[-62.66,65.64],[-63.46,65.85],[-63.65,65.66],[-63.34,65.62],[-63.36,65.23],[-63.61,64.93],[-64.35,65.17],[-64.27,65.4],[-64.55,65.12],[-65.4,65.76],[-64.45,66.32],[-65.82,66],[-65.66,66.2],[-66.06,66.13],[-66.99,66.63],[-67.31,66.57],[-67.23,66.31],[-67.88,66.47],[-67.18,66.03],[-67.35,65.93],[-68.75,66.2],[-68.22,66.08],[-67.87,65.77],[-67.94,65.56],[-67.12,65.44],[-67.34,65.35],[-66.7,64.82],[-66.63,65],[-66.21,64.72],[-65.94,64.89],[-65.43,64.73],[-65.27,64.63],[-65.53,64.51],[-65.08,64.44],[-65.58,64.29],[-64.68,64.03],[-64.8,63.92],[-64.41,63.71],[-64.67,63.24],[-65.19,63.76],[-64.67,62.92],[-65.16,62.93],[-65.11,62.63],[-66.66,63.26],[-66.72,63.08],[-67.89,63.73],[-67.72,63.42],[-68.91,63.7],[-65.98,62.21],[-66.33,61.87],[-71.35,63.07],[-71.99,63.42],[-71.38,63.58],[-72.5,63.82],[-73.45,64.4],[-73.27,64.58],[-74.07,64.43],[-74.68,64.83],[-74.92,64.77],[-74.7,64.5],[-76.86,64.24],[-78.17,64.62],[-78.05,64.98],[-77.36,65.2],[-77.33,65.45],[-75.83,65.23],[-75.45,64.84],[-75.36,65.01],[-75.8,65.3],[-73.55,65.48],[-74.42,66.17],[-72.22,67.26],[-73.28,68.36],[-73.82,68.36],[-73.85,68.7],[-74.42,68.58],[-74.91,68.82],[-74.85,69.07],[-76.59,68.7],[-76.56,69.01],[-75.65,69.21],[-76.52,69.52],[-76.23,69.66],[-77.09,69.64],[-76.86,69.78],[-77.59,69.85],[-77.77,70.24],[-79.07,70.6],[-79.4,70.4],[-78.81,70.18],[-79.09,69.93],[-81.65,70.1],[-80.92,69.73],[-81.56,69.94],[-85.78,70.04],[-86.32,70.15],[-86.4,70.47],[-87.9,70.25],[-88.85,70.52],[-89.46,71.06],[-87.14,71.01],[-89.69,71.42],[-90.02,71.95],[-89.66,72.17],[-89.82,72.47],[-88.71,73.4],[-86.77,73.83],[-85.01,73.78],[-86.67,72.76],[-86.32,72.46],[-86.22,71.9],[-85.02,71.35],[-86.47,71.04]],[[-69.49,83.02],[-66.42,82.93],[-68.47,82.65],[-64.9,82.9],[-63.5,82.79],[-63.64,82.71],[-63.09,82.56],[-63.25,82.45],[-61.21,82.34],[-68.69,81.29],[-64.78,81.49],[-69.55,80.38],[-70.71,80.54],[-70.26,80.23],[-72.06,80.12],[-70.56,80.07],[-71.39,79.76],[-74.39,79.87],[-74.66,79.84],[-73.2,79.6],[-76.9,79.51],[-74.48,79.23],[-74.53,79.05],[-78.58,79.08],[-74.43,78.72],[-76.42,78.51],[-75.19,78.33],[-75.97,77.99],[-78.01,77.95],[-78.08,77.52],[-78.49,77.37],[-81.66,77.53],[-81.28,77.37],[-82.06,77.3],[-79.5,77.2],[-79.22,76.94],[-78,76.85],[-78.28,76.57],[-80.8,76.17],[-80.97,76.47],[-82.53,76.72],[-82.23,76.47],[-83.89,76.45],[-84.22,76.67],[-84.28,76.36],[-86.45,76.58],[-86.68,76.38],[-87.49,76.59],[-87.5,76.39],[-88.4,76.41],[-88.49,76.77],[-88.54,76.42],[-89.57,76.49],[-89.5,76.83],[-88.56,77.07],[-86.81,77.19],[-87.68,77.44],[-88.02,77.78],[-86.76,77.86],[-84.49,77.37],[-83.61,77.44],[-82.59,77.99],[-83.78,77.53],[-84.86,77.5],[-85.29,77.56],[-85.55,77.93],[-84.22,78.18],[-84.91,78.24],[-84.78,78.53],[-85.59,78.11],[-86.22,78.08],[-85.92,78.34],[-87.55,78.18],[-86.81,78.77],[-81.75,78.98],[-84.41,79],[-84.57,79.07],[-83.58,79.05],[-86.42,79.84],[-86.5,80.26],[-83.72,80.23],[-80.48,79.61],[-80.12,79.67],[-81.01,79.69],[-82.99,80.32],[-76.86,80.87],[-78.72,80.95],[-76.88,81.43],[-81.01,80.66],[-85.15,80.52],[-86.62,80.63],[-83.29,81.15],[-85.78,81.04],[-87.71,80.66],[-89.26,80.91],[-84.94,81.29],[-89.62,81.03],[-89.98,81.12],[-89.21,81.25],[-89.68,81.33],[-89.43,81.39],[-87.6,81.53],[-90.31,81.4],[-90.61,81.43],[-89.82,81.63],[-91.68,81.64],[-88.06,82.1],[-85.05,81.98],[-86.62,82.22],[-84.9,82.45],[-79.43,81.85],[-82.45,82.39],[-81.68,82.52],[-82.12,82.63],[-80.81,82.59],[-81.18,82.75],[-81.01,82.78],[-78.75,82.68],[-80.16,82.91],[-79.89,82.94],[-77.48,82.88],[-76.01,82.54],[-75.57,82.61],[-77.13,83.01],[-74.41,83.01],[-72.66,82.72],[-73.44,82.95],[-69.57,83.02]],[[133.47,-0.73],[134.11,-0.85],[134.19,-2.31],[134.46,-2.83],[134.63,-2.54],[135.09,-3.35],[135.49,-3.34],[136.39,-2.27],[137.07,-2.11],[137.12,-1.84],[137.91,-1.48],[139.79,-2.35],[144.48,-3.83],[145.77,-4.82],[145.75,-5.4],[147.42,-5.97],[147.8,-6.31],[147.81,-6.7],[146.95,-6.88],[147.26,-7.46],[148.13,-8.1],[148.58,-9.05],[149.2,-9.03],[149.26,-9.5],[150.01,-9.69],[149.76,-9.81],[149.87,-10.01],[150.85,-10.24],[150.45,-10.31],[150.65,-10.52],[150.32,-10.65],[149.75,-10.35],[147.77,-10.07],[146.03,-8.08],[144.51,-7.57],[144.14,-7.76],[143.65,-7.46],[143.94,-7.95],[143.52,-8],[143.61,-8.2],[142.21,-8.2],[143.38,-8.76],[142.65,-9.33],[141.13,-9.22],[140,-8.2],[140.12,-7.92],[139.38,-8.19],[139.25,-7.98],[138.93,-8.26],[139.09,-7.59],[138.75,-7.25],[139.18,-7.19],[138.6,-6.94],[138.87,-6.86],[138.44,-6.34],[138.34,-5.68],[138.09,-5.71],[137.28,-4.95],[135.19,-4.45],[134.68,-4.08],[134.89,-3.94],[133.97,-3.82],[133.68,-3.48],[133.84,-3.05],[133.4,-3.9],[132.97,-4.09],[132.75,-3.29],[131.97,-2.79],[132.72,-2.79],[133.19,-2.44],[133.7,-2.62],[133.92,-2.1],[132.31,-2.24],[131.93,-1.56],[131,-1.42],[131.26,-0.86],[132.39,-0.36],[133.27,-0.64]],[[116.81,6.69],[117.23,6.94],[117.69,6.35],[117.5,5.88],[118,6.05],[117.97,5.71],[118.35,5.81],[119.26,5.37],[119.13,5.1],[118.26,4.99],[118.55,4.38],[117.5,4.13],[117.78,3.69],[117.06,3.62],[118.06,2.32],[117.79,2.03],[118.99,0.98],[118.53,0.81],[117.91,1.1],[117.52,0.24],[117.56,-0.77],[116.91,-1.22],[116.74,-1.04],[116.75,-1.33],[116.28,-1.79],[116.55,-2.41],[115.96,-3.59],[114.7,-4.17],[114.34,-3.24],[113.71,-3.46],[113.04,-2.93],[112.76,-3.32],[111.86,-3.55],[111.7,-2.89],[110.26,-2.97],[109.98,-1.28],[109.29,-0.85],[109.13,-0.45],[109.26,0.03],[108.91,0.79],[109.08,1.5],[109.63,2.03],[111.22,1.4],[111.04,1.63],[111.51,2.74],[112.99,3.16],[114.01,4.57],[114.99,5.02],[115.43,4.97],[115.42,5.41],[115.88,5.61],[116.78,6.99],[116.84,6.77]],[[-114.52,72.59],[-113.58,72.65],[-113.08,73],[-111.27,72.71],[-111.89,72.36],[-111.67,72.3],[-110.21,72.66],[-110.66,73.01],[-110.01,72.98],[-108.76,72.55],[-108.19,71.72],[-107.81,71.63],[-107.3,71.9],[-107.7,72.15],[-108.24,73.15],[-107.93,73.22],[-108.03,73.35],[-106.48,73.2],[-105.41,72.79],[-104.38,71.58],[-104.51,71.06],[-103.59,70.63],[-101.09,70.14],[-100.91,69.81],[-102.24,69.84],[-102.62,69.55],[-103.43,69.67],[-103.05,69.47],[-103.12,69.2],[-102.15,69.49],[-101.79,69.18],[-102.89,68.82],[-105.1,68.92],[-105.02,69.08],[-106.14,69.16],[-106.66,69.44],[-107.44,69],[-109.47,68.68],[-113.02,68.48],[-113.55,68.77],[-113.69,69.19],[-116.51,69.43],[-117.19,70.05],[-111.63,70.31],[-113.76,70.69],[-117.59,70.63],[-118.38,70.97],[-115.3,71.49],[-117.94,71.39],[-118.23,71.47],[-117.74,71.66],[-118.99,71.76],[-118.94,71.99],[-118.21,72.26],[-118.37,72.53],[-116.57,73.06],[-114.21,73.3],[-114.08,72.91],[-114.5,72.63]],[[49.54,-12.43],[49.94,-13.07],[50.41,-15.63],[50.19,-15.96],[49.89,-15.46],[49.66,-15.52],[49.84,-16.49],[49.45,-17.24],[49.36,-18.34],[47.18,-24.79],[46.73,-25.15],[45.11,-25.54],[44.03,-25],[43.26,-22.38],[43.5,-21.36],[44.4,-19.92],[43.98,-17.39],[44.48,-16.22],[46.16,-15.74],[46.4,-15.93],[46.47,-15.51],[46.94,-15.22],[47.1,-15.43],[47.35,-14.77],[47.48,-15.01],[47.97,-14.67],[47.77,-14.37],[47.94,-13.66],[48.26,-13.72],[48.8,-13.27],[48.79,-12.47],[49.21,-12.08],[49.48,-12.35]],[[96.49,5.23],[97.55,5.21],[98.31,4.09],[99.73,3.18],[100.31,2.47],[100.53,2.19],[100.82,1.99],[100.89,1.95],[100.83,2.24],[100.94,2.29],[101.05,2.26],[101.3,2.01],[101.48,1.69],[101.79,1.62],[102.39,0.84],[102.57,0.75],[102.85,0.72],[103.03,0.58],[103.07,0.49],[102.79,0.3],[102.55,0.22],[102.78,0.24],[103.34,0.51],[103.48,0.48],[103.67,0.29],[103.79,0.05],[103.43,-0.19],[103.53,-0.75],[104.38,-1.07],[104.51,-1.82],[104.85,-2.09],[104.65,-2.59],[105.4,-2.38],[106.04,-3.11],[105.89,-5.01],[105.82,-5.68],[105.75,-5.82],[105.62,-5.8],[105.52,-5.67],[104.64,-5.52],[104.6,-5.91],[101.58,-3.17],[100.89,-2.25],[100.31,-0.83],[99.16,0.35],[98.6,1.87],[97.7,2.36],[96.97,3.58],[95.58,4.66],[95.23,5.56],[96.25,5.27]],[[-3.11,58.52],[-3.99,57.96],[-3.86,57.82],[-4.13,57.58],[-1.96,57.68],[-1.78,57.47],[-2.09,57.1],[-2.26,56.86],[-2.59,56.56],[-3.31,56.36],[-2.89,56.4],[-2.65,56.32],[-2.67,56.25],[-2.98,56.19],[-3.36,56.03],[-3.79,56.09],[-3.61,56.02],[-3.05,55.95],[-2.84,56.03],[-2.6,56.03],[-2.15,55.9],[-1.65,55.57],[-1.23,54.7],[-0.08,54.12],[0.12,53.61],[-0.66,53.72],[0.13,53.47],[0.35,53.16],[0.21,53.03],[0.05,52.91],[0.33,52.81],[0.52,52.94],[1.66,52.75],[1.75,52.47],[1.32,51.96],[1.23,51.97],[1.28,51.84],[1.19,51.8],[0.96,51.81],[0.75,51.73],[0.9,51.69],[0.89,51.57],[0.42,51.47],[0.53,51.49],[0.69,51.39],[0.89,51.36],[1.42,51.36],[1.4,51.18],[1.05,51.05],[0.96,50.93],[0.77,50.93],[0.2,50.76],[-0.2,50.82],[-0.79,50.76],[-1.42,50.9],[-1.33,50.82],[-1.52,50.75],[-3,50.72],[-3.4,50.63],[-3.68,50.24],[-3.79,50.23],[-4.2,50.39],[-4.73,50.29],[-5.01,50.16],[-5.12,50.04],[-5.23,50.02],[-5.43,50.11],[-5.62,50.05],[-5.66,50.13],[-5.34,50.25],[-4.89,50.53],[-4.58,50.78],[-4.52,50.98],[-4.3,51.03],[-4.19,51.19],[-3.84,51.23],[-3.26,51.19],[-3.04,51.25],[-2.43,51.74],[-3.29,51.39],[-3.56,51.41],[-3.89,51.59],[-4.24,51.57],[-4.09,51.66],[-4.39,51.74],[-4.6,51.74],[-4.9,51.63],[-5.12,51.71],[-5.2,51.86],[-5.26,51.88],[-5.09,52],[-4.38,52.2],[-4.15,52.33],[-4.1,52.92],[-4.68,52.84],[-3.81,53.3],[-3.32,53.35],[-3.1,53.26],[-3.17,53.39],[-3.07,53.43],[-2.92,53.3],[-2.75,53.31],[-2.91,53.35],[-3.07,53.51],[-2.93,53.73],[-3.03,53.77],[-3.03,53.91],[-2.9,53.96],[-2.87,54.18],[-3.17,54.13],[-3.57,54.47],[-3.59,54.56],[-3.47,54.77],[-3.27,54.91],[-3.04,54.95],[-3.55,54.95],[-3.96,54.78],[-4.3,54.84],[-4.91,54.69],[-5.17,54.92],[-4.68,55.5],[-4.73,55.6],[-4.87,55.87],[-4.58,55.94],[-4.67,55.97],[-4.8,56.16],[-5.23,55.89],[-5.09,56.2],[-5.77,55.36],[-5.19,56.76],[-5.65,56.53],[-6.13,56.71],[-5.59,57.1],[-5.82,57.44],[-5.58,57.55],[-5.69,57.78],[-5.16,57.88],[-5.41,58.07],[-5.01,58.26],[-4.98,58.58],[-3.06,58.59]],[[141.23,41.37],[141.45,41.4],[141.43,40.72],[141.8,40.29],[141.98,39.43],[141.47,38.4],[140.96,38.15],[141,37.11],[140.79,36.85],[140.63,36.5],[140.57,36.23],[140.62,36.06],[140.87,35.72],[140.64,35.66],[140.46,35.51],[140.36,35.18],[140.06,35.04],[139.92,34.9],[139.8,34.96],[139.84,35.01],[139.83,35.3],[140.1,35.59],[139.99,35.67],[139.83,35.66],[139.77,35.49],[139.65,35.41],[139.74,35.25],[139.68,35.15],[139.47,35.3],[139.25,35.28],[139.13,35.15],[139.09,34.84],[138.98,34.7],[138.84,34.62],[138.76,34.7],[138.8,34.97],[138.9,35.02],[138.72,35.12],[138.58,35.09],[138.35,34.85],[138.19,34.6],[137.06,34.58],[137.3,34.73],[137.1,34.76],[136.96,34.84],[136.94,34.72],[136.87,34.73],[136.85,34.98],[136.9,35.03],[136.8,35.05],[136.69,34.98],[136.53,34.68],[136.88,34.43],[136.85,34.32],[136.33,34.18],[135.92,33.56],[135.69,33.49],[135.45,33.55],[135.13,34.01],[135.1,34.29],[135.31,34.42],[135.42,34.62],[135.04,34.63],[134.74,34.77],[134.25,34.71],[133.97,34.53],[132.31,34.32],[132.14,33.84],[131.74,34.05],[130.92,33.98],[131,34.39],[131.35,34.41],[132.75,35.45],[134.21,35.54],[134.46,35.63],[135.18,35.75],[135.27,35.72],[135.23,35.59],[135.27,35.55],[135.68,35.5],[136.01,35.68],[136.09,35.77],[136.01,35.99],[136.07,36.12],[136.7,36.74],[136.84,37.38],[137.32,37.52],[136.9,37.12],[137.3,36.75],[138.32,37.22],[139.36,38.1],[140.04,39.41],[140,39.86],[139.74,39.92],[140.01,40.26],[139.92,40.6],[140.39,41.23],[140.75,40.83],[141.12,40.88],[141.25,41.21],[140.8,41.25],[140.94,41.5],[141.11,41.46]],[[-119.74,74.11],[-117.51,74.23],[-115.39,73.5],[-118.96,72.68],[-120.18,72.21],[-120.62,71.51],[-122.84,71.1],[-124.01,71.68],[-125.84,71.98],[-124.99,72.59],[-124.97,72.84],[-124.57,72.94],[-124.8,73.13],[-123.8,73.77],[-124.7,74.35],[-121.5,74.54],[-119.56,74.23],[-119.74,74.13]],[[-91.89,81.13],[-90.64,80.59],[-89.24,80.51],[-88.86,80.17],[-88.2,80.11],[-88.61,80.26],[-88.52,80.42],[-87.67,80.37],[-87.92,80.1],[-86.98,79.89],[-87.3,79.58],[-85.65,79.61],[-85.04,79.28],[-87.62,78.68],[-87.92,78.75],[-87.83,79.05],[-88.04,79],[-88.25,78.67],[-87.98,78.54],[-88.74,78.58],[-88.79,78.19],[-90.04,78.61],[-89.49,78.17],[-91.41,78.19],[-92.85,78.46],[-91.87,78.54],[-93.27,78.61],[-93.64,78.75],[-93.16,78.78],[-94.17,78.97],[-91.3,79.37],[-95.1,79.29],[-95.73,79.42],[-94.4,79.74],[-95.86,79.67],[-96.77,80.14],[-94.26,80.2],[-96.39,80.32],[-95.55,80.37],[-96.15,80.55],[-95.93,80.72],[-93.93,80.56],[-95.51,80.84],[-95.27,81],[-93.24,81.13],[-94.18,81.34],[-92,81.18]],[[-15.54,66.23],[-14.6,66.38],[-15.11,66.1],[-14.7,66.02],[-14.83,65.76],[-14.39,65.79],[-14.47,65.57],[-13.62,65.52],[-13.8,65.35],[-13.57,65.07],[-14.63,64.42],[-18.08,63.5],[-20.49,63.69],[-20.41,63.81],[-20.65,63.74],[-21.14,63.89],[-21.09,63.93],[-21.15,63.94],[-21.45,63.86],[-22.65,63.83],[-22.69,63.87],[-22.74,64.02],[-22.7,64.08],[-22.51,63.99],[-22.06,64.07],[-21.67,64.35],[-21.46,64.38],[-21.65,64.4],[-22.05,64.31],[-21.9,64.39],[-22,64.41],[-21.95,64.52],[-21.59,64.63],[-22.16,64.54],[-22.33,64.63],[-22.25,64.73],[-22.47,64.8],[-24.02,64.86],[-23.32,64.96],[-22.79,65.05],[-21.89,65.05],[-21.8,65.11],[-21.78,65.19],[-22.04,65.13],[-22.51,65.2],[-21.84,65.45],[-22.31,65.48],[-22.64,65.57],[-24.47,65.52],[-23.86,65.54],[-24.09,65.78],[-23.29,65.75],[-23.83,65.85],[-23.52,65.88],[-23.78,66.02],[-23.45,66.18],[-22.44,65.91],[-22.95,66.21],[-22.48,66.27],[-23.12,66.34],[-22.89,66.44],[-21.41,66.03],[-21.38,65.74],[-21.66,65.72],[-21.36,65.58],[-21.43,65.47],[-21.23,65.42],[-21.13,65.27],[-21.05,65.43],[-20.45,65.57],[-20.21,66.1],[-19.49,65.77],[-19.38,66.08],[-18.84,66.18],[-18.14,65.73],[-18.3,66.16],[-17.55,65.96],[-16.49,66.2],[-16.54,66.45],[-16.25,66.52],[-15.65,66.26]],[[-94.29,76.91],[-93.21,76.75],[-93.53,76.45],[-91.31,76.68],[-90.54,76.5],[-91.41,76.46],[-89.29,76.3],[-91.41,76.22],[-89.28,75.79],[-89.65,75.57],[-88.92,75.45],[-88.65,75.66],[-85.95,75.4],[-83.93,75.82],[-82.15,75.83],[-79.66,75.45],[-79.51,75.26],[-80.38,75.03],[-79.4,74.92],[-80.35,74.9],[-80.15,74.8],[-80.28,74.58],[-81.94,74.47],[-82.93,74.57],[-83.52,74.9],[-83.34,74.77],[-83.53,74.59],[-84.43,74.51],[-88.42,74.49],[-88.34,74.78],[-88.53,74.83],[-89.56,74.56],[-90.88,74.82],[-91.51,74.65],[-92.39,75.26],[-92.07,75.66],[-92.18,75.85],[-93.09,76.35],[-95.27,76.26],[-96.04,76.49],[-95.65,76.58],[-96.9,76.75],[-96.4,76.8],[-96.76,76.97],[-95.85,77.07],[-94.61,76.96]],[[173.12,-41.28],[173.95,-40.92],[173.8,-41.27],[174,-40.99],[174.3,-41.02],[174.04,-41.24],[174.37,-41.1],[174.07,-41.43],[174.21,-41.85],[172.53,-43.47],[173.1,-43.84],[172.04,-43.7],[172.18,-43.9],[171.24,-44.26],[170.78,-45.87],[169.69,-46.55],[169.1,-46.63],[168.38,-46.61],[167.54,-46.15],[166.83,-46.23],[166.92,-45.96],[166.49,-45.96],[167,-45.71],[166.73,-45.54],[166.87,-45.31],[167.16,-45.41],[167.03,-45.12],[167.91,-44.67],[168.37,-44.08],[169.18,-43.91],[171.04,-42.86],[172.27,-40.76],[172.94,-40.52],[172.7,-40.67],[173.07,-41.19]],[[16.79,79.91],[17.83,79.8],[17.67,79.39],[18.4,79.61],[18.82,79.43],[18.68,79.26],[20.61,79.11],[20.77,79.06],[20.5,78.98],[21.39,78.74],[19.15,78.38],[16.7,76.58],[14,77.51],[16.91,77.9],[14.09,77.77],[13.68,78.03],[17.17,78.42],[16.45,78.5],[16.78,78.66],[15.42,78.47],[15.38,78.77],[14.69,78.72],[14.43,78.49],[14.64,78.41],[13.15,78.24],[11.37,78.95],[12.4,78.95],[11.98,79.03],[11.98,79.29],[11.21,79.13],[10.68,79.76],[13.69,79.86],[13.92,79.76],[12.56,79.57],[13.96,79.34],[14.59,79.8],[16.34,78.98],[15.83,79.71],[16.25,80.05],[16.52,80.02]],[[67.77,76.24],[61.36,75.32],[59.67,74.61],[58.53,74.5],[58.62,74.23],[57.77,74.01],[57.76,73.77],[57.31,73.84],[57.54,73.66],[56.63,73.31],[54.3,73.35],[53.76,73.77],[55.34,74.42],[56.14,74.5],[55.58,74.63],[56.5,74.96],[55.81,75.12],[57.61,75.34],[58.88,75.86],[60.94,76.07],[61.2,76.28],[64.46,76.38],[67.53,77.01],[68.94,76.71],[68.16,76.28]],[[124.89,1],[124.43,0.47],[123.75,0.31],[120.58,0.53],[120.19,0.27],[120.06,-0.55],[120.67,-1.37],[121.15,-1.34],[121.58,-0.83],[121.97,-0.93],[123.17,-0.57],[123.43,-0.78],[123.38,-1],[122.9,-0.9],[122.25,-1.55],[121.36,-1.88],[122.29,-2.91],[122.25,-3.62],[122.85,-4.07],[122.87,-4.39],[122.12,-4.54],[122.04,-4.83],[121.59,-4.76],[121.62,-4.09],[120.89,-3.52],[121.05,-2.75],[120.65,-2.67],[120.26,-2.95],[120.43,-5.59],[119.56,-5.61],[119.36,-5.32],[119.62,-4.03],[119.47,-3.51],[118.92,-3.48],[118.78,-2.72],[119.32,-1.93],[119.51,-0.91],[119.71,-0.68],[119.84,-0.86],[119.72,-0.09],[120.27,0.97],[120.6,0.85],[121.08,1.33],[122.84,0.85],[123.85,0.84],[125.11,1.69],[125.23,1.5],[124.97,1.08]],[[-55.46,51.54],[-56.03,51.33],[-55.8,51.03],[-56.82,49.61],[-56.18,50.12],[-56.16,49.94],[-55.5,49.98],[-56.14,49.62],[-55.23,49.51],[-55.35,49.08],[-54.5,49.53],[-54.45,49.33],[-53.62,49.32],[-53.57,49.14],[-54.16,48.79],[-53.71,48.66],[-54.11,48.39],[-53.03,48.63],[-53.87,48.02],[-53.64,48.02],[-53.86,47.8],[-53.67,47.65],[-52.86,48.11],[-53.17,47.51],[-52.78,47.77],[-52.65,47.55],[-53.07,46.68],[-53.59,46.64],[-53.6,47.15],[-54.18,46.88],[-53.85,47.44],[-54.19,47.86],[-54.49,47.4],[-55.79,46.87],[-55.92,47.02],[-54.78,47.66],[-55.58,47.46],[-56.13,47.5],[-55.86,47.82],[-56.77,47.57],[-59.26,47.63],[-59.34,47.93],[-58.33,48.52],[-59.17,48.56],[-58.71,48.6],[-58.41,49.08],[-57.99,48.99],[-58.21,49.39],[-57.79,49.49],[-57.93,49.7],[-57.04,51.01],[-56.03,51.57],[-55.45,51.56]],[[-108.29,76.06],[-107.72,76],[-108.02,75.8],[-107.21,75.89],[-106.91,75.68],[-106.68,76.02],[-105.9,76.01],[-105.48,75.7],[-106.09,75.09],[-108.83,75.07],[-112.52,74.42],[-114.38,74.67],[-111.03,75.23],[-113.71,75.07],[-113.85,75.26],[-113.47,75.42],[-114.01,75.43],[-114.52,75.28],[-114.45,75.09],[-115.73,74.97],[-117.6,75.27],[-115.14,75.68],[-117.16,75.65],[-114.99,75.9],[-116.66,75.96],[-116.21,76.19],[-114.78,76.17],[-115.83,76.3],[-115,76.5],[-112.7,76.2],[-111.05,75.55],[-109.09,75.51],[-108.92,75.67],[-109.87,75.93],[-109.43,76.11],[-110.31,76.4],[-108.83,76.82],[-108.47,76.74],[-108.63,76.59],[-108.12,76.23],[-108.39,76.07]],[[173.27,-34.93],[174.37,-35.33],[174.54,-35.58],[174.51,-35.67],[174.58,-35.79],[174.39,-35.8],[174.8,-36.31],[174.75,-36.49],[174.82,-36.61],[174.72,-36.84],[174.89,-36.91],[174.95,-36.85],[175.3,-36.99],[175.38,-37.21],[175.54,-37.2],[175.49,-36.69],[175.38,-36.56],[175.46,-36.48],[175.68,-36.75],[175.77,-36.73],[175.99,-37.44],[176.12,-37.54],[176.13,-37.59],[176.03,-37.58],[176.11,-37.64],[177.27,-37.99],[178.01,-37.55],[178.53,-37.69],[177.91,-39.24],[177.08,-39.22],[176.84,-40.16],[175.98,-41.21],[175.31,-41.61],[174.87,-41.22],[174.64,-41.29],[175.21,-40.2],[173.76,-39.32],[174.57,-38.84],[174.65,-38.43],[174.84,-38.02],[174.8,-37.9],[174.93,-37.8],[174.73,-37.45],[174.77,-37.34],[174.71,-37.33],[174.59,-37.1],[174.66,-37.09],[174.73,-37.22],[174.81,-37.11],[174.93,-37.09],[174.78,-36.94],[174.6,-36.98],[174.47,-36.94],[174.38,-36.73],[174.19,-36.49],[174.4,-36.6],[174.46,-36.51],[174.36,-36.38],[174.39,-36.24],[174.27,-36.16],[174.25,-36.25],[174.03,-36.12],[173.92,-35.91],[173.92,-36.02],[174.17,-36.33],[174.15,-36.38],[174.06,-36.36],[173.41,-35.54],[173.63,-35.32],[173.31,-35.44],[172.71,-34.46],[173.04,-34.43],[173.24,-34.9]],[[-7.18,55.06],[-6.13,55.22],[-5.72,54.82],[-5.71,54.76],[-5.88,54.68],[-5.88,54.64],[-5.58,54.66],[-5.47,54.5],[-5.48,54.44],[-5.67,54.55],[-5.66,54.38],[-5.56,54.37],[-5.61,54.27],[-5.83,54.24],[-6.02,54.05],[-6.22,54.09],[-6.16,54.02],[-6.35,53.99],[-6.14,53.58],[-6.15,53.37],[-6.03,52.93],[-6.17,52.74],[-6.22,52.54],[-6.46,52.34],[-6.32,52.25],[-6.89,52.16],[-6.96,52.25],[-7.08,52.14],[-7.22,52.14],[-9.3,51.5],[-10.12,51.6],[-9.6,51.87],[-10.34,51.8],[-9.91,52.12],[-10.36,52.21],[-8.78,52.68],[-9.92,52.57],[-8.93,53.21],[-10.09,53.41],[-9.58,53.8],[-9.91,53.86],[-10.06,54.26],[-8.54,54.24],[-8.13,54.64],[-8.76,54.68],[-8.27,55.15],[-7.67,55.26],[-7.66,54.97],[-7.31,55.37],[-6.96,55.24],[-7.22,55.09]],[[107.37,-6.01],[107.56,-6.18],[108.14,-6.3],[108.29,-6.26],[108.42,-6.38],[108.78,-6.81],[110.43,-6.95],[110.84,-6.42],[112.54,-6.93],[113.01,-7.66],[114.41,-7.79],[114.58,-8.77],[113.25,-8.29],[111.51,-8.3],[107.29,-7.47],[106.53,-7.39],[106.41,-7.31],[106.52,-7.05],[105.94,-6.86],[105.48,-6.85],[105.26,-6.84],[105.34,-6.67],[105.37,-6.66],[105.4,-6.77],[105.48,-6.78],[105.66,-6.47],[105.79,-6.46],[105.87,-6.12],[106.07,-5.91],[106.83,-6.1],[107.01,-6.01],[107.05,-5.9],[107.33,-5.98]],[[142.76,54.39],[143.33,52.96],[143.19,51.95],[144.71,48.64],[144.05,49.25],[143.1,49.2],[142.56,47.74],[143.58,46.36],[143.43,46.03],[143.28,46.56],[142.58,46.7],[142.08,45.92],[141.83,46.45],[142.18,48.01],[141.86,48.75],[142.14,49.57],[142.21,51.22],[141.72,51.74],[141.66,52.27],[141.83,53.34],[142.53,53.45],[142.71,53.89],[142.34,54.28],[142.69,54.42]],[[-81.84,23.16],[-79.82,22.89],[-74.15,20.17],[-77.72,19.86],[-77.23,20.64],[-78.12,20.76],[-78.73,21.59],[-81.85,22.21],[-82.08,22.39],[-81.71,22.5],[-81.7,22.59],[-81.84,22.67],[-82.74,22.69],[-84.84,21.83],[-84.04,22.67],[-83.26,22.97],[-82.1,23.19]],[[143.82,44.12],[144.72,43.93],[145.37,44.33],[145.14,43.66],[145.34,43.3],[145.83,43.39],[143.97,42.88],[143.24,42],[141.85,42.58],[140.99,42.34],[140.48,42.56],[140.33,42.29],[141.15,41.81],[140.04,41.47],[139.86,42.58],[140.43,42.95],[140.39,43.3],[141.38,43.28],[141.76,44.48],[141.67,45.4],[141.94,45.51],[143.76,44.13]],[[121.1,18.62],[121.85,18.29],[122.27,18.46],[122.15,17.66],[122.52,17.12],[122.14,16.19],[121.69,16.02],[121.6,15.93],[121.56,15.83],[121.61,15.67],[121.39,15.32],[121.69,14.77],[121.63,14.58],[121.77,14.17],[121.91,14.02],[122.21,13.93],[122.29,14],[122.2,14.15],[122.49,14.32],[122.94,14.19],[123.1,13.75],[123.32,14.06],[123.86,13.8],[123.55,13.65],[123.79,13.11],[124.14,13.04],[124.06,12.57],[123.95,12.92],[123.31,13.04],[122.59,13.91],[122.6,13.19],[122.21,13.65],[122.07,13.79],[121.78,13.94],[121.5,13.84],[121.45,13.71],[121.34,13.65],[121.1,13.68],[120.93,13.76],[120.84,13.89],[120.73,13.9],[120.64,13.81],[120.62,14.19],[120.92,14.49],[120.94,14.65],[120.59,14.88],[120.55,14.77],[120.59,14.48],[120.44,14.45],[120.25,14.79],[120.08,14.85],[119.93,15.43],[119.77,16.25],[120.37,16.11],[120.6,18.51],[121.05,18.61]],[[-100,73.95],[-99.16,73.73],[-97.11,73.79],[-97,73.67],[-97.63,73.5],[-97.27,73.39],[-98.43,72.96],[-97.63,73.03],[-97.13,72.63],[-96.54,72.7],[-96.47,72.43],[-96.8,72.32],[-96.61,71.83],[-97.58,71.63],[-98.32,71.85],[-98.2,71.44],[-99.17,71.37],[-100.59,72.15],[-102.71,72.77],[-102.2,73.08],[-101.27,72.72],[-100.13,72.91],[-100.54,73.2],[-99.82,73.21],[-101.52,73.49],[-100.52,73.45],[-100.99,73.77],[-100.14,73.93]],[[55.32,73.31],[56.43,73.2],[56.12,72.81],[55.4,72.55],[55.52,72.22],[55.3,71.94],[56.45,71.11],[57.62,70.73],[56.26,70.71],[56.44,70.56],[53.72,70.81],[53.38,70.87],[54.16,71.12],[53.41,71.34],[53.41,71.53],[51.81,71.49],[51.44,71.78],[51.58,72.07],[52.62,72.3],[52.92,72.67],[52.55,72.77],[53.37,72.92],[53.25,73.18],[55.12,73.36]],[[-84.92,65.26],[-84.5,65.46],[-82.05,64.64],[-81.68,64.21],[-81.89,64.02],[-80.83,64.09],[-80.26,63.8],[-81.05,63.46],[-83.3,64.14],[-84.63,63.31],[-85.39,63.12],[-85.77,63.7],[-87.18,63.6],[-86.25,64.14],[-86.37,64.57],[-85.81,65.83],[-85.24,65.8],[-85.06,65.44]],[[126.01,9.32],[126.09,9.26],[126.19,9.28],[126.19,9.12],[126.21,9.08],[126.3,8.95],[126.32,8.84],[126.26,8.74],[126.22,8.7],[126.14,8.63],[126.14,8.6],[126.17,8.56],[126.28,8.54],[126.37,8.48],[126.38,8.33],[126.46,8.2],[126.46,8.15],[126.43,7.93],[126.44,7.83],[126.49,7.76],[126.54,7.72],[126.57,7.68],[126.59,7.55],[126.59,7.33],[126.58,7.25],[126.55,7.18],[126.44,7.01],[126.29,6.88],[126.22,6.89],[126.19,6.85],[126.24,6.73],[126.22,6.48],[126.19,6.31],[126.14,6.4],[126.11,6.49],[126.08,6.73],[126.04,6.84],[125.98,6.94],[125.96,7.03],[125.9,7.12],[125.82,7.33],[125.77,7.32],[125.69,7.26],[125.67,7.22],[125.66,7.16],[125.64,7.11],[125.54,7.02],[125.46,6.91],[125.4,6.8],[125.38,6.69],[125.43,6.61],[125.49,6.57],[125.56,6.5],[125.59,6.47],[125.67,6.23],[125.67,5.98],[125.61,5.87],[125.46,5.66],[125.35,5.6],[125.29,5.63],[125.24,5.76],[125.23,5.81],[125.26,5.93],[125.27,6.03],[125.23,6.07],[125.19,6.06],[125.17,6.05],[125.08,5.91],[125.04,5.87],[124.98,5.87],[124.93,5.88],[124.64,6],[124.4,6.12],[124.21,6.23],[124.08,6.4],[124.05,6.53],[124.05,6.67],[123.99,6.86],[123.98,6.93],[123.99,6.99],[124.05,7.11],[124.12,7.18],[124.16,7.22],[124.19,7.27],[124.21,7.33],[124.21,7.4],[124.18,7.44],[124.07,7.58],[123.97,7.66],[123.76,7.74],[123.72,7.79],[123.67,7.82],[123.61,7.83],[123.55,7.83],[123.49,7.81],[123.48,7.76],[123.48,7.71],[123.48,7.67],[123.39,7.41],[123.28,7.46],[123.18,7.53],[123.15,7.58],[123.14,7.63],[123.12,7.67],[123.1,7.7],[123.05,7.61],[122.99,7.55],[122.92,7.53],[122.84,7.53],[122.82,7.56],[122.79,7.72],[122.71,7.77],[122.62,7.76],[122.5,7.67],[122.47,7.64],[122.45,7.56],[122.32,7.34],[122.25,7.17],[122.18,7],[122.14,6.95],[122.1,6.91],[122.03,6.93],[121.96,6.97],[121.9,7.08],[121.92,7.2],[121.99,7.28],[122.05,7.36],[122.11,7.66],[122.12,7.77],[122.13,7.81],[122.24,7.95],[122.34,8.03],[122.39,8.05],[122.59,8.09],[122.67,8.13],[122.8,8.13],[122.91,8.16],[123,8.22],[123,8.29],[123,8.36],[123.02,8.4],[123.05,8.43],[123.1,8.48],[123.15,8.52],[123.29,8.54],[123.34,8.57],[123.38,8.62],[123.43,8.7],[123.5,8.68],[123.56,8.65],[123.68,8.62],[123.78,8.55],[123.85,8.43],[123.86,8.38],[123.88,8.19],[123.85,8.15],[123.75,8.06],[123.8,8.05],[123.93,8.13],[124,8.16],[124.16,8.2],[124.2,8.23],[124.23,8.27],[124.28,8.39],[124.33,8.51],[124.36,8.56],[124.4,8.6],[124.45,8.61],[124.62,8.52],[124.73,8.56],[124.76,8.69],[124.79,8.87],[124.81,8.92],[124.87,8.97],[124.94,8.96],[125.05,8.89],[125.14,8.87],[125.18,8.92],[125.21,9.03],[125.25,9.03],[125.38,8.99],[125.5,9.01],[125.53,9.14],[125.51,9.28],[125.41,9.67],[125.47,9.76],[125.52,9.76],[125.64,9.65],[125.88,9.51],[125.95,9.43]],[[140.05,75.83],[140.82,75.63],[140.99,75.96],[141.49,76.14],[145.36,75.53],[144.02,75.04],[142.82,75.27],[142.7,75.45],[142.94,75.71],[142.31,75.69],[142.09,75.66],[142.2,75.39],[143.13,74.97],[139.68,74.96],[139.1,74.66],[138.09,74.8],[136.95,75.33],[137.29,75.35],[137.27,75.75],[137.71,75.76],[137.56,75.96],[138.21,76.12],[138.92,76.2],[139.74,75.95]],[[-93.17,74.16],[-90.36,73.87],[-92.12,72.75],[-94.21,72.76],[-93.54,72.44],[-94.14,72],[-95.19,72.03],[-95.6,72.88],[-95.63,73.7],[-94.7,73.66],[-95.15,73.91],[-94.97,74.04],[-93.41,74.18]],[[145.04,-40.79],[146.32,-41.16],[148.22,-40.85],[148.34,-42.22],[148.22,-41.97],[148.02,-42.26],[147.98,-43.16],[147.3,-42.79],[146.87,-43.61],[146.04,-43.55],[146.21,-43.32],[145.49,-42.93],[145.2,-42.23],[145.52,-42.35],[144.77,-41.39],[144.72,-40.67],[144.82,-40.72]],[[20.9,80.25],[22.29,80.05],[22.45,80.4],[23.01,80.47],[23.32,80.42],[23.11,80.19],[24.4,80.36],[26.86,80.16],[27.2,79.91],[23.95,79.19],[20.13,79.49],[19.68,79.59],[20.78,79.75],[18.73,79.76],[18.25,79.93],[18.86,80.04],[17.92,80.14],[19.34,80.12],[19.54,80.16],[19.18,80.33],[19.75,80.23],[19.73,80.48],[20.69,80.3]],[[-71.95,19.72],[-69.96,19.67],[-69.74,19.3],[-69.32,19.33],[-69.23,19.27],[-69.32,19.2],[-69.61,19.21],[-69.62,19.12],[-68.36,18.54],[-68.69,18.21],[-68.93,18.41],[-69.27,18.44],[-69.77,18.44],[-70.02,18.37],[-70.18,18.25],[-70.48,18.22],[-70.64,18.34],[-71.03,18.27],[-71.11,18.07],[-71.44,17.64],[-72.06,18.23],[-73.88,18.04],[-74.39,18.62],[-72.35,18.62],[-72.7,19.44],[-73.4,19.81]],[[-69.17,-52.67],[-68.63,-52.65],[-68.24,-53.08],[-68.49,-53.26],[-67.29,-54.05],[-66.24,-54.53],[-65.18,-54.68],[-66.51,-55.03],[-71.9,-54.6],[-70.8,-54.33],[-70.31,-54.53],[-70.86,-54.11],[-70.53,-53.63],[-70.38,-53.99],[-70.63,-54],[-70.24,-54.35],[-69.05,-54.43],[-70.15,-53.89],[-69.39,-53.37],[-70.21,-53.41],[-70.46,-53.21],[-70.13,-52.94],[-70.38,-52.75],[-69.94,-52.82],[-69.5,-52.49],[-69.41,-52.49]],[[97.67,80.16],[98.02,80.02],[97.65,79.76],[98.6,80.05],[99.95,79.85],[99.68,79.32],[99.04,79.29],[99.93,78.96],[97.56,78.83],[93.07,79.5],[94.99,80.1],[97.59,80.17]],[[-115.55,77.36],[-116.33,77.14],[-115.81,76.94],[-116.25,76.9],[-115.94,76.71],[-117,76.53],[-117.23,76.28],[-117.99,76.41],[-117.88,76.8],[-118.79,76.51],[-118.62,76.37],[-118.99,76.15],[-119.58,76.33],[-119.74,76.12],[-119.54,75.98],[-119.91,75.86],[-120.41,75.83],[-120.85,76.18],[-122.4,75.94],[-122.9,76.13],[-119.09,77.3],[-116.84,77.34],[-117.04,77.46],[-116.51,77.55],[-116.01,77.46]],[[79.98,9.81],[80.71,9.37],[81.83,7.43],[81.77,6.61],[81.38,6.24],[80.73,5.98],[80.5,5.95],[80.27,6.01],[80.1,6.15],[79.86,6.83],[79.71,8.07],[79.75,8.29],[79.75,8.05],[79.81,8.05],[79.85,8.41],[80.08,9.58],[80.43,9.48],[79.97,9.79]],[[-97.7,76.47],[-97.53,76.11],[-97.89,75.76],[-97.41,75.67],[-97.34,75.42],[-97.88,75.42],[-97.66,75.15],[-98.07,75.2],[-97.99,75.05],[-100.23,75.01],[-100.48,75.19],[-100.14,75.25],[-100.73,75.35],[-99.19,75.7],[-102.8,75.6],[-102.15,75.87],[-100.97,75.8],[-101.87,76.08],[-101.56,76.24],[-102.14,76.28],[-101.79,76.45],[-99.87,75.92],[-99.69,75.96],[-100.11,76.12],[-99.54,76.15],[-100.89,76.48],[-100.07,76.63],[-98.89,76.47],[-99.02,76.61],[-98.71,76.69],[-97.72,76.5]],[[96.53,81.08],[97.86,80.7],[97.11,80.61],[97.42,80.32],[97.17,80.24],[93.87,80.01],[91.53,80.36],[92.83,80.62],[93.26,80.79],[92.61,80.81],[93.36,81.03],[95.16,81.27],[96.47,81.1]],[[-103.43,79.32],[-102.58,78.88],[-101.7,79.08],[-100.01,78.73],[-99.58,78.56],[-99.75,78.3],[-99,78],[-99.96,77.79],[-101.07,78.19],[-104.51,78.29],[-105,78.52],[-103.57,78.54],[-104.02,78.63],[-103.37,78.74],[-104.18,78.78],[-103.88,78.9],[-104.15,78.99],[-104.9,78.81],[-104.75,79.03],[-105.58,79.11],[-105.39,79.32],[-103.71,79.35]],[[102.88,79.25],[102.41,78.84],[103.8,79.15],[105.34,78.59],[104.74,78.34],[99.29,78.04],[100.42,78.75],[100.95,78.79],[101.05,79.12],[101.59,79.35],[103.1,79.3],[102.94,79.27]],[[131.18,33.6],[131.69,33.6],[131.54,33.27],[131.9,33.25],[132.01,32.92],[131.34,31.4],[131.07,31.44],[130.69,31.01],[130.78,31.71],[130.59,31.18],[130.15,31.41],[130.55,32.83],[130.24,33.18],[130.34,32.7],[129.77,32.57],[129.68,33.06],[129.99,32.85],[129.58,33.24],[130.72,33.93],[131.06,33.67]],[[-127.2,50.64],[-125.48,50.32],[-124.83,49.53],[-123.85,49.12],[-123.5,48.58],[-123.41,48.7],[-123.29,48.46],[-123.31,48.41],[-123.45,48.43],[-123.57,48.32],[-125.12,48.76],[-124.81,49.21],[-125.49,48.93],[-125.93,49.4],[-126.52,49.4],[-126.54,49.59],[-126.13,49.67],[-127.12,49.88],[-127.25,50.14],[-127.86,50.13],[-127.91,50.45],[-127.49,50.41],[-127.46,50.58],[-128.35,50.7],[-127.92,50.86],[-127.71,50.82]],[[121.01,22.62],[120.84,21.92],[120.08,23.09],[120.13,23.65],[120.63,24.48],[121.04,25.03],[121.59,25.28],[121.91,25.06],[121.93,24.97],[121.82,24.82],[121.83,24.53],[121.64,24.13],[121.52,23.67],[121.16,22.78]],[[-79.54,73.65],[-77.21,73.5],[-76.09,72.88],[-79.5,72.76],[-80.78,73.33],[-80.86,73.67],[-79.89,73.7]],[[-49.63,-0.23],[-48.39,-0.3],[-48.83,-1.39],[-49.8,-1.79],[-50.51,-1.79],[-50.79,-0.91],[-50.65,-0.27],[-50.25,-0.12]],[[110.89,19.99],[111.01,19.66],[110.02,18.42],[109.52,18.22],[108.7,18.54],[108.67,19.3],[109.26,19.88],[110.65,20.14],[110.81,20.02]],[[151.92,-4.3],[152.41,-4.34],[152.35,-4.82],[151.98,-5.07],[152.08,-5.46],[151.52,-5.55],[150.47,-6.26],[149.65,-6.29],[148.34,-5.67],[148.43,-5.47],[149.83,-5.52],[150.09,-5.01],[150.18,-5.52],[150.74,-5.51],[151.67,-4.88],[151.59,-4.2],[151.87,-4.26]],[[-97.44,69.64],[-95.27,68.83],[-96.6,68.46],[-99.56,69.03],[-98.5,69.31],[-98.55,69.57],[-98.04,69.46],[-98.3,69.67],[-98.08,69.83],[-97.47,69.67]],[[21.61,78.6],[22.04,78.58],[22.3,78.23],[23.45,78.15],[23.12,77.99],[24.9,77.76],[22.8,77.28],[22.43,77.32],[22.69,77.55],[21.05,77.44],[20.87,77.57],[21.65,77.92],[20.23,78.48],[21.45,78.6]],[[15.58,38.22],[15.1,37.46],[15.29,37.06],[15.11,36.69],[14.37,36.97],[14.14,37.1],[13.8,37.14],[12.92,37.57],[12.64,37.59],[12.44,37.82],[12.55,38.05],[12.74,38.18],[12.9,38.03],[13.16,38.19],[13.35,38.18],[13.38,38.13],[13.79,37.98],[14.05,38.04],[14.51,38.05],[14.79,38.17],[15.63,38.27]],[[9.63,40.88],[9.8,40.5],[9.56,39.17],[9.06,39.24],[8.97,38.96],[8.65,38.93],[8.42,39.21],[8.55,39.84],[8.2,40.87],[9.23,41.26],[9.57,40.91]],[[127.3,-8.42],[125.41,-9.28],[124.43,-10.15],[123.61,-10.27],[123.71,-9.62],[125.18,-8.65],[127.26,-8.39]],[[-93.54,75.03],[-93.57,74.67],[-94.54,74.64],[-96.6,75.06],[-95.95,75.44],[-94.88,75.63],[-93.91,75.42],[-93.55,75.05]],[[134.36,34.26],[134.64,34.23],[134.68,33.85],[134.74,33.82],[134.38,33.61],[134.18,33.25],[133.69,33.52],[133.29,33.36],[132.87,32.75],[132.49,32.92],[132.41,33.43],[132.03,33.34],[132.94,34.1],[133.47,33.97],[133.95,34.35],[134.07,34.36],[134.22,34.32]],[[-75.67,68.32],[-75.06,68.14],[-75.13,67.54],[-75.4,67.37],[-76.95,67.25],[-77.31,67.69],[-76.69,68.26],[-75.87,68.34]],[[-96.21,78.53],[-94.92,78.39],[-95.33,78.22],[-94.93,78.08],[-96.99,77.81],[-97.66,78.09],[-96.94,78.15],[-98.05,78.33],[-98.34,78.75],[-96.26,78.55]],[[-52.73,69.94],[-51.9,69.6],[-53.75,69.26],[-54.18,69.4],[-53.66,69.47],[-53.83,69.54],[-54.92,69.71],[-54.79,69.95],[-54.32,69.94],[-54.83,70.13],[-54.37,70.32],[-53.1,70.14]],[[-110.46,78.1],[-109.62,78.06],[-110.86,77.83],[-110.15,77.76],[-110.2,77.53],[-111.95,77.34],[-113.17,77.53],[-113.28,77.81],[-110.73,78.1]],[[146.8,75.37],[150.82,75.16],[150.58,74.92],[149.05,74.77],[146.15,75.2],[146.44,75.56],[146.75,75.43]],[[127.73,0.85],[128.69,1.57],[128.7,1.11],[128.26,0.73],[128.9,0.22],[127.98,0.47],[127.89,0.3],[128.43,-0.89],[127.69,-0.24],[127.43,1.14],[127.63,1.84],[128.04,2.2],[128.01,1.33],[127.68,0.89]],[[180,71.54],[181.56,71.54],[182.5,71.22],[178.79,70.82],[178.63,71.05],[179.88,71.52]],[[142.19,73.9],[143.34,73.57],[143.49,73.25],[139.69,73.42],[141.08,73.87],[141.93,73.91]],[[-152.9,57.82],[-152.43,57.83],[-152.21,57.58],[-152.94,57.5],[-152.68,57.34],[-153.97,56.77],[-153.79,56.99],[-154.25,57.14],[-154.34,56.92],[-154.71,57.34],[-154.12,57.65],[-153.69,57.3],[-153.84,57.86],[-152.85,57.9]],[[129.75,-2.87],[130.57,-3.13],[130.81,-3.86],[129.84,-3.33],[129.47,-3.45],[128.86,-3.24],[128.52,-3.45],[128.13,-3.16],[127.9,-3.5],[128.2,-2.87],[129.6,-2.81]],[[50.28,80.93],[51.7,80.69],[48.9,80.37],[48.68,80.3],[48.98,80.16],[48.39,80.1],[46.64,80.3],[49.09,80.52],[49.24,80.82],[50.13,80.92]],[[164.2,-20.25],[165.19,-20.77],[166.97,-22.32],[166.47,-22.26],[164.93,-21.29],[164.06,-20.14]],[[122.78,-8.61],[121.04,-8.93],[119.81,-8.7],[119.88,-8.42],[120.61,-8.24],[122.32,-8.63],[122.92,-8.1],[122.82,-8.6]],[[125.24,12.53],[125.54,12.19],[125.74,11.05],[125.03,11.34],[125,11.77],[124.44,12.15],[124.29,12.57],[125.15,12.57]],[[-105.29,72.92],[-106.95,73.51],[-105.51,73.77],[-104.59,73.58],[-104.62,73.31],[-105.2,72.95]],[[-133.57,56.34],[-133.2,56.32],[-132.17,55.48],[-132.63,55.47],[-131.98,55.21],[-132.02,54.73],[-133.12,55.33],[-133.03,55.59],[-133.68,55.79],[-133.24,55.92],[-133.74,55.96],[-133.6,56.32]],[[12.57,55.79],[12.54,55.66],[12.32,55.59],[12.22,55.47],[12.39,55.39],[12.41,55.29],[12.09,55.19],[12.05,54.81],[11.86,54.77],[11.74,54.92],[11.66,55.19],[11.29,55.2],[11.17,55.33],[11.19,55.47],[11.12,55.6],[11.01,55.64],[10.98,55.72],[11.32,55.75],[11.48,55.94],[11.63,55.96],[11.69,55.91],[11.69,55.73],[11.82,55.7],[11.94,55.9],[11.87,55.97],[12.22,56.12],[12.58,56.06],[12.61,56.03],[12.53,55.92]],[[34.46,35.59],[33.94,35.29],[34.05,34.99],[33.01,34.57],[32.32,34.95],[32.94,35.39],[34.55,35.66]],[[-25.43,70.92],[-25.4,70.65],[-26.22,70.45],[-28.04,70.49],[-27.62,70.91],[-25.46,70.94]],[[106.04,-1.67],[106.36,-2.46],[106.82,-2.57],[106.67,-3.07],[106,-2.83],[105.79,-2.18],[105.13,-2.04],[105.46,-1.57],[106.03,-1.59]],[[-82,62.96],[-82.12,62.65],[-83.02,62.21],[-83.7,62.16],[-83.91,62.43],[-83.38,62.9],[-82.05,62.97]],[[122.5,11.61],[123.16,11.54],[123.12,11.29],[122.77,10.82],[121.95,10.44],[122.1,11.64],[121.92,11.85],[122.4,11.7]],[[-61.11,45.94],[-60.86,45.98],[-61.06,45.7],[-60.74,45.75],[-60.3,46.31],[-59.83,45.96],[-60.67,45.59],[-61.45,45.72],[-61.41,46.17],[-60.49,47.01],[-60.49,46.27],[-60.91,46.04]],[[123.13,9.06],[122.4,9.82],[122.86,10.09],[122.98,10.89],[123.26,10.99],[123.57,10.78],[123.16,9.86],[123.32,9.27],[123.19,9.09]],[[-73.77,-43.35],[-74.39,-43.23],[-74.04,-41.8],[-73.53,-41.9],[-73.42,-42.19],[-73.79,-42.59],[-73.44,-42.94],[-73.74,-43.29]],[[118.24,-8.32],[118.93,-8.3],[119.13,-8.67],[116.79,-9.01],[116.83,-8.53],[117.16,-8.37],[117.97,-8.73],[118.23,-8.59],[117.76,-8.15],[118.2,-8.27]],[[62.17,80.83],[62.08,80.62],[61.05,80.42],[59.29,80.57],[59.72,80.84],[62.1,80.87]],[[117.31,8.44],[117.35,8.71],[119.22,10.48],[119.55,11.31],[119.69,10.5],[117.41,8.5]],[[-109.82,78.65],[-109.35,78.37],[-113.29,78.33],[-110.88,78.74],[-109.94,78.68]],[[54.72,81.12],[57.69,80.79],[55.89,80.63],[54.07,80.81],[54.63,81.11]],[[9.48,42.81],[9.56,42.16],[9.19,41.39],[8.81,41.59],[8.57,42.36],[9.32,42.71],[9.36,43.02],[9.48,42.86]],[[50.27,69.19],[48.91,68.74],[48.28,69.04],[48.42,69.35],[48.96,69.51],[50.17,69.26]],[[178.28,-17.37],[178.67,-18.08],[177.96,-18.26],[177.32,-18.08],[177.51,-17.54],[178.25,-17.33]],[[-61.8,49.09],[-63.04,49.23],[-64.49,49.89],[-62.86,49.71],[-61.75,49.11]],[[-77.26,18.46],[-76.91,18.39],[-76.7,18.26],[-76.35,18.15],[-76.21,17.91],[-76.52,17.87],[-76.85,17.97],[-76.94,17.85],[-77.12,17.88],[-77.2,17.71],[-77.36,17.83],[-77.77,17.88],[-78.33,18.35],[-77.87,18.52]],[[-44.87,82.08],[-47.35,82.6],[-44.92,82.48],[-44.78,82.24]],[[-158.28,21.58],[-158.12,21.71],[-157.98,21.71],[-157.65,21.31],[-157.71,21.26],[-157.95,21.3],[-158.1,21.3],[-158.23,21.46]],[[-155.87,20.27],[-155.1,19.86],[-154.81,19.51],[-155.62,18.91],[-155.88,19.07],[-156.05,19.73],[-155.83,20]],[[-156.69,20.95],[-156.4,20.92],[-156,20.8],[-156,20.62],[-156.45,20.58],[-156.51,20.78],[-156.69,20.88]],[[-159.79,22.07],[-159.4,22.23],[-159.29,22.1],[-159.38,21.88],[-159.68,21.95]],[[-157.31,21.1],[-156.71,21.16],[-156.75,21.08],[-157.25,21.08]],[[144.62,13.24],[144.66,13.43],[144.79,13.53],[144.95,13.65],[144.88,13.43],[144.76,13.25],[144.7,13.23]],[[134.45,7.35],[134.48,7.28],[134.56,7.42],[134.65,7.7],[134.6,7.73],[134.52,7.55]],[[171,7.04],[171.42,7.03],[171.45,7.14],[171,7.12]],[[159.6,-9.25],[160.2,-9.4],[160.8,-9.85],[160.6,-9.95],[159.95,-9.75],[159.6,-9.5]],[[-149.62,-17.5],[-149.37,-17.53],[-149.18,-17.87],[-149.32,-17.78],[-149.6,-17.8],[-149.62,-17.66]],[[-172.07,-13.8],[-171.44,-13.79],[-171.43,-14.05],[-172,-14.04]],[[-172.78,-13.48],[-172.21,-13.58],[-172.25,-13.8],[-172.7,-13.78]],[[-170.84,-14.29],[-170.56,-14.24],[-170.56,-14.31],[-170.82,-14.36]],[[-175.36,-21.1],[-175.05,-21.13],[-175.08,-21.24],[-175.3,-21.2]],[[146.95,-9.25],[147.45,-9.2],[147.55,-9.55],[147.05,-9.65]],[[166.25,-22.1],[166.65,-22.05],[166.7,-22.4],[166.3,-22.45]],[[178.2,-17.95],[178.6,-17.95],[178.6,-18.25],[178.2,-18.25]],[[-64.89,32.25],[-64.82,32.29],[-64.7,32.36],[-64.64,32.39],[-64.67,32.35],[-64.76,32.28],[-64.85,32.23]],[[-25.86,37.9],[-25.48,37.83],[-25.13,37.83],[-25.15,37.72],[-25.5,37.71],[-25.85,37.76]],[[-27.38,38.78],[-27.05,38.76],[-27.04,38.64],[-27.35,38.66]],[[-28.55,38.55],[-28.05,38.43],[-28.1,38.39],[-28.5,38.46]],[[-28.83,38.64],[-28.6,38.62],[-28.62,38.52],[-28.8,38.53]],[[-16.92,28.37],[-16.65,28.4],[-16.13,28.58],[-16.35,28.37],[-16.5,28.06],[-16.75,28.03],[-16.88,28.2]],[[-15.8,28.15],[-15.4,28.17],[-15.36,27.9],[-15.6,27.74],[-15.82,27.9]],[[-13.85,29.22],[-13.45,29.24],[-13.47,28.88],[-13.85,28.9]],[[-14.2,28.75],[-13.84,28.72],[-13.9,28.25],[-14.5,28.06]],[[-17.92,28.85],[-17.75,28.83],[-17.83,28.46],[-17.96,28.62]],[[-17.35,28.2],[-17.1,28.2],[-17.12,28.02],[-17.32,28.03]],[[-18.15,27.8],[-17.9,27.83],[-17.95,27.65],[-18.12,27.7]],[[-23.76,15.27],[-23.47,15.33],[-23.43,15.02],[-23.52,14.91],[-23.78,15.05]],[[-24.5,15],[-24.3,15],[-24.3,14.82],[-24.5,14.82]],[[-25.08,16.9],[-24.88,16.9],[-24.88,16.78],[-25.05,16.8]],[[-25.35,17.2],[-24.98,17.1],[-25,16.98],[-25.33,17]],[[-22.98,16.84],[-22.88,16.84],[-22.88,16.6],[-22.98,16.6]],[[-22.95,16.2],[-22.7,16.15],[-22.72,15.98],[-22.93,16]],[[-5.79,-15.9],[-5.65,-15.9],[-5.63,-16],[-5.75,-16.03]],[[-65.63,18.28],[-65.6,18.22],[-65.74,18.18],[-65.94,17.97],[-66.2,17.92],[-66.77,18],[-66.93,17.93],[-67.18,17.94],[-67.15,18.2],[-67.27,18.36],[-67.1,18.52],[-66.38,18.49],[-65.62,18.39]],[[-77.48,24.99],[-77.55,25],[-77.56,25.02],[-77.55,25.04],[-77.5,25.06],[-77.34,25.08],[-77.26,25.06],[-77.38,25],[-77.44,25.01],[-77.47,24.99]],[[-61,10.7],[-61.04,10.51],[-60.96,10.33],[-61,10.14],[-61.19,10.07],[-61.93,10.06],[-61.67,10.18],[-61.63,10.25],[-61.51,10.24],[-61.46,10.28],[-61.49,10.63],[-61.67,10.71],[-61.37,10.8],[-60.95,10.85],[-60.91,10.84]],[[-59.43,13.16],[-59.43,13.13],[-59.51,13.06],[-59.62,13.09],[-59.65,13.16],[-59.65,13.32],[-59.59,13.33],[-59.54,13.23]],[[-60.81,14.46],[-61.07,14.47],[-61.11,14.52],[-61,14.57],[-61.16,14.67],[-61.22,14.85],[-60.88,14.78],[-60.94,14.67]],[[-68.78,12.1],[-68.74,12.05],[-68.81,12.04],[-68.98,12.12],[-69.16,12.29],[-69.17,12.39],[-69.07,12.34],[-69,12.22],[-68.84,12.17]],[[55.79,-21.1],[55.85,-21.16],[55.81,-21.34],[55.58,-21.37],[55.35,-21.27],[55.23,-21.03],[55.29,-20.91],[55.41,-20.86],[55.58,-20.87],[55.7,-20.94]],[[57.8,-20.22],[57.78,-20.34],[57.67,-20.48],[57.38,-20.51],[57.31,-20.44],[57.36,-20.41],[57.4,-20.2],[57.6,-19.98],[57.68,-20]],[[55.4,-4.66],[55.37,-4.64],[55.43,-4.56],[55.46,-4.57],[55.46,-4.63],[55.53,-4.68],[55.54,-4.8],[55.46,-4.76],[55.48,-4.71]],[[-130.12,-25.07],[-130.11,-25.06],[-130.1,-25.06],[-130.09,-25.07],[-130.09,-25.08],[-130.1,-25.08],[-130.11,-25.08],[-130.11,-25.07]],[[-166.29,53.73],[-167.85,53.31],[-166.8,53.63],[-167.16,53.83],[-167.02,53.96],[-166.37,54.01],[-166.22,53.91],[-166.58,53.71]],[[73.55,4.24],[73.55,4.23],[73.54,4.18],[73.51,4.16],[73.43,4.18],[73.51,4.19]]]; +// Cebu, from the same Natural Earth 1:50m land (the simplified rings had dropped it). +COAST_LL.push([[123.37,9.45],[123.33,9.42],[123.32,9.49],[123.33,9.58],[123.4,9.89],[123.39,9.97],[123.51,10.14],[123.59,10.3],[123.71,10.47],[123.73,10.56],[123.83,10.73],[123.93,10.96],[123.92,11.04],[123.95,11.08],[123.96,11.14],[123.97,11.19],[124.04,11.27],[124.06,11.22],[124.04,11.11],[124.04,11.05],[124.05,11.03],[124.05,10.93],[124.03,10.77],[124.05,10.59],[124,10.4],[123.95,10.32],[123.87,10.26],[123.79,10.22],[123.7,10.13],[123.64,10.02],[123.63,9.92],[123.49,9.59]]); +// Antigua, St Kitts, Dominica, St Lucia, St Vincent and Grenada, from the same Natural Earth 1:50m land. +COAST_LL.push([[-61.72,17.04],[-61.75,17],[-61.86,17.01],[-61.88,17.06],[-61.89,17.1],[-61.82,17.17],[-61.74,17.14],[-61.71,17.11],[-61.68,17.1],[-61.68,17.07],[-61.7,17.05]],[[-62.63,17.24],[-62.66,17.23],[-62.7,17.29],[-62.78,17.3],[-62.84,17.34],[-62.84,17.35],[-62.84,17.37],[-62.83,17.39],[-62.79,17.4],[-62.71,17.35],[-62.67,17.29],[-62.64,17.26]],[[-61.28,15.25],[-61.38,15.23],[-61.41,15.4],[-61.48,15.53],[-61.47,15.6],[-61.46,15.63],[-61.32,15.58],[-61.28,15.53],[-61.25,15.37]],[[-60.9,13.82],[-60.95,13.72],[-61.06,13.78],[-61.07,13.87],[-61.06,13.92],[-61,14.01],[-60.94,14.07],[-60.91,14.09],[-60.89,14.01]],[[-61.17,13.16],[-61.2,13.14],[-61.28,13.21],[-61.27,13.29],[-61.22,13.33],[-61.18,13.36],[-61.14,13.36],[-61.12,13.29],[-61.13,13.2]],[[-61.72,12.01],[-61.78,12.01],[-61.76,12.05],[-61.75,12.11],[-61.71,12.19],[-61.66,12.24],[-61.61,12.22],[-61.63,12.05]]); +// Malta, from the same Natural Earth 1:50m land. +COAST_LL.push([[14.57,35.85],[14.53,35.82],[14.44,35.82],[14.35,35.87],[14.35,35.98],[14.45,35.96],[14.54,35.89]]); +// Bahrain, from the same Natural Earth 1:50m land. +COAST_LL.push([[50.61,25.88],[50.58,25.81],[50.54,25.83],[50.47,25.97],[50.49,26.06],[50.45,26.19],[50.47,26.23],[50.56,26.25],[50.59,26.24],[50.56,26.2],[50.61,26.12],[50.62,26]]); +// Timor, Tarawa, Pohnpei, Nauru, Funafuti and Efate, from the same Natural Earth 1:50m land. +COAST_LL.push([[127.3,-8.42],[127.12,-8.58],[126.91,-8.72],[126.79,-8.76],[126.67,-8.78],[126.57,-8.83],[126.49,-8.91],[126.38,-8.96],[126.27,-8.97],[126.17,-9],[126.07,-9.04],[125.95,-9.12],[125.9,-9.13],[125.84,-9.13],[125.74,-9.16],[125.41,-9.28],[125.21,-9.4],[125,-9.56],[124.96,-9.67],[124.84,-9.76],[124.71,-9.91],[124.6,-9.99],[124.51,-10.09],[124.43,-10.15],[124.33,-10.17],[124.17,-10.18],[123.97,-10.3],[123.86,-10.34],[123.75,-10.35],[123.65,-10.31],[123.61,-10.27],[123.61,-10.22],[123.65,-10.17],[123.69,-10.13],[123.72,-10.08],[123.6,-10.01],[123.59,-9.97],[123.63,-9.84],[123.67,-9.71],[123.71,-9.62],[123.88,-9.45],[123.98,-9.37],[124.2,-9.26],[124.57,-9.16],[124.65,-9.12],[124.71,-9.06],[124.89,-8.97],[125.03,-8.86],[125.12,-8.71],[125.18,-8.65],[125.32,-8.59],[125.38,-8.58],[125.81,-8.49],[125.91,-8.49],[126.17,-8.49],[126.53,-8.47],[126.62,-8.46],[126.73,-8.42],[126.85,-8.38],[126.9,-8.34],[126.97,-8.32],[127.06,-8.35],[127.22,-8.37],[127.26,-8.39]]); +COAST_LL.push([[173.04,1.34],[173.01,1.34],[173.03,1.36],[173.14,1.38],[173.15,1.39],[173.17,1.38],[173.17,1.36],[173.16,1.36],[173.11,1.36],[173.06,1.35]]); +COAST_LL.push([[158.31,6.81],[158.26,6.79],[158.18,6.8],[158.16,6.88],[158.13,6.9],[158.13,6.94],[158.19,6.98],[158.3,6.95],[158.33,6.89],[158.31,6.85]]); +COAST_LL.push([[166.96,-0.52],[166.94,-0.55],[166.92,-0.55],[166.91,-0.52],[166.91,-0.5],[166.94,-0.49],[166.96,-0.5]]); +COAST_LL.push([[179.22,-8.52],[179.2,-8.54],[179.2,-8.51],[179.2,-8.49],[179.2,-8.47],[179.21,-8.49],[179.22,-8.51]]); +COAST_LL.push([[168.45,-17.54],[168.54,-17.68],[168.58,-17.7],[168.52,-17.8],[168.4,-17.81],[168.25,-17.78],[168.31,-17.75],[168.28,-17.71],[168.23,-17.7],[168.18,-17.72],[168.16,-17.71],[168.19,-17.64],[168.27,-17.55],[168.3,-17.55],[168.32,-17.54],[168.34,-17.55]]); +// Grande Comore, São Tomé and Bioko, from the same Natural Earth 1:50m land. +COAST_LL.push([[43.47,-11.9],[43.45,-11.92],[43.36,-11.86],[43.3,-11.84],[43.23,-11.75],[43.26,-11.43],[43.28,-11.39],[43.3,-11.37],[43.34,-11.37],[43.39,-11.41],[43.38,-11.61],[43.45,-11.75],[43.49,-11.86]]); +COAST_LL.push([[6.66,0.12],[6.56,0.05],[6.52,0.07],[6.5,0.12],[6.47,0.23],[6.48,0.28],[6.53,0.34],[6.63,0.4],[6.69,0.41],[6.75,0.33],[6.75,0.24]]); +COAST_LL.push([[8.74,3.76],[8.76,3.75],[8.91,3.76],[8.95,3.71],[8.95,3.63],[8.79,3.4],[8.76,3.3],[8.7,3.22],[8.65,3.22],[8.48,3.26],[8.44,3.29],[8.43,3.33],[8.45,3.42],[8.47,3.45],[8.55,3.47],[8.58,3.48],[8.62,3.58],[8.64,3.67],[8.67,3.74]]); +const COAST=COAST_LL.map(poly=>poly.map(q=>proj(q[0],q[1]))); diff --git a/src/game/20-world/40-city-coords.js b/src/game/20-world/40-city-coords.js new file mode 100644 index 0000000..9d1fc60 --- /dev/null +++ b/src/game/20-world/40-city-coords.js @@ -0,0 +1,415 @@ +const CITY_LL={ + "aas":[-52.87,68.71], + "abj":[-4.03,5.32], + "abv":[7.4,9.08], + "acc":[-0.19,5.6], + "add":[38.75,9.03], + "adl":[138.6,-34.93], + "aju":[-37.07,-10.91], + "akl":[174.76,-36.85], + "ala":[1.52,42.51], + "alb":[-73.76,42.65], + "alg":[3.06,36.75], + "amm":[35.93,31.95], + "ams":[4.9,52.37], + "anc":[-149.9,61.22], + "anp":[-76.49,38.98], + "anu":[-61.85,17.12], + "apw":[-171.76,-13.83], + "asb":[58.38,37.95], + "ash":[-77.49,39.04], + "ask":[-5.29,6.83], + "asm":[38.93,15.32], + "asp":[133.88,-23.7], + "asu":[-57.58,-25.26], + "ath":[23.73,37.98], + "atn":[-84.39,33.75], + "aug":[-69.78,44.31], + "auh":[54.37, 24.45], + "aus":[-97.74,30.27], + "bah":[50.59,26.23], + "bas":[-62.72,17.3], + "bcn":[2.17,41.39], + "bcv":[-88.77,17.25], + "bda":[-64.78,32.29], + "bde":[-4.54,50.83], + "beg":[20.46,44.79], + "bel":[-48.5,-1.46], + "ber":[13.4,52.52], + "bet":[6.1,49.52], + "bey":[35.5,33.89], + "bgf":[18.56,4.39], + "bgi":[-59.58,13.12], + "bgw":[44.37,33.31], + "bhz":[-43.94,-19.92], + "bio":[-2.93,43.26], + "bis":[-100.78,46.81], + "bjl":[-16.5,13.51], + "bkk":[100.5, 13.76], + "bko":[-8.0,12.64], + "blr":[77.59, 12.97], + "bna":[-86.78,36.16], + "bne":[153.03, -27.47], + "bod":[-0.58,44.84], + "bog":[-74.07, 4.71], + "boi":[-116.2,43.62], + "bom":[72.88,19.08], + "bos":[-71.06,42.36], + "brn":[7.45,46.95], + "bru":[4.35,50.85], + "brw":[-156.75,71.28], + "bsb":[-47.88,-15.79], + "btr":[-91.15,30.45], + "bts":[17.11,48.15], + "bud":[19.04, 47.5], + "bue":[-58.38, -34.6], + "buh":[26.1, 44.43], + "bvb":[-60.67,2.82], + "bwn":[114.94,4.9], + "bzv":[15.28,-4.27], + "cac":[-53.46,-24.96], + "cae":[-81.03,34.0], + "cai":[31.24,30.04], + "cal":[-114.07,51.05], + "cas":[-7.59,33.57], + "cau":[-35.98,-8.28], + "cbo":[80.0, 6.95], + "cbr":[149.13,-35.28], + "ccs":[-66.9,10.49], + "ceb":[123.89,10.32], + "cgb":[-56.1,-15.6], + "cgr":[-54.65,-20.47], + "chc":[172.55,-43.53], + "chi":[-87.63,41.88], + "cky":[-13.58,9.64], + "cmh":[-82.99,39.96], + "con":[-71.54,43.21], + "cor":[-64.18,-31.42], + "cph":[12.57,55.68], + "cpq":[-47.06,-22.91], + "cpt":[18.42, -33.92], + "cpv":[-35.88,-7.23], + "crw":[-81.63,38.35], + "csn":[-119.77,39.16], + "cur":[-68.92,12.13], + "cwb":[-49.27,-25.43], + "cxj":[-51.18,-29.17], + "cys":[-104.82,41.14], + "dac":[90.41, 23.81], + "dal":[-96.8,32.78], + "dam":[36.29,33.51], + "dar":[39.28,-6.79], + "del":[77.21, 28.61], + "den":[-104.99,39.74], + "dil":[125.57,-8.56], + "dkr":[-17.45,14.69], + "dks":[80.65,73.51], + "dla":[9.7,4.05], + "dod":[35.75,-6.16], + "doh":[51.45,25.28], + "dom":[-61.39,15.3], + "dov":[-75.52,39.16], + "drw":[131.05,-12.46], + "dsm":[-93.61,41.59], + "dub":[-6.26,53.35], + "dur":[31.03,-29.86], + "dus":[6.78,51.22], + "dut":[-166.53,53.88], + "dvo":[125.6,7.08], + "dxb":[55.27,25.2], + "dyr":[177.4,64.7], + "dyu":[68.77,38.56], + "ebj":[8.52,55.48], + "edi":[-3.19,55.95], + "esb":[32.86,39.93], + "evn":[44.51,40.18], + "fdf":[-61.03,14.64], + "fec":[-38.97,-12.27], + "fft":[-84.87,38.2], + "fih":[15.27,-4.33], + "fln":[-48.55,-27.6], + "fna":[-13.19,8.44], + "fnj":[125.76,39.04], + "for":[-38.54, -3.73], + "fra":[8.68,50.11], + "fru":[74.59,42.87], + "fuj":[56.15,25.07], + "fuk":[130.4,33.59], + "fun":[179.21,-8.51], + "gbe":[25.91,-24.65], + "gdl":[-103.35,20.67], + "gdx":[150.8,59.57], + "geo":[-58.16,6.8], + "gid":[29.93,-3.43], + "gnd":[-61.75,12.05], + "got":[11.97,57.71], + "gua":[-90.51,14.63], + "gum":[144.75,13.47], + "gyd":[49.87,40.41], + "gyn":[-49.25,-16.69], + "hah":[43.26,-11.7], + "ham":[9.99,53.55], + "han":[105.85,21.03], + "har":[-76.88,40.27], + "hav":[-82.37,23.09], + "hba":[147.25,-42.85], + "hel":[24.94,60.17], + "hfd":[-72.68,41.76], + "hfx":[-63.62,44.68], + "hir":[159.95,-9.43], + "hkg":[114.17,22.32], + "hln":[-112.03,46.59], + "hnl":[-157.86,21.31], + "hou":[-95.37,29.76], + "hpa":[24.14,65.89], + "hre":[31.05,-17.83], + "hyd":[78.49, 17.39], + "icn":[126.98,37.57], + "igu":[-54.59,-25.55], + "ind":[-86.16,39.77], + "inu":[166.93,-0.52], + "isb":[73.05,33.68], + "ist":[28.98, 41.01], + "ivc":[168.35,-46.41], + "jam":[-5.72,-15.93], + "jan":[-90.18,32.3], + "jed":[39.25,21.55], + "jef":[-92.17,38.58], + "jer":[35.21,31.77], + "jib":[43.15,11.59], + "jkt":[106.85,-6.2], + "jnb":[28.05,-26.2], + "jnu":[-134.36,58.31], + "jpa":[-34.86,-7.12], + "jub":[31.58,4.85], + "kbl":[69.17,34.53], + "kcy":[-94.58,39.1], + "kgl":[30.06,-1.95], + "khi":[67.14,25.0], + "kin":[-76.78,18.05], + "kiv":[28.86,47.01], + "kla":[32.58,0.35], + "krs":[8.0,58.15], + "krt":[32.56,15.5], + "ktm":[85.32,27.72], + "kul":[101.69, 3.14], + "kwi":[47.99,29.38], + "kyv":[30.52,50.45], + "lad":[13.23,-8.84], + "lag":[3.38,6.52], + "lan":[-84.56,42.73], + "lax":[-118.24,34.05], + "lbv":[9.49,0.5], + "ldb":[-51.16,-23.31], + "lfw":[1.22,6.13], + "lil":[3.06,50.63], + "lim":[-76.85,-12.05], + "lis":[-9.14,38.72], + "lit":[-92.29,34.75], + "ljd":[-51.96,-29.47], + "lju":[14.51,46.06], + "llw":[33.79,-13.96], + "lnk":[-96.7,40.81], + "lon":[-0.13,51.51], + "lpb":[-68.15,-16.5], + "lun":[28.32,-15.39], + "lys":[4.84,45.76], + "maa":[80.18,13.25], + "mad":[-3.7,40.42], + "maj":[171.38,7.09], + "man":[-2.24,53.48], + "mao":[-60.02,-3.12], + "mba":[39.67,-4.04], + "mco":[7.42,43.74], + "mcp":[-51.07,0.03], + "mct":[58.41,23.59], + "mcz":[-35.74,-9.67], + "mde":[-75.57,6.24], + "mel":[144.96, -37.81], + "mex":[-99.13,19.43], + "mga":[-86.25,12.13], + "mgf":[-51.94,-23.42], + "mgm":[-86.3,32.37], + "mgq":[45.32,2.05], + "mia":[-80.19,25.76], + "mil":[9.19,45.46], + "mla":[14.51,35.9], + "mle":[73.51,4.18], + "mmk":[33.08,68.97], + "mmx":[13.0,55.6], + "mnl":[120.98,14.6], + "mos":[37.62,55.76], + "mpm":[32.57,-25.97], + "mpv":[-72.58,44.26], + "mrs":[5.37,43.3], + "mru":[57.52,-20.18], + "msn":[-89.4,43.07], + "msq":[27.56,53.9], + "msu":[27.48,-29.31], + "mtl":[-73.57,45.5], + "mty":[-100.31,25.69], + "muc":[11.58,48.14], + "mvd":[-56.16,-34.9], + "nas":[-77.35,25.04], + "nat":[-35.21,-5.79], + "nbo":[36.82,-1.29], + "ndj":[15.06,12.13], + "nic":[33.38,35.19], + "nim":[2.11,13.51], + "nkc":[-15.98,18.08], + "nou":[166.46,-22.27], + "nqz":[71.45,51.17], + "nsi":[11.5,3.85], + "nte":[-1.55,47.22], + "nuk":[-51.72,64.18], + "nyc":[-74.0,40.71], + "nyt":[96.08,19.76], + "okc":[-97.52,35.47], + "olm":[-122.9,47.04], + "ome":[-165.38,64.52], + "oos":[3.23,51.15], + "osa":[135.5, 34.69], + "osl":[10.75,59.91], + "ott":[-75.7,45.42], + "oua":[-1.52,12.37], + "oxb":[-15.6,11.9], + "pan":[-79.52, 8.98], + "pap":[-72.34,18.54], + "par":[2.35,48.86], + "pbh":[89.64,27.47], + "pbm":[-55.2,5.85], + "pcn":[-130.1,-25.07], + "pdl":[-25.67,37.74], + "pek":[116.4,39.9], + "per":[115.86,-31.95], + "phe":[118.61,-20.31], + "phx":[-112.07,33.45], + "pir":[-100.35,44.37], + "pkc":[158.65,53.02], + "pmo":[13.36,38.12], + "pmw":[-48.33,-10.18], + "pnh":[104.92,11.56], + "pni":[158.16,6.92], + "poa":[-51.23,-30.03], + "pom":[147.18,-9.44], + "pos":[-61.48,10.66], + "ppg":[-170.7,-14.28], + "ppt":[-149.57,-17.53], + "prg":[14.42, 50.08], + "prr":[-130.32,54.31], + "pry":[28.19,-25.75], + "pto":[2.63,6.5], + "pvd":[-71.41,41.82], + "pvh":[-63.9,-8.76], + "pvs":[170.31,69.7], + "qaq":[-46.04,60.72], + "qmn":[31.14,-26.31], + "qro":[-100.39,20.59], + "rai":[-23.55,14.98], + "rao":[-47.81,-21.18], + "rba":[-6.84,34.02], + "rbr":[-67.81,-9.97], + "rdu":[-78.64,35.78], + "rec":[-34.88,-8.05], + "rek":[-21.94,64.15], + "ria":[-53.81,-29.68], + "ric":[-77.44,37.54], + "rio":[-43.11,-22.57], + "rix":[24.11,56.95], + "rns":[-1.68,48.11], + "rob":[-10.7,6.38], + "rom":[12.5,41.9], + "ror":[134.48,7.34], + "ruh":[46.72,24.71], + "run":[55.46,-20.92], + "sac":[-121.49,38.58], + "saf":[-105.94,35.69], + "sah":[44.19,15.37], + "sal":[-89.19,13.69], + "sao":[-46.63,-23.55], + "scl":[-70.67, -33.45], + "sdq":[-69.93,18.5], + "sea":[-122.33,47.61], + "sez":[55.47,-4.65], + "sgn":[106.66, 10.76], + "sha":[121.47,31.23], + "sin":[103.82,1.35], + "sis":[-53.67,66.94], + "sjc":[-121.89,37.34], + "sjj":[18.41,43.86], + "sjo":[-84.09,9.93], + "sjp":[-49.38,-20.81], + "sju":[-66.1,18.4], + "skp":[21.43,41.99], + "slc":[-111.89,40.76], + "sle":[-123.03,44.94], + "slu":[-60.99,14.01], + "slz":[-44.3,-2.53], + "smr":[12.45,43.94], + "sof":[23.32,42.7], + "spi":[-89.65,39.8], + "sre":[-65.26,-19.04], + "ssa":[-38.5,-12.97], + "ssg":[8.78,3.75], + "stg":[9.18,48.78], + "sto":[18.07,59.33], + "stp":[-93.09,44.95], + "suv":[178.44,-18.14], + "svd":[-61.22,13.16], + "svg":[5.73,58.97], + "sxb":[7.75,48.57], + "syd":[151.21,-33.87], + "tas":[69.24,41.3], + "tbs":[44.79,41.72], + "tbu":[-175.2,-21.14], + "tci":[-16.3,28.44], + "tgd":[19.26,42.44], + "tgu":[-87.19,14.07], + "the":[-42.8,-5.09], + "thr":[51.39,35.69], + "tia":[19.82,41.33], + "tik":[128.87,71.64], + "tip":[13.19,32.89], + "tlh":[-84.28,30.44], + "tll":[24.45,58.9], + "tls":[1.44,43.6], + "tms":[6.73,0.34], + "tnr":[47.52,-18.88], + "tok":[139.69,35.69], + "top":[-95.68,39.05], + "tor":[-79.38,43.65], + "tpe":[121.56, 25.03], + "trw":[173.03,1.35], + "tsv":[146.82,-19.26], + "ttn":[-74.76,40.22], + "tun":[10.18,36.81], + "uio":[-78.47,-0.18], + "uln":[106.91,47.89], + "uus":[142.74,46.96], + "van":[-123.12,49.28], + "vdz":[9.52,47.14], + "vie":[16.37, 48.21], + "vix":[-40.31,-20.32], + "vli":[168.32,-17.73], + "vno":[25.28,54.69], + "vte":[102.63,17.98], + "vvo":[131.89,43.12], + "was":[-77.04,38.91], + "waw":[21.01, 52.23], + "wdh":[17.08,-22.56], + "wlg":[174.8,-41.2], + "yeg":[-113.49,53.55], + "yfb":[-68.52,63.75], + "yfc":[-66.64,45.96], + "yqb":[-71.21,46.81], + "yqr":[-104.62,50.45], + "ywg":[-97.14,49.9], + "yxe":[-106.67,52.13], + "yxy":[-135.06,60.72], + "yyg":[-63.13,46.24], + "yyj":[-123.37,48.43], + "yyt":[-52.71,47.56], + "yzf":[-114.37,62.45], + "zag":[15.98,45.81], + "zrh":[8.54,47.37], +}; diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js new file mode 100644 index 0000000..4c9d512 --- /dev/null +++ b/src/game/20-world/50-cities.js @@ -0,0 +1,521 @@ +const CITIES=[ + {id:'sea',name:'Seattle',x:205,y:245,land:'am',reg:'AM',cc:'US',P:300,ix:'Sea-IX',dc:'Westerly Carrier Hotel'}, + {id:'sjc',name:'San Jose',x:240,y:345,land:'am',reg:'AM',cc:'US',P:500,ix:'Silly-Con Valley IX',dc:'Equinox SV'}, + {id:'dal',name:'Dallas',x:385,y:415,land:'am',reg:'AM',cc:'US',P:450,ix:'Yee-Haw-IX',dc:'Infomaniac Building'}, + {id:'chi',name:'Chicago',x:470,y:270,land:'am',reg:'AM',cc:'US',P:600,ix:'Windy-IX',dc:'350 Cermak'}, + {id:'ash',name:'Ashburn',x:572,y:332,land:'am',reg:'AM',cc:'US',P:250,ix:'Equinox Ashburn IX',dc:'Data Center Alley',note:tr('cities.the_data_center_capital_rumor_says')}, + {id:'nyc',name:'New York',x:615,y:283,land:'am',reg:'AM',cc:'US',P:1200,ix:'NY-Yikes',dc:'60 Hudson'}, + {id:'mia',name:'Miami',x:530,y:482,land:'am',reg:'AM',cc:'US',P:400,ix:'Miam-IX',dc:'Nap of the Americas',note:tr('cities.cable_landing_hub_for_south_america')}, + {id:'sao',name:'São Paulo',x:640,y:730,land:'sa',reg:'SA',cc:'BR',P:900,br:true,andes:'e',ix:'IX.brrr São Paulo',ixCheap:0.3,dc:'Digital Reality SP',note:tr('cities.south_america_s_biggest_market_and')}, + {id:'lon',name:'London',x:935,y:275,land:'uk',reg:'EU',cc:'GB',P:1000,ix:'LYNX',dc:'Telly-House Docklands',note:tr('cities.on_an_island_so_every_link')}, + {id:'ams',name:'Amsterdam',x:1015,y:245,land:'eu',reg:'EU',cc:'NL',P:350,ix:'HAMS-IX',dc:'Science Park'}, + {id:'fra',name:'Frankfurt',x:1075,y:295,land:'eu',reg:'EU',cc:'DE',P:600,ix:'DE-KICKS',dc:'Kleyerstraße Campus',note:tr('cities.europe_s_crossroads_lots_of_networks')}, + {id:'par',name:'Paris',x:990,y:320,land:'eu',reg:'EU',cc:'FR',P:900,ix:'Fromage-IX',dc:'Interaction PAR'}, + {id:'lys',name:'Lyon',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:220,ix:'Quenelle-IX',dc:'Croix-Rousse Silk Rack'}, + {id:'tls',name:'Toulouse',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:140,ix:'Cassoulet-IX',dc:'Pink City Colo'}, + {id:'lil',name:'Lille',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:120,ix:'Maroilles-IX',dc:'Belfry Colo'}, + {id:'bod',name:'Bordeaux',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:120,ix:'Claret-IX',dc:'Wine Cellar DC'}, + {id:'sxb',name:'Strasbourg',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:80,ix:'Choucroute-IX',dc:'Cathedral Clock DC'}, + {id:'rns',name:'Rennes',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:75,ix:'Galette-IX',dc:'Breton Cold Room'}, + {id:'nte',name:'Nantes',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:90,ix:'',dc:'Mechanical Elephant DC'}, + {id:'mrs',name:'Marseille',x:1045,y:378,land:'eu',reg:'EU',cc:'FR',P:250,ix:'Bouilla-IX',dc:'Cable Landing Station',note:tr('cities.subsea_cables_to_africa_and_asia')}, + {id:'tor',name:'Toronto',ca:true,x:548,y:252,land:'am',reg:'AM',cc:'CA',P:500,ix:'Sorry-IX',dc:'151 Front Street',note:tr('cities.canada_s_hub_polite_packets_long')}, + {id:'bru',name:'Brussels',x:0,y:0,land:'eu',reg:'EU',cc:'BE',P:150,be:true,tape:true,ix:'Frites-IX',dc:'Digital Unreality BRU1',note:tr('cities.right_between_london_amsterdam_paris')}, + {id:'oos',name:'Oostkamp',x:0,y:0,land:'eu',reg:'EU',cc:'BE',P:30,be:true,tape:true,ix:'',dc:'DC-Starfish Oostkamp',note:tr('cities.inland_from_ostend_where_the_cables')}, + {id:'bet',name:'Bettembourg',x:0,y:0,land:'eu',reg:'EU',cc:'LU',P:60,arpu:1.4,lux:true,ix:'LU-SICK',dc:'LuxDisconnect DC1.2',note:tr('cities.luxembourg_s_data_centers_are_not')}, + {id:'mtl',name:'Montreal',ca:true,x:598,y:238,land:'am',reg:'AM',cc:'CA',P:300,ix:'Poutine-IX',dc:'Hydro-powered Hangar',note:tr('cities.cheap_hydro_power_makes_it_a')}, + {id:'kcy',name:'Kansas City',x:0,y:0,land:'am',reg:'AM',cc:'US',P:200,ix:'Toto-IX',dc:'The Limestone Cave',note:tr('cities.the_geographic_middle_of_the_us')}, + {id:'cal',name:'Calgary',x:0,y:0,land:'am',reg:'AM',cc:'CA',P:150,ca:true,ix:'Stampede-IX',dc:'Bow & Arrow DC',note:tr('cities.the_prairie_gateway_between')}, + {id:'van',name:'Vancouver',x:0,y:0,land:'am',reg:'AM',cc:'CA',P:250,ca:true,ix:'Raincouver-IX',dc:'Colo-Logics VAN3',note:tr('cities.canada_s_pacific_door_it_rains')}, + {id:'ott',name:'Ottawa',x:0,y:0,land:'am',reg:'AM',cc:'CA',P:120,ca:true,blackout:true,ix:'Bytown-IX',dc:'Purely Colo (Mostly)',note:tr('cities.canada_s_capital_once_called_bytown')}, + {id:'lax',name:'Los Angeles',x:270,y:395,land:'am',reg:'AM',cc:'US',P:900,ix:'Any2-Anywhere',dc:'One Wilshire',note:tr('cities.pacific_cables_land_nearby_and')}, + {id:'mex',name:'Mexico City',x:368,y:470,land:'am',reg:'AM',cc:'MX',P:700,ix:'',dc:'Querétaro Campus',note:tr('cities.huge_mobile_market_most_of_its')}, + {id:'rek',name:'Reykjavik',x:850,y:170,land:'is',reg:'EU',cc:'IS',P:60,ix:'',dc:'Geothermal Bitcoin Barn',note:tr('cities.free_cooling_and_geothermal_power')}, + {id:'dub',name:'Dublin',x:876,y:268,land:'ie',reg:'EU',cc:'IE',P:250,ix:'Craic-IX',dc:'Clonsilla Hyperscale Campus',note:tr('cities.every_hyperscaler_s_european_hq')}, + {id:'osl',name:'Oslo',x:1062,y:172,land:'eu',reg:'EU',cc:'NO',P:200,ix:'NIX-NIX',dc:'Fjord-cooled Mountain Hall'}, + {id:'cph',name:'Copenhagen',x:1085,y:215,land:'eu',reg:'EU',cc:'DK',P:250,ix:'Hygge-IX',dc:'Danish Design DC',note:tr('cities.landing_point_for_cables_from_the')}, + {id:'hel',name:'Helsinki',x:1168,y:140,land:'eu',reg:'EU',cc:'FI',P:200,ix:'Sauna-IX',dc:'Underground Sauna Bunker',note:tr('cities.fast_fiber_east_and_west_and')}, + {id:'beg',name:'Belgrade',x:1122,y:338,land:'eu',reg:'EU',cc:'RS',P:250,ix:'',dc:'Danube Docks DC'}, + {id:'sof',name:'Sofia',x:1165,y:358,land:'eu',reg:'EU',cc:'BG',P:250,ix:'Rakija-IX',dc:'Vitosha DC',note:tr('cities.balkan_peering_hub_with_famously')}, + {id:'dxb',name:'Dubai',x:1292,y:428,land:'eu',reg:'AS',cc:'AE',P:400,uae:true,ix:'Sand-IX',dc:'Air-conditioned Mirage DC',note:tr('cities.crossroads_for_cables_between_europe')}, + {id:'mos',name:'Moscow',x:1235,y:192,land:'eu',reg:'EU',cc:'RU',P:900,ru:true,arpu:0.5,ix:'Borscht-IX',dc:'Very Secure Bunker',note:tr('cities.sovereign_internet_rules_every_pop')}, + {id:'akl',name:'Auckland',x:1964,y:826,land:'nz',reg:'OC',cc:'NZ',P:250,ix:'Kiwi-IX',dc:'Sheep-cooled Shed',note:tr('cities.far_from_everything_every_packet')}, + {id:'per',name:'Perth',x:1712,y:785,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:200,ix:'Beard-IX',dc:'Very Remote DC',dc2:'Next-Door-DC P#',dc2N:2,note:tr('cities.the_most_isolated_big_city_on')}, + {id:'jkt',name:'Jakarta',x:1614,y:624,land:'idn',reg:'AS',cc:'ID',P:900,ix:'Nasi-IX',dc:'Monsoon-proof DC',note:tr('cities.270_million_people_on_17_000')}, + {id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',cc:'PH',ph:true,arpu:PH_ARPU,P:1000,ix:'GotchaFIX Manila',ixCheap:1.8,dc:'Typhoon-rated DC',note:tr('cities.typhoons_earthquakes_and_a_lot_of')}, + {id:'ber',name:'Berlin',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:450,ix:'Currywurst-IX',dc:'Former Brewery DC',note:tr('cities.startups_techno_and_a_surprising')}, + {id:'ham',name:'Hamburg',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:250,ix:'Moin-IX',dc:'Speicherstadt Colo',note:tr('cities.germany_s_port_city_everyone_says')}, + {id:'dus',name:'Düsseldorf',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:300,ix:'Altbier-IX',dc:'Königsallee Cage',note:tr('cities.the_rhine_ruhr_hub_more_carrier')}, + {id:'muc',name:'Munich',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:250,ix:'Brezn-IX',dc:'Weißwurst Works',note:tr('cities.bavaria_s_capital_cars_insurers_and')}, + {id:'zrh',name:'Zurich',x:0,y:0,land:'eu',reg:'EU',cc:'CH',P:250,ix:'Cuckoo-IX',dc:'Bank Vault DC',note:tr('cities.banks_very_punctual_packets_and')}, + {id:'nbo',name:'Nairobi',x:0,y:0,land:'af',reg:'AF',cc:'KE',P:350,ix:'Safari-IX',dc:'Silicon Savannah Campus',note:tr('cities.east_africa_s_hub_cables_land')}, + {id:'cai',name:'Cairo',x:0,y:0,land:'af',land2:'eu',reg:'AF',cc:'EG',P:600,ix:'Pharaoh-IX',dc:'Pyramid-adjacent DC',note:tr('cities.almost_every_europe_asia_cable')}, + {id:'stg',name:'Stuttgart',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:300,ix:'Spätzle-IX',dc:'Kehrwoche-certified DC',ixOnly:true,note:tr('cities.cars_engineers_and_kehrwoche_every')}, + {id:'sto',name:'Stockholm',x:1110,y:160,land:'eu',reg:'EU',cc:'SE',P:300,ix:'NodNod',dc:'Nuclear Bunker DC'}, + {id:'bcn',name:'Barcelona',x:0,y:0,land:'eu',reg:'EU',cc:'ES',P:300,ix:'Catnip-IX',dc:'Poblenou DC',note:tr('cities.catalonia_s_own_exchange_small_and')}, + {id:'mad',name:'Madrid',x:935,y:392,land:'eu',reg:'EU',cc:'ES',P:600,ix:'Siesta-IX',dc:'Interaction MAD'}, + {id:'bio',name:'Bilbao',x:0,y:0,land:'eu',reg:'EU',cc:'ES',P:150,ix:'',dc:'Guggen-Rack',note:tr('cities.the_transatlantic_cables_come_ashore_here')}, + {id:'lag',name:'Lagos',x:1010,y:565,land:'af',reg:'AF',cc:'NG',P:500,ix:'Jollof-IX',dc:'Rack-n-Roll Centre'}, + {id:'jnb',name:'Johannesburg',x:1130,y:730,land:'af',reg:'AF',cc:'ZA',P:400,za:true,ix:'Braai-IX',dc:'Tera-Cotta Campus'}, + {id:'bom',name:'Mumbai',x:1385,y:488,land:'eu',reg:'AS',cc:'IN',P:1100,india:true,ix:'Mumb-IX',dc:'Goregaon Tech Park'}, + {id:'sin',name:'Singapore',x:1556,y:568,land:'eu',reg:'AS',cc:'SG',P:450,ix:'Lah-IX',dc:'Equinox SG',note:tr('cities.asia_s_hub_expensive_humid_very')}, + {id:'hkg',name:'Hong Kong',x:1645,y:440,land:'eu',reg:'AS',cc:'HK',P:600,ix:'HK-Kicks',dc:'Mega-Eye Plus'}, + {id:'icn',name:'Seoul',x:1722,y:302,land:'eu',reg:'AS',cc:'KR',P:900,kr:true,ix:'Kimch-IX',dc:'Gasan Digital Complex',note:tr('cities.some_of_the_fastest_home_broadband')}, + {id:'pek',name:'Beijing',x:1652,y:318,land:'eu',reg:'AS',cc:'CN',P:1800,cn:true,arpu:0.6,ix:'',dc:'Zhongguancun DC',note:tr('cities.mainland_china_behind_the_great')}, + {id:'sha',name:'Shanghai',x:1680,y:388,land:'eu',reg:'AS',cc:'CN',P:2200,cn:true,arpu:0.6,ix:'',dc:'Lujiazui Data Center',note:tr('cities.mainland_china_enormous_market')}, + {id:'tok',name:'Tokyo',x:1795,y:320,land:'jp',reg:'AS',cc:'JP',P:1400,ix:'JP-Naptime',dc:'Otemachi Tower'}, + {id:'syd',name:'Sydney',x:1860,y:790,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:500,ix:'IX Straya',dc:'Next-Door-DC S#',dcN:3,dc2:'Equinox SY#',dc2N:7,note:tr('cities.the_harbour_the_bridge_and_most')}, +{id:'for',name:'Fortaleza',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:250,br:true,andes:'e',ix:'IX.brrr Fortaleza',ixCheap:0.3,dc:'Praia Landing Station',note:tr('cities.where_south_america_s_cables')}, + {id:'rio',name:'Rio de Janeiro',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:600,br:true,andes:'e',ix:'IX.brrr Rio',ixCheap:0.3,dc:'Copacabana Colo',note:tr('cities.beaches_cable_landings_and_a')}, + {id:'bsb',name:'Brasília',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:200,br:true,andes:'e',ix:'IX.brrr Brasília',ixCheap:0.3,dc:'Modernist Concrete Colo',note:tr('cities.brazil_s_planned_capital_shaped_like')}, + {id:'bhz',name:'Belo Horizonte',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:250,br:true,andes:'e',ix:'IX.brrr BH',ixCheap:0.3,dc:'Pão de Queijo Point',note:tr('cities.mountains_mines_and_more_bars_per')}, + {id:'cwb',name:'Curitiba',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:200,br:true,andes:'e',ix:'IX.brrr Curitiba',ixCheap:0.3,dc:'Pine Nut Park DC',note:tr('cities.brazil_s_coldest_big_city_and')}, + {id:'poa',name:'Porto Alegre',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:200,br:true,andes:'e',ix:'IX.brrr Porto Alegre',ixCheap:0.3,dc:'Chimarrão Colo',note:tr('cities.the_deep_south_halfway_to_buenos')}, + {id:'aju',off:true,name:'Aracaju',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:40,br:true,andes:'e',ix:'IX.brrr Aracaju',ixCheap:0.3,dc:'Crab Walk Colo'}, + {id:'bel',name:'Belém',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:100,br:true,andes:'e',rain:true,ix:'IX.brrr Belém',ixCheap:0.3,dc:'Açaí Bowl DC',note:tr('cities.gateway_to_the_amazon_at_the')}, + {id:'bvb',name:'Boa Vista',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',rain:true,ix:'IX.brrr Boa Vista',ixCheap:0.3,dc:'Northern Lights Racks',note:tr('cities.brazil_s_northernmost_capital_the')}, + {id:'cac',off:true,name:'Cascavel',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',ix:'IX.brrr Cascavel',ixCheap:0.3,dc:'Soybean Silo DC'}, + {id:'cpv',off:true,name:'Campina Grande',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',ix:'IX.brrr Campina Grande',ixCheap:0.3,dc:'Forró Forum DC',note:tr('cities.throws_the_biggest_sao_joao_festival')}, + {id:'cpq',name:'Campinas',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:130,br:true,andes:'e',ix:'IX.brrr Campinas',ixCheap:0.3,dc:'Silicon Sugarcane Park',note:tr('cities.brazil_s_tech_hub_an_hour')}, + {id:'cgr',name:'Campo Grande',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:40,br:true,andes:'e',ix:'IX.brrr Campo Grande',ixCheap:0.3,dc:'Pantanal Edge Colo'}, + {id:'cau',off:true,name:'Caruaru',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',ix:'IX.brrr Caruaru',ixCheap:0.3,dc:'Clay Doll Datacenter'}, + {id:'cgb',name:'Cuiabá',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:40,br:true,andes:'e',ix:'IX.brrr Cuiabá',ixCheap:0.3,dc:'Forty Degrees DC',note:tr('cities.the_geographic_center_of_south')}, + {id:'cxj',off:true,name:'Caxias do Sul',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',ix:'IX.brrr Caxias do Sul',ixCheap:0.3,dc:'Wine Cellar Racks',note:tr('cities.italian_immigrants_vineyards_and')}, + {id:'fec',off:true,name:'Feira de Santana',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',ix:'IX.brrr Feira de Santana',ixCheap:0.3,dc:'Crossroads Colo'}, + {id:'fln',off:true,name:'Florianópolis',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:50,br:true,andes:'e',ix:'IX.brrr Florianópolis',ixCheap:0.3,dc:'Island Uplink DC',note:tr('cities.an_island_capital_of_beaches_and')}, + {id:'igu',off:true,name:'Foz do Iguaçu',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:15,br:true,andes:'e',ix:'IX.brrr Foz do Iguaçu',ixCheap:0.3,dc:'Triple Border Racks',note:tr('cities.where_brazil_argentina_and_paraguay')}, + {id:'gyn',name:'Goiânia',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:100,br:true,andes:'e',ix:'IX.brrr Goiânia',ixCheap:0.3,dc:'Pequi Peak DC',note:tr('cities.agribusiness_capital_and_home_of')}, + {id:'jpa',off:true,name:'João Pessoa',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:50,br:true,andes:'e',ix:'IX.brrr João Pessoa',ixCheap:0.3,dc:'Sunrise Point DC',note:tr('cities.the_easternmost_city_of_the_americas')}, + {id:'ljd',off:true,name:'Lajeado',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:10,br:true,andes:'e',ix:'IX.brrr Lajeado',ixCheap:0.3,dc:'Valley Co-op Colo',note:tr('cities.a_small_town_with_its_own')}, + {id:'ldb',name:'Londrina',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:35,br:true,andes:'e',ix:'IX.brrr Londrina',ixCheap:0.3,dc:'Red Soil DC'}, + {id:'mcp',name:'Macapá',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',rain:true,blackout:true,ix:'IX.brrr Macapá',ixCheap:0.3,dc:'Equator Line Colo',note:tr('cities.right_on_the_equator_at_the')}, + {id:'mcz',off:true,name:'Maceió',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:55,br:true,andes:'e',ix:'IX.brrr Maceió',ixCheap:0.3,dc:'Lagoon View Racks'}, + {id:'mao',name:'Manaus',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:90,br:true,andes:'e',rain:true,ix:'IX.brrr Manaus',ixCheap:0.3,dc:'Free Zone Colo',note:tr('cities.two_million_people_in_the_middle')}, + {id:'mgf',off:true,name:'Maringá',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:30,br:true,andes:'e',ix:'IX.brrr Maringá',ixCheap:0.3,dc:'Cathedral Cone DC'}, + {id:'nat',name:'Natal',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:60,br:true,andes:'e',ix:'IX.brrr Natal',ixCheap:0.3,dc:'Dune Buggy DC',note:tr('cities.dunes_buggies_and_the_corner_of')}, + {id:'pmw',name:'Palmas',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:15,br:true,andes:'e',ix:'IX.brrr Palmas',ixCheap:0.3,dc:'Planned Grid DC',note:tr('cities.brazil_s_youngest_state_capital')}, + {id:'pvh',name:'Porto Velho',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',rain:true,ix:'IX.brrr Porto Velho',ixCheap:0.3,dc:'Madeira River Racks'}, + {id:'rao',off:true,name:'Ribeirão Preto',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:50,br:true,andes:'e',ix:'IX.brrr Ribeirão Preto',ixCheap:0.3,dc:'Sugarcane & Servers',note:tr('cities.brazil_s_agribusiness_capital')}, + {id:'rec',name:'Recife',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:160,br:true,andes:'e',ix:'IX.brrr Recife',ixCheap:0.3,dc:'Frevo Colo',note:tr('cities.the_venice_of_brazil_all_bridges')}, + {id:'rbr',name:'Rio Branco',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',rain:true,ix:'IX.brrr Rio Branco',ixCheap:0.3,dc:'Acre-ly Real DC',note:tr('cities.the_capital_of_acre_a_state')}, + {id:'ssa',name:'Salvador',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:160,br:true,andes:'e',ix:'IX.brrr Salvador',ixCheap:0.3,dc:'Axé Uplink DC',note:tr('cities.brazil_s_first_capital_with_cables')}, + {id:'ria',off:true,name:'Santa Maria',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:15,br:true,andes:'e',ix:'IX.brrr Santa Maria',ixCheap:0.3,dc:'Gaúcho Plains Colo'}, + {id:'sjp',off:true,name:'São José do Rio Preto',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',ix:'IX.brrr São José do Rio Preto',ixCheap:0.3,dc:'Rio Preto Racks'}, + {id:'slz',name:'São Luís',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:65,br:true,andes:'e',ix:'IX.brrr São Luís',ixCheap:0.3,dc:'Reggae Island DC',note:tr('cities.an_island_city_of_tiled_colonial')}, + {id:'the',name:'Teresina',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:50,br:true,andes:'e',ix:'IX.brrr Teresina',ixCheap:0.3,dc:'Sunbaked Server Hall',note:tr('cities.the_only_northeastern_capital_away')}, + {id:'vix',name:'Vitória',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:80,br:true,andes:'e',ix:'IX.brrr Vitória',ixCheap:0.3,dc:'Moqueca Colo',note:tr('cities.an_island_capital_with_a_big')}, + {id:'mvd',name:'Montevideo',x:0,y:0,land:'sa',reg:'SA',cc:'UY',P:150,andes:'e',ix:'Chivito-IX',dc:'Rambla Racks',note:tr('cities.uruguay_fiber_to_almost_every_home')}, + {id:'asu',name:'Asunción',x:0,y:0,land:'sa',reg:'SA',cc:'PY',P:120,andes:'e',ix:'Chipa-IX',dc:'Hydro Surplus DC',note:tr('cities.paraguay_shares_two_giant_dams_with')}, + {id:'cor',name:'Córdoba',x:0,y:0,land:'sa',reg:'SA',cc:'AR',P:150,andes:'e',arpu:0.7,ix:'Fernet-IX',dc:'Sierras Server Shed',note:tr('cities.argentina_s_second_city_universities')}, + {id:'lpb',name:'La Paz',x:0,y:0,land:'sa',reg:'SA',cc:'BO',P:80,andes:'m',ix:'Salteña-IX',dc:'Cable Car Colo',note:tr('cities.the_highest_seat_of_government_on')}, + {id:'uio',name:'Quito',x:0,y:0,land:'sa',reg:'SA',cc:'EC',P:100,andes:'m',ix:'Equator-IX',dc:'Middle of the World DC',note:tr('cities.a_capital_high_in_the_andes')}, + {id:'mde',name:'Medellín',x:0,y:0,land:'sa',reg:'SA',cc:'CO',P:150,andes:'m',ix:'Paisa-IX',dc:'Eternal Spring DC',note:tr('cities.the_city_of_eternal_spring_with')}, + {id:'ccs',name:'Caracas',x:0,y:0,land:'sa',reg:'SA',cc:'VE',P:120,blackout:true,ix:'Cachapa-IX',dc:'Generator Included DC',note:tr('cities.a_capital_in_a_valley_under')}, + {id:'gua',name:'Guatemala City',x:0,y:0,land:'am',reg:'AM',cc:'GT',P:120,ix:'Quetzal-IX',dc:'Volcano View Colo',note:tr('cities.central_america_s_biggest_city')}, + {id:'sjo',name:'San José',x:0,y:0,land:'am',reg:'AM',cc:'CR',P:80,ix:'Pura Vida-IX',dc:'Cloud Forest DC',note:tr('cities.costa_rica_runs_almost_entirely_on')}, + {id:'qro',name:'Querétaro',x:0,y:0,land:'am',reg:'AM',cc:'MX',P:120,ix:'Gordita-IX',dc:'Bajío Bit Barn',note:tr('cities.mexico_s_data_center_boom_town')}, + {id:'mty',name:'Monterrey',x:0,y:0,land:'am',reg:'AM',cc:'MX',P:200,ix:'Cabrito-IX',dc:'Saddle Mountain Colo',note:tr('cities.mexico_s_industrial_capital_a_few')}, + {id:'gdl',name:'Guadalajara',x:0,y:0,land:'am',reg:'AM',cc:'MX',P:200,ix:'Tequila-IX',dc:'Mariachi Mainframes',note:tr('cities.mexico_s_silicon_valley_home_of')}, + {id:'bue',name:'Buenos Aires',x:0,y:0,land:'sa',reg:'SA',cc:'AR',P:500,andes:'e',arpu:0.7,ix:'Asado-IX',dc:'Puerto Madero DC',note:tr('cities.tango_steak_and_a_very')}, + {id:'scl',name:'Santiago',x:0,y:0,land:'sa',reg:'SA',cc:'CL',P:350,andes:'w',ix:'Empanada-IX',dc:'Andes-view Bunker',note:tr('cities.the_pacific_gateway_the_andes_sit')}, + {id:'lim',name:'Lima',x:0,y:0,land:'sa',reg:'SA',cc:'PE',P:400,andes:'w',ix:'Ceviche-IX',dc:'Fog-cooled DC',note:tr('cities.it_almost_never_rains_but_the')}, + {id:'bog',name:'Bogotá',x:0,y:0,land:'sa',reg:'SA',cc:'CO',P:400,andes:'m',ix:'Arepa-IX',dc:'2,600 m Above Sea Level DC',note:tr('cities.high_up_in_the_andes_no')}, + {id:'pan',name:'Panama City',x:0,y:0,land:'am',reg:'AM',cc:'PA',P:80,ix:'Canal-IX',dc:'Isthmus Interconnect',note:tr('cities.every_cable_between_the_americas')}, + {id:'del',name:'Delhi',x:0,y:0,land:'eu',reg:'AS',cc:'IN',P:1600,arpu:0.4,india:true,ix:'Butter-Chicken-IX',dc:'Smog-filtered DC',note:tr('cities.an_enormous_very_online_city_a')}, + {id:'maa',name:'Chennai',x:0,y:0,land:'eu',reg:'AS',cc:'IN',P:500,arpu:0.5,india:true,ix:'Dosa-IX',dc:'Cyclone-rated Landing Bay',note:tr('cities.india_s_east_coast_landing_hub')}, + {id:'blr',name:'Bengaluru',x:0,y:0,land:'eu',reg:'AS',cc:'IN',P:600,arpu:0.6,india:true,ix:'Filter-Kaapi-IX',dc:'Traffic-jam-adjacent Campus',note:tr('cities.india_s_tech_capital_packets_move')}, + {id:'hyd',name:'Hyderabad',x:0,y:0,land:'eu',reg:'AS',cc:'IN',P:400,arpu:0.5,india:true,ix:'Biryani-IX',dc:'Hyperscale Hills',note:tr('cities.every_hyperscaler_is_building_a')}, + {id:'tpe',name:'Taipei',x:0,y:0,land:'tw',reg:'AS',cc:'TW',P:450,ix:'Bubble-Tea-IX',dc:'Typhoon-proof Tower',note:tr('cities.makes_most_of_the_world_s')}, + {id:'auh',name:'Abu Dhabi',x:0,y:0,land:'eu',reg:'AS',cc:'AE',P:200,arpu:1.4,uae:true,ix:'',dc:'Oasis-cooled Campus',note:tr('cities.the_capital_sovereign_ai_money_and')}, + {id:'fuj',name:'Fujairah',x:0,y:0,land:'eu',reg:'AS',cc:'AE',P:20,uae:true,ix:'',dc:'Cable Landing Sandcastle',note:tr('cities.most_uae_cables_land_on_this')}, + {id:'cpt',name:'Cape Town',x:0,y:0,land:'af',reg:'AF',cc:'ZA',P:250,za:true,ix:'Biltong-IX',dc:'Table Mountain Colo',note:tr('cities.where_the_atlantic_cables_to_africa')}, + {id:'dkr',name:'Dakar',x:0,y:0,land:'af',reg:'AF',P:140,cc:'SN',ix:'Thieboudienne-IX',dc:'Teranga Racks',note:tr('cities.africa_s_westernmost_capital_where')}, + {id:'abj',name:'Abidjan',x:0,y:0,land:'af',reg:'AF',P:200,cc:'CI',ix:'Attiéké-IX',dc:'Plateau Point DC',note:tr('cities.the_business_capital_of_french')}, + {id:'acc',name:'Accra',x:0,y:0,land:'af',reg:'AF',P:170,cc:'GH',ix:'Kelewele-IX',dc:'Black Star Colo',note:tr('cities.ghana_s_capital_and_a_favourite')}, + {id:'dla',name:'Douala',x:0,y:0,land:'af',reg:'AF',P:130,cc:'CM',ix:'Ndolé-IX',dc:'Wouri Riverside DC',note:tr('cities.cameroon_s_port_city_a_cable')}, + {id:'fih',name:'Kinshasa',x:0,y:0,land:'af',reg:'AF',P:350,cc:'CD',blackout:true,ix:'Rumba-IX',dc:'Congo River Colo',note:tr('cities.one_of_africa_s_biggest_cities')}, + {id:'lad',name:'Luanda',x:0,y:0,land:'af',reg:'AF',P:250,cc:'AO',ix:'Muamba-IX',dc:'Marginal View DC',note:tr('cities.angola_s_oil_capital_and_the')}, + {id:'cas',name:'Casablanca',x:0,y:0,land:'af',reg:'AF',P:150,cc:'MA',ix:'Tagine-IX',dc:'Here’s Looking at You, Rack',note:tr('cities.morocco_s_business_capital_on_the')}, + {id:'alg',name:'Algiers',x:0,y:0,land:'af',reg:'AF',P:130,cc:'DZ',ix:'Couscous-IX',dc:'Kasbah Colo',note:tr('cities.white_houses_climbing_up_from_the')}, + {id:'tun',name:'Tunis',x:0,y:0,land:'af',reg:'AF',P:100,cc:'TN',ix:'Harissa-IX',dc:'Carthage Was Here DC',note:tr('cities.a_capital_next_to_the_ruins')}, + {id:'jib',name:'Djibouti',x:0,y:0,land:'af',reg:'AF',P:40,cc:'DJ',ix:'Lake Assal-IX',dc:'Cable Landing Capital DC',note:tr('cities.a_tiny_country_at_the_mouth')}, + {id:'add',name:'Addis Ababa',x:0,y:0,land:'af',reg:'AF',P:170,cc:'ET',ix:'Injera-IX',dc:'Highland Coffee DC',note:tr('cities.ethiopia_s_capital_at_2_400')}, + {id:'mba',name:'Mombasa',x:0,y:0,land:'af',reg:'AF',P:60,cc:'KE',ix:'Pwani-IX',dc:'Old Town Landing Station',note:tr('cities.where_east_africa_s_cables_come')}, + {id:'dar',name:'Dar es Salaam',x:0,y:0,land:'af',reg:'AF',P:220,cc:'TZ',ix:'Bongo-IX',dc:'Kariakoo Colo',note:tr('cities.tanzania_s_biggest_city_and_the')}, + {id:'kla',name:'Kampala',x:0,y:0,land:'af',reg:'AF',P:130,cc:'UG',ix:'Matooke-IX',dc:'Seven Hills DC',note:tr('cities.a_city_on_seven_hills_by')}, + {id:'kgl',name:'Kigali',x:0,y:0,land:'af',reg:'AF',P:60,cc:'RW',ix:'Umuganda-IX',dc:'Clean Streets Colo',note:tr('cities.probably_the_cleanest_capital_in')}, + {id:'mpm',name:'Maputo',x:0,y:0,land:'af',reg:'AF',P:70,cc:'MZ',ix:'Matapa-IX',dc:'Polana Point DC',note:tr('cities.mozambique_s_capital_an_hour_from')}, + {id:'dur',name:'Durban',x:0,y:0,land:'af',reg:'AF',P:130,cc:'ZA',za:true,ix:'Bunny Chow-IX',dc:'Golden Mile Colo',note:tr('cities.south_africa_s_east_coast_surf')}, + {id:'wdh',name:'Windhoek',x:0,y:0,land:'af',reg:'AF',P:25,cc:'NA',ix:'Kapana-IX',dc:'Desert Breeze DC',note:tr('cities.a_small_capital_in_the_middle')}, + {id:'lun',name:'Lusaka',x:0,y:0,land:'af',reg:'AF',P:100,cc:'ZM',blackout:true,ix:'Nshima-IX',dc:'Copperbelt Colo',note:tr('cities.zambia_runs_on_hydro_power_from')}, + {id:'hre',name:'Harare',x:0,y:0,land:'af',reg:'AF',P:70,cc:'ZW',blackout:true,ix:'Sadza-IX',dc:'Jacaranda DC',note:tr('cities.purple_jacaranda_trees_and_long')}, + {id:'gbe',name:'Gaborone',x:0,y:0,land:'af',reg:'AF',P:25,cc:'BW',ix:'Seswaa-IX',dc:'Diamond Dust DC',note:tr('cities.botswana_quiet_safe_and_rich_in')}, +{id:'mel',name:'Melbourne',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:450,ix:'Flat-White-IX',dc:'Four-Seasons-a-Day DC',dc2:'Next-Door-DC M#',dc2N:3,note:tr('cities.four_seasons_in_one_day_and')}, + {id:'bne',name:'Brisbane',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:250,ix:'Bris-Vegas-IX',dc:'Sunshine State Shed',dc2:'Next-Door-DC B#',dc2N:2,note:tr('cities.brisvegas_big_sky_a_thunderstorm_at')}, + {id:'drw',name:'Darwin',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,wet:true,arpu:AU_ARPU,P:15,ix:'Gator-IX',dc:'Crocodile-proof Landing Station',note:tr('cities.tiny_tropical_and_the_closest')}, + {id:'adl',name:'Adelaide',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:150,ix:'Vineyard-IX',dc:'OurDC',dc2:'Next-Door-DC A1',note:tr('cities.twenty_minutes_from_everything')}, + {id:'cbr',capital:true,name:'Canberra',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:50,ix:'Capital-IX',dc:'Classified Data Cupboard',dc2:'Next-Door-DC C1',note:tr('cities.built_for_the_government_the_data')}, + {id:'chc',name:'Christchurch',x:0,y:0,land:'nzs',reg:'OC',cc:'NZ',P:40,ix:'Garden-City-IX',dc:'Mainland Colo',note:tr('cities.the_garden_city_and_the_biggest')}, + {id:'ivc',name:'Invercargill',x:0,y:0,land:'nzs',reg:'OC',cc:'NZ',P:10,ix:'',dc:'Sheargrid Makarewa',note:tr('cities.the_bottom_of_the_country_on')}, + {id:'hba',name:'Hobart',x:0,y:0,land:'tas',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:25,ix:'Cousin-IX',dc:'Firmest',note:tr('cities.the_bottom_of_the_map_cool')}, + {id:'hnl',name:'Honolulu',x:0,y:0,land:'hi',reg:'OC',cc:'US',P:70,ix:'Poke-IX',dc:'Dr. Fortress of Solitude',note:tr('cities.halfway_between_california_and')}, + {id:'gum',name:'Guam',x:0,y:0,land:'gu',reg:'OC',cc:'GU',P:15,blackout:true,ix:'Spam-IX',dc:'Typhoon-Proof Bunker',note:tr('cities.a_small_island_where_cables_from')}, + {id:'ror',name:'Koror',x:0,y:0,land:'pw',reg:'OC',cc:'PW',P:3,ix:'',dc:'Jellyfish Lake Landing',note:tr('cities.palau_on_a_branch_cable_from')}, + {id:'maj',name:'Majuro',x:0,y:0,land:'mh',reg:'OC',cc:'MH',P:3,ix:'',dc:'Two Metres Up Colo',note:tr('cities.the_capital_of_the_marshall_islands')}, + {id:'pom',name:'Port Moresby',x:0,y:0,land:'pg',reg:'OC',cc:'PG',P:40,blackout:true,ix:'',dc:'Bird of Paradise DC',note:tr('cities.papua_new_guinea_s_capital_in')}, + {id:'hir',name:'Honiara',x:0,y:0,land:'sb',reg:'OC',cc:'SB',P:8,blackout:true,ix:'Shell Money-IX',dc:'Guadalcanal Grotto',note:tr('cities.the_solomon_islands_capital_on')}, + {id:'nou',name:'Nouméa',x:0,y:0,land:'nc',reg:'OC',cc:'NC',P:20,ix:'Bougna-IX',dc:'Lagoon Rack',note:tr('cities.new_caledonia_a_slice_of_france')}, + {id:'suv',name:'Suva',x:0,y:0,land:'fj',reg:'OC',cc:'FJ',P:25,ix:'Kava-IX',dc:'Bula Bula Colo',note:tr('cities.fiji_s_capital_and_the_crossroads')}, + {id:'tbu',name:'Nuku’alofa',x:0,y:0,land:'to',reg:'OC',cc:'TO',P:4,ix:'',dc:'Volcano View DC',note:tr('cities.tonga_hangs_on_one_cable_from')}, + {id:'apw',name:'Apia',x:0,y:0,land:'ws',reg:'OC',cc:'WS',P:5,ix:'',dc:'Siva Shed',note:tr('cities.samoa_s_capital_with_cables_to')}, + {id:'ppg',name:'Pago Pago',x:0,y:0,land:'as',reg:'OC',cc:'AS',P:4,ix:'',dc:'Rainmaker Rack',note:tr('cities.american_samoa_a_deep_harbour_tuna')}, + {id:'ppt',name:'Papeete',x:0,y:0,land:'pf',reg:'OC',cc:'PF',P:18,ix:'',dc:'Overwater Bungalow DC',note:tr('cities.tahiti_in_french_polynesia_a_cable')}, + {id:'hfx',name:'Halifax',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,P:45,ix:'Donair-IX',dc:'Bluenose Bunker',note:tr('cities.nova_scotia_s_capital_and_the')}, + {id:'bda',name:'Bermuda',x:0,y:0,land:'bm',reg:'AM',cc:'BM',P:6,ix:'',dc:'Pink Sand Colo',note:tr('cities.a_thousand_kilometres_off_the')}, + {id:'pdl',name:'Ponta Delgada',x:0,y:0,land:'az',reg:'EU',cc:'PT',P:8,ix:'',dc:'Caldeira Colo',note:tr('cities.the_azores_in_the_middle_of')}, + {id:'tci',name:'Tenerife',x:0,y:0,land:'ic',reg:'EU',cc:'ES',P:25,ix:'',dc:'Mojo Picón DC',note:tr('cities.the_canary_islands_a_short_hop')}, + {id:'rai',name:'Praia',x:0,y:0,land:'cv',reg:'AF',cc:'CV',P:5,ix:'Cachupa-IX',dc:'Morabeza Rack',note:tr('cities.cape_verde_s_capital_off_the')}, + {id:'jam',name:'St Helena',x:0,y:0,land:'sh',reg:'AF',cc:'SH',P:1,blackout:true,ix:'',dc:'Napoleon’s Last Rack',note:tr('cities.one_of_the_most_remote_islands')}, + {id:'osa',name:'Osaka',x:0,y:0,land:'jp',reg:'AS',cc:'JP',P:700,ix:'Takoyaki-IX',dc:'Dojima DC',note:tr('cities.japan_s_second_hub_and_tokyo')}, + {id:'kul',name:'Kuala Lumpur',x:0,y:0,land:'eu',reg:'AS',cc:'MY',P:350,ix:'Satay-IX',dc:'Twin Towers Colo',note:tr('cities.cheaper_than_singapore_next_door_the')}, + {id:'bkk',name:'Bangkok',x:0,y:0,land:'eu',reg:'AS',cc:'TH',P:600,ix:'Tom-Yum-IX',dc:'Floating Market DC',note:tr('cities.big_busy_and_flooded_with_traffic')}, + {id:'sgn',name:'Ho Chi Minh City',x:0,y:0,land:'eu',reg:'AS',cc:'VN',P:500,vn:true,ix:'Pho-IX',dc:'Scooter-cooled DC',note:tr('cities.very_online_and_badly_served_by')}, + {id:'khi',name:'Karachi',x:0,y:0,land:'eu',reg:'AS',cc:'PK',P:500,arpu:0.4,ix:'Chai-IX',dc:'Seaview Landing Station',note:tr('cities.pakistan_s_door_to_the_sea')}, + {id:'dac',name:'Dhaka',x:0,y:0,land:'eu',reg:'AS',cc:'BD',P:700,arpu:0.3,ix:'Rickshaw-IX',dc:'Monsoon-mapped DC',note:tr('cities.huge_dense_and_hungry_its')}, + {id:'cbo',name:'Colombo',x:0,y:0,land:'lk',reg:'AS',cc:'LK',P:120,ix:'Hopper-IX',dc:'Tea-cooled Landing Station',note:tr('cities.a_small_island_at_the_crossroads')}, + {id:'waw',name:'Warsaw',x:0,y:0,land:'eu',reg:'EU',cc:'PL',P:550,ix:'Pierogi-IX',dc:'Palace-of-Culture-adjacent DC',note:tr('cities.central_europe_s_rising_hub_more')}, + {id:'prg',name:'Prague',x:0,y:0,land:'eu',reg:'EU',cc:'CZ',P:300,ix:'Pilsner-IX',dc:'Castle-view Colo',note:tr('cities.beer_is_cheaper_than_water_here')}, + {id:'vie',name:'Vienna',x:0,y:0,land:'eu',reg:'EU',cc:'AT',P:300,ix:'Schnitzel-IX',dc:'Waltz-cooled DC',note:tr('cities.the_old_gateway_to_eastern_europe')}, + {id:'bud',name:'Budapest',x:0,y:0,land:'eu',reg:'EU',cc:'HU',P:300,ix:'Goulash-IX',dc:'Thermal Bath DC',note:tr('cities.waste_heat_goes_straight_into_the')}, + {id:'buh',name:'Bucharest',x:0,y:0,land:'eu',reg:'EU',cc:'RO',P:400,ix:'Sarmale-IX',dc:'Parliament-sized DC',note:tr('cities.gigabit_home_broadband_for_the_price')}, + {id:'tll',name:'Tallinn',x:0,y:0,land:'eu',reg:'EU',cc:'EE',P:80,ix:'E-Stonia-IX',dc:'Medieval Wall DC',note:tr('cities.digital_everything_e_residency_for')}, + {id:'ist',name:'Istanbul',x:0,y:0,land:'eu',reg:'EU',cc:'TR',P:900,ix:'Baklava-IX',dc:'Bosphorus Bridge DC',note:tr('cities.one_foot_in_europe_one_in')}, + {id:'kyv',name:'Kyiv',x:0,y:0,land:'eu',reg:'EU',cc:'UA',P:500,blackout:true,ix:'Varenyky-IX',dc:'Generator-backed Bunker DC',note:tr('cities.ukrainian_network_engineers_kept_the')}, + {id:'jed',name:'Jeddah',x:0,y:0,land:'eu',reg:'AS',cc:'SA',P:300,saudi:true,gcc:true,ix:'',dc:'Red Sea Landing Palace',note:tr('cities.saudi_arabia_s_red_sea_cable')}, + {id:'ruh',name:'Riyadh',x:0,y:0,land:'eu',reg:'AS',cc:'SA',P:600,saudi:true,gcc:true,ix:'Kabsa-IX',dc:'Desert Megaproject DC',note:tr('cities.the_capital_building_ai_campuses_at')}, + {id:'doh',name:'Doha',x:0,y:0,land:'eu',reg:'AS',cc:'QA',P:150,arpu:1.5,qa:true,ix:'Pearl-IX',dc:'Air-cooled Stadium DC',note:tr('cities.small_rich_and_very_well_connected')}, + {id:'mil',name:'Milan',x:0,y:0,land:'eu',reg:'EU',cc:'IT',P:450,ix:'MIX-and-Match',dc:'Caldera Park Campus',note:tr('cities.italy_s_digital_capital_fashion_week')}, + {id:'rom',name:'Rome',x:0,y:0,land:'eu',reg:'EU',cc:'IT',P:450,ix:'Carbonara-IX',dc:'Colosseum-adjacent Colo',note:tr('cities.all_roads_lead_to_rome_most')}, + {id:'pmo',name:'Palermo',x:0,y:0,land:'eu',reg:'EU',cc:'IT',P:60,ix:'Cannoli-IX',dc:'Sicilian Hub-a-Dub',note:tr('cities.a_small_city_on_a_big')}, + {id:'lis',name:'Lisbon',x:0,y:0,land:'eu',reg:'EU',cc:'PT',P:300,ix:'Pastel-de-Nata-IX',dc:'Seven Hills Colo',note:tr('cities.europe_s_new_atlantic_gateway_cables')}, + {id:'ath',name:'Athens',x:0,y:0,land:'eu',reg:'EU',cc:'GR',P:350,ix:'Souvlaki-IX',dc:'Acropolis-view DC',note:tr('cities.ancient_city_brand_new_cables_greece')}, + {id:'atn',name:'Atlanta',x:0,y:0,land:'am',reg:'AM',cc:'US',P:450,ix:'Peach-IX',dc:'56 Marietta',note:tr('cities.the_southeast_s_carrier_hotel')}, + {id:'den',name:'Denver',x:0,y:0,land:'am',reg:'AM',cc:'US',P:250,ix:'Mile-High-IX',dc:'Thin Air DC',note:tr('cities.a_mile_up_and_halfway_between')}, + {id:'phx',name:'Phoenix',x:0,y:0,land:'am',reg:'AM',cc:'US',P:300,ix:'Cactus-IX',dc:'Dry Heat Campus',note:tr('cities.cheap_land_cheap_power_and_48')}, + {id:'bos',name:'Boston',x:0,y:0,land:'am',reg:'AM',cc:'US',P:350,ix:'Chowder-IX',dc:'One Summer Street',note:tr('cities.universities_biotech_and_a_carrier')}, + {id:'hou',name:'Houston',x:0,y:0,land:'am',reg:'AM',cc:'US',P:450,ix:'Rodeo-IX',dc:'Hurricane-hardened DC',note:tr('cities.oil_gas_and_hurricanes_the')}, + {id:'slc',name:'Salt Lake City',x:0,y:0,land:'am',reg:'AM',cc:'US',P:150,ix:'Fry-Sauce-IX',dc:'Great Salt Lake DC',note:tr('cities.cheap_power_dry_air_and_a')}, + {id:'man',name:'Manchester',x:0,y:0,land:'uk',reg:'EU',cc:'GB',P:350,ix:'Rainy-City-IX',dc:'Old Cotton Mill Colo',note:tr('cities.the_north_s_hub_with_its')}, + {id:'edi',name:'Edinburgh',x:0,y:0,land:'uk',reg:'EU',cc:'GB',P:200,ix:'Haggis-IX',dc:'Castle Rock Colo',note:tr('cities.scotland_s_capital_north_sea_cables')}, + {id:'bde',name:'Bude',x:0,y:0,land:'uk',reg:'EU',cc:'GB',P:3,ix:'',dc:'Clifftop Landing Station',note:tr('cities.a_tiny_surfing_town_in_cornwall')}, + {id:'svg',name:'Stavanger',x:0,y:0,land:'eu',reg:'EU',cc:'NO',P:60,ix:'Brunost-IX',dc:'Inside-a-Mountain DC',note:tr('cities.norway_s_oil_capital_now_full')}, + // The Caribbean (#125) + {id:'sju',name:'San Juan',x:0,y:0,land:'pr',reg:'AM',cc:'PR',P:120,ix:'Mofongo-IX',dc:'El Morro Colo',note:tr('cities.puerto_rico_s_capital_where_a')}, + {id:'sdq',name:'Santo Domingo',x:0,y:0,land:'hs',reg:'AM',cc:'DO',P:150,ix:'',dc:'Merengue Racks',note:tr('cities.the_dominican_republic_s_capital_the')}, + {id:'kin',name:'Kingston',x:0,y:0,land:'jm',reg:'AM',cc:'JM',P:60,ix:'Jerk-IX',dc:'Blue Mountain Colo',note:tr('cities.jamaica_s_capital_with_cables_to')}, + {id:'hav',name:'Havana',x:0,y:0,land:'cu',reg:'AM',cc:'CU',P:40,arpu:0.3,ix:'',dc:'1957 Chevy Server Room',note:tr('cities.cuba_s_only_cable_comes_from')}, + {id:'nas',name:'Nassau',x:0,y:0,land:'bs',reg:'AM',cc:'BS',P:20,ix:'',dc:'Conch Shell Colo',note:tr('cities.the_bahamas_capital_a_short_hop')}, + {id:'pos',name:'Port of Spain',x:0,y:0,land:'tt',reg:'AM',cc:'TT',P:40,ix:'Doubles-IX',dc:'Steelpan Server Hall',note:tr('cities.trinidad_s_capital_at_the_southern')}, + {id:'bgi',name:'Bridgetown',x:0,y:0,land:'bb',reg:'AM',cc:'BB',P:15,ix:'',dc:'Rum Shop Racks',note:tr('cities.barbados_sits_out_east_of_the')}, + {id:'fdf',name:'Fort-de-France',x:0,y:0,land:'mq',reg:'AM',cc:'MQ',P:18,ix:'',dc:'Pelée Shadow DC',note:tr('cities.martinique_a_corner_of_france_in')}, + {id:'cur',name:'Willemstad',x:0,y:0,land:'cw',reg:'AM',cc:'CW',P:10,ix:'Blue-Curaçao-IX',dc:'Pastel Waterfront DC',note:tr('cities.a_dutch_island_off_venezuela_that')}, + // The south-west Indian Ocean (#152) and Pitcairn (#124) + {id:'run',name:'Saint-Denis',x:0,y:0,land:'re',reg:'AF',cc:'RE',P:30,ix:'Rougail SAUCIX',dc:'Piton Colo',note:tr('cities.r_union_a_piece_of_france')}, + {id:'mru',name:'Port Louis',x:0,y:0,land:'mu',reg:'AF',cc:'MU',P:30,ix:'Dholl-Puri-IX',dc:'Dodo Data Centre',note:tr('cities.mauritius_an_island_of_banks_call')}, + {id:'tnr',name:'Antananarivo',x:0,y:0,land:'mg',reg:'AF',cc:'MG',P:80,arpu:0.3,blackout:true,ix:'Zebu-IX',dc:'Baobab Avenue DC',note:tr('cities.madagascar_s_capital_up_in_the')}, + {id:'sez',name:'Victoria',x:0,y:0,land:'sc',reg:'AF',cc:'SC',P:4,ix:'',dc:'Giant Tortoise Colo',note:tr('cities.the_seychelles_capital_on_mah')}, + {id:'pcn',name:'Adamstown',x:0,y:0,land:'pn',reg:'OC',cc:'PN',P:0.2,blackout:true,beach:true,ix:'',dc:'Bounty Bunker',note:tr('cities.pitcairn_island_about_forty_people')}, + // Alaska, northern British Columbia and Russia's Arctic and Pacific coasts (#145) + {id:'anc',name:'Anchorage',x:0,y:0,land:'am',reg:'AM',cc:'US',P:30,ix:'Mukluk-IX',dc:'Moose Crossing Colo',note:tr('cities.alaska_s_biggest_city_with_cables')}, + {id:'jnu',name:'Juneau',x:0,y:0,land:'aks',reg:'AM',cc:'US',P:3,ix:'',dc:'No Road In DC',note:tr('cities.alaska_s_capital_has_no_road')}, + {id:'ome',name:'Nome',x:0,y:0,land:'swd',reg:'AM',cc:'US',P:0.4,blackout:true,ix:'',dc:'Gold Rush Racks',note:tr('cities.a_gold_rush_town_on_the')}, + {id:'brw',name:'Utqiaġvik',x:0,y:0,land:'nsl',reg:'AM',cc:'US',P:0.5,blackout:true,ix:'',dc:'Top of the World Colo',note:tr('cities.the_northernmost_town_in_the_united')}, + {id:'dut',name:'Unalaska',x:0,y:0,land:'al',reg:'AM',cc:'US',P:0.5,ix:'',dc:'Deadliest Catch DC',note:tr('cities.the_aleutians_fishing_capital')}, + {id:'prr',name:'Prince Rupert',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,P:1.5,ix:'',dc:'Rain Gauge Racks',note:tr('cities.a_pacific_port_in_northern_british')}, + {id:'mmk',name:'Murmansk',x:0,y:0,land:'eu',reg:'EU',cc:'RU',P:25,ru:true,beach:true,arpu:0.5,ix:'',dc:'Polar Night DC',note:tr('cities.the_biggest_city_north_of_the')}, + {id:'dks',name:'Dikson',x:0,y:0,land:'tay',reg:'AS',cc:'RU',P:0.1,ru:true,beach:true,arpu:0.5,blackout:true,ix:'',dc:'Last Weather Station Rack',note:tr('cities.a_weather_station_and_a_port')}, + {id:'tik',name:'Tiksi',x:0,y:0,land:'lap',reg:'AS',cc:'RU',P:0.5,ru:true,beach:true,arpu:0.5,blackout:true,ix:'',dc:'Permafrost Colo',note:tr('cities.a_port_on_the_laptev_sea')}, + {id:'pvs',name:'Pevek',x:0,y:0,land:'pvk',reg:'AS',cc:'RU',P:0.5,ru:true,beach:true,arpu:0.5,ix:'',dc:'Floating Reactor Rack',note:tr('cities.russia_s_northernmost_town_powered_by')}, + {id:'dyr',name:'Anadyr',x:0,y:0,land:'chu',reg:'AS',cc:'RU',P:1.3,ru:true,arpu:0.5,ix:'',dc:'Date Line Colo',note:tr('cities.chukotka_s_capital_closer_to_alaska')}, + {id:'pkc',name:'Petropavlovsk',x:0,y:0,land:'kam',reg:'AS',cc:'RU',P:16,ru:true,arpu:0.5,ix:'',dc:'Volcano Row DC',note:tr('cities.kamchatka_s_capital_ringed_by_volcanoes')}, + {id:'gdx',name:'Magadan',x:0,y:0,land:'eu',reg:'AS',cc:'RU',P:9,ru:true,arpu:0.5,ix:'',dc:'Kolyma Highway Colo',note:tr('cities.a_port_on_the_sea_of')}, + {id:'uus',name:'Yuzhno-Sakhalinsk',x:0,y:0,land:'sak',reg:'AS',cc:'RU',P:18,ru:true,arpu:0.5,ix:'',dc:'Oil Platform Racks',note:tr('cities.sakhalin_s_capital_on_an_island')}, + {id:'vvo',name:'Vladivostok',x:0,y:0,land:'eu',reg:'AS',cc:'RU',P:60,ru:true,arpu:0.5,ix:'Ikra-IX',dc:'Golden Horn Colo',note:tr('cities.the_end_of_the_trans_siberian')}, + // More landings around the North Sea and the Baltic, the Gulf of Oman, the Maldives and Kyushu + {id:'krs',name:'Kristiansand',x:0,y:0,land:'eu',reg:'EU',cc:'NO',P:12,ix:'',dc:'Skagerrak Shore DC',note:tr('cities.norway_s_southern_tip_where_cables')}, + {id:'ebj',name:'Esbjerg',x:0,y:0,land:'eu',reg:'EU',cc:'DK',P:12,ix:'',dc:'Wind Farm Racks',note:tr('cities.denmark_s_west_coast_where_the')}, + {id:'rix',name:'Riga',x:0,y:0,land:'eu',reg:'EU',cc:'LV',P:60,ix:'Black-Balsam-IX',dc:'Art Nouveau DC',note:tr('cities.latvia_s_capital_its_cables_to')}, + {id:'mct',name:'Muscat',x:0,y:0,land:'eu',reg:'AS',cc:'OM',P:50,ix:'Halwa-IX',dc:'Frankincense Colo',note:tr('cities.oman_s_capital_just_outside_the')}, + {id:'mle',name:'Malé',x:0,y:0,land:'mv',reg:'AS',cc:'MV',P:4,ix:'',dc:'One-Metre-Up DC',note:tr('cities.the_maldives_capital_a_stop_on')}, + {id:'fuk',name:'Fukuoka',x:0,y:0,land:'jp',reg:'AS',cc:'JP',P:120,ix:'Mentaiko-IX',dc:'Hakata Ramen Racks',note:tr('cities.japan_s_closest_city_to_korea')}, + // The Philippines beyond Luzon + {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',cc:'PH',ph:true,arpu:PH_ARPU,P:125,ix:'GotchaFIX Cebu',ixCheap:1.8,dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, + {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',cc:'PH',ph:true,arpu:PH_ARPU,P:135,ix:'GotchaFIX Davao',ixCheap:1.8,dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, + {id:'phe',name:'Port Hedland',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,wet:true,arpu:AU_ARPU,P:2,ix:'',dc:'Next-Door-DC PH1',note:tr('cities.iron_ore_red_dust_and_two')}, + {id:'tsv',name:'Townsville',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,wet:true,arpu:AU_ARPU,P:20,ix:'',dc:'DigiCroc TSV1',note:tr('cities.north_queensland_s_capital_in_waiting')}, + {id:'asp',name:'Alice Springs',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:3,ix:'',dc:'Old Telegraph Station',note:tr('cities.the_middle_of_everywhere_no_sea')}, + // The United States: every state capital and Washington, DC + {id:'was',name:'Washington',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:120,ix:'Filibuster-IX',dc:'Capitol Hill Colo',note:tr('cities.the_capital_writes_the_rules_the')}, + {id:'mgm',name:'Montgomery',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:35,ix:'Sweet-Home-IX',dc:'Riverboat Racks'}, + {id:'lit',name:'Little Rock',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:65,ix:'Pebble-IX',dc:'Natural Stone Colo'}, + {id:'sac',name:'Sacramento',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:200,ix:'Sacra-Mental-IX',dc:'Gold Country Colo'}, + {id:'hfd',name:'Hartford',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:100,ix:'',dc:'Insurance Policy DC'}, + {id:'dov',name:'Dover',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:15,ix:'',dc:'First State Rack'}, + {id:'tlh',name:'Tallahassee',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:35,ix:'',dc:'Hurricane-Rated Hut'}, + {id:'boi',name:'Boise',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:70,ix:'Spud-IX',dc:'Blue Turf Colo'}, + {id:'spi',name:'Springfield',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:18,ix:'',dc:'Lincoln Logs Colo'}, + {id:'ind',name:'Indianapolis',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:190,ix:'Brickyard-IX',dc:'Pit Stop DC'}, + {id:'dsm',name:'Des Moines',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:60,ix:'Caucus-IX',dc:'Corn Maze Colo'}, + {id:'top',name:'Topeka',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:20,ix:'',dc:'Tornado Alley Rack'}, + {id:'fft',name:'Frankfort',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:6,ix:'',dc:'Bourbon Barrel Racks'}, + {id:'btr',name:'Baton Rouge',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:75,ix:'Bayou-IX',dc:'Crawfish Colo'}, + {id:'aug',name:'Augusta',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:10,ix:'',dc:'Lobster Trap DC'}, + {id:'anp',name:'Annapolis',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:30,ix:'',dc:'Naval Academy Annex'}, + {id:'lan',name:'Lansing',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:45,ix:'',dc:'Motor City Overflow'}, + {id:'stp',name:'Saint Paul',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:250,ix:'Hot-Dish-IX',dc:'Skyway Colo',note:tr('cities.twin_cities_one_exchange_and_skyways')}, + {id:'jan',name:'Jackson',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:50,ix:'',dc:'Magnolia Rack'}, + {id:'jef',name:'Jefferson City',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:12,ix:'',dc:'Show-Me Colo'}, + {id:'hln',name:'Helena',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:7,ix:'',dc:'Last Chance Gulch DC'}, + {id:'lnk',name:'Lincoln',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:30,ix:'',dc:'Cornhusker Colo'}, + {id:'csn',name:'Carson City',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:10,ix:'',dc:'Silver State Shed'}, + {id:'con',name:'Concord',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:15,ix:'',dc:'Live Free or Rack'}, + {id:'ttn',name:'Trenton',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:35,ix:'',dc:'Trenton Makes Colo'}, + {id:'saf',name:'Santa Fe',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:15,ix:'',dc:'Adobe Rack'}, + {id:'alb',name:'Albany',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:80,ix:'Upstate-IX',dc:'Empire State Plaza Colo'}, + {id:'rdu',name:'Raleigh',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:150,ix:'Tri-Angle-IX',dc:'Research Triangle Racks'}, + {id:'bis',name:'Bismarck',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:10,ix:'',dc:'Prairie Wind DC'}, + {id:'cmh',name:'Columbus',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:190,ix:'Buckeye-IX',dc:'Short North Colo'}, + {id:'okc',name:'Oklahoma City',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:125,ix:'Sooner-IX',dc:'Thunder Dome DC'}, + {id:'sle',name:'Salem',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:40,ix:'',dc:'Willamette Rack'}, + {id:'har',name:'Harrisburg',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:50,ix:'',dc:'Keystone Colo'}, + {id:'pvd',name:'Providence',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:150,ix:'',dc:'Coffee Milk Colo'}, + {id:'cae',name:'Columbia',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:75,ix:'',dc:'Famously Hot DC'}, + {id:'pir',name:'Pierre',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:2,ix:'',dc:'Missouri River Shack'}, + {id:'bna',name:'Nashville',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:180,ix:'Honky-Tonk-IX',dc:'Music Row Colo'}, + {id:'aus',name:'Austin',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:210,ix:'Keep-It-Weird-IX',dc:'Silicon Hills Colo'}, + {id:'mpv',name:'Montpelier',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:3,ix:'',dc:'Maple Syrup Rack'}, + {id:'ric',name:'Richmond',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:110,ix:'Rich-IX',dc:'Subsea Spur Colo',note:tr('cities.virginia_s_capital_where_the_transatlantic')}, + {id:'olm',name:'Olympia',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:25,ix:'',dc:"It's the Water Colo"}, + {id:'crw',name:'Charleston',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:20,ix:'Mountain-Mama-IX',dc:'Country Roads Colo'}, + {id:'msn',name:'Madison',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:60,ix:'Cheese-Curd-IX',dc:'Isthmus Colo'}, + {id:'cys',name:'Cheyenne',x:0,y:0,land:'am',reg:'AM',cc:'US',capital:true,P:8,ix:'',dc:'Big Sky Hyperscale Hangar',note:tr('cities.cheap_wind_cold_air_and_a')}, + // Canada: every provincial and territorial capital + {id:'yyj',name:'Victoria',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:35,ix:'',dc:'Garden City Colo',note:tr('cities.british_columbia_s_capital_across_the')}, + {id:'yeg',name:'Edmonton',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:140,ix:'YEG-Nog-IX',dc:'Mall of the Racks'}, + {id:'yqr',name:'Regina',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:22,ix:'',dc:'Roughrider Rack'}, + {id:'yxe',name:'Saskatoon',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,P:30,ix:'Saska-Toonie-IX',dc:'Bridge City Colo'}, + {id:'ywg',name:'Winnipeg',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:75,ix:'Slurpee-IX',dc:'Portage and Main Colo'}, + {id:'yqb',name:'Quebec City',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:75,ix:'Carnaval-IX',dc:'Old Town Walls DC'}, + {id:'yfc',name:'Fredericton',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:10,ix:'',dc:'Fiddlehead Rack'}, + {id:'yyg',name:'Charlottetown',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:8,ix:'Green-Gables-IX',dc:'Red Sand Rack'}, + {id:'yyt',name:"St. John's",x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:20,ix:'',dc:'Jellybean Row Colo',note:tr('cities.north_america_s_easternmost_city_on_the')}, + {id:'yxy',name:'Whitehorse',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:3,blackout:true,ix:'',dc:'Midnight Sun Colo',note:tr('cities.the_yukon_s_capital_on_one')}, + {id:'yzf',name:'Yellowknife',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,capital:true,P:2,blackout:true,ix:'',dc:'Ice Road Rack',note:tr('cities.the_northwest_territories_capital_at_the')}, + {id:'yfb',name:'Iqaluit',x:0,y:0,land:'baf',reg:'AM',cc:'CA',ca:true,capital:true,P:0.8,blackout:true,beach:true,ix:'',dc:'Satellite Dish Shed',note:tr('cities.nunavut_s_capital_has_no_fiber')}, + // Greenland: the capital and the towns on its cables + {id:'nuk',name:'Nuuk',x:0,y:0,land:'gln',reg:'AM',cc:'GL',capital:true,P:2,blackout:true,ix:'',dc:'Northern Lights Rack',note:tr('cities.greenland_s_capital_lands_the_cable')}, + {id:'qaq',name:'Qaqortoq',x:0,y:0,land:'glq',reg:'AM',cc:'GL',P:0.3,blackout:true,ix:'',dc:'Cable Landing Shed'}, + {id:'sis',name:'Sisimiut',x:0,y:0,land:'gls',reg:'AM',cc:'GL',P:0.5,blackout:true,ix:'',dc:'Dog Sled Depot'}, + {id:'aas',name:'Aasiaat',x:0,y:0,land:'gla',reg:'AM',cc:'GL',P:0.3,blackout:true,ix:'',dc:'Iceberg View Rack'}, + // Central America, the Caribbean and the Guianas: every capital (and Sucre, Bolivia's constitutional one) + {id:'anu',name:"Saint John's",x:0,y:0,land:'anu',reg:'AM',cc:'AG',capital:true,P:6,ix:'',dc:'Beach-a-Day Colo'}, + {id:'bas',name:'Basseterre',x:0,y:0,land:'kna',reg:'AM',cc:'KN',capital:true,P:3,ix:'Sugar-Train-IX',dc:'Sugar Mill Rack',note:tr('cities.four_cables_land_on_st_kitts')}, + {id:'dom',name:'Roseau',x:0,y:0,land:'dma',reg:'AM',cc:'DM',capital:true,P:3,ix:'Nature-Isle-IX',dc:'Boiling Lake DC'}, + {id:'slu',name:'Castries',x:0,y:0,land:'lca',reg:'AM',cc:'LC',capital:true,P:8,ix:'',dc:'Twin Pitons Colo'}, + {id:'svd',name:'Kingstown',x:0,y:0,land:'vct',reg:'AM',cc:'VC',capital:true,P:5,ix:'Vincy-IX',dc:'Grenadines Hop DC',note:tr('cities.a_cable_strings_the_grenadines_together')}, + {id:'gnd',name:"Saint George's",x:0,y:0,land:'grd',reg:'AM',cc:'GD',capital:true,P:6,ix:'Nutmeg-IX',dc:'Spice Isle Rack',note:tr('cities.grenada_s_exchange_has_a_dozen')}, + {id:'bcv',name:'Belmopan',x:0,y:0,land:'am',reg:'AM',cc:'BZ',capital:true,P:2,ix:'',dc:'Jungle Capital Colo',note:tr('cities.a_capital_built_inland_after_a')}, + {id:'sal',name:'San Salvador',x:0,y:0,land:'am',reg:'AM',cc:'SV',capital:true,P:70,ix:'',dc:'Pupusa Racks',note:tr('cities.san_salvador_has_an_exchange_and')}, + {id:'tgu',name:'Tegucigalpa',x:0,y:0,land:'am',reg:'AM',cc:'HN',capital:true,P:50,ix:'Baleada-IX',dc:'Hilltop Colo',note:tr('cities.the_capital_s_exchange_is_small')}, + {id:'mga',name:'Managua',x:0,y:0,land:'am',reg:'AM',cc:'NI',capital:true,P:45,ix:'',dc:'Lake & Volcano DC'}, + {id:'geo',name:'Georgetown',x:0,y:0,land:'sa',reg:'SA',cc:'GY',capital:true,P:12,ix:'',dc:'Stilt House Colo'}, + {id:'pbm',name:'Paramaribo',x:0,y:0,land:'sa',reg:'SA',cc:'SR',capital:true,P:12,ix:'Pom-IX',dc:'Wooden Cathedral Colo',note:tr('cities.suriname_s_first_cable_comes_ashore')}, + {id:'pap',name:'Port-au-Prince',x:0,y:0,land:'hs',reg:'AM',cc:'HT',capital:true,P:50,ix:'Kompa-IX',dc:'Gingerbread House DC'}, + {id:'sre',name:'Sucre',x:0,y:0,land:'sa',reg:'SA',cc:'BO',capital:true,P:10,ix:'',dc:'White City Colo',note:tr('cities.bolivia_s_constitutional_capital_the_courts')}, + // Europe: every capital not yet on the map (Vatican City is Rome's), and Bern + {id:'tia',name:'Tirana',x:0,y:0,land:'eu',reg:'EU',cc:'AL',capital:true,P:70,ix:'Byrek-IX',dc:'Bunker Colo',note:tr('cities.albania_s_exchange_is_run_by')}, + {id:'ala',name:'Andorra la Vella',x:0,y:0,land:'eu',reg:'EU',cc:'AD',capital:true,P:3,ix:'',dc:'Duty-Free Rack',note:tr('cities.andorra_brought_fibre_to_every_home')}, + {id:'msq',name:'Minsk',x:0,y:0,land:'eu',reg:'EU',cc:'BY',capital:true,P:140,ix:'Draniki-IX',dc:'Tractor Factory DC',note:tr('cities.belarus_sends_its_traffic_through_two')}, + {id:'sjj',name:'Sarajevo',x:0,y:0,land:'eu',reg:'EU',cc:'BA',capital:true,P:40,ix:'Ćevapi-IX',dc:'Old Bazaar Colo'}, + {id:'zag',name:'Zagreb',x:0,y:0,land:'eu',reg:'EU',cc:'HR',capital:true,P:90,ix:'Štrukli-IX',dc:'Funicular Racks'}, + {id:'nic',name:'Nicosia',x:0,y:0,land:'cyp',reg:'EU',cc:'CY',capital:true,P:30,ix:'Halloumi-IX',dc:'Green Line DC',note:tr('cities.a_divided_capital_the_south_s')}, + {id:'vdz',name:'Vaduz',x:0,y:0,land:'eu',reg:'EU',cc:'LI',capital:true,P:3,ix:'Postage-Stamp-IX',dc:'Royal Postage Rack'}, + {id:'vno',name:'Vilnius',x:0,y:0,land:'eu',reg:'EU',cc:'LT',capital:true,P:60,ix:'Cepelinai-IX',dc:'Užupis Republic Colo',note:tr('cities.four_exchanges_in_one_city_of')}, + {id:'mla',name:'Valletta',x:0,y:0,land:'mlt',reg:'EU',cc:'MT',capital:true,P:40,ix:'',dc:"Knights' Vault DC",note:tr('cities.each_of_malta_s_three_operators')}, + {id:'kiv',name:'Chișinău',x:0,y:0,land:'eu',reg:'EU',cc:'MD',capital:true,P:55,ix:'Plăcintă-IX',dc:'Wine Cellar Colo'}, + {id:'mco',name:'Monaco',x:0,y:0,land:'eu',reg:'EU',cc:'MC',capital:true,P:4,ix:'',dc:'Casino Vault DC',note:tr('cities.one_telco_for_the_whole_principality')}, + {id:'tgd',name:'Podgorica',x:0,y:0,land:'eu',reg:'EU',cc:'ME',capital:true,P:15,ix:'Black-Mountain-IX',dc:'Millennium Bridge Rack'}, + {id:'skp',name:'Skopje',x:0,y:0,land:'eu',reg:'EU',cc:'MK',capital:true,P:45,ix:'Ajvar-IX',dc:'Stone Bridge Colo'}, + {id:'smr',name:'San Marino',x:0,y:0,land:'eu',reg:'EU',cc:'SM',capital:true,P:3,ix:'',dc:'Three Towers DC'}, + {id:'bts',name:'Bratislava',x:0,y:0,land:'eu',reg:'EU',cc:'SK',capital:true,P:55,ix:'Bryndza-IX',dc:'UFO Bridge Colo',note:tr('cities.two_rival_exchanges_one_at_the')}, + {id:'lju',name:'Ljubljana',x:0,y:0,land:'eu',reg:'EU',cc:'SI',capital:true,P:45,ix:'Potica-IX',dc:'Dragon Bridge DC'}, + {id:'brn',name:'Bern',x:0,y:0,land:'eu',reg:'EU',cc:'CH',capital:true,P:35,ix:'',dc:'Bear Pit Colo',note:tr('cities.switzerland_s_federal_city_governs_from')}, + // The Middle East, the Caucasus and Central Asia: every capital, and Ankara and Islamabad + {id:'evn',name:'Yerevan',x:0,y:0,land:'eu',reg:'AS',cc:'AM',capital:true,P:70,ix:'Apricot-IX',dc:'Ararat View Colo',note:tr('cities.armenia_s_fibre_leaves_through_georgia')}, + {id:'gyd',name:'Baku',x:0,y:0,land:'eu',reg:'AS',cc:'AZ',capital:true,P:150,ix:'',dc:'Flame Towers DC',note:tr('cities.the_caspian_has_no_way_out')}, + {id:'tbs',name:'Tbilisi',x:0,y:0,land:'eu',reg:'AS',cc:'GE',capital:true,P:80,ix:'Khachapuri-IX',dc:'Sulfur Bath Racks',note:tr('cities.a_cable_under_the_black_sea')}, + {id:'nqz',name:'Astana',x:0,y:0,land:'eu',reg:'AS',cc:'KZ',capital:true,P:90,ix:'Beshbarmak-IX',dc:'Baiterek Tower Colo'}, + {id:'fru',name:'Bishkek',x:0,y:0,land:'eu',reg:'AS',cc:'KG',capital:true,P:50,ix:'Kumis-IX',dc:'Yurt Rack'}, + {id:'dyu',name:'Dushanbe',x:0,y:0,land:'eu',reg:'AS',cc:'TJ',capital:true,P:40,ix:'Pamir-IX',dc:'Monday Market DC'}, + {id:'asb',name:'Ashgabat',x:0,y:0,land:'eu',reg:'AS',cc:'TM',capital:true,P:25,ix:'',dc:'White Marble DC',note:tr('cities.nine_networks_for_the_whole_country')}, + {id:'tas',name:'Tashkent',x:0,y:0,land:'eu',reg:'AS',cc:'UZ',capital:true,P:150,ix:'Plov-IX',dc:'Silk Road Caravanserai',note:tr('cities.the_gateway_for_half_of_central')}, + {id:'kbl',name:'Kabul',x:0,y:0,land:'eu',reg:'AS',cc:'AF',capital:true,P:60,ix:'Kite-Runner-IX',dc:'Kite Hill Colo',note:tr('cities.afghanistan_buys_its_internet_from_four')}, + {id:'thr',name:'Tehran',x:0,y:0,land:'eu',reg:'AS',cc:'IR',capital:true,P:500,ix:'Saffron-IX',dc:'Bazaar Basement DC',note:tr('cities.every_big_iranian_operator_reaches_the')}, + {id:'bgw',name:'Baghdad',x:0,y:0,land:'eu',reg:'AS',cc:'IQ',capital:true,P:300,ix:'Masgouf-IX',dc:'House of Wisdom DC'}, + {id:'jer',name:'Jerusalem',x:0,y:0,land:'eu',reg:'AS',cc:'IL',capital:true,P:110,ix:'',dc:'Old City Wall Rack',note:tr('cities.israel_s_exchanges_and_data_centres')}, + {id:'amm',name:'Amman',x:0,y:0,land:'eu',reg:'AS',cc:'JO',capital:true,P:250,ix:'',dc:'Seven Hills Colo',note:tr('cities.jordan_s_only_exchange_is_in')}, + {id:'kwi',name:'Kuwait City',x:0,y:0,land:'eu',reg:'AS',cc:'KW',capital:true,P:250,ix:'Dhow-IX',dc:'Towers Colo'}, + {id:'bey',name:'Beirut',x:0,y:0,land:'eu',reg:'AS',cc:'LB',capital:true,P:150,ix:'Hummus-IX',dc:'Cedar Colo',note:tr('cities.both_mobile_networks_buy_from_the')}, + {id:'dam',name:'Damascus',x:0,y:0,land:'eu',reg:'AS',cc:'SY',capital:true,P:80,ix:'',dc:'Straight Street DC'}, + {id:'sah',name:'Sanaa',x:0,y:0,land:'eu',reg:'AS',cc:'YE',capital:true,P:40,ix:'',dc:'Mud Tower Rack',note:tr('cities.six_networks_and_one_gateway_for')}, + {id:'bah',name:'Manama',x:0,y:0,land:'bhr',reg:'AS',cc:'BH',capital:true,P:70,ix:'Pearl-IX',dc:'Pearl Diver DC',note:tr('cities.a_cloud_region_on_an_island')}, + {id:'esb',name:'Ankara',x:0,y:0,land:'eu',reg:'AS',cc:'TR',capital:true,P:350,ix:'Simit-IX',dc:'Mausoleum Hill Colo'}, + {id:'isb',name:'Islamabad',x:0,y:0,land:'eu',reg:'AS',cc:'PK',capital:true,P:150,ix:'',dc:'Margalla Hills DC'}, + // South, East and Southeast Asia and the Pacific: every capital, and Hanoi and Wellington + {id:'pbh',name:'Thimphu',x:0,y:0,land:'eu',reg:'AS',cc:'BT',capital:true,P:15,ix:'Ema-Datshi-IX',dc:'Dzong Colo',note:tr('cities.bhutan_peers_at_home_and_crosses')}, + {id:'ktm',name:'Kathmandu',x:0,y:0,land:'eu',reg:'AS',cc:'NP',capital:true,P:150,ix:'Momo-IX',dc:'Everest Base Rack',note:tr('cities.a_second_way_out_over_the')}, + {id:'bwn',name:'Bandar Seri Begawan',x:0,y:0,land:'brn',reg:'AS',cc:'BN',capital:true,P:25,ix:'Hornbill-IX',dc:'Water Village DC',note:tr('cities.one_state_company_owns_every_wire')}, + {id:'pnh',name:'Phnom Penh',x:0,y:0,land:'eu',reg:'AS',cc:'KH',capital:true,P:120,ix:'Amok-IX',dc:'Riverside Colo'}, + {id:'vte',name:'Vientiane',x:0,y:0,land:'eu',reg:'AS',cc:'LA',capital:true,P:50,ix:'',dc:'Patuxai Rack',note:tr('cities.no_exchange_so_lao_traffic_detours')}, + {id:'uln',name:'Ulaanbaatar',x:0,y:0,land:'eu',reg:'AS',cc:'MN',capital:true,P:60,ix:'Buuz-IX',dc:'Ger District DC',note:tr('cities.no_sea_three_exchanges_and_barely')}, + {id:'nyt',name:'Naypyidaw',x:0,y:0,land:'eu',reg:'AS',cc:'MM',capital:true,P:150,ix:'',dc:'Twenty-Lane Highway Colo',note:tr('cities.a_capital_built_from_scratch_with')}, + {id:'fnj',name:'Pyongyang',x:0,y:0,land:'eu',reg:'AS',cc:'KP',capital:true,P:0.3,ix:'',dc:'Ryugyong Hotel Rack',note:tr('cities.the_whole_country_is_one_network')}, + {id:'dil',name:'Dili',x:0,y:0,land:'tim',reg:'AS',cc:'TL',capital:true,P:15,ix:'',dc:'Cristo Rei Colo',note:tr('cities.timor_leste_s_first_cable_switched_on')}, + {id:'trw',name:'South Tarawa',x:0,y:0,land:'kir',reg:'OC',cc:'KI',capital:true,P:3,ix:'',dc:'Atoll Hut DC',note:tr('cities.tarawa_s_first_cable_came_in')}, + {id:'pni',name:'Palikir',x:0,y:0,land:'pnp',reg:'OC',cc:'FM',capital:true,P:2,ix:'',dc:'Nan Madol Rack'}, + {id:'inu',name:'Yaren',x:0,y:0,land:'nru',reg:'OC',cc:'NR',capital:true,P:0.5,ix:'',dc:'Phosphate Pit DC',note:tr('cities.twelve_thousand_people_and_their_first')}, + {id:'fun',name:'Funafuti',x:0,y:0,land:'tuv',reg:'OC',cc:'TV',capital:true,P:0.4,ix:'',dc:'Runway Rack',note:tr('cities.when_the_cable_arrived_the_whole')}, + {id:'vli',name:'Port Vila',x:0,y:0,land:'vut',reg:'OC',cc:'VU',capital:true,P:6,ix:'Kava-IX',dc:'Kava Bar Colo'}, + {id:'han',name:'Hanoi',x:0,y:0,land:'eu',reg:'AS',cc:'VN',capital:true,P:300,ix:'Bun-Cha-IX',dc:'Old Quarter Colo'}, + {id:'wlg',name:'Wellington',x:0,y:0,land:'nz',reg:'OC',cc:'NZ',capital:true,P:40,ix:'Windy-Welly-IX',dc:'Beehive Basement DC'}, + // Africa: every capital, and Yamoussoukro, Abuja, Yaoundé, Pretoria, Dodoma and Rabat + {id:'pto',name:'Porto-Novo',x:0,y:0,land:'af',reg:'AF',cc:'BJ',capital:true,P:50,ix:'',dc:'Lagoon Colo',note:tr('cities.the_capital_is_here_the_internet')}, + {id:'oua',name:'Ouagadougou',x:0,y:0,land:'af',reg:'AF',cc:'BF',capital:true,P:60,ix:'Riz-Gras-IX',dc:'Film Festival Vault'}, + {id:'bjl',name:'Banjul',x:0,y:0,land:'af',reg:'AF',cc:'GM',capital:true,P:20,ix:'Domoda-IX',dc:'Arch 22 Rack',note:tr('cities.one_cable_and_a_whole_country')}, + {id:'cky',name:'Conakry',x:0,y:0,land:'af',reg:'AF',cc:'GN',capital:true,P:50,ix:'Fonio-IX',dc:'Peninsula Colo'}, + {id:'oxb',name:'Bissau',x:0,y:0,land:'af',reg:'AF',cc:'GW',capital:true,P:8,ix:'',dc:'Cashew Shed DC'}, + {id:'rob',name:'Monrovia',x:0,y:0,land:'af',reg:'AF',cc:'LR',capital:true,P:20,ix:'',dc:'Ducor Hill Rack',note:tr('cities.the_whole_country_on_one_cable')}, + {id:'bko',name:'Bamako',x:0,y:0,land:'af',reg:'AF',cc:'ML',capital:true,P:60,ix:'Djenné-IX',dc:'Niger Riverbank DC'}, + {id:'nkc',name:'Nouakchott',x:0,y:0,land:'af',reg:'AF',cc:'MR',capital:true,P:25,ix:'',dc:'Sand Dune Colo',note:tr('cities.when_its_one_cable_was_cut')}, + {id:'nim',name:'Niamey',x:0,y:0,land:'af',reg:'AF',cc:'NE',capital:true,P:40,ix:'',dc:'Giraffe Crossing DC'}, + {id:'fna',name:'Freetown',x:0,y:0,land:'af',reg:'AF',cc:'SL',capital:true,P:30,ix:'Lion-Mountain-IX',dc:'Cotton Tree Colo'}, + {id:'lfw',name:'Lomé',x:0,y:0,land:'af',reg:'AF',cc:'TG',capital:true,P:40,ix:'Fufu-IX',dc:'Grand Marché Rack',note:tr('cities.the_first_african_stop_of_a')}, + {id:'ask',name:'Yamoussoukro',x:0,y:0,land:'af',reg:'AF',cc:'CI',capital:true,P:10,ix:'',dc:'Basilica Basement DC',note:tr('cities.a_capital_in_law_with_the')}, + {id:'abv',name:'Abuja',x:0,y:0,land:'af',reg:'AF',cc:'NG',capital:true,P:120,ix:'Suya-IX',dc:'Aso Rock Colo'}, + {id:'gid',name:'Gitega',x:0,y:0,land:'af',reg:'AF',cc:'BI',capital:true,P:25,ix:'',dc:'Drum Sanctuary Rack',note:tr('cities.the_government_moved_up_the_hill')}, + {id:'bgf',name:'Bangui',x:0,y:0,land:'af',reg:'AF',cc:'CF',capital:true,P:10,ix:'',dc:'Oubangui Riverside DC'}, + {id:'ndj',name:"N'Djamena",x:0,y:0,land:'af',reg:'AF',cc:'TD',capital:true,P:25,ix:'Boule-IX',dc:'Chari Bank Colo'}, + {id:'hah',name:'Moroni',x:0,y:0,land:'com',reg:'AF',cc:'KM',capital:true,P:6,ix:'',dc:'Volcano View Rack',note:tr('cities.wired_four_ways_for_under_a')}, + {id:'asm',name:'Asmara',x:0,y:0,land:'af',reg:'AF',cc:'ER',capital:true,P:5,ix:'',dc:'Art Deco Garage DC',note:tr('cities.one_network_for_the_whole_country')}, + {id:'qmn',name:'Mbabane',x:0,y:0,land:'af',reg:'AF',cc:'SZ',capital:true,P:12,ix:'',dc:'Ezulwini Colo'}, + {id:'lbv',name:'Libreville',x:0,y:0,land:'af',reg:'AF',cc:'GA',capital:true,P:25,ix:'Nyembwe-IX',dc:'Okoumé Rack',note:tr('cities.five_cables_land_on_one_beach')}, + {id:'msu',name:'Maseru',x:0,y:0,land:'af',reg:'AF',cc:'LS',capital:true,P:15,ix:'Basotho-Hat-IX',dc:'Mountain Kingdom DC'}, + {id:'tip',name:'Tripoli',x:0,y:0,land:'af',reg:'AF',cc:'LY',capital:true,P:70,ix:'',dc:'Red Castle Colo'}, + {id:'llw',name:'Lilongwe',x:0,y:0,land:'af',reg:'AF',cc:'MW',capital:true,P:40,ix:'Chambo-IX',dc:'Lake Malawi Rack'}, + {id:'tms',name:'São Tomé',x:0,y:0,land:'stp',reg:'AF',cc:'ST',capital:true,P:2,ix:'',dc:'Cocoa Plantation DC'}, + {id:'mgq',name:'Mogadishu',x:0,y:0,land:'af',reg:'AF',cc:'SO',capital:true,P:40,ix:'',dc:'Lido Beach Colo'}, + {id:'jub',name:'Juba',x:0,y:0,land:'af',reg:'AF',cc:'SS',capital:true,P:15,ix:'',dc:'Nile Junction DC',note:tr('cities.the_long_haul_to_johannesburg')}, + {id:'krt',name:'Khartoum',x:0,y:0,land:'af',reg:'AF',cc:'SD',capital:true,P:120,ix:'Ful-IX',dc:'Two Niles Colo'}, + {id:'ssg',name:'Malabo',x:0,y:0,land:'bio',reg:'AF',cc:'GQ',capital:true,P:10,ix:'',dc:'Cloud Forest DC',note:tr('cities.malabo_sits_on_an_island_the')}, + {id:'nsi',name:'Yaoundé',x:0,y:0,land:'af',reg:'AF',cc:'CM',capital:true,P:90,ix:'Ndolé-IX',dc:'Unity Palace Colo'}, + {id:'pry',name:'Pretoria',x:0,y:0,land:'af',reg:'AF',cc:'ZA',capital:true,P:150,ix:'',dc:'Jacaranda Colo'}, + {id:'dod',name:'Dodoma',x:0,y:0,land:'af',reg:'AF',cc:'TZ',capital:true,P:25,ix:'Ugali-IX',dc:'Baobab Rack',note:tr('cities.a_capital_in_law_inland_the')}, + {id:'rba',name:'Rabat',x:0,y:0,land:'af',reg:'AF',cc:'MA',capital:true,P:85,ix:'',dc:'Hassan Tower DC'}, + // Brazzaville, across the river from Kinshasa + {id:'bzv',name:'Brazzaville',x:0,y:0,land:'af',reg:'AF',cc:'CG',capital:true,P:40,ix:'Saka-Saka-IX',dc:'Corniche Colo'}, + // Sweden beyond Stockholm (#206): Gothenburg between Oslo and Copenhagen, Malmö across the Øresund, Haparanda on the land border with Finland + {id:'got',name:'Gothenburg',x:0,y:0,land:'eu',reg:'EU',cc:'SE',P:120,ix:'Feske-IX',dc:'Fish Church Colo',note:tr('cities.swedens_west_coast_where_the_fibre')}, + {id:'mmx',name:'Malmö',x:0,y:0,land:'eu',reg:'EU',cc:'SE',P:70,ix:'Haj-IX',dc:'Turning Torso Racks',note:tr('cities.across_the_oresund_from_copenhagen')}, + {id:'hpa',name:'Haparanda',x:0,y:0,land:'eu',reg:'EU',cc:'SE',P:5,ix:'',dc:'Border Twin Racks',note:tr('cities.on_the_finnish_border_twinned_with')}, +]; +// Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat. +const CITY_NUDGE={ + aas:[0.8,1.2], + aju:[-13.5,-2.7], + akl:[.6,.4], + ala:[-1.8,-1.8], + alg:[0.9,0.9], + anp:[-0.3,0.6], + asu:[-1.2,-0.8], + auh:[-5,6], + bah:[-0.15,-0.06], + bcn:[-6,-4], + bel:[0.4,0.4], + bey:[0.6,0], + bgw:[-15,0], + brn:[-3.5,2], + bru:[1,3], + bts:[4.5,-2.25], + bzv:[-1.5,-2.5], + cac:[2.4,-0.7], + cas:[0.6,0.6], + cau:[-10.2,2.4], + cph:[-.7,.3], + cpq:[-2.8,-5.2], + cpv:[-10.2,-5.1], + cxj:[5.4,-9.4], + dal:[0,-4], + dar:[0,12.6], + dur:[-0.2,0], + dxb:[9,-7], + fec:[-10.8,1.4], + fln:[0.8,4.4], + fuj:[1,2], + gdl:[-1.2,0.2], + gyn:[-4,2.6], + hel:[-.8,-.2], + hkg:[.8,0], + hou:[0,6], + igu:[-3.9,5.3], + ist:[.8,0], + jib:[0.1,0.2], + jpa:[-0.9,0.6], + khi:[-2,-6], + kwi:[-0.4,0.5], + ldb:[6.2,0.1], + lil:[-14,6], + lis:[.8,0], + ljd:[-5.2,-7.7], + mba:[-0.8,0], + mco:[-0.5,-0.4], + mcp:[-1.7,1.7], + mcz:[-7.2,8], + mde:[-1.7,-1.9], + mgf:[-5.8,-4.4], + mia:[-.6,.4], + mmx:[6,2], + mtl:[.8,0], + mvd:[2.2,-4.3], + nat:[-1.5,-3.3], + nuk:[-0.8,-0.9], + nyc:[.3,-.7], + oos:[-3,0], + osa:[-10,6], + ott:[-3,-3], + qaq:[0.4,0.1], + qro:[-1.9,-3.9], + rao:[3.6,-2.6], + rba:[9,-6], + rec:[-2.4,7.2], + ria:[-2.4,4.9], + rix:[-2,18], + rns:[-6,2], + sea:[1,4], + sin:[-1.3,-1.3], + sis:[0.3,-0.8], + sjp:[-3.5,0.4], + slz:[0.3,0.3], + ssa:[0.5,-0.2], + stg:[7,1], + tgd:[-0.8,-1.3], + tll:[4,10], + tls:[0,-6], + van:[-3,-6], + vie:[-4.5,2.25], + vix:[-0.4,0.4], + yqb:[0.3,0.2], + yyg:[-2,3.4], + zrh:[-3,3], +}; +for(const c of CITIES){const q=CITY_LL[c.id];if(q){c.lon=q[0];c.lat=q[1];const pt=proj(q[0],q[1]),n=CITY_NUDGE[c.id]||[0,0];c.x=pt[0]+n[0];c.y=pt[1]+n[1];}} +const CITY=Object.fromEntries(CITIES.map(c=>[c.id,c])),CIDX=Object.fromEntries(CITIES.map((c,i)=>[c.id,i])); diff --git a/src/game/20-world/55-city-pdb.js b/src/game/20-world/55-city-pdb.js new file mode 100644 index 0000000..9cd64bb --- /dev/null +++ b/src/game/20-world/55-city-pdb.js @@ -0,0 +1,420 @@ +/* Real-world calibration, pulled 2026-10-25 (Pacific islands 2026-10-26). Per city: [carrier-neutral facilities, network presences across them, + ASNs registered in its country]. Facilities and presences are PeeringDB facilities within 50 km or in the same city + (peeringdb.com/api/fac, net_count summed); ASNs per country are from bgp.he.net/report/world. + Cities PeeringDB barely knows (added 2026-10-28) are marked: est. is an estimate from what is known to be there, with + the country's ASN count. A city missing here keeps the plain regional price. One entry per line, sorted by id. */ +const CITY_PDB={ + aas:[0,0,2], // est. + abj:[5,11,32], + abv:[3,20,274], + acc:[7,78,124], + add:[2,3,10], + adl:[6,70,3196], // est. + aju:[4,3,9693], + akl:[27,398,755], + ala:[1,2,3], // est. + alb:[3,12,33300], // est. + alg:[0,0,16], + amm:[2,5,58], + ams:[69,2731,1827], + anc:[3,12,33300], // est. + anp:[0,0,33300], // est. + anu:[1,1,20], + apw:[0,0,11], + asb:[1,2,9], // est. + ash:[86,1010,33300], + ask:[0,0,142], // est. + asm:[0,0,1], // est. + asp:[0,0,3196], // est.: no carrier-neutral facility, the incumbent's exchange + asu:[3,8,124], + ath:[6,108,307], + atn:[42,589,33300], + aug:[0,0,33300], // est. + auh:[4,1,231], + aus:[9,55,33300], // est. + bah:[8,8,28], + bas:[0,3,9], // est. + bcn:[13,159,1341], + bcv:[0,1,38], // est. + bda:[2,8,25], // est. + bde:[0,0,4027], + beg:[7,49,227], + bel:[3,7,9693], + ber:[22,351,3705], + bet:[16,174,152], + bey:[2,1,191], + bgf:[0,0,5], // est. + bgi:[1,5,20], // est. + bgw:[3,2,222], + bhz:[13,40,9693], + bio:[1,8,1341], // pulled 2026-11-01: PeeringDB lists Telxius Derio DC alone (8 networks); ASNs are Spain's + bis:[0,0,33300], // est. + bjl:[1,1,12], + bkk:[32,397,675], + bko:[2,2,11], + blr:[14,104,6412], + bna:[7,35,33300], // est. + bne:[21,277,3196], + bod:[1,29,2249], + bog:[16,195,598], + boi:[3,12,33300], // est. + bom:[59,1050,6412], + bos:[31,209,33300], + brn:[7,29,1209], + bru:[33,328,443], + brw:[0,0,33300], // est. + bsb:[14,108,9693], + btr:[2,6,33300], // est. + bts:[4,97,199], + bud:[6,146,369], + bue:[28,372,1357], + buh:[23,289,1424], + bvb:[3,6,9693], + bwn:[3,2,11], + bzv:[1,4,9], // est. + cac:[4,6,9693], + cae:[2,5,33300], // est. + cai:[5,28,97], + cal:[15,127,2595], + cas:[2,2,39], + cau:[2,2,9693], + cbo:[1,0,33], + cbr:[5,60,3196], // est. + ccs:[6,32,296], + ceb:[4,25,750], // est. + cgb:[4,5,9693], + cgr:[4,4,9693], + chc:[4,30,755], // est. + chi:[64,809,33300], + cky:[1,5,20], + cmh:[9,50,33300], // est. + con:[0,0,33300], // est. + cor:[2,29,1357], + cph:[30,290,529], + cpq:[19,65,9693], + cpt:[6,267,879], + cpv:[4,12,9693], + crw:[1,3,33300], // est. + csn:[0,0,33300], // est. + cur:[3,20,25], // est. + cwb:[11,79,9693], + cxj:[2,3,9693], + cys:[1,2,33300], // est. + dac:[30,107,2105], + dal:[59,969,33300], + dam:[0,0,15], // est. + dar:[9,67,124], + del:[31,479,6412], + den:[28,310,33300], + dil:[1,0,21], // est. + dkr:[2,4,23], + dks:[0,0,6683], // est. + dla:[3,14,34], + dod:[1,4,90], + doh:[6,29,31], + dom:[0,2,8], // est. + dov:[0,0,33300], // est. + drw:[3,15,3196], + dsm:[3,10,33300], // est. + dub:[21,277,350], + dur:[4,137,879], + dus:[13,350,3705], // 14 listed, one closed; Digital Realty DUS1-3 alone has 141 networks + dut:[0,0,33300], // est. + dvo:[2,10,750], // est. + dxb:[8,135,231], + dyr:[0,0,6683], // est. + dyu:[1,3,45], + ebj:[1,5,529], // est. + edi:[4,46,4027], + esb:[8,24,1295], + evn:[7,6,161], + fdf:[1,5,10], // est. + fec:[5,4,9693], + fft:[0,0,33300], // est. + fih:[7,19,57], + fln:[5,23,9693], + fna:[2,10,22], + fnj:[0,0,1], // est. + for:[16,362,9693], + fra:[56,2450,3705], + fru:[2,3,78], + fuj:[1,49,231], + fuk:[5,50,1330], // QTnet QD3 has 14 networks, BBIX Fukuoka is there; the rest est. + fun:[1,0,3], // est. + gbe:[1,2,39], + gdl:[4,22,814], + gdx:[1,2,6683], // est. + geo:[0,2,8], // est. + gid:[0,0,9], // est. + gnd:[0,2,11], // est. + got:[8,45,1011], // est. + gua:[5,16,103], + gum:[6,28,11], + gyd:[7,15,131], + gyn:[5,28,9693], + hah:[0,0,4], // est. + ham:[26,228,3705], + han:[7,19,1029], + har:[2,6,33300], // est. + hav:[0,0,8], // est.: no neutral data center + hba:[2,10,3196], // est. + hel:[23,232,427], + hfd:[3,12,33300], // est. + hfx:[3,20,2595], // est. + hir:[1,0,11], + hkg:[57,1107,1514], + hln:[0,0,33300], // est. + hnl:[7,33,33300], + hou:[21,173,33300], + hpa:[0,2,1011], // est. + hre:[1,0,37], + hyd:[17,152,6412], + icn:[37,201,1197], + igu:[5,26,124], + ind:[8,45,33300], // est. + inu:[1,0,5], // est. + isb:[3,4,488], + ist:[28,334,1290], + ivc:[1,2,755], // est. + jam:[0,0,2], // est. + jan:[1,3,33300], // est. + jed:[5,25,220], + jef:[0,0,33300], // est. + jer:[2,10,454], // est. + jib:[3,19,5], + jkt:[98,3015,4108], + jnb:[14,561,879], + jnu:[1,2,33300], // est. + jpa:[4,18,9693], + jub:[1,0,23], + kbl:[1,5,84], // est. + kcy:[22,313,33300], + kgl:[5,14,34], + khi:[7,15,488], + kin:[2,10,30], // est. + kiv:[5,12,132], + kla:[2,18,71], + krs:[3,15,448], // est. + krt:[2,4,13], + ktm:[8,4,223], + kul:[20,210,434], + kwi:[3,2,91], + kyv:[33,506,2342], + lad:[8,27,79], + lag:[13,279,304], + lan:[1,3,33300], // est. + lax:[44,939,33300], + lbv:[4,11,12], + ldb:[3,7,9693], + lfw:[1,4,11], + lil:[4,24,2249], // pulled 2026-11-06, Tourcoing and Roubaix included + lim:[12,156,267], + lis:[9,129,187], + lit:[2,6,33300], // est. + ljd:[1,2,9693], + lju:[9,34,270], + llw:[0,5,36], // est. + lnk:[1,3,33300], // est. + lon:[100,2588,4027], + lpb:[1,2,71], + lun:[4,3,24], + lys:[1,84,2249], + maa:[20,374,6412], + mad:[31,578,1341], + maj:[0,0,12], + man:[29,353,4027], + mao:[7,15,9693], + mba:[4,176,274], + mco:[1,3,4], // est. + mcp:[2,0,9693], + mct:[3,25,45], // Equinix MC1 and WCS; presences est. + mcz:[1,5,9693], + mde:[2,18,598], + mel:[20,395,3196], + mex:[18,122,814], + mga:[1,2,35], // est. + mgf:[4,9,9693], + mgm:[1,4,33300], // est. + mgq:[1,0,24], + mia:[27,553,33300], + mil:[29,728,1534], + mla:[3,10,43], // est. + mle:[1,3,15], // est. + mmk:[2,4,6683], // est. + mmx:[4,18,1011], // est. + mnl:[17,352,750], + mos:[49,632,6683], + mpm:[7,20,36], + mpv:[0,0,33300], // est. + mrs:[8,273,2249], + mru:[3,20,60], // est. + msn:[3,15,33300], // est. + msq:[2,7,107], + msu:[0,3,11], // est. + mtl:[35,283,2595], + mty:[5,27,814], + muc:[22,230,3705], + mvd:[1,2,53], + nas:[1,4,20], // est. + nat:[1,3,9693], + nbo:[9,283,274], + ndj:[1,1,18], + nic:[1,3,139], + nim:[1,3,10], // est. + nkc:[1,3,10], // est. + nou:[2,2,19], + nqz:[2,3,284], + nsi:[3,6,61], + nte:[1,3,2249], // est. + nuk:[0,0,2], // est. + nyc:[96,1322,33300], + nyt:[0,0,173], // est. + okc:[4,18,33300], // est. + olm:[0,0,33300], // est. + ome:[0,0,33300], // est. + oos:[5,22,443], + osa:[19,229,1330], + osl:[20,209,448], + ott:[6,21,2595], + oua:[3,8,33], + oxb:[1,2,2], // est. + pan:[8,26,158], + pap:[0,3,14], // est. + par:[77,1528,2249], + pbh:[3,2,43], + pbm:[2,8,7], + pcn:[0,0,0], // est.: no network of its own + pdl:[1,3,187], // est. + pek:[10,15,6717], + per:[12,248,3196], + phe:[1,3,3196], // est.: one carrier-neutral facility + phx:[26,279,33300], + pir:[0,0,33300], // est. + pkc:[1,2,6683], // est. + pmo:[3,46,1534], + pmw:[3,8,9693], + pnh:[9,18,160], + pni:[1,0,6], // est. + poa:[22,120,9693], + pom:[2,0,46], + pos:[2,10,35], // est. + ppg:[0,0,2], + ppt:[0,0,6], + prg:[24,336,775], + prr:[0,0,2595], // est. + pry:[8,102,1600], + pto:[1,1,20], + pvd:[3,10,33300], // est. + pvh:[3,4,9693], + pvs:[0,0,6683], // est. + qaq:[0,0,2], // est. + qmn:[0,0,13], // est. + qro:[11,144,814], + rai:[1,3,8], // est. + rao:[6,3,9693], + rba:[2,2,98], + rbr:[0,0,9693], + rdu:[6,30,33300], // est. + rec:[6,31,9693], + rek:[15,51,93], + ria:[2,2,9693], + ric:[5,25,33300], // est. + rio:[33,577,9693], + rix:[8,60,330], // 8 listed, Perses 2 has 19 networks; presences est. + rns:[1,3,2249], // est. + rob:[1,2,18], + rom:[12,213,1534], + ror:[0,0,4], + ruh:[8,29,220], + run:[3,15,15], // est. + sac:[6,30,33300], // est. + saf:[0,0,33300], // est. + sah:[1,0,6], + sal:[1,2,56], // est. + sao:[70,1875,9693], + scl:[36,274,450], + sdq:[4,25,90], // est. + sea:[37,539,33300], + sez:[1,4,20], // est. + sgn:[6,36,1068], + sha:[11,27,6717], + sin:[58,1271,782], + sis:[0,0,2], // est. + sjc:[57,1048,33300], + sjj:[1,2,46], + sjo:[8,6,128], + sjp:[2,4,9693], + sju:[5,40,60], // est. + skp:[4,8,60], + slc:[22,202,33300], + sle:[1,2,33300], // est. + slu:[0,2,8], // est. + slz:[1,6,9693], + smr:[1,3,10], // est. + sof:[15,451,889], + spi:[1,2,33300], // est. + sre:[0,0,71], // est. + ssa:[13,44,9693], + ssg:[1,1,7], + stg:[18,63,3705], + sto:[31,539,1011], + stp:[10,90,33300], // est. + suv:[0,0,23], + svd:[0,2,6], // est. + svg:[2,14,448], + sxb:[2,54,2249], + syd:[40,979,3196], + tas:[7,3,140], + tbs:[4,15,185], + tbu:[0,0,5], + tci:[3,30,1341], // est. + tgd:[2,4,21], // est. + tgu:[1,4,126], // est. + the:[2,1,9693], + thr:[2,2,950], + tia:[6,22,124], + tik:[0,0,6683], // est. + tip:[0,0,34], // est. + tlh:[1,3,33300], // est. + tll:[7,80,256], + tls:[1,18,2249], + tms:[0,0,2], // est. + tnr:[1,4,25], // est. + tok:[58,917,1330], + top:[1,2,33300], // est. + tor:[46,509,2595], + tpe:[15,274,500], + trw:[1,0,6], // est. + tsv:[1,2,3196], // est. + ttn:[1,3,33300], // est. + tun:[2,0,30], + uio:[9,16,287], + uln:[3,20,82], // est. + uus:[1,3,6683], // est. + van:[13,214,2595], + vdz:[4,7,25], + vie:[30,377,860], + vix:[6,30,9693], + vli:[1,2,15], + vno:[11,52,190], + vte:[3,1,45], + vvo:[5,25,6683], // est. + was:[3,20,33300], // est. + waw:[25,855,2743], + wdh:[1,2,22], + wlg:[13,80,755], + yeg:[5,15,2595], + yfb:[0,0,2595], // est. + yfc:[0,0,2595], // est. + yqb:[1,6,2595], + yqr:[2,4,2595], + ywg:[8,48,2595], + yxe:[4,18,2595], + yxy:[0,0,2595], // est. + yyg:[1,1,2595], + yyj:[1,1,2595], + yyt:[0,0,2595], // est. + yzf:[0,0,2595], // est. + zag:[6,59,147], + zrh:[38,535,1209], +}; diff --git a/src/game/20-world/60-cables.js b/src/game/20-world/60-cables.js new file mode 100644 index 0000000..b0e1c33 --- /dev/null +++ b/src/game/20-world/60-cables.js @@ -0,0 +1,203 @@ +const CABLES=[ + {"id":"marea","name":"Marea Carey","price":0.8,"age":"new","blurb":tr('cables.hits_the_high_notes_across_the'),"pairs":[["ash","bio",[[-75.7,36.85],[-60,39.5],[-40,42.5],[-20.95,44.76],[-4.25,44],[-3.2,43.55]]]]}, + {"id":"grace","name":"Grace Hopscotch","price":0.85,"age":"new","blurb":tr('cables.hops_from_new_york_to_the'),"pairs":[["nyc","lon",[[-73.5,40.5],[-70.5,41],[-62.76,43.86],[-55,46],[-5,50],[-1,50],[-0.25,50.75]]],["nyc","bio",[[-70.5,41],[-62,44],[-53.28,45.88],[-43.34,47.11],[-33.84,47.46],[-21.48,46.73],[-4.25,44],[-3.2,43.55]]]]}, + {"id":"dunant","name":"Dunno-ant","price":0.85,"age":"new","blurb":tr('cables.nobody_remembers_who_it_is_named'),"pairs":[["ash","nte",[[-75.7,36.85],[-60,39.5],[-40,43],[-20,46.5],[-5,46.4],[-2.5,46.5]]]]}, + {"id":"amitie","name":"Ami-Tea","price":0.9,"age":"new","blurb":tr('cables.a_friendly_cable_with_french_manners'),"pairs":[["nyc","lon",[[-73.5,40.5],[-70.5,41],[-62.76,43.86],[-55,46],[-5,50],[-1,50],[-0.25,50.75]]],["nyc","bod",[[-70.5,41],[-61.91,43.92],[-53.25,46],[-20,46.5],[-5,45.2],[-1.6,44.8]]]]}, + {"id":"hibx","name":"Hibernia Express-o","price":1.7,"age":"mid","blurb":tr('cables.the_straightest_line_across_the'),"pairs":[["nyc","lon",[[-68,42],[-55,46.5],[-30,51.3],[-11,51.1],[-6.2,50.9],[-4.6,51.25],[-3.1,51.3]]],["nyc","hfx",[[-70.5,41],[-65.25,43]]],["hfx","lon",[[-60,45.5],[-55,46.5],[-30,51.3],[-11,51.1],[-6.2,50.9],[-4.6,51.25],[-3.1,51.3]]]],"lat":0.9}, + {"id":"tat","name":"TAT-14 Retirement Home","price":1.3,"age":"old","blurb":tr('cables.laid_last_century_cuts_often_costs'),"pairs":[["nyc","ams",[[-70.5,41],[-55,46],[-1,50]]]]}, + {"id":"ella","name":"EllaLink-ing","price":1.0,"age":"new","blurb":tr('cables.brazil_straight_to_iberia_skipping'),"pairs":[["for","mad",[[-37,-2.2],[-32,5],[-22,20],[-14,33],[-10,37.5]]],["sao","mad",[[-42.5,-24],[-38.75,-20.25],[-30,4],[-12.75,29.75],[-6.25,36],[-2.5,36],[0.75,38.75],[0.25,39.5]]],["for","lis",[[-37,-2.2],[-32,5],[-22,20],[-14,33],[-9.6,37.9]]],["for","rai",[[-37,-2.2],[-32,5],[-26,13]]],["rai","lis",[[-22,20],[-14,33],[-9.6,37.9]]]]}, + {"id":"sacs","name":"SACS-y Cable","price":1.0,"age":"mid","blurb":tr('cables.south_atlantic_cool_and_confident'),"pairs":[["for","lag",[[-36,-3],[-20,0],[0,3]]],["sao","lag",[[-46,-24],[-42,-24],[-30.51,-17.71],[-14.49,-7.05],[2,5]]],["for","lad",[[-37,-2.5],[-20,-5],[0,-8],[12.6,-9]]]]}, + {"id":"col3","name":"Columbus III-and-a-half","price":1.4,"age":"old","blurb":tr('cables.crossed_the_atlantic_again_old'),"pairs":[["mia","mad",[[-79.5,25.75],[-60,31],[-35,35.5],[-15,36.3],[-7.5,36.2],[-6.1,36.3]]],["mia","pdl",[[-79,26],[-60,30],[-35,36]]],["pdl","lis",[[-15,38.2]]]]}, + {"id":"twoaf","name":"2Africa-n-Back","price":0.75,"age":"new","blurb":tr('cables.all_the_way_around_africa_and'),"pairs":[["lon","lag",[[-0.25,50.75],[-1,50],[-4.5,49.25],[-9,44.27],[-12.48,39.05],[-16.49,31.46],[-17.75,28.75],[-18,14],[-17.5,12.75],[-13.75,8.25],[-8.75,4.25],[-2,4.25],[2.75,5.75]]],["jnb","mrs",[[32,-30],[32,-30],[32.34,-29.6],[32.67,-29.2],[33.01,-28.8],[33.34,-28.39],[33.67,-27.99],[33.99,-27.58],[34.32,-27.18],[34.64,-26.77],[34.96,-26.36],[35.27,-25.96],[35.59,-25.55],[35.9,-25.14],[36.21,-24.73],[36.52,-24.32],[36.82,-23.91],[37.13,-23.5],[37.43,-23.08],[37.73,-22.67],[38.03,-22.26],[38.33,-21.84],[38.62,-21.43],[38.92,-21.01],[39.21,-20.6],[39.5,-20.18],[39.79,-19.77],[40.07,-19.35],[40.36,-18.93],[40.65,-18.51],[40.93,-18.1],[41.21,-17.68],[41.49,-17.26],[41.77,-16.84],[42.05,-16.42],[42.32,-16],[42.6,-15.58],[42.87,-15.16],[43.15,-14.74],[43.42,-14.32],[43.69,-13.89],[43.96,-13.47],[44.23,-13.05],[44.5,-12.63],[44.77,-12.2],[45.03,-11.78],[45.3,-11.36],[45.56,-10.93],[45.83,-10.51],[46.09,-10.09],[46.35,-9.66],[46.62,-9.24],[46.88,-8.81],[47.14,-8.39],[47.4,-7.96],[47.66,-7.54],[47.92,-7.11],[48.18,-6.69],[48.43,-6.26],[48.69,-5.84],[48.95,-5.41],[49.21,-4.98],[49.46,-4.56],[49.72,-4.13],[49.98,-3.71],[50.23,-3.28],[50.49,-2.85],[50.74,-2.43],[51,-2],[51.03,-1.51],[51.05,-1.02],[51.08,-0.53],[51.11,-0.04],[51.13,0.46],[51.16,0.95],[51.19,1.44],[51.21,1.93],[51.24,2.42],[51.26,2.91],[51.29,3.4],[51.32,3.89],[51.34,4.38],[51.37,4.88],[51.4,5.37],[51.42,5.86],[51.45,6.35],[51.48,6.84],[51.5,7.33],[51.53,7.82],[51.56,8.31],[51.59,8.8],[51.61,9.29],[51.64,9.79],[51.67,10.28],[51.69,10.77],[51.72,11.26],[51.75,11.75],[51,12.5],[50.5,12.47],[50,12.44],[49.5,12.41],[49,12.38],[48.5,12.34],[48,12.31],[47.5,12.27],[47,12.24],[46.5,12.2],[46,12.16],[45.5,12.12],[45,12.08],[44.5,12.04],[44,12],[43.75,12.25],[43.5,12.5],[43.25,12.75],[43.25,13],[43.25,13.25],[43,13.5],[42.75,13.75],[42.5,14],[42.26,14.43],[42.02,14.86],[41.78,15.3],[41.54,15.73],[41.3,16.16],[41.05,16.59],[40.81,17.02],[40.56,17.45],[40.31,17.88],[40.06,18.31],[39.82,18.74],[39.56,19.17],[39.31,19.6],[39.06,20.03],[38.8,20.46],[38.55,20.88],[38.29,21.31],[38.03,21.74],[37.77,22.17],[37.51,22.59],[37.24,23.02],[36.98,23.44],[36.71,23.87],[36.44,24.29],[36.17,24.72],[35.89,25.14],[35.62,25.56],[35.34,25.99],[35.06,26.41],[34.78,26.83],[34.5,27.25],[34.25,27.5],[34,27.75],[33.75,28],[33.5,28.25],[33.25,28.5],[33,28.75],[33,29],[32.75,29.25],[32.5,29.5],[32.5,29.75],[32.5,30.5],[32.5,31.25],[32.25,31.5],[32,31.75],[31.6,32.11],[31.2,32.47],[30.8,32.83],[30.39,33.19],[29.98,33.55],[29.56,33.9],[29.14,34.25],[28.72,34.61],[28.3,34.96],[27.87,35.31],[27.44,35.65],[27,36],[26.43,36.01],[25.86,36.01],[25.29,36.02],[24.71,36.02],[24.14,36.01],[23.57,36.01],[23,36],[22,36],[21.42,36.02],[20.83,36.03],[20.25,36.04],[19.67,36.05],[19.08,36.05],[18.5,36.05],[17.92,36.05],[17.33,36.05],[16.75,36.04],[16.17,36.03],[15.58,36.02],[15,36],[14.07,36.36],[13.14,36.71],[12.21,37.07],[11.29,37.43],[10.36,37.79],[9.43,38.14],[8.5,38.5],[7.75,39.25],[7.54,39.66],[7.33,40.06],[7.11,40.47],[6.9,40.88],[6.68,41.28],[6.45,41.69],[6.23,42.1],[6,42.5],[6,42.5]]],["mrs","bom",[[5.25,43.25],[5.25,43],[5.25,42.75],[5.58,42.32],[5.9,41.88],[6.22,41.44],[6.53,41.01],[6.84,40.57],[7.15,40.13],[7.45,39.69],[7.75,39.25],[8.5,38.5],[9.43,38.14],[10.36,37.79],[11.29,37.43],[12.21,37.07],[13.14,36.71],[14.07,36.36],[15,36],[15.58,36.02],[16.17,36.03],[16.75,36.04],[17.33,36.05],[17.92,36.05],[18.5,36.05],[19.08,36.05],[19.67,36.05],[20.25,36.04],[20.83,36.03],[21.42,36.02],[22,36],[23,36],[23.57,36.01],[24.14,36.01],[24.71,36.02],[25.29,36.02],[25.86,36.01],[26.43,36.01],[27,36],[27.44,35.65],[27.87,35.31],[28.3,34.96],[28.72,34.61],[29.14,34.25],[29.56,33.9],[29.98,33.55],[30.39,33.19],[30.8,32.83],[31.2,32.47],[31.6,32.11],[32,31.75],[32.25,31.5],[32.5,31.25],[32.5,30.5],[32.5,29.75],[32.5,29.5],[32.75,29.25],[33,29],[33,28.75],[33.25,28.5],[33.5,28.25],[33.75,28],[34,27.75],[34.25,27.5],[34.5,27.25],[34.78,26.83],[35.06,26.41],[35.34,25.99],[35.62,25.56],[35.89,25.14],[36.17,24.72],[36.44,24.29],[36.71,23.87],[36.98,23.44],[37.24,23.02],[37.51,22.59],[37.77,22.17],[38.03,21.74],[38.29,21.31],[38.55,20.88],[38.8,20.46],[39.06,20.03],[39.31,19.6],[39.56,19.17],[39.82,18.74],[40.06,18.31],[40.31,17.88],[40.56,17.45],[40.81,17.02],[41.05,16.59],[41.3,16.16],[41.54,15.73],[41.78,15.3],[42.02,14.86],[42.26,14.43],[42.5,14],[42.75,13.75],[43,13.5],[43.25,13.25],[43.25,13],[43.25,12.75],[43.5,12.5],[43.75,12.25],[44,12],[44.5,12],[45.25,12.38],[46,12.75],[46.48,12.9],[46.97,13.04],[47.46,13.19],[47.94,13.33],[48.43,13.47],[48.92,13.61],[49.4,13.75],[49.89,13.89],[50.38,14.03],[50.87,14.17],[51.36,14.31],[51.85,14.44],[52.34,14.58],[52.84,14.71],[53.33,14.84],[53.82,14.97],[54.32,15.1],[54.81,15.23],[55.31,15.36],[55.8,15.49],[56.3,15.61],[56.8,15.74],[57.29,15.86],[57.79,15.98],[58.29,16.11],[58.79,16.23],[59.29,16.35],[59.79,16.46],[60.29,16.58],[60.79,16.7],[61.3,16.81],[61.8,16.92],[62.3,17.04],[62.81,17.15],[63.31,17.26],[63.82,17.36],[64.32,17.47],[64.83,17.58],[65.34,17.68],[65.85,17.78],[66.35,17.89],[66.86,17.99],[67.37,18.08],[67.88,18.18],[68.39,18.28],[68.91,18.37],[69.42,18.47],[69.93,18.56],[70.44,18.65],[70.96,18.74],[71.47,18.83],[71.98,18.91],[72.5,19],[72.75,19]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]],["abj","acc",[[-3,4],[0,5]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]],["lag","lad",[[3.2,5.8],[6,3],[9,3.6],[8,-2],[11.5,-6],[12.6,-9]]],["lad","cpt",[[12.5,-9.5],[11.25,-15.25],[12,-26]]],["cpt","dur",[[17.6,-34.4],[22,-35.5],[28,-34],[32,-30.3]]],["dur","mpm",[[32,-30.3],[34.5,-26]]],["mpm","dar",[[34.5,-26],[38,-20],[41.5,-14],[40.4,-7]]],["dar","mba",[[40.4,-7],[40.6,-4.3]]],["mba","jib",[[48.25,4],[51.5,9.5],[51.75,11.75],[51,12.5]]],["jib","cai",[[43.25,11.75],[44,12],[43,13],[43,13.5],[42.5,14],[39.06,20.03],[35.89,25.14],[34.5,27.25],[33,28.75],[33,29],[32.5,29.5],[32.5,29.75]]],["lon","tci",[[-1,50],[-4.75,49],[-6.49,47.39],[-15.4,36.87],[-16,36]]],["tci","lag",[[-18,25],[-20,20],[-18,8],[-5,3],[3,5.5]]],["doh","fuj",[[56.5,26.5]]],["fuj","mct",[[58.25,24.25]]],["mct","khi",[[58.75,24]]],["khi","bom",[[66.75,24],[70,20.75]]]]}, + {"id":"equi","name":"Equi-yes","price":0.8,"age":"new","blurb":tr('cables.always_agrees_with_you_iberia_to'),"pairs":[["lfw","lag",[[2.1,5.9],[3.3,6.1]]],["lag","cpt",[[4,3],[6,-5],[10,-20],[16,-33]]],["mad","lag",[[0.25,39.5],[0.75,38.75],[-2,36.25],[-6.25,36],[-17.5,24],[-18,14],[-13.75,8.25],[-8.75,4.25],[-2,4.25],[2.75,5.75]]],["lis","lag",[[-12.28,35.71],[-17.75,28.75],[-18,14],[-13.75,8.25],[-8.75,4.25],[-2,4.25],[2.75,5.75]]],["lag","wdh",[[12,-20.5],[14,-22.5]]],["wdh","cpt",[[13.5,-22.7],[15,-30],[17.6,-34.4]]],["lag","jam",[[4,3],[2,-5],[-3,-12]]],["jam","wdh",[[-2,-18],[8,-21.5],[13.5,-22.7]]]]}, + {"id":"smw6","name":"SEE-ME-WAVE 6","price":0.95,"age":"new","blurb":tr('cables.sixth_in_a_long_running_series'),"pairs":[["mrs","bom",[[5.25,43.25],[5.25,43],[5.25,42.75],[5.58,42.32],[5.9,41.88],[6.22,41.44],[6.53,41.01],[6.84,40.57],[7.15,40.13],[7.45,39.69],[7.75,39.25],[8.5,38.5],[9.43,38.14],[10.36,37.79],[11.29,37.43],[12.21,37.07],[13.14,36.71],[14.07,36.36],[15,36],[15.58,36.02],[16.17,36.03],[16.75,36.04],[17.33,36.05],[17.92,36.05],[18.5,36.05],[19.08,36.05],[19.67,36.05],[20.25,36.04],[20.83,36.03],[21.42,36.02],[22,36],[23,36],[23.57,36.01],[24.14,36.01],[24.71,36.02],[25.29,36.02],[25.86,36.01],[26.43,36.01],[27,36],[27.44,35.65],[27.87,35.31],[28.3,34.96],[28.72,34.61],[29.14,34.25],[29.56,33.9],[29.98,33.55],[30.39,33.19],[30.8,32.83],[31.2,32.47],[31.6,32.11],[32,31.75],[32.25,31.5],[32.5,31.25],[32.5,30.5],[32.5,29.75],[32.5,29.5],[32.75,29.25],[33,29],[33,28.75],[33.25,28.5],[33.5,28.25],[33.75,28],[34,27.75],[34.25,27.5],[34.5,27.25],[34.78,26.83],[35.06,26.41],[35.34,25.99],[35.62,25.56],[35.89,25.14],[36.17,24.72],[36.44,24.29],[36.71,23.87],[36.98,23.44],[37.24,23.02],[37.51,22.59],[37.77,22.17],[38.03,21.74],[38.29,21.31],[38.55,20.88],[38.8,20.46],[39.06,20.03],[39.31,19.6],[39.56,19.17],[39.82,18.74],[40.06,18.31],[40.31,17.88],[40.56,17.45],[40.81,17.02],[41.05,16.59],[41.3,16.16],[41.54,15.73],[41.78,15.3],[42.02,14.86],[42.26,14.43],[42.5,14],[42.75,13.75],[43,13.5],[43.25,13.25],[43.25,13],[43.25,12.75],[43.5,12.5],[43.75,12.25],[44,12],[44.5,12],[45.25,12.38],[46,12.75],[46.48,12.9],[46.97,13.04],[47.46,13.19],[47.94,13.33],[48.43,13.47],[48.92,13.61],[49.4,13.75],[49.89,13.89],[50.38,14.03],[50.87,14.17],[51.36,14.31],[51.85,14.44],[52.34,14.58],[52.84,14.71],[53.33,14.84],[53.82,14.97],[54.32,15.1],[54.81,15.23],[55.31,15.36],[55.8,15.49],[56.3,15.61],[56.8,15.74],[57.29,15.86],[57.79,15.98],[58.29,16.11],[58.79,16.23],[59.29,16.35],[59.79,16.46],[60.29,16.58],[60.79,16.7],[61.3,16.81],[61.8,16.92],[62.3,17.04],[62.81,17.15],[63.31,17.26],[63.82,17.36],[64.32,17.47],[64.83,17.58],[65.34,17.68],[65.85,17.78],[66.35,17.89],[66.86,17.99],[67.37,18.08],[67.88,18.18],[68.39,18.28],[68.91,18.37],[69.42,18.47],[69.93,18.56],[70.44,18.65],[70.96,18.74],[71.47,18.83],[71.98,18.91],[72.5,19],[72.75,19]]],["bom","sin",[[72.75,19],[72.5,19],[72.25,18.5],[72.38,18.04],[72.5,17.58],[72.63,17.13],[72.75,16.67],[72.88,16.21],[73,15.75],[73.21,15.3],[73.41,14.85],[73.61,14.4],[73.82,13.95],[74.02,13.5],[74.22,13.05],[74.42,12.6],[74.62,12.15],[74.82,11.7],[75.02,11.25],[75.21,10.8],[75.41,10.35],[75.61,9.9],[75.8,9.45],[76,9],[76.5,8.5],[77,8],[78,7],[78.36,6.75],[78.72,6.5],[79.07,6.25],[79.43,6],[79.79,5.75],[80.14,5.5],[80.5,5.25],[81,5.28],[81.5,5.31],[82,5.34],[82.5,5.37],[83,5.4],[83.5,5.43],[84,5.46],[84.5,5.49],[85,5.52],[85.5,5.55],[86,5.58],[86.5,5.6],[87,5.63],[87.5,5.66],[88,5.68],[88.5,5.71],[89,5.73],[89.5,5.76],[90,5.78],[90.5,5.81],[91,5.83],[91.5,5.85],[92,5.87],[92.5,5.9],[93,5.92],[93.5,5.94],[94,5.96],[94.5,5.98],[95,6],[95.83,6],[96.67,6],[97.5,6],[97.83,5.68],[98.15,5.35],[98.48,5.03],[98.8,4.7],[99.13,4.38],[99.45,4.05],[99.78,3.73],[100.1,3.4],[100.43,3.08],[100.75,2.75],[101,2.75],[101.25,2.75],[101.5,2.5],[101.75,2.25],[102,2],[102.25,1.75],[102.5,1.5],[102.75,1.25],[103,1.25],[103.25,1.25],[103.5,1.25],[103.75,1.25]]],["mrs","sin",[[5.25,43.25],[5.25,43],[5.25,42.75],[5.57,42.35],[5.88,41.96],[6.19,41.56],[6.49,41.16],[6.8,40.76],[7.09,40.36],[7.39,39.96],[7.68,39.56],[7.97,39.15],[8.25,38.75],[9,38.25],[9.59,38.06],[10.17,37.87],[10.76,37.68],[11.34,37.48],[11.91,37.28],[12.49,37.08],[13.06,36.88],[13.62,36.67],[14.19,36.46],[14.75,36.25],[15.34,36.15],[15.93,36.04],[16.52,35.93],[17.11,35.82],[17.7,35.71],[18.28,35.59],[18.87,35.47],[19.45,35.35],[20.03,35.23],[20.6,35.1],[21.18,34.97],[21.75,34.83],[22.33,34.7],[22.9,34.56],[23.47,34.42],[24.03,34.28],[24.6,34.13],[25.16,33.98],[25.72,33.83],[26.28,33.67],[26.83,33.52],[27.39,33.36],[27.94,33.2],[28.49,33.03],[29.04,32.87],[29.59,32.7],[30.13,32.53],[30.67,32.35],[31.21,32.18],[31.75,32],[32,31.75],[32.25,31.5],[32.5,31.25],[32.5,30.5],[32.5,29.75],[32.5,29.5],[32.75,29.25],[33,29],[33,28.75],[33.25,28.5],[33.5,28.25],[33.75,28],[34,27.75],[34.25,27.5],[34.5,27.25],[34.78,26.83],[35.06,26.41],[35.34,25.99],[35.62,25.56],[35.89,25.14],[36.17,24.72],[36.44,24.29],[36.71,23.87],[36.98,23.44],[37.24,23.02],[37.51,22.59],[37.77,22.17],[38.03,21.74],[38.29,21.31],[38.55,20.88],[38.8,20.46],[39.06,20.03],[39.31,19.6],[39.56,19.17],[39.82,18.74],[40.06,18.31],[40.31,17.88],[40.56,17.45],[40.81,17.02],[41.05,16.59],[41.3,16.16],[41.54,15.73],[41.78,15.3],[42.02,14.86],[42.26,14.43],[42.5,14],[42.75,13.75],[43,13.5],[43,13.25],[43,13],[44,12],[44.48,12.04],[44.97,12.08],[45.45,12.12],[45.93,12.15],[46.41,12.19],[46.9,12.22],[47.38,12.26],[47.86,12.29],[48.35,12.32],[48.83,12.35],[49.31,12.39],[49.8,12.42],[50.28,12.44],[50.77,12.47],[51.25,12.5],[51.74,12.4],[52.24,12.3],[52.73,12.21],[53.22,12.11],[53.72,12.01],[54.21,11.9],[54.7,11.8],[55.19,11.7],[55.68,11.59],[56.17,11.49],[56.66,11.38],[57.15,11.28],[57.64,11.17],[58.13,11.06],[58.62,10.95],[59.11,10.84],[59.6,10.73],[60.08,10.62],[60.57,10.51],[61.06,10.4],[61.54,10.28],[62.03,10.17],[62.52,10.06],[63,9.94],[63.49,9.82],[63.97,9.71],[64.46,9.59],[64.94,9.47],[65.42,9.35],[65.91,9.23],[66.39,9.11],[66.87,8.99],[67.36,8.87],[67.84,8.75],[68.32,8.62],[68.8,8.5],[69.28,8.38],[69.76,8.25],[70.24,8.13],[70.73,8],[71.21,7.88],[71.68,7.75],[72.16,7.62],[72.64,7.49],[73.12,7.37],[73.6,7.24],[74.08,7.11],[74.56,6.98],[75.04,6.85],[75.51,6.72],[75.99,6.59],[76.47,6.45],[76.94,6.32],[77.42,6.19],[77.9,6.06],[78.37,5.92],[78.85,5.79],[79.32,5.65],[79.8,5.52],[80.28,5.39],[80.75,5.25],[81.24,5.28],[81.73,5.31],[82.22,5.34],[82.71,5.37],[83.2,5.4],[83.7,5.43],[84.19,5.46],[84.68,5.49],[85.17,5.52],[85.66,5.55],[86.15,5.58],[86.64,5.6],[87.13,5.63],[87.62,5.66],[88.12,5.68],[88.61,5.71],[89.1,5.73],[89.59,5.76],[90.08,5.78],[90.57,5.8],[91.07,5.83],[91.56,5.85],[92.05,5.87],[92.54,5.9],[93.03,5.92],[93.52,5.94],[94.02,5.96],[94.51,5.98],[95,6],[95.83,6],[96.67,6],[97.5,6],[97.83,5.68],[98.15,5.35],[98.48,5.03],[98.8,4.7],[99.13,4.38],[99.45,4.05],[99.78,3.73],[100.1,3.4],[100.43,3.08],[100.75,2.75],[101,2.75],[101.25,2.75],[101.5,2.5],[101.75,2.25],[102,2],[102.25,1.75],[102.5,1.5],[102.75,1.25],[103,1.25],[103.25,1.25],[103.5,1.25],[103.75,1.25]]],["mrs","cai",[[5.25,43.25],[5.25,43],[5.25,42.75],[5.58,42.32],[5.9,41.88],[6.22,41.44],[6.53,41.01],[6.84,40.57],[7.15,40.13],[7.45,39.69],[7.75,39.25],[8.75,38.25],[9.74,37.93],[10.73,37.61],[11.71,37.29],[12.7,36.96],[13.69,36.64],[14.68,36.32],[15.67,36],[16.65,35.68],[17.64,35.36],[18.63,35.04],[19.62,34.71],[20.61,34.39],[21.6,34.07],[22.58,33.75],[23.57,33.43],[24.56,33.11],[25.55,32.79],[26.54,32.46],[27.52,32.14],[28.51,31.82],[29.5,31.5],[29.75,31.25],[30.5,30.65]]],["cai","jed",[[32.5,29.75],[33,28.75]]],["jed","jib",[[38.75,21],[43,13],[44,12]]],["jib","khi",[[43.25,11.75],[43.5,11.75],[43.97,11.91],[44.45,12.08],[44.92,12.24],[45.4,12.4],[45.88,12.56],[46.35,12.72],[46.83,12.88],[47.31,13.03],[47.79,13.19],[48.27,13.35],[48.75,13.5],[49.21,13.72],[49.67,13.93],[50.14,14.15],[50.6,14.36],[51.07,14.58],[51.53,14.79],[52,15],[52.43,15.22],[52.85,15.43],[53.28,15.65],[53.71,15.86],[54.14,16.08],[54.57,16.29],[55,16.5],[55.96,17.19],[56.92,17.88],[57.88,18.56],[58.83,19.25],[59.79,19.94],[60.75,20.63],[61.71,21.31],[62.67,22],[63.63,22.69],[64.58,23.38],[65.54,24.06],[66.5,24.75],[66.75,24.75]]],["khi","bom",[[66.75,24],[70,20.75]]],["bom","mle",[[72.75,19],[72.5,19],[72.25,18.5],[72.3,18.01],[72.34,17.52],[72.39,17.03],[72.43,16.53],[72.48,16.04],[72.52,15.55],[72.56,15.06],[72.61,14.57],[72.65,14.08],[72.7,13.59],[72.74,13.1],[72.78,12.6],[72.83,12.11],[72.87,11.62],[72.91,11.13],[72.95,10.64],[73,10.15],[73.04,9.66],[73.08,9.16],[73.12,8.67],[73.17,8.18],[73.21,7.69],[73.25,7.2],[73.29,6.71],[73.33,6.22],[73.38,5.72],[73.42,5.23],[73.46,4.74],[73.5,4.25]]],["mle","cbo",[[76.75,5.56]]],["cbo","maa",[[79,8],[79,9],[80.5,10.5],[80.75,13]]],["maa","dac",[[89.5,21.5]]],["dac","kul",[[91.5,22.75],[91.25,22],[93.75,16.5],[97.75,12.5],[97.75,8.25],[100.5,3.5]]],["kul","sin",[[102.75,1.25]]]]}, + {"id":"peace","name":"PEACE-out","price":0.85,"age":"new","blurb":tr('cables.marseille_to_singapore_then_it'),"pairs":[["mrs","mla",[[5.25,42.75],[8.6,38.3],[11.8,37.1],[13.9,36.0]]],["mla","nic",[[16,35],[25,34.2],[31.8,34.5],[32.5,34.75]]],["nic","cai",[[32.4,34.6],[31.6,32.4],[30.2,31.6]]],["mrs","sin",[[5.25,43.25],[5.25,43],[5.25,42.75],[5.57,42.35],[5.88,41.96],[6.19,41.56],[6.49,41.16],[6.8,40.76],[7.09,40.36],[7.39,39.96],[7.68,39.56],[7.97,39.15],[8.25,38.75],[9,38.25],[9.59,38.06],[10.17,37.87],[10.76,37.68],[11.34,37.48],[11.91,37.28],[12.49,37.08],[13.06,36.88],[13.62,36.67],[14.19,36.46],[14.75,36.25],[15.34,36.15],[15.93,36.04],[16.52,35.93],[17.11,35.82],[17.7,35.71],[18.28,35.59],[18.87,35.47],[19.45,35.35],[20.03,35.23],[20.6,35.1],[21.18,34.97],[21.75,34.83],[22.33,34.7],[22.9,34.56],[23.47,34.42],[24.03,34.28],[24.6,34.13],[25.16,33.98],[25.72,33.83],[26.28,33.67],[26.83,33.52],[27.39,33.36],[27.94,33.2],[28.49,33.03],[29.04,32.87],[29.59,32.7],[30.13,32.53],[30.67,32.35],[31.21,32.18],[31.75,32],[32,31.75],[32.25,31.5],[32.5,31.25],[32.5,30.5],[32.5,29.75],[32.5,29.5],[32.75,29.25],[33,29],[33,28.75],[33.25,28.5],[33.5,28.25],[33.75,28],[34,27.75],[34.25,27.5],[34.5,27.25],[34.78,26.83],[35.06,26.41],[35.34,25.99],[35.62,25.56],[35.89,25.14],[36.17,24.72],[36.44,24.29],[36.71,23.87],[36.98,23.44],[37.24,23.02],[37.51,22.59],[37.77,22.17],[38.03,21.74],[38.29,21.31],[38.55,20.88],[38.8,20.46],[39.06,20.03],[39.31,19.6],[39.56,19.17],[39.82,18.74],[40.06,18.31],[40.31,17.88],[40.56,17.45],[40.81,17.02],[41.05,16.59],[41.3,16.16],[41.54,15.73],[41.78,15.3],[42.02,14.86],[42.26,14.43],[42.5,14],[42.75,13.75],[43,13.5],[43,13.25],[43,13],[44,12],[44.48,12.04],[44.97,12.08],[45.45,12.12],[45.93,12.15],[46.41,12.19],[46.9,12.22],[47.38,12.26],[47.86,12.29],[48.35,12.32],[48.83,12.35],[49.31,12.39],[49.8,12.42],[50.28,12.44],[50.77,12.47],[51.25,12.5],[51.74,12.4],[52.24,12.3],[52.73,12.21],[53.22,12.11],[53.72,12.01],[54.21,11.9],[54.7,11.8],[55.19,11.7],[55.68,11.59],[56.17,11.49],[56.66,11.38],[57.15,11.28],[57.64,11.17],[58.13,11.06],[58.62,10.95],[59.11,10.84],[59.6,10.73],[60.08,10.62],[60.57,10.51],[61.06,10.4],[61.54,10.28],[62.03,10.17],[62.52,10.06],[63,9.94],[63.49,9.82],[63.97,9.71],[64.46,9.59],[64.94,9.47],[65.42,9.35],[65.91,9.23],[66.39,9.11],[66.87,8.99],[67.36,8.87],[67.84,8.75],[68.32,8.62],[68.8,8.5],[69.28,8.38],[69.76,8.25],[70.24,8.13],[70.73,8],[71.21,7.88],[71.68,7.75],[72.16,7.62],[72.64,7.49],[73.12,7.37],[73.6,7.24],[74.08,7.11],[74.56,6.98],[75.04,6.85],[75.51,6.72],[75.99,6.59],[76.47,6.45],[76.94,6.32],[77.42,6.19],[77.9,6.06],[78.37,5.92],[78.85,5.79],[79.32,5.65],[79.8,5.52],[80.28,5.39],[80.75,5.25],[81.24,5.28],[81.73,5.31],[82.22,5.34],[82.71,5.37],[83.2,5.4],[83.7,5.43],[84.19,5.46],[84.68,5.49],[85.17,5.52],[85.66,5.55],[86.15,5.58],[86.64,5.6],[87.13,5.63],[87.62,5.66],[88.12,5.68],[88.61,5.71],[89.1,5.73],[89.59,5.76],[90.08,5.78],[90.57,5.8],[91.07,5.83],[91.56,5.85],[92.05,5.87],[92.54,5.9],[93.03,5.92],[93.52,5.94],[94.02,5.96],[94.51,5.98],[95,6],[95.83,6],[96.67,6],[97.5,6],[97.83,5.68],[98.15,5.35],[98.48,5.03],[98.8,4.7],[99.13,4.38],[99.45,4.05],[99.78,3.73],[100.1,3.4],[100.43,3.08],[100.75,2.75],[101,2.75],[101.25,2.75],[101.5,2.5],[101.75,2.25],[102,2],[102.25,1.75],[102.5,1.5],[102.75,1.25],[103,1.25],[103.25,1.25],[103.5,1.25],[103.75,1.25]]],["mba","cai",[[40.25,-4],[48.25,4],[51.5,9.5],[51.75,11.75],[51,12.5],[44,12],[43,13],[43,13.5],[42.5,14],[38.29,21.31],[34.5,27.25],[33,28.75],[32.5,29.75]]],["sez","mba",[[52,-4.5],[45,-4],[40.6,-4.2]]],["khi","jib",[[66.75,24.75],[66.5,24.75],[65.54,24.06],[64.58,23.38],[63.63,22.69],[62.67,22],[61.71,21.31],[60.75,20.63],[59.79,19.94],[58.83,19.25],[57.88,18.56],[56.92,17.88],[55.96,17.19],[55,16.5],[54.57,16.29],[54.14,16.08],[53.71,15.86],[53.28,15.65],[52.85,15.43],[52.43,15.22],[52,15],[51.53,14.79],[51.07,14.58],[50.6,14.36],[50.14,14.15],[49.67,13.93],[49.21,13.72],[48.75,13.5],[48.27,13.35],[47.79,13.19],[47.31,13.03],[46.83,12.88],[46.35,12.72],[45.88,12.56],[45.4,12.4],[44.92,12.24],[44.45,12.08],[43.97,11.91],[43.5,11.75],[43.25,11.75]]],["mrs","tun",[[5.25,42.75],[8.25,38.75],[10,37.75]]]]}, + {"id":"aae","name":"AAAAAE-1","price":1.0,"age":"mid","blurb":tr('cables.asia_africa_europe_and_one_more'),"pairs":[["jib","sah",[[43.4,12.3],[44.6,12.6],[45,12.8]]],["khi","sin",[[66.75,24.75],[66.5,24.5],[68.76,21.1],[70.92,17.67],[73.25,13.78],[76,9],[78,7],[80.5,5.25],[92,5.87],[95,6],[97.5,6],[100.75,2.75],[101.25,2.75],[102.75,1.25],[103.75,1.25]]],["mrs","hkg",[[5.25,43.25],[5.25,43],[5.25,42.75],[5.58,42.32],[5.9,41.88],[6.22,41.44],[6.53,41.01],[6.84,40.57],[7.15,40.13],[7.45,39.69],[7.75,39.25],[8.5,38.5],[9.43,38.14],[10.36,37.79],[11.29,37.43],[12.21,37.07],[13.14,36.71],[14.07,36.36],[15,36],[15.58,36.02],[16.17,36.03],[16.75,36.04],[17.33,36.05],[17.92,36.05],[18.5,36.05],[19.08,36.05],[19.67,36.05],[20.25,36.04],[20.83,36.03],[21.42,36.02],[22,36],[23,36],[23.57,36.01],[24.14,36.01],[24.71,36.02],[25.29,36.02],[25.86,36.01],[26.43,36.01],[27,36],[27.44,35.65],[27.87,35.31],[28.3,34.96],[28.72,34.61],[29.14,34.25],[29.56,33.9],[29.98,33.55],[30.39,33.19],[30.8,32.83],[31.2,32.47],[31.6,32.11],[32,31.75],[32.25,31.5],[32.5,31.25],[32.5,30.5],[32.5,29.75],[32.5,29.5],[32.75,29.25],[33,29],[33,28.75],[33.25,28.5],[33.5,28.25],[33.75,28],[34,27.75],[34.25,27.5],[34.5,27.25],[34.78,26.83],[35.06,26.41],[35.34,25.99],[35.62,25.56],[35.89,25.14],[36.17,24.72],[36.44,24.29],[36.71,23.87],[36.98,23.44],[37.24,23.02],[37.51,22.59],[37.77,22.17],[38.03,21.74],[38.29,21.31],[38.55,20.88],[38.8,20.46],[39.06,20.03],[39.31,19.6],[39.56,19.17],[39.82,18.74],[40.06,18.31],[40.31,17.88],[40.56,17.45],[40.81,17.02],[41.05,16.59],[41.3,16.16],[41.54,15.73],[41.78,15.3],[42.02,14.86],[42.26,14.43],[42.5,14],[42.75,13.75],[43,13.5],[43.25,13.25],[43.25,13],[43.25,12.75],[43.5,12.5],[43.75,12.25],[44,12],[44.48,12.04],[44.96,12.08],[45.44,12.12],[45.93,12.16],[46.41,12.2],[46.89,12.23],[47.37,12.27],[47.85,12.31],[48.34,12.34],[48.82,12.37],[49.3,12.41],[49.78,12.44],[50.27,12.47],[50.75,12.5],[51.25,12.4],[51.75,12.31],[52.26,12.21],[52.76,12.11],[53.26,12.01],[53.76,11.91],[54.26,11.81],[54.76,11.7],[55.26,11.6],[55.76,11.5],[56.25,11.39],[56.75,11.28],[57.25,11.18],[57.75,11.07],[58.24,10.96],[58.74,10.85],[59.24,10.74],[59.73,10.63],[60.23,10.52],[60.72,10.41],[61.22,10.29],[61.71,10.18],[62.21,10.07],[62.7,9.95],[63.19,9.83],[63.69,9.72],[64.18,9.6],[64.67,9.48],[65.16,9.36],[65.66,9.24],[66.15,9.12],[66.64,9],[67.13,8.88],[67.62,8.76],[68.11,8.63],[68.6,8.51],[69.09,8.39],[69.58,8.26],[70.07,8.14],[70.56,8.01],[71.04,7.88],[71.53,7.76],[72.02,7.63],[72.51,7.5],[72.99,7.37],[73.48,7.24],[73.97,7.11],[74.45,6.98],[74.94,6.85],[75.42,6.72],[75.91,6.59],[76.39,6.46],[76.88,6.33],[77.36,6.19],[77.85,6.06],[78.33,5.93],[78.82,5.79],[79.3,5.66],[79.78,5.52],[80.27,5.39],[80.75,5.25],[81.75,6],[82.72,6],[83.69,6],[84.66,6],[85.63,6],[86.59,6],[87.56,6],[88.53,6],[89.5,6],[90.47,6],[91.44,6],[92.41,6],[93.38,6],[94.34,6],[95.31,6],[96.28,6],[97.25,6],[97.6,5.68],[97.95,5.35],[98.3,5.03],[98.65,4.7],[99,4.38],[99.35,4.05],[99.7,3.73],[100.05,3.4],[100.4,3.08],[100.75,2.75],[101,2.5],[101.25,2.5],[101.5,2.5],[101.75,2.25],[102,2],[102.25,1.75],[102.5,1.5],[103.25,1],[103.5,0.75],[103.75,0.75],[104.75,1.75],[104.97,2.19],[105.2,2.64],[105.42,3.08],[105.65,3.53],[105.87,3.97],[106.1,4.41],[106.32,4.86],[106.55,5.3],[106.77,5.74],[107,6.19],[107.23,6.63],[107.45,7.07],[107.68,7.52],[107.91,7.96],[108.14,8.4],[108.36,8.85],[108.59,9.29],[108.82,9.73],[109.05,10.17],[109.29,10.62],[109.52,11.06],[109.75,11.5],[109.92,11.96],[110.08,12.42],[110.25,12.87],[110.42,13.33],[110.58,13.79],[110.75,14.25],[110.92,14.7],[111.09,15.16],[111.26,15.62],[111.44,16.07],[111.61,16.53],[111.78,16.99],[111.96,17.44],[112.13,17.9],[112.31,18.36],[112.48,18.81],[112.66,19.27],[112.84,19.72],[113.02,20.18],[113.2,20.64],[113.38,21.09],[113.57,21.55],[113.75,22],[114,22.25]]],["sin","hkg",[[104.5,1.5],[108,6],[111,12],[114,20],[114.2,22]]],["jib","cai",[[43.25,11.75],[44,12],[43,13],[43,13.5],[42.5,14],[39.06,20.03],[35.89,25.14],[34.5,27.25],[33,28.75],[33,29],[32.5,29.5],[32.5,29.75]]],["jed","jib",[[38.75,21],[43,13],[44,12]]],["jib","mct",[[43.25,11.75],[43.5,11.75],[43.97,11.91],[44.45,12.08],[44.92,12.24],[45.4,12.4],[45.88,12.56],[46.35,12.72],[46.83,12.88],[47.31,13.03],[47.79,13.19],[48.27,13.35],[48.75,13.5],[49.21,13.72],[49.67,13.93],[50.14,14.15],[50.6,14.36],[51.07,14.58],[51.53,14.79],[52,15],[52.43,15.22],[52.85,15.43],[53.28,15.65],[53.71,15.86],[54.14,16.08],[54.57,16.29],[55,16.5],[55.92,17.17],[56.83,17.83],[57.75,18.5],[58.5,19.25],[58.75,19.67],[58.99,20.08],[59.24,20.5],[59.49,20.92],[59.75,21.33],[60,21.75],[60,22],[60,23],[59,23.75],[58.75,23.75],[58.5,23.75]]],["mct","fuj",[[58.25,24.25]]],["fuj","doh",[[56.5,26.5]]],["mct","khi",[[58.75,24]]],["khi","bom",[[66.75,24],[70,20.75]]],["sin","sgn",[[104.75,1.75],[107,9]]],["sgn","hkg",[[108,10],[109.75,11.5]]]]}, + {"id":"apg","name":"A Pretty Gateway","price":0.9,"age":"mid","blurb":tr('cables.the_pretty_way_around_east_asia'),"pairs":[["tpe","tok",[[123,25.5],[130,29.5],[137,33.5]]],["hkg","tpe",[[116.5,21.8],[119.5,22.8]]],["sin","hkg",[[105,2],[109,7],[112,13],[114.6,20],[114.4,22]]],["hkg","tok",[[116.5,22.25],[127,30],[130.75,30.5],[139,34.5]]],["hkg","icn",[[116,22],[122,26],[125,32],[126,35],[126.2,36.8]]],["tok","icn",[[139,34.5],[130.5,30.5],[125.75,34.5],[125.75,36.5]]],["tok","sha",[[139,34.5],[130.75,30.5]]],["sin","kul",[[102.75,1.25]]],["kul","hkg",[[101.75,2.5],[102.5,1.5],[103.5,0.75],[103.75,0.75],[104.75,1.75],[109.75,11.5],[113.75,22]]]]}, + {"id":"jup","name":"Jupiterrible","price":0.9,"age":"new","blurb":tr('cables.named_after_a_planet_behaves_like'),"pairs":[["lax","osa",[[-119,33.5],[-130.53,36.65],[-142.21,38.54],[-152.39,39.2],[-162,39],[-172.16,40.43],[-182.61,40.95],[-193.72,40.45],[-204.5,38.92],[-215.28,36.28],[-224.25,33],[-225,33.5]]],["lax","tok",[[-119,33.5],[-130.53,36.65],[-142.21,38.54],[-152.39,39.2],[-162,39],[-171.51,40.37],[-181.29,40.93],[-198.22,39.95],[-209.99,37.72],[-219.5,34.75],[-220.25,35]]],["tok","mnl",[[139,34.5],[128.03,26.23],[119.5,18],[119.25,15.25],[120,14.25]]]]}, + {"id":"fast","name":"FASTEST","price":0.85,"age":"mid","blurb":tr('cables.its_predecessor_was_faster_marketing'),"pairs":[["sea","tok",[[-122.75,48.25],[-125.75,48.5],[-134.32,50.63],[-145.95,52.33],[-158.17,52.81],[-171.1,51.94],[-181.73,50.08],[-196.99,46.06],[-208.93,41.09],[-219.5,34.75],[-220.25,35]]],["tok","tpe",[[139,34],[130.37,30.02]]],["sea","osa",[[-122.75,48.25],[-124,48.25],[-124.25,48.5],[-125.75,48.5],[-135.24,50.17],[-142.9,50.9],[-153.85,51.06],[-164.63,50.2],[-172,49],[-224,33],[-224.5,33],[-225,33.5],[-225,34.25]]]]}, + {"id":"ncp","name":"Crosspatch Pacific","price":1.0,"age":"mid","blurb":tr('cables.crosses_the_pacific_mildly_annoyed'),"pairs":[["sea","tpe",[[-125,46],[-155,45],[-185,38],[-212,28],[-235,25.6]]],["sea","icn",[[-122.75,48.25],[-124,48.25],[-124.25,48.5],[-125.75,48.5],[-135.32,49.97],[-142.99,50.55],[-149.99,50.62],[-217.5,46],[-217.75,45.75],[-218.5,45.75],[-231,34.5],[-233,34],[-234,34],[-234.25,34.5],[-234.25,36.5]]],["sea","sha",[[-125,46.2],[-155,45.5],[-185,40],[-212,31],[-236,30.5]]],["sea","tok",[[-122.75,48.25],[-125.75,48.5],[-134.32,50.63],[-145.95,52.33],[-158.17,52.81],[-171.1,51.94],[-181.73,50.08],[-196.99,46.06],[-208.93,41.09],[-219.5,34.75],[-220.25,35]]]]}, + {"id":"plcn","name":"Pacific Lite","price":1.1,"age":"mid","blurb":tr('cables.lighter_on_paperwork_than_its'),"pairs":[["lax","tpe",[[-121,33],[-150,25],[-180,22],[-215,22],[-236,24]]],["lax","hkg",[[-121,33],[-150,25],[-180,22],[-215,21],[-240,21.5]]],["lax","mnl",[[-119,33.5],[-130.53,36.65],[-142.21,38.54],[-152.39,39.2],[-162,39],[-170.86,40.3],[-179.98,40.91],[-180.64,40.92],[-190.47,40.71],[-200.12,39.67],[-209.99,37.72],[-219.25,35],[-240.25,18.25],[-240.5,15],[-240,14.25]]]]}, + {"id":"scx","name":"Southern Cross-ed Fingers","price":1.2,"age":"old","blurb":tr('cables.old_pacific_workhorse_everyone_hopes'),"pairs":[["sjc","syd",[[-123,37],[-150,20],[-175,0],[-190,-20],[-200,-30],[-207,-33.5]]],["akl","syd",[[168,-37],[158,-35]]],["sjc","hnl",[[-123,36.5],[-140,28],[-156.2,21.5]]],["hnl","suv",[[-158.5,19.5],[-168,6],[-176,-8],[-181.2,-17.5]]],["suv","syd",[[177.5,-19],[166,-25.5],[156,-32],[152,-33.8]]],["akl","suv",[[175.2,-35.5],[176.5,-27],[178.2,-19]]]]}, + {"id":"hwk","name":"Hawaiki-wiki","price":0.95,"age":"new","blurb":tr('cables.quick_pacific_crossing_with_a_stop'),"pairs":[["sea","syd",[[-122.75,48.25],[-125,48.5],[-184.97,-10.9],[-195,-20],[-196,-20],[-204.16,-29.84],[-208.25,-34]]],["akl","sea",[[178,-34],[190,-20],[210,10],[230,40],[234.5,47]]],["sea","hnl",[[-122.75,48.25],[-124,48.25],[-124.25,48.5],[-126,48.25]]],["hnl","syd",[[-158.5,20],[-172,0],[-185,-25],[-200,-32],[-206,-33.8]]],["hnl","akl",[[-158.5,20],[-174,-5],[-182,-28],[-185.1,-36]]],["hnl","ppg",[[-158.6,20.5],[-166,2],[-170.5,-13.8]]]]}, + {"id":"indigo","name":"Indi-Go-Down","price":0.9,"age":"new","blurb":tr('cables.singapore_to_sydney_via_perth_on'),"pairs":[["sin","syd",[[115.5,-7.5],[127,-7.75],[142.5,-10.25],[153.75,-26],[154.25,-29.25],[153,-32.75]]],["sin","per",[[115,-8],[113,-27],[115,-31.5]]],["per","syd",[[114.25,-34],[117.5,-37],[134.21,-39.13],[149,-39],[151.5,-36.5]]]]}, + {"id":"guam","name":"Guam-bling","price":1.1,"age":"mid","blurb":tr('cables.a_bet_on_a_tiny_island'),"pairs":[["tok","syd",[[139.75,34.5],[146.29,26.24],[153,16],[154.25,-30.75],[151.75,-34]]],["tok","gum",[[142.22,24.58]]],["gum","syd",[[148,4],[148,-7],[151,-10],[154.25,-29],[153,-32.75]]]]}, + {"id":"sushi","name":"Sushi Train Cable","price":1.15,"age":"old","blurb":tr('cables.sydney_to_tokyo_by_way_of'),"pairs":[["syd","tok",[[151.75,-34],[154.25,-30.75],[153,16],[146.29,26.24],[139.75,34.5]]]]}, + {"id":"aloha","name":"Aloha Mate","price":1.05,"age":"mid","blurb":tr('cables.sydney_to_honolulu_and_not_a'),"pairs":[["hnl","syd",[[-158.5,20],[-168,4],[-180,-15],[-197,-30],[-205.5,-33.6]]]]}, + {"id":"avo","name":"Cut Lunch Cable","price":0.9,"age":"new","fragile":true,"blurb":tr('cables.perth_to_singapore_and_jakarta'),"pairs":[["per","sin",[[115,-31.5],[113,-27],[115,-8]]],["per","jkt",[[114,-31.8],[110,-24],[106.5,-10],[106.8,-6.3]]]]}, + {"id":"ferry","name":"Ferry Express","price":1.0,"age":"mid","blurb":tr('cables.crosses_bass_strait_faster_than_the'),"pairs":[["mel","hba",[[144.5,-38.5],[145,-39],[148.75,-41],[149,-42.5],[148,-43.25]]]]}, + {"id":"smap","name":"SMAP (Somewhere, Maybe Also Perth)","price":0.95,"age":"new","blurb":tr('cables.sydney_melbourne_adelaide_and_perth'),"pairs":[["syd","mel",[[151.5,-36.5],[149,-39],[145.25,-39.25],[144.5,-38.5]]],["mel","adl",[[143.75,-39.25],[141,-39],[138,-35.75]]],["adl","per",[[137,-36],[132.14,-36.22],[115.75,-35.5],[114.25,-34]]]]}, + {"id":"ohman","name":"Oh-Man Australia Cable","price":1.0,"age":"new","blurb":tr('cables.perth_to_the_gulf_across_the'),"pairs":[["per","dxb",[[115.5,-31.75],[115,-31.75],[108.48,-26.87],[103.66,-22.77],[98.4,-17.81],[90.35,-9.4],[76.05,6.67],[70.26,12.96],[63.06,20.19],[60,23],[57.25,25.25],[57,25.75],[56.5,26.25],[56.5,26.5],[56,26.5],[55,25.5]]],["per","mct",[[108.88,-27.21],[99.48,-18.9],[68.8,14.4],[59.54,23.31],[58.75,24]]]]}, + {"id":"cook","name":"Cook Strait Talking","price":1.0,"age":"mid","blurb":tr('cables.down_the_west_coast_and_across'),"pairs":[["akl","chc",[[175.75,-36.25],[178,-37],[179,-38],[178.5,-39.25],[174.25,-43.5]]]]}, + {"id":"ring","name":"Lord of the Tasman Rings","price":0.9,"age":"new","blurb":tr('cables.one_ring_to_bind_invercargill_to'),"pairs":[["ivc","syd",[[167.6,-46.9],[160,-42],[153,-35]]],["ivc","mel",[[167.6,-46.9],[156,-43.5],[146.2,-39.4]]],["ivc","akl",[[169,-47.25],[170.5,-47.25],[178.5,-39.25],[179,-38],[178,-37],[175.75,-36.25]]]]}, + {"id":"tasman","name":"Tasman Global Excess","price":0.95,"age":"new","blurb":tr('cables.sydney_to_auckland_with_plenty_to'),"pairs":[["akl","syd",[[170,-36],[158,-34.5]]]]}, + {"id":"bifrost","name":"Bi-Frosted","price":0.9,"age":"new","blurb":tr('cables.a_rainbow_bridge_from_singapore_to'),"pairs":[["sin","jkt",[[107,-2]]],["gum","lax",[[145.5,14.2],[180,22],[210,30],[235,33.5]]],["jkt","gum",[[107.25,-5.25],[113,-5.25],[116,-4.25],[121,2],[139.42,11.57],[143.5,13.5]]],["jkt","dvo",[[107.25,-5.25],[113,-5.25],[116,-4.25],[121,2],[124.5,4.6],[125.5,5.3],[125.75,6.2],[125.7,6.8]]],["dvo","gum",[[125.75,6.4],[126.1,5.6],[127,5.8],[130,8],[139.42,11.57],[143.5,13.5]]],["gum","sea",[[149.93,19.74],[155.17,25.45],[160.51,30.59],[165.55,34.81],[170.63,38.48],[176.24,41.9],[181.86,44.75],[188.04,47.3],[190.71,48.15],[198.76,49.45],[205.61,50.09],[211.8,50.31],[218.01,50.21],[224.91,49.69],[234.5,48.25],[235.75,48.5],[236,48.25],[237.25,48.25]]]]}, + {"id":"sjcph","name":"Sushi-Jollibee Cable","price":0.9,"age":"mid","blurb":tr('cables.southeast_asia_to_japan_with_snacks'),"pairs":[["hkg","mnl",[[116,21],[119.5,16],[120.3,14.6]]],["mnl","sin",[[119,12],[115,8],[110,5],[105,2]]],["mnl","tok",[[120,14.25],[119.25,15.25],[119.5,18],[128.03,26.23],[139,34.5]]],["sin","hkg",[[104.75,1.75],[109.75,11.5]]],["hkg","tok",[[116.5,22.25],[127,30],[130.75,30.5],[139,34.5]]]]}, + {"id":"farice","name":"Far-Ice-1","price":1.2,"age":"old","blurb":tr('cables.iceland_s_lifeline_to_scotland'),"pairs":[["rek","lon",[[-23,64],[-22.25,63.25],[-20.25,63],[-7,63],[-1.63,57.93],[2,53],[1.75,51.75]]]]}, + {"id":"danice","name":"Dance-Ice","price":1.0,"age":"mid","blurb":tr('cables.iceland_to_denmark_choreographed'),"pairs":[["rek","cph",[[-23,64],[-22.25,63.25],[7,57.5],[10.5,57.75],[11,57.5],[10.5,55.25],[12,54.75]]]]}, + {"id":"gcon","name":"Greenland Connect-the-Dots","price":1.4,"age":"old","blurb":tr('cables.hops_via_greenland_polar_bears'),"pairs":[["rek","mtl",[[-23.5,63],[-33,61.5],[-43.5,59.2],[-50,53],[-50.5,47.5],[-55,46.2],[-59.8,47],[-63.5,49.7],[-66.5,49.6],[-68.6,48.8],[-70.3,47.6],[-71.2,46.85]]],["rek","qaq",[[-23.5,63],[-33,61.5],[-43.5,59.2],[-45.5,60.2]]],["qaq","nuk",[[-47,60.3],[-49.5,61.5],[-51,63],[-52,63.9]]],["nuk","yyt",[[-52.6,63.8],[-53,61],[-51,56],[-50,51],[-52,48.3]]]]}, + {"id":"gcn","name":"Connect-the-Dots North","price":1.3,"age":"new","blurb":tr('cables.greenland_s_west_coast_town_by'),"pairs":[["nuk","sis",[[-52.4,64.6],[-53.2,65.6],[-54,66.6]]],["sis","aas",[[-54.2,67.4],[-53.6,68.3]]]]}, + {"id":"iris","name":"IRIS Scan","price":0.9,"age":"new","blurb":tr('cables.iceland_to_ireland_brand_new_and'),"pairs":[["rek","dub",[[-23,64],[-22.25,63.25],[-14.21,60.08],[-6.5,55.75],[-5.25,54.5]]]]}, + {"id":"aec","name":"AEConnect-the-Dots","price":0.85,"age":"new","blurb":tr('cables.new_york_to_ireland_the_tech'),"pairs":[["nyc","dub",[[-73.5,40.5],[-70.5,41],[-70,41.5],[-61.5,44.5],[-60.25,45.25],[-9,51],[-6.75,51.5],[-6,52],[-6,53.25]]]]}, + {"id":"havf","name":"Havfun","price":0.8,"age":"new","blurb":tr('cables.danish_for_sea_fun_probably'),"pairs":[["nyc","cph",[[-71.5,40.75],[-53.25,46],[-46.48,49.83],[-38.62,53.21],[-21.96,57.57],[-4.25,59.25],[7,57.5],[10.5,57.75],[11,57.5],[10.5,55.25],[12,54.75]]],["dub","cph",[[-5.5,53.5],[-5.25,54.75],[-6.75,57.25],[-4.25,59.25],[7,57.5],[10.5,57.75],[11,57.5],[10.5,55.25],[12,54.75]]],["nyc","dub",[[-70.5,41],[-60.25,45.25],[-9,51],[-6,52]]],["nyc","ebj",[[-71.5,40.75],[-53.25,46],[-45,54],[-31.51,57.46],[-17.87,59.12],[-3.5,59.25]]],["ebj","krs",[[7.5,56]]]]}, + {"id":"celtix","name":"Celtix Connected","price":0.7,"age":"mid","blurb":tr('cables.dublin_to_london_across_the_irish'),"pairs":[["dub","lon",[[-5,53.4]]]]}, + {"id":"falcon","name":"Falcon Punch","price":0.9,"age":"mid","blurb":tr('cables.dubai_to_mumbai_hits_hard'),"pairs":[["doh","bah",[[51.7,26.2],[51,26.4]]],["bah","kwi",[[50.9,27.2],[49.2,28.5],[48.3,29.3]]],["cai","dxb",[[31.87,29.9],[32.5,29.75],[32.5,29.5],[32.75,29.25],[33,29],[33,28.75],[33.25,28.5],[33.5,28.25],[33.75,28],[34,27.75],[34.25,27.5],[34.5,27.25],[34.78,26.83],[35.06,26.41],[35.34,25.99],[35.62,25.56],[35.89,25.14],[36.17,24.72],[36.44,24.29],[36.71,23.87],[36.98,23.44],[37.24,23.02],[37.51,22.59],[37.77,22.17],[38.03,21.74],[38.29,21.31],[38.55,20.88],[38.8,20.46],[39.06,20.03],[39.31,19.6],[39.56,19.17],[39.82,18.74],[40.06,18.31],[40.31,17.88],[40.56,17.45],[40.81,17.02],[41.05,16.59],[41.3,16.16],[41.54,15.73],[41.78,15.3],[42.02,14.86],[42.26,14.43],[42.5,14],[42.75,13.75],[43,13.5],[43,13.25],[43,13],[44,12],[44.47,12.14],[44.94,12.28],[45.41,12.42],[45.88,12.56],[46.36,12.7],[46.83,12.84],[47.3,12.98],[47.78,13.11],[48.25,13.25],[48.66,13.45],[49.08,13.64],[49.49,13.84],[49.91,14.03],[50.33,14.23],[50.74,14.42],[51.16,14.62],[51.58,14.81],[52,15],[52.43,15.22],[52.85,15.43],[53.28,15.65],[53.71,15.86],[54.14,16.08],[54.57,16.29],[55,16.5],[55.92,17.17],[56.83,17.83],[57.75,18.5],[58.5,19.25],[58.75,19.67],[58.99,20.08],[59.24,20.5],[59.49,20.92],[59.75,21.33],[60,21.75],[60,22],[60,23],[59.63,23.32],[59.26,23.63],[58.89,23.94],[58.51,24.26],[58.14,24.57],[57.76,24.88],[57.38,25.19],[57,25.5],[57,25.75],[56.75,26],[56.5,26.25],[56.5,26.5],[56.25,26.5],[56,26.5],[55.25,25.75],[55.25,25.5],[55.25,25.25]]],["fuj","bom",[[58,24.8],[63,22.3],[70,19.2]]],["dxb","bom",[[57,25.5],[60,23],[66,21],[71,19]]]]}, + {"id":"eig","name":"Eye-Gee","price":1.0,"age":"mid","blurb":tr('cables.a_gateway_from_europe_to_india'),"pairs":[["mrs","tip",[[5.3,42.5],[8.6,38.4],[12.2,34.7],[13.2,33.1]]],["tip","cai",[[14.5,33.5],[22,33.2],[29.9,31.4]]],["dxb","mrs",[[55.25,25.25],[55,25.5],[56,26.5],[56.25,26.5],[56.5,26.5],[56.5,26.25],[56.75,26],[57,25.75],[57.25,25.25],[57.62,24.95],[57.98,24.64],[58.35,24.34],[58.71,24.04],[59.07,23.73],[59.43,23.42],[59.79,23.12],[60.15,22.81],[60.5,22.5],[60.24,22.11],[59.99,21.72],[59.74,21.34],[59.49,20.95],[59.24,20.56],[58.99,20.17],[58.74,19.78],[58.5,19.39],[58.25,19],[57.5,18.25],[57.08,17.96],[56.66,17.67],[56.24,17.38],[55.83,17.09],[55.41,16.79],[55,16.5],[54.55,16.28],[54.09,16.06],[53.64,15.83],[53.19,15.61],[52.74,15.39],[52.29,15.16],[51.84,14.93],[51.39,14.71],[50.95,14.48],[50.5,14.25],[49.5,13.88],[48.5,13.5],[47.5,13.13],[46.5,12.75],[45.5,12.38],[44.5,12],[44,12],[43.75,12.25],[43.5,12.5],[43.25,12.75],[43.25,13],[43.25,13.25],[43,13.5],[42.75,13.75],[42.5,14],[42.26,14.43],[42.02,14.86],[41.78,15.3],[41.54,15.73],[41.3,16.16],[41.05,16.59],[40.81,17.02],[40.56,17.45],[40.31,17.88],[40.06,18.31],[39.82,18.74],[39.56,19.17],[39.31,19.6],[39.06,20.03],[38.8,20.46],[38.55,20.88],[38.29,21.31],[38.03,21.74],[37.77,22.17],[37.51,22.59],[37.24,23.02],[36.98,23.44],[36.71,23.87],[36.44,24.29],[36.17,24.72],[35.89,25.14],[35.62,25.56],[35.34,25.99],[35.06,26.41],[34.78,26.83],[34.5,27.25],[34.25,27.5],[34,27.75],[33.75,28],[33.5,28.25],[33.25,28.5],[33,28.75],[33,29],[32.75,29.25],[32.5,29.5],[32.5,29.75],[32.5,30.5],[32.5,31.25],[32.25,31.5],[32,31.75],[31.6,32.11],[31.2,32.47],[30.8,32.83],[30.39,33.19],[29.98,33.55],[29.56,33.9],[29.14,34.25],[28.72,34.61],[28.3,34.96],[27.87,35.31],[27.44,35.65],[27,36],[26.43,36.01],[25.86,36.01],[25.29,36.02],[24.71,36.02],[24.14,36.01],[23.57,36.01],[23,36],[22,36],[21.42,36.02],[20.83,36.03],[20.25,36.04],[19.67,36.05],[19.08,36.05],[18.5,36.05],[17.92,36.05],[17.33,36.05],[16.75,36.04],[16.17,36.03],[15.58,36.02],[15,36],[14.07,36.36],[13.14,36.71],[12.21,37.07],[11.29,37.43],[10.36,37.79],[9.43,38.14],[8.5,38.5],[7.75,39.25],[7.45,39.69],[7.15,40.13],[6.84,40.57],[6.53,41.01],[6.22,41.44],[5.9,41.88],[5.58,42.32],[5.25,42.75],[5.25,43],[5.25,43.25]]]]}, + {"id":"clion","anchor":true,"name":"C-Lion King","price":1.0,"age":"new","blurb":tr('cables.helsinki_to_germany_under_the_baltic'),"pairs":[["hel","fra",[[24,59.8],[20,57.5],[15,55.2],[12.2,54.3]]],["hel","ham",[[23.25,59.75],[16.25,55.75],[13.25,54.75],[11,54.75],[10.5,55.5],[11,56],[11,57.5],[8.75,57.75],[7.5,56.25],[8,54.25]]]]}, + {"id":"uly","df":true,"name":"Ulysseless","price":0.8,"age":"old","blurb":tr('cables.short_hop_across_the_north_sea'),"pairs":[["lon","ams",[[2,51.8]]]]}, + {"id":"chn","df":true,"name":"Channel Hopper","price":0.7,"age":"mid","blurb":tr('cables.london_to_paris_under_the_channel'),"pairs":[["lon","par",[[1,50.5]]]]}, + {"id":"medn","name":"Med-Nauti-lust","price":0.9,"age":"mid","blurb":tr('cables.across_the_mediterranean_egypt_to'),"pairs":[["nic","jer",[[32.9,34.3],[34.4,32.2]]],["ath","nic",[[24,37.5],[26,35.6],[30,35],[33.3,34.65]]],["ist","mrs",[[26.5,40],[25,37],[23,36],[15,36],[8.5,38.5],[6.5,42.6]]],["cai","mrs",[[30.5,30.65],[29.75,31.25],[29.5,31.5],[28.51,31.82],[27.52,32.14],[26.54,32.46],[25.55,32.79],[24.56,33.11],[23.57,33.43],[22.58,33.75],[21.6,34.07],[20.61,34.39],[19.62,34.71],[18.63,35.04],[17.64,35.36],[16.65,35.68],[15.67,36],[14.68,36.32],[13.69,36.64],[12.7,36.96],[11.71,37.29],[10.73,37.61],[9.74,37.93],[8.75,38.25],[7.75,39.25],[7.45,39.69],[7.15,40.13],[6.84,40.57],[6.53,41.01],[6.22,41.44],[5.9,41.88],[5.58,42.32],[5.25,42.75],[5.25,43],[5.25,43.25]]]]}, + {"id":"eassy","name":"EASSy Peasy","price":0.95,"age":"mid","blurb":tr('cables.east_africa_up_to_europe_via'),"pairs":[["dar","hah",[[40.5,-7.5],[43,-11.3]]],["mba","mgq",[[41.8,-2.8],[44.8,0.8],[45.9,1.6]]],["mgq","jib",[[47.5,4.5],[51.5,11.5],[44,11.8]]],["jib","krt",[[43,13],[40.5,16.5],[37.6,19.6]]],["nbo","mrs",[[39.7,-4],[39.75,-4],[40,-4.25],[40.34,-3.91],[40.69,-3.56],[41.03,-3.22],[41.38,-2.88],[41.72,-2.53],[42.07,-2.19],[42.41,-1.85],[42.75,-1.5],[43.1,-1.16],[43.44,-0.81],[43.78,-0.47],[44.13,-0.13],[44.47,0.22],[44.81,0.56],[45.16,0.91],[45.5,1.25],[45.84,1.59],[46.19,1.94],[46.53,2.28],[46.87,2.63],[47.22,2.97],[47.56,3.31],[47.91,3.66],[48.25,4],[48.79,4.96],[49.33,5.92],[49.88,6.88],[50.42,7.83],[50.96,8.79],[51.5,9.75],[51.63,10.75],[51.75,11.75],[51,12.5],[50.5,12.47],[50,12.44],[49.5,12.41],[49,12.38],[48.5,12.34],[48,12.31],[47.5,12.27],[47,12.24],[46.5,12.2],[46,12.16],[45.5,12.12],[45,12.08],[44.5,12.04],[44,12],[43.75,12.25],[43.5,12.5],[43.25,12.75],[43.25,13],[43.25,13.25],[43,13.5],[42.75,13.75],[42.5,14],[42.26,14.43],[42.02,14.86],[41.78,15.3],[41.54,15.73],[41.3,16.16],[41.05,16.59],[40.81,17.02],[40.56,17.45],[40.31,17.88],[40.06,18.31],[39.82,18.74],[39.56,19.17],[39.31,19.6],[39.06,20.03],[38.8,20.46],[38.55,20.88],[38.29,21.31],[38.03,21.74],[37.77,22.17],[37.51,22.59],[37.24,23.02],[36.98,23.44],[36.71,23.87],[36.44,24.29],[36.17,24.72],[35.89,25.14],[35.62,25.56],[35.34,25.99],[35.06,26.41],[34.78,26.83],[34.5,27.25],[34.25,27.5],[34,27.75],[33.75,28],[33.5,28.25],[33.25,28.5],[33,28.75],[33,29],[32.75,29.25],[32.5,29.5],[32.5,29.75],[32.5,30.5],[32.5,31.25],[32.25,31.5],[32,31.75],[31.6,32.11],[31.2,32.47],[30.8,32.83],[30.39,33.19],[29.98,33.55],[29.56,33.9],[29.14,34.25],[28.72,34.61],[28.3,34.96],[27.87,35.31],[27.44,35.65],[27,36],[26.43,36.01],[25.86,36.01],[25.29,36.02],[24.71,36.02],[24.14,36.01],[23.57,36.01],[23,36],[22,36],[21.42,36.02],[20.83,36.03],[20.25,36.04],[19.67,36.05],[19.08,36.05],[18.5,36.05],[17.92,36.05],[17.33,36.05],[16.75,36.04],[16.17,36.03],[15.58,36.02],[15,36],[14.07,36.36],[13.14,36.71],[12.21,37.07],[11.29,37.43],[10.36,37.79],[9.43,38.14],[8.5,38.5],[7.75,39.38],[7,40.25],[6.25,41.13],[5.5,42],[5.4,42.1]]],["dur","mpm",[[32,-30.3],[34.5,-26]]],["mpm","dar",[[34.5,-26],[38,-20],[41.5,-14],[40.4,-7]]],["dar","mba",[[40.4,-7],[40.6,-4.3]]],["mba","jib",[[48.25,4],[51.5,9.5],[51.75,11.75],[51,12.5]]],["mpm","tnr",[[41.7,-26.09],[46,-26],[46.75,-25.75],[49,-23.5],[49,-21],[48.75,-20.75],[48.75,-20.25]]]]}, + {"id":"teams","name":"TEAMS-work","price":0.9,"age":"mid","blurb":tr('cables.kenya_to_the_gulf_makes_the'),"pairs":[["nbo","dxb",[[39.7,-4],[39.75,-4],[40,-4.25],[40.34,-3.91],[40.69,-3.56],[41.03,-3.22],[41.38,-2.88],[41.72,-2.53],[42.07,-2.19],[42.41,-1.85],[42.75,-1.5],[43.1,-1.16],[43.44,-0.81],[43.78,-0.47],[44.13,-0.13],[44.47,0.22],[44.81,0.56],[45.16,0.91],[45.5,1.25],[45.84,1.59],[46.19,1.94],[46.53,2.28],[46.87,2.63],[47.22,2.97],[47.56,3.31],[47.91,3.66],[48.25,4],[48.89,4.96],[49.53,5.92],[50.17,6.88],[50.81,7.83],[51.44,8.79],[52.08,9.75],[52.72,10.71],[53.36,11.67],[54,12.63],[54.64,13.58],[55.28,14.54],[55.92,15.5],[56.56,16.46],[57.19,17.42],[57.83,18.38],[58.47,19.33],[59.11,20.29],[59.75,21.25],[60,21.75],[60,22],[60,23],[59.67,23.34],[59.34,23.67],[59.01,24],[58.67,24.34],[58.34,24.67],[58,25],[57,25],[57,25]]],["mba","fuj",[[39.75,-4],[40,-4],[40.25,-4],[40.6,-3.65],[40.96,-3.3],[41.31,-2.94],[41.66,-2.59],[42.01,-2.24],[42.37,-1.89],[42.72,-1.54],[43.07,-1.18],[43.42,-0.83],[43.77,-0.48],[44.13,-0.13],[44.48,0.23],[44.83,0.58],[45.18,0.93],[45.53,1.28],[45.88,1.64],[46.24,1.99],[46.59,2.34],[46.94,2.69],[47.29,3.05],[47.65,3.4],[48,3.75],[48.27,4.17],[48.53,4.58],[48.8,5],[49.06,5.41],[49.33,5.83],[49.6,6.24],[49.87,6.66],[50.14,7.07],[50.4,7.49],[50.67,7.9],[50.94,8.32],[51.21,8.73],[51.48,9.15],[51.76,9.56],[52.03,9.97],[52.3,10.39],[52.57,10.8],[52.85,11.21],[53.12,11.63],[53.4,12.04],[53.68,12.45],[53.95,12.86],[54.23,13.27],[54.51,13.69],[54.79,14.1],[55.08,14.51],[55.36,14.92],[55.64,15.33],[55.93,15.74],[56.21,16.15],[56.5,16.56],[56.79,16.96],[57.08,17.37],[57.37,17.78],[57.66,18.19],[57.95,18.59],[58.25,19],[58.5,19.39],[58.74,19.78],[58.99,20.17],[59.24,20.56],[59.49,20.95],[59.74,21.34],[59.99,21.72],[60.24,22.11],[60.5,22.5],[59.75,23.25],[59,24],[58,24.5],[57,25],[56.75,25],[56.5,25]]]]}, + {"id":"monet","name":"Mo-Net-y","price":0.9,"age":"new","blurb":tr('cables.brazil_to_florida_the_invoice'),"pairs":[["sao","mia",[[-46,-24],[-42.5,-24],[-35,-16],[-34.25,-7.25],[-34.75,-5.25],[-53,13],[-66.56,20.08]]],["for","mia",[[-37,-2.2],[-45,4.5],[-62,16.5],[-76,25.3]]]]}, + {"id":"seabras","name":"Sea-Bras","price":0.9,"age":"new","blurb":tr('cables.straight_from_sao_paulo_to_new'),"pairs":[["sao","nyc",[[-46,-24],[-42.5,-24],[-35,-16],[-34.25,-7.25],[-34.75,-5.25],[-47.2,12.91],[-55.94,24.18],[-65.11,33.76],[-70.23,38.09]]]]}, + {"id":"sam1","name":"SAM-1-and-Done","price":1.2,"age":"old","blurb":tr('cables.an_old_ring_around_the_whole'),"pairs":[["mia","for",[[-75,24],[-62,16],[-45,4],[-37,-2.5]]],["for","rio",[[-35.25,-4.75],[-34.5,-5.75],[-34.25,-7.5],[-36,-17],[-41.5,-23]]],["for","ssa",[[-35.25,-4.75],[-34.25,-7.5],[-34.75,-10],[-37.75,-13]]],["ssa","rio",[[-37.5,-14],[-38.5,-18],[-41,-23.6]]],["rio","sao",[[-44,-24.3]]],["sao","bue",[[-47,-27],[-52,-35],[-56,-36]]],["bue","scl",[[-57,-35],[-56,-36.75],[-61.29,-49],[-65,-55],[-66.25,-55.75],[-69.55,-55.5],[-72,-55.25],[-76,-51],[-76,-46.5],[-74.25,-37.5],[-72.25,-33.5]]],["scl","lim",[[-73.5,-30],[-74,-20],[-78,-13]]],["lim","pan",[[-77.5,-12.25],[-82,-6],[-81,6],[-79.5,7.5]]],["pan","mia",[[-79.5,10],[-77,15],[-74,19.5],[-75,23],[-79,25]]],["sju","sdq",[[-67.3,18.0],[-68.5,18.3]]]]}, + {"id":"curie","name":"Curie-osity","price":0.85,"age":"new","blurb":tr('cables.los_angeles_to_chile_with_a'),"pairs":[["lax","scl",[[-120,30],[-108,14],[-92,0],[-80,-20],[-73,-33]]],["lax","pan",[[-118.5,33.25],[-115.5,27.75],[-110,22.25],[-103,17.5],[-89.54,11.31],[-83,7.5],[-80,7]]]]}, + {"id":"pccs","name":"Caribbean Cruise Control","price":1.0,"age":"mid","blurb":tr('cables.hops_the_caribbean_so_bogota_can'),"pairs":[["mia","bog",[[-80,24],[-73.75,20.25],[-76,17],[-76,12],[-75,10.5]]],["pan","bog",[[-79.6,9.6],[-77,9.9],[-75.5,10.5]]]]}, + {"id":"tannat","name":"Tannat Wine Line","price":0.9,"age":"mid","blurb":tr('cables.named_after_a_wine_sao_paulo'),"pairs":[["sao","bue",[[-46,-26],[-50,-32],[-55,-35.5]]],["sao","mvd",[[-46,-26],[-50,-32],[-55,-35.3]]]]}, + {"id":"humb","name":"Humboldt Penguin","price":1.3,"age":"new","blurb":tr('cables.the_first_cable_from_south_america'),"pairs":[["scl","syd",[[-72.25,-33.5],[-79.37,-41.07],[-86.71,-47.03],[-93.34,-51.13],[-101.17,-54.79],[-110.43,-57.84],[-120.2,-59.96],[-132.02,-61.4],[-142.38,-61.87],[-153.81,-61.47],[-165.57,-59.99],[-176.03,-57.57],[-185,-54.4],[-192,-51],[-197.37,-46.82],[-203.82,-40.38]]],["scl","ppt",[[-75,-34],[-100,-30],[-130,-22],[-149,-17.9]]],["ppt","syd",[[-166.04,-25.37],[-180.69,-30.43],[-198.41,-33.93]]]]}, + {"id":"wacs","name":"WACS-a-Mole","price":1.1,"age":"mid","blurb":tr('cables.up_the_west_coast_of_africa'),"pairs":[["acc","lfw",[[0.4,5.5],[1.2,5.95]]],["lfw","lag",[[2,6],[3.2,6.2]]],["cpt","lag",[[16,-34],[10,-20],[6,-5],[4,3]]],["lag","lon",[[2.75,5.75],[-2,4.25],[-8.75,4.25],[-13.75,8.25],[-18,14],[-17.75,28.75],[-16.49,31.46],[-9,44.27],[-4.5,49.25],[-1,50]]],["abj","acc",[[-3,4],[0,5]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]],["lag","dla",[[3.2,5.8],[6,3],[9,3.6]]],["dla","lad",[[9,3.6],[8,-2],[11.5,-6],[12.6,-9]]],["lad","wdh",[[12,-10],[11.25,-19.75],[14,-22.5]]],["wdh","cpt",[[13.5,-22.7],[15,-30],[17.6,-34.4]]],["lon","tci",[[-1,50],[-4.75,49],[-6.49,47.39],[-15.4,36.87],[-16,36]]],["tci","rai",[[-18,24],[-22,17]]],["rai","abj",[[-8.75,4.25],[-5,4]]]]}, + {"id":"safe","name":"SAFE-ty Not Guaranteed","price":1.4,"age":"old","blurb":tr('cables.an_old_cable_from_cape_town'),"pairs":[["cpt","bom",[[22,-36],[45,-30],[57,-20],[65,0],[70,15]]],["dur","run",[[33,-30.5],[45,-28],[54,-22]]],["run","mru",[[56.4,-20.4]]],["mru","bom",[[60,-15],[65,0],[70,15]]]]}, + {"id":"bbg","name":"Bay of Bengal Gate-Delay","price":0.95,"age":"mid","blurb":tr('cables.fujairah_to_mumbai_round_the_tip'),"pairs":[["fuj","bom",[[58,24.5],[63,22],[69.5,19.5]]],["bom","maa",[[72.75,19],[72.5,19],[72.25,18.5],[72.38,18.04],[72.5,17.58],[72.63,17.13],[72.75,16.67],[72.88,16.21],[73,15.75],[73.21,15.3],[73.41,14.85],[73.61,14.4],[73.82,13.95],[74.02,13.5],[74.22,13.05],[74.42,12.6],[74.62,12.15],[74.82,11.7],[75.02,11.25],[75.21,10.8],[75.41,10.35],[75.61,9.9],[75.8,9.45],[76,9],[76.63,8.25],[77.25,7.5],[77.75,7.75],[78,8],[79,9],[79.25,9],[79.5,9.25],[79.5,9.5],[80.5,10.5],[80.58,11.25],[80.67,12],[80.75,12.75],[80.75,13],[80.5,13.25]]],["maa","sin",[[82,12],[90,8],[96.5,6],[100,3.5],[102.5,2],[103.6,1.25]]]]}, + {"id":"i2i","name":"Eye-to-Eye","price":0.85,"age":"mid","blurb":tr('cables.chennai_to_singapore_looking_it'),"pairs":[["maa","sin",[[82.61,12.7],[98,5.5],[102.75,1.25]]]]}, + {"id":"tse","name":"Strait Outta Taipei","price":1.5,"age":"old","blurb":tr('cables.a_short_cable_across_a_very'),"pairs":[["tpe","sha",[[122.2,26.5],[122.6,29],[122.2,31]]]]}, + {"id":"gbi","name":"Gulf Bridge Over Troubled Water","price":1.0,"age":"mid","blurb":tr('cables.leaves_the_gulf_from_fujairah_and'),"pairs":[["fuj","mrs",[[56.5,25],[56.75,25],[57,25],[58,24.5],[59,24],[59.75,23.25],[60.5,22.5],[60.24,22.11],[59.99,21.72],[59.74,21.34],[59.49,20.95],[59.24,20.56],[58.99,20.17],[58.74,19.78],[58.5,19.39],[58.25,19],[57.5,18.25],[57.08,17.96],[56.66,17.67],[56.24,17.38],[55.83,17.09],[55.41,16.79],[55,16.5],[54.55,16.28],[54.09,16.06],[53.64,15.83],[53.19,15.61],[52.74,15.39],[52.29,15.16],[51.84,14.93],[51.39,14.71],[50.95,14.48],[50.5,14.25],[49.5,13.88],[48.5,13.5],[47.5,13.13],[46.5,12.75],[45.5,12.38],[44.5,12],[44,12],[43.75,12.25],[43.5,12.5],[43.25,12.75],[43.25,13],[43.25,13.25],[43,13.5],[42.75,13.75],[42.5,14],[42.26,14.43],[42.02,14.86],[41.78,15.3],[41.54,15.73],[41.3,16.16],[41.05,16.59],[40.81,17.02],[40.56,17.45],[40.31,17.88],[40.06,18.31],[39.82,18.74],[39.56,19.17],[39.31,19.6],[39.06,20.03],[38.8,20.46],[38.55,20.88],[38.29,21.31],[38.03,21.74],[37.77,22.17],[37.51,22.59],[37.24,23.02],[36.98,23.44],[36.71,23.87],[36.44,24.29],[36.17,24.72],[35.89,25.14],[35.62,25.56],[35.34,25.99],[35.06,26.41],[34.78,26.83],[34.5,27.25],[34.25,27.5],[34,27.75],[33.75,28],[33.5,28.25],[33.25,28.5],[33,28.75],[33,29],[32.75,29.25],[32.5,29.5],[32.5,29.75],[32.5,30.5],[32.5,31.25],[32.25,31.5],[32,31.75],[31.6,32.11],[31.2,32.47],[30.8,32.83],[30.39,33.19],[29.98,33.55],[29.56,33.9],[29.14,34.25],[28.72,34.61],[28.3,34.96],[27.87,35.31],[27.44,35.65],[27,36],[26.43,36.01],[25.86,36.01],[25.29,36.02],[24.71,36.02],[24.14,36.01],[23.57,36.01],[23,36],[22,36],[21.42,36.02],[20.83,36.03],[20.25,36.04],[19.67,36.05],[19.08,36.05],[18.5,36.05],[17.92,36.05],[17.33,36.05],[16.75,36.04],[16.17,36.03],[15.58,36.02],[15,36],[14.07,36.36],[13.14,36.71],[12.21,37.07],[11.29,37.43],[10.36,37.79],[9.43,38.14],[8.5,38.5],[7.75,39.25],[7.45,39.69],[7.15,40.13],[6.84,40.57],[6.53,41.01],[6.22,41.44],[5.9,41.88],[5.58,42.32],[5.25,42.75],[5.25,43],[5.25,43.25]]]]}, + {"id":"aagony","name":"AAG-ony","price":1.1,"age":"old","blurb":tr('cables.an_asia_america_gateway_cable_that'),"pairs":[["sgn","hkg",[[108,10],[109.75,11.5]]],["sgn","sin",[[106,7],[104.6,3]]]]}, + {"id":"darwin","name":"Darwin Award Cable","price":1.0,"age":"new","blurb":tr('cables.darwin_to_singapore_via_jakarta'),"pairs":[["drw","jkt",[[117,-10],[114.25,-7.25],[111.75,-6],[107.5,-5.5]]],["drw","sin",[[117,-10]]],["phe","sin",[[118.25,-19.5],[117,-10]]]]}, + {"id":"nwcs","name":"No Worries Cable System","price":1.0,"age":"mid","blurb":tr('cables.darwin_to_port_hedland_past_the'),"pairs":[["drw","phe",[[130.25,-12],[128,-12.75],[124.5,-14.25],[121.5,-17.25],[119,-19.5]]]]}, + {"id":"jga","name":"J-G’day-A (Japan–Guam–Aussie)","price":0.9,"age":"new","blurb":tr('cables.brisbane_to_tokyo_with_a_beach'),"pairs":[["bne","tok",[[155,-25],[156,-5],[146,13],[141,30]]],["bne","gum",[[155,-25],[156,-5],[146,12.8]]],["gum","tok",[[145.3,14.5],[141,30]]]]}, + {"id":"smw4","name":"SEE-ME-WAVE 4","price":1.2,"age":"old","blurb":tr('cables.the_previous_generation_still'),"pairs":[["khi","mrs",[[66.75,24.75],[66.5,24.75],[65.54,24.06],[64.58,23.38],[63.63,22.69],[62.67,22],[61.71,21.31],[60.75,20.63],[59.79,19.94],[58.83,19.25],[57.88,18.56],[56.92,17.88],[55.96,17.19],[55,16.5],[54.55,16.28],[54.09,16.06],[53.64,15.83],[53.19,15.61],[52.74,15.39],[52.29,15.16],[51.84,14.93],[51.39,14.71],[50.95,14.48],[50.5,14.25],[49.5,13.88],[48.5,13.5],[47.5,13.13],[46.5,12.75],[45.5,12.38],[44.5,12],[44,12],[43.75,12.25],[43.5,12.5],[43.25,12.75],[43.25,13],[43.25,13.25],[43,13.5],[42.75,13.75],[42.5,14],[42.26,14.43],[42.02,14.86],[41.78,15.3],[41.54,15.73],[41.3,16.16],[41.05,16.59],[40.81,17.02],[40.56,17.45],[40.31,17.88],[40.06,18.31],[39.82,18.74],[39.56,19.17],[39.31,19.6],[39.06,20.03],[38.8,20.46],[38.55,20.88],[38.29,21.31],[38.03,21.74],[37.77,22.17],[37.51,22.59],[37.24,23.02],[36.98,23.44],[36.71,23.87],[36.44,24.29],[36.17,24.72],[35.89,25.14],[35.62,25.56],[35.34,25.99],[35.06,26.41],[34.78,26.83],[34.5,27.25],[34.25,27.5],[34,27.75],[33.75,28],[33.5,28.25],[33.25,28.5],[33,28.75],[33,29],[32.75,29.25],[32.5,29.5],[32.5,29.75],[32.5,30.5],[32.5,31.25],[32.25,31.5],[32,31.75],[31.6,32.11],[31.2,32.47],[30.8,32.83],[30.39,33.19],[29.98,33.55],[29.56,33.9],[29.14,34.25],[28.72,34.61],[28.3,34.96],[27.87,35.31],[27.44,35.65],[27,36],[26.43,36.01],[25.86,36.01],[25.29,36.02],[24.71,36.02],[24.14,36.01],[23.57,36.01],[23,36],[22,36],[21.42,36.02],[20.83,36.03],[20.25,36.04],[19.67,36.05],[19.08,36.05],[18.5,36.05],[17.92,36.05],[17.33,36.05],[16.75,36.04],[16.17,36.03],[15.58,36.02],[15,36],[14.07,36.36],[13.14,36.71],[12.21,37.07],[11.29,37.43],[10.36,37.79],[9.43,38.14],[8.5,38.5],[7.75,39.25],[7.45,39.69],[7.15,40.13],[6.84,40.57],[6.53,41.01],[6.22,41.44],[5.9,41.88],[5.58,42.32],[5.25,42.75],[5.25,43],[5.25,43.25]]],["khi","bom",[[67,23],[70,20.5]]],["bom","cbo",[[72,15],[75,8],[78.5,6.3]]],["cbo","maa",[[80.6,8.6],[81,11.5]]],["maa","dac",[[89.5,21.5]]],["dac","sin",[[91.5,22.75],[91.25,22],[93.75,16.5],[97.75,12.5],[97.75,8.25],[100.5,3.5],[102.75,1.25]]],["mrs","pmo",[[5.25,42.75],[9,38.25]]],["pmo","cai",[[12,38],[13.25,36.75],[29.5,31.5]]],["cai","jed",[[32.5,29.75],[33,28.75]]],["jed","fuj",[[39,21.5],[38.75,21.25],[38.75,21],[38.99,20.56],[39.24,20.13],[39.48,19.69],[39.72,19.26],[39.95,18.82],[40.19,18.38],[40.43,17.95],[40.66,17.51],[40.89,17.07],[41.13,16.63],[41.36,16.19],[41.59,15.76],[41.82,15.32],[42.05,14.88],[42.27,14.44],[42.5,14],[42.75,13.75],[43,13.5],[43.25,13.25],[43.25,13],[43.25,12.75],[43.5,12.5],[43.75,12.25],[44,12],[44.5,12],[45.5,12.38],[46.5,12.75],[47.5,13.13],[48.5,13.5],[49.5,13.88],[50.5,14.25],[50.95,14.48],[51.39,14.71],[51.84,14.93],[52.29,15.16],[52.74,15.39],[53.19,15.61],[53.64,15.83],[54.09,16.06],[54.55,16.28],[55,16.5],[55.41,16.79],[55.83,17.09],[56.24,17.38],[56.66,17.67],[57.08,17.96],[57.5,18.25],[58.25,19],[58.5,19.39],[58.74,19.78],[58.99,20.17],[59.24,20.56],[59.49,20.95],[59.74,21.34],[59.99,21.72],[60.24,22.11],[60.5,22.5],[59.75,23.25],[59,24],[58,24.5],[57,25],[56.75,25],[56.5,25]]],["fuj","khi",[[62.5,24.5]]]]}, + {"id":"balt","anchor":true,"name":"Baltic Anchor Magnet","price":0.8,"age":"mid","blurb":tr('cables.short_hops_under_the_baltic_sea'),"pairs":[["tll","hel",[[24.8,59.8]]],["tll","sto",[[22,59.3],[19.5,59.3]]]]}, + {"id":"bsea","name":"Black Sea Shanty","price":1.0,"age":"mid","blurb":tr('cables.istanbul_to_bucharest_s_coast_across'),"pairs":[["ist","buh",[[29.5,42],[29.5,43.5],[28.8,44.2]]]]}, + {"id":"concerto","name":"Concerto in Sea Minor","price":0.55,"age":"new","df":true,"blurb":tr('cables.north_sea_workhorse_from_london_to'),"pairs":[["lon","ams",[[1.6,51.72],[3.6,52.02]]]]}, + {"id":"circe","name":"Circe du Soleil","price":0.6,"age":"mid","df":true,"blurb":tr('cables.another_london_amsterdam_route'),"pairs":[["lon","ams",[[1.8,52.18],[3.8,52.58]]]]}, + {"id":"nshuttle","name":"North Sea Shuttle","price":0.5,"age":"new","df":true,"blurb":tr('cables.brand_new_cheap_and_it_lands'),"pairs":[["lon","ams",[[1.5,51.42],[3.9,51.88]]]]}, + {"id":"imewe","name":"I-ME-WE-Us","price":1.05,"age":"mid","blurb":tr('cables.india_the_middle_east_and_western'),"pairs":[["cai","fuj",[[31.87,29.9],[32.5,29.75],[32.5,29.5],[32.75,29.25],[33,29],[33,28.75],[33.25,28.5],[33.5,28.25],[33.75,28],[34,27.75],[34.25,27.5],[34.5,27.25],[34.78,26.83],[35.06,26.41],[35.34,25.99],[35.62,25.56],[35.89,25.14],[36.17,24.72],[36.44,24.29],[36.71,23.87],[36.98,23.44],[37.24,23.02],[37.51,22.59],[37.77,22.17],[38.03,21.74],[38.29,21.31],[38.55,20.88],[38.8,20.46],[39.06,20.03],[39.31,19.6],[39.56,19.17],[39.82,18.74],[40.06,18.31],[40.31,17.88],[40.56,17.45],[40.81,17.02],[41.05,16.59],[41.3,16.16],[41.54,15.73],[41.78,15.3],[42.02,14.86],[42.26,14.43],[42.5,14],[42.75,13.75],[43,13.5],[43,13.25],[43,13],[44,12],[44.47,12.14],[44.94,12.28],[45.41,12.42],[45.88,12.56],[46.36,12.7],[46.83,12.84],[47.3,12.98],[47.78,13.11],[48.25,13.25],[48.66,13.45],[49.08,13.64],[49.49,13.84],[49.91,14.03],[50.33,14.23],[50.74,14.42],[51.16,14.62],[51.58,14.81],[52,15],[52.43,15.22],[52.85,15.43],[53.28,15.65],[53.71,15.86],[54.14,16.08],[54.57,16.29],[55,16.5],[55.92,17.17],[56.83,17.83],[57.75,18.5],[58.5,19.25],[58.75,19.67],[58.99,20.08],[59.24,20.5],[59.49,20.92],[59.75,21.33],[60,21.75],[60,22],[60,23],[59.67,23.34],[59.34,23.67],[59.01,24],[58.67,24.34],[58.34,24.67],[58,25],[57,25],[56.75,25],[56.5,25]]],["cai","bom",[[32.5,29.75],[33,28.75],[34.5,27.25],[38.29,21.31],[42.5,14],[43.25,13.25],[43.25,12.75],[44,12],[44.5,12],[46,12.75],[48.92,13.61],[57.79,15.98]]]]}, + {"id":"jedx","name":"Jeddah-i Express","price":0.95,"age":"new","blurb":tr('cables.new_cables_increasingly_land_in'),"pairs":[["jed","bom",[[38.75,21],[42.5,14],[44,12],[57.79,15.98]]],["jed","sin",[[38.75,21],[43,13],[44,12],[51.25,12.5],[64.94,9.47],[80.75,5.25],[97.5,6],[102.75,1.25]]]]}, + {"id":"rsea","name":"Red Sea Shortcut","price":0.9,"age":"mid","blurb":tr('cables.a_quick_hop_across_the_red'),"pairs":[["cai","jed",[[32.5,29.75],[32.5,29.5],[33,29],[33,28.75],[34.5,27.25],[38.5,22.25]]]]}, + {"id":"qgulf","name":"Doha Detour","price":1.0,"age":"mid","blurb":tr('cables.connects_doha_to_the_rest_of'),"pairs":[["doh","fuj",[[52.5,26.2],[55,26.4],[56.6,26],[56.9,25.3]]],["doh","bom",[[56.5,26.5],[57.25,25.25]]]]}, + {"id":"nouk","name":"NO-UK-Way","price":0.6,"age":"new","df":true,"blurb":tr('cables.norway_to_the_uk_across_the'),"pairs":[["svg","edi",[[5.3,58.8],[2,57.5],[-1.5,56.2]]]]}, + {"id":"celtn","name":"Celtic Norsemen","price":0.85,"age":"new","blurb":tr('cables.ireland_to_norway_the_long_way'),"pairs":[["dub","svg",[[-5.25,54.75],[-6.75,57.25],[-4.75,59.25]]]]}, + {"id":"havh","name":"Havhingsten Hoofbeat","price":0.8,"age":"new","blurb":tr('cables.the_sea_stallion_blackpool_to'),"pairs":[["man","cph",[[-4.5,54.25],[-6.25,55.75],[-6.75,57.25],[-4.25,59.25],[7,57.5],[10.5,57.75],[11,57.5],[10.5,55.25],[12,54.75]]],["dub","man",[[-5.5,53.75]]],["edi","ebj",[[2.67,55.72]]]]}, + {"id":"shefa","name":"Shefa Sheep Line","price":1.1,"age":"mid","blurb":tr('cables.scotland_to_iceland_via_shetland_and'),"pairs":[["edi","rek",[[-2.5,56.2],[-1,58],[-1.3,60.2],[-6.8,62],[-14,63.4],[-20,63.6]]]]}, + {"id":"apollo","name":"Apollo 13 (Houston, We Have Latency)","price":0.95,"age":"mid","blurb":tr('cables.new_york_to_the_cliffs_of'),"pairs":[["nyc","bde",[[-70,40],[-50,43],[-25,48.5],[-8,50.2],[-5,50.8]]]]}, + {"id":"yellow","name":"Yellow Brick Road","price":0.9,"age":"mid","blurb":tr('cables.long_island_to_cornwall_follow_it'),"pairs":[["nyc","bde",[[-71,40.5],[-50,44.5],[-25,49.3],[-8,50.6],[-5,50.9]]]]}, + {"id":"ace","name":"ACE of Spades","price":1.0,"age":"mid","blurb":tr('cables.africa_coast_to_europe_twenty_odd'),"pairs":[["tci","nkc",[[-16.5,26],[-17.3,21],[-16.6,18.2]]],["nkc","dkr",[[-16.6,17.5],[-17.6,14.9]]],["dkr","bjl",[[-17.6,14.4],[-16.9,13.5]]],["bjl","oxb",[[-17.1,13],[-16.3,11.6]]],["oxb","cky",[[-16,11],[-14,9.4]]],["cky","fna",[[-13.8,9.2],[-13.4,8.6]]],["fna","rob",[[-13.4,8],[-11,6.2]]],["rob","abj",[[-10.9,5.9],[-8,4.1],[-6,4.3],[-4.1,5.1]]],["acc","pto",[[0,5.3],[2.4,6.2]]],["pto","lag",[[2.9,6.25]]],["lbv","tms",[[8.5,0.5],[7,0.3]]],["lis","dkr",[[-9.6,37.9],[-12,34],[-8.2,33.9],[-15,28],[-18,21],[-18,14.7]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]],["abj","acc",[[-3,4],[0,5]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]],["lag","lad",[[3.2,5.8],[6,3],[9,3.6],[8,-2],[11.5,-6],[12.6,-9]]],["lad","cpt",[[12.5,-9.5],[11.25,-15.25],[12,-26]]],["lis","tci",[[-9.6,37.9],[-12,34],[-15.4,29.5]]],["tci","dkr",[[-17,26],[-18,21],[-18,14.7]]]]}, + {"id":"sat3","name":"SAT-3-Legged Stool","price":1.25,"age":"old","blurb":tr('cables.west_africa_s_first_big_cable'),"pairs":[["acc","pto",[[0.2,5.2],[2.4,6.15]]],["pto","lag",[[2.95,6.2]]],["dla","lbv",[[9.3,3.4],[9.1,1.2]]],["lis","dkr",[[-9.6,37.9],[-12,34],[-8.2,33.9],[-15,28],[-18,21],[-18,14.7]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]],["abj","acc",[[-3,4],[0,5]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]],["lag","dla",[[3.2,5.8],[6,3],[9,3.6]]],["dla","lad",[[9,3.6],[8,-2],[11.5,-6],[12.6,-9]]],["lad","cpt",[[12.5,-9.5],[11.25,-15.25],[12,-26]]],["lis","tci",[[-9.6,37.9],[-12,34],[-15.4,29.5]]],["tci","dkr",[[-17,26],[-18,21],[-18,14.7]]]]}, + {"id":"mone","name":"MainOne-Track Mind","price":1.0,"age":"mid","blurb":tr('cables.portugal_to_lagos_with_stops_in'),"pairs":[["lis","dkr",[[-9.6,37.9],[-12,34],[-8.2,33.9],[-15,28],[-18,21],[-18,14.7]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]],["abj","acc",[[-3,4],[0,5]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]]]}, + {"id":"mtwa","name":"Mint Tea West Africa","price":1.05,"age":"new","blurb":tr('cables.casablanca_down_the_coast_to_abidjan'),"pairs":[["cas","dkr",[[-8.2,33.9],[-15,28],[-18,21],[-18,14.7]]],["dkr","abj",[[-18,14.7],[-17,10],[-14,5],[-8,4],[-4,4.8]]]]}, + {"id":"sail","name":"Set SAIL","price":1.0,"age":"new","blurb":tr('cables.straight_across_the_south_atlantic'),"pairs":[["for","dla",[[-37,-2.5],[-20,0],[0,2.5],[9,3.6]]]]}, + {"id":"seacm","name":"Sea-Comedy Hour","price":0.95,"age":"mid","blurb":tr('cables.the_cable_that_brought_east_africa'),"pairs":[["dur","mpm",[[32,-30.3],[34.5,-26]]],["mpm","dar",[[34.5,-26],[38,-20],[41.5,-14],[40.4,-7]]],["dar","mba",[[40.4,-7],[40.6,-4.3]]],["mba","jib",[[48.25,4],[51.5,9.5],[51.75,11.75],[51,12.5]]],["jib","bom",[[56.3,15.61]]]]}, + {"id":"dare","name":"Dare-Devil-1","price":0.9,"age":"new","blurb":tr('cables.djibouti_down_to_durban_hugging_the'),"pairs":[["jib","mgq",[[44.2,11.9],[51.8,12.1],[52,10.5],[49.2,5]]],["jib","mba",[[51,12.5],[51.75,11.75],[51.5,9.5],[48.25,4]]],["mba","dar",[[40.6,-4.3],[40.4,-7]]],["dar","mpm",[[40.4,-7],[41.5,-14],[38,-20],[34.5,-26]]],["mpm","dur",[[34.5,-26],[32,-30.3]]]]}, + {"id":"glo1","name":"Glo-in-the-Dark","price":1.05,"age":"mid","blurb":tr('cables.cornwall_to_lagos_down_the_west'),"pairs":[["bde","lag",[[-5.2,50.6],[-11,45],[-15,30],[-19,15],[-12,4],[2,4.5],[3.4,6]]],["acc","lag",[[-0.2,5.1],[3.2,5.8]]]]}, + {"id":"pasdc","name":"Pas de Câble","price":0.6,"age":"new","df":true,"blurb":tr('cables.another_hop_across_the_channel_with'),"pairs":[["lon","par",[[1.3,51.0],[1.7,50.7]]]]}, + {"id":"tampn","name":"Oil Rig Wi-Fi","price":0.9,"age":"mid","blurb":tr('cables.stavanger_to_the_netherlands_and'),"pairs":[["svg","ams",[[5.3,58.6],[4.5,56],[4.2,53.5],[4.6,52.6]]],["svg","lon",[[5.4,59.15],[2.47,58.19],[3.2,56.55],[2.6,54],[1.9,52.5]]]]}, + {"id":"medusa","name":"Medusa Stare","price":0.85,"age":"new","blurb":tr('cables.lisbon_to_barcelona_and_marseille'),"pairs":[["lis","bcn",[[-9.6,37.9],[-8.9,36.6],[-5.6,35.9],[-2,36.4],[0.5,38.5],[2.6,41.1]]],["bcn","mrs",[[2.8,41.3],[3.8,42.4],[5,43]]],["lis","cas",[[-9.6,37.9],[-12,34],[-8.2,33.9]]],["mrs","alg",[[5,42.8],[4.5,40],[3,37.2]]],["alg","tun",[[3,37.2],[10.6,37.4]]]]}, + {"id":"nuvem","name":"Nuvem-ber Rain","price":0.85,"age":"new","blurb":tr('cables.portugal_to_the_us_southeast_via'),"pairs":[["lis","atn",[[-9.6,37.9],[-30,35],[-64.8,32.3],[-78.9,33.7]]],["atn","bda",[[-78.9,33.7],[-72,33.2]]],["bda","lis",[[-50,34.5],[-30,35],[-9.6,37.9]]]]}, + {"id":"blue","name":"Feeling Blue","price":0.85,"age":"new","blurb":tr('cables.genoa_to_sicily_and_on_to'),"pairs":[["nic","jer",[[33,34.4],[34.4,32.3]]],["ath","nic",[[24.1,37.4],[26.2,35.5],[30,34.85],[32.4,34.7]]],["mil","pmo",[[9.25,43.75]]],["pmo","ath",[[12,38],[15,36],[23,36]]]]}, + {"id":"cannoli","name":"Sicilian Spaghetti Junction","price":0.9,"age":"mid","blurb":tr('cables.palermo_to_marseille_and_alexandria'),"pairs":[["pmo","mrs",[[9,38.25],[5.25,42.75]]],["pmo","cai",[[13.6,37.8],[15.5,35.6],[22,33.4],[29.9,31.4]]]]}, + {"id":"ouzo","name":"Ouzo Express","price":0.9,"age":"new","blurb":tr('cables.athens_to_alexandria_and_up_the'),"pairs":[["ath","cai",[[24,37.5],[25.2,35.5],[28,33],[29.9,31.4]]],["ath","ist",[[24.3,38.5],[25.6,39.9],[26.5,40.3],[28.2,40.8]]]]}, + {"id":"tea","name":"Boston Tea Party Line","price":0.9,"age":"mid","blurb":tr('cables.boston_to_dublin_nobody_has_thrown'),"pairs":[["bos","dub",[[-65.25,43],[-26,51],[-8.5,51],[-5.75,52.25],[-5.5,53.25]]]]}, + {"id":"clementine","name":"Clementine","price":0.6,"age":"new","df":true,"blurb":tr('cables.a_small_sweet_cable_from_broadstairs'),"pairs":[["lon","oos",[[1.44,51.36],[2.92,51.23]]]]}, + {"id":"seaus","name":"SEA-US Later","price":1.0,"age":"mid","blurb":tr('cables.los_angeles_to_hawaii_guam_and'),"pairs":[["lax","hnl",[[-119,33.5],[-140,27],[-157.6,21.6]]],["hnl","gum",[[-158.3,21.2],[-180,18],[-200,15],[-214.6,13.5]]],["gum","dvo",[[144,13.7],[135,10.5],[128,6.8],[126.4,5.7],[125.85,6.2],[125.7,6.75]]],["gum","ror",[[144.5,13.1],[139,9.5],[134.8,7.5]]]]}, + {"id":"aag","name":"Asia-America Gateaux","price":1.25,"age":"old","blurb":tr('cables.california_to_hong_kong_via_hawaii'),"pairs":[["bwn","sin",[[113.5,4.8],[109,2.8],[105,1.6]]],["sjc","hnl",[[-122.8,35],[-140,27.5],[-158.2,21.4]]],["hnl","gum",[[-158.4,21.5],[-180,19],[-200,16],[-214.4,13.7]]],["gum","hkg",[[144.5,14],[130,17.5],[121,20],[115,21.6],[114.3,22.2]]]]}, + {"id":"echo","name":"Echo-Chamber","price":0.85,"age":"new","blurb":tr('cables.california_to_singapore_via_guam'),"pairs":[["sjc","gum",[[-125,38],[-150,30],[-180,21],[-214.8,14]]],["gum","sin",[[137.45,12.58],[125,10.25],[123.75,9],[122,9],[108,5],[104.25,1.25]]]]}, + {"id":"hantru","name":"HANTRU-ly Yours","price":1.3,"age":"mid","blurb":tr('cables.guam_to_the_marshall_islands_with'),"pairs":[["pni","gum",[[155,9],[150,11.5],[146,13.2]]],["pni","maj",[[162,6.5],[168,7]]],["gum","maj",[[145,13.3],[158,7],[167,8.5],[171.2,7.2]]]]}, + {"id":"coral","name":"Coral Sea Shanty","price":1.0,"age":"new","blurb":tr('cables.sydney_to_papua_new_guinea_and'),"pairs":[["syd","pom",[[153,-32.75],[154.25,-29.25],[153.75,-26]]],["syd","hir",[[152,-33.5],[156.5,-25],[160.5,-14],[160,-9.6]]]]}, + {"id":"gond","name":"Gondwanna-Be","price":1.1,"age":"mid","blurb":tr('cables.sydney_to_noumea_wishes_it_were'),"pairs":[["syd","nou",[[152,-33.5],[158,-28],[164,-23.5],[166.2,-22.5]]]]}, + {"id":"tonga","name":"Tonga Twister","price":1.3,"age":"mid","blurb":tr('cables.fiji_to_tonga_the_only_way'),"pairs":[["suv","tbu",[[178.8,-18.5],[181.5,-20],[184.6,-21]]]]}, + {"id":"tui","name":"Tui-Some-More","price":1.1,"age":"new","blurb":tr('cables.fiji_to_samoa_always_room_for'),"pairs":[["suv","apw",[[179,-18],[183,-15.5],[188,-13.95]]]]}, + {"id":"ashc","name":"ASH-tray","price":1.4,"age":"old","blurb":tr('cables.american_samoa_to_hawaii_and_samoa'),"pairs":[["ppg","hnl",[[-170.5,-13.9],[-166,0],[-158.1,20.9]]],["ppg","apw",[[-170.9,-14.1],[-171.6,-13.9]]]]}, + {"id":"hono","name":"Hono-tuna","price":1.2,"age":"mid","blurb":tr('cables.tahiti_to_hawaii_trolling_for'),"pairs":[["ppt","hnl",[[-149.7,-17.2],[-153,0],[-156.5,19.5],[-157.7,21.1]]]]}, + {"id":"mana","name":"Mana-tea","price":1.1,"age":"new","blurb":tr('cables.samoa_to_tahiti_by_way_of'),"pairs":[["apw","ppt",[[-171.5,-14.2],[-165,-18],[-159.8,-21.2],[-152,-18.5],[-149.8,-17.6]]]]}, + {"id":"scxn","name":"Southern Cross-ed Fingers NEXT","price":0.95,"age":"new","blurb":tr('cables.the_old_workhorse_s_younger_sibling'),"pairs":[["lax","suv",[[-119,33],[-140,15],[-165,-5],[-178,-15],[-181.2,-17.3]]],["suv","syd",[[177.8,-18.6],[166,-25],[156,-31.5],[152,-33.9]]]]}, + {"id":"sol","name":"Sol Survivor","price":0.85,"age":"new","blurb":tr('cables.florida_to_northern_spain_via'),"pairs":[["mia","bda",[[-80,27],[-80.9,29.6],[-74,31.5]]],["bda","pdl",[[-50,35.5],[-35,37.5]]],["pdl","bio",[[-17.64,41.25],[-7.75,44.25],[-4.25,44],[-3.2,43.55]]]]}, + {"id":"atl2","name":"Atlantis-2: The Sequel","price":1.4,"age":"old","blurb":tr('cables.argentina_to_portugal_via_brazil'),"pairs":[["bue","for",[[-58.25,-34.5],[-58,-34.75],[-57.75,-34.75],[-57.5,-35],[-57,-35],[-56.75,-35.25],[-54.25,-35.5],[-50.91,-32.65],[-47.39,-29.35],[-44.1,-25.96],[-41,-22.5],[-38.25,-19.75],[-34.25,-7.75],[-34.25,-6.5],[-35,-5],[-35.75,-4.5],[-37.75,-3.75]]],["for","rai",[[-36,-1.5],[-28,8],[-24,14]]],["rai","dkr",[[-20,14.7]]],["dkr","tci",[[-18,17],[-17.5,24],[-16.6,27.9]]],["tci","lis",[[-15.5,31],[-11,36.5],[-9.2,38.3]]]]}, + {"id":"canl","name":"Canary in the Cable Mine","price":0.8,"age":"mid","blurb":tr('cables.tenerife_to_the_spanish_mainland_as'),"pairs":[["tci","mad",[[-14.5,30.5],[-9,35],[-6.1,36.3]]]]}, + {"id":"arcos","name":"ARC-ade Ring","price":1.2,"age":"old","blurb":tr('cables.a_ring_around_the_caribbean_from'),"pairs":[["mia","nas",[[-79.5,25.6]]],["nas","sdq",[[-75,23.5],[-71.5,20.6],[-68.3,19.2],[-68.6,18.2]]],["sdq","sju",[[-68.8,18.15],[-67.3,18.25]]],["sju","cur",[[-66.5,17.6],[-67.5,14.5],[-68.6,12.5]]],["cur","bog",[[-72,13],[-75.5,11.25]]],["pan","sjo",[[-79.5,9.7],[-82.5,10.2]]],["sjo","gua",[[-85.5,9.25],[-90.5,13.5]]]]}, + {"id":"am2","name":"Americas-Too","price":1.3,"age":"old","blurb":tr('cables.florida_to_brazil_down_the_island'),"pairs":[["mia","sju",[[-79.5,25.8],[-73,24],[-68,20.4],[-66.2,18.7]]],["sju","fdf",[[-65,18.4],[-62.5,17.2],[-61.3,15]]],["fdf","pos",[[-61.3,14.2],[-61.3,11.3]]],["pos","for",[[-60.5,11],[-55,8],[-48,3],[-41,-1.5]]],["sju","cur",[[-66.3,17.7],[-67.2,14.5],[-68.4,12.6]]],["cur","ccs",[[-68.5,11.6],[-67,10.7]]]]}, + {"id":"ecfs","name":"ECFS (Every Coconut Fully Spliced)","price":1.35,"age":"old","blurb":tr('cables.island_hops_down_the_lesser_antilles'),"pairs":[["sju","anu",[[-64.32,17.8]]],["anu","bas",[[-62.63,17.21]]],["bas","dom",[[-62.41,16.3]]],["dom","fdf",[[-61.58,14.95]]],["fdf","slu",[[-61.38,14.3]]],["slu","bgi",[[-60.66,13.55]]],["bgi","svd",[[-60.77,13.13]]],["svd","gnd",[[-61.84,12.61]]],["gnd","pos",[[-61.98,11.36]]],["sju","fdf",[[-64.8,18.2],[-62.3,17],[-61.2,15.1]]],["fdf","bgi",[[-60.6,14.2],[-59.8,13.3]]],["bgi","pos",[[-59.8,12.6],[-61,11]]]]}, + {"id":"scf","name":"Southern Cari-Bean","price":1.0,"age":"mid","blurb":tr('cables.newer_glass_along_the_same_island'),"pairs":[["sju","bas",[[-64.06,17.88]]],["bas","anu",[[-61.93,17.21]]],["anu","dom",[[-61.27,16.21]]],["dom","fdf",[[-60.88,14.95]]],["fdf","slu",[[-60.68,14.3]]],["slu","svd",[[-60.76,13.59]]],["svd","gnd",[[-61.13,12.61]]],["gnd","pos",[[-61.28,11.36]]],["sju","fdf",[[-65.2,18.1],[-62.7,16.9],[-61.4,15.1]]],["fdf","bgi",[[-60.7,14.1],[-59.9,13.2]]],["bgi","pos",[[-59.9,12.5],[-61.1,11.1]]]]}, + {"id":"alba","name":"ALBA-tross","price":1.1,"age":"mid","blurb":tr('cables.cuba_s_only_cable_laid_from'),"pairs":[["ccs","hav",[[-75,18.5],[-73.75,20.25],[-77.25,23.75],[-81.75,23.75]]],["hav","kin",[[-82.5,22.2],[-80,21.3],[-77.5,19.5],[-76.9,18.4]]]]}, + {"id":"cfx","name":"Columbus’ Fixer-1","price":1.0,"age":"mid","blurb":tr('cables.florida_to_jamaica_and_colombia_along'),"pairs":[["mia","kin",[[-79.5,25],[-78,23],[-74.5,20.4],[-75.5,18.2],[-76.6,17.8]]],["kin","bog",[[-76.5,17.6],[-76,13],[-75.6,10.6]]]]}, + {"id":"fibr","name":"Fibra-Linky","price":1.0,"age":"mid","blurb":tr('cables.a_short_cable_from_jamaica_to'),"pairs":[["kin","sdq",[[-76.3,17.8],[-73,17.5],[-71,17.8],[-70,18.3]]]]}, + {"id":"bics","name":"Conch-nected","price":0.9,"age":"mid","blurb":tr('cables.nassau_to_florida_the_shortest_hop'),"pairs":[["mia","nas",[[-79.3,25.4]]]]}, + {"id":"amx","name":"AMX-1 Mexican Wave","price":0.95,"age":"mid","blurb":tr('cables.from_florida_round_the_caribbean_to'),"pairs":[["mia","sju",[[-79.6,25.9],[-73.2,24.2],[-68.2,20.6],[-66.4,18.8]]],["sju","sdq",[[-67.2,18.1],[-68.9,18.1]]],["sdq","bog",[[-70,18.1],[-73,13.5],[-75,11]]],["bog","for",[[-75.75,11],[-73,13],[-53,11],[-40,-1.5]]]]}, + {"id":"lion","name":"LION-hearted","price":1.05,"age":"mid","blurb":tr('cables.madagascar_reunion_and_mauritius_tied'),"pairs":[["tnr","run",[[49.6,-18.2],[52,-19.5],[55,-20.6]]],["run","mru",[[56.5,-20.6]]],["tnr","mba",[[49.75,-18.75],[51,-16],[50.5,-13]]]]}, + {"id":"metiss","name":"METISS-ing Link","price":0.95,"age":"new","blurb":tr('cables.the_newest_cable_from_south_africa'),"pairs":[["dur","tnr",[[31.25,-30],[31.5,-30],[32.05,-29.88],[32.59,-29.76],[33.13,-29.64],[33.67,-29.52],[34.21,-29.39],[34.75,-29.26],[35.29,-29.13],[35.83,-29],[36.36,-28.86],[36.89,-28.73],[37.43,-28.59],[37.96,-28.45],[38.48,-28.3],[39.01,-28.16],[39.54,-28.01],[40.06,-27.86],[40.59,-27.71],[41.11,-27.56],[41.63,-27.4],[42.15,-27.25],[42.66,-27.09],[43.18,-26.93],[43.69,-26.76],[44.21,-26.6],[44.72,-26.43],[45.23,-26.27],[45.74,-26.1],[46.24,-25.92],[46.75,-25.75],[47.08,-25.43],[47.4,-25.11],[47.72,-24.79],[48.05,-24.47],[48.37,-24.15],[48.68,-23.82],[49,-23.5],[49,-22.67],[49,-21.83],[49,-21],[48.75,-20.75],[48.75,-20.5],[48.75,-20.25],[48.13,-19.56]]],["tnr","run",[[48,-25.5],[52,-23],[55,-21.3]]],["run","mru",[[56.6,-20.8]]]]}, + {"id":"seas","name":"SEAS-shells","price":1.1,"age":"mid","blurb":tr('cables.the_seychelles_first_cable_to_tanzania'),"pairs":[["sez","dar",[[54,-5.5],[47,-6.5],[40.3,-6.8]]]]}, + {"id":"akorn","name":"A-CORN-y","price":1.1,"age":"mid","blurb":tr('cables.anchorage_to_oregon_under_the_gulf'),"pairs":[["anc","sea",[[-151.25,61],[-152,60.25],[-152,59],[-151,58],[-125.75,48.5],[-122.75,48.25]]]]}, + {"id":"auf","name":"Alaska United-We-Stand","price":1.25,"age":"old","blurb":tr('cables.alaska_s_old_pair_of_cables'),"pairs":[["anc","jnu",[[-151.25,61],[-152,60.25],[-152,59],[-151,58],[-135,58]]],["jnu","sea",[[-134.25,55.75],[-127,49],[-125.75,48.5],[-122.75,48.25]]],["anc","sea",[[-151.25,61],[-152,60.25],[-152,59],[-151,58],[-125.75,48.5],[-122.75,48.25]]]]}, + {"id":"aleu","name":"Aleu-Shun Fiber","price":1.0,"age":"new","blurb":tr('cables.kodiak_to_the_aleutians_finished_in'),"pairs":[["anc","dut",[[-151.25,61],[-152,60.25],[-151.75,57.75],[-153,56.5]]]]}, + {"id":"qtl","name":"Quintillion Bits","price":1.4,"age":"new","fragile":true,"blurb":tr('cables.the_first_subsea_fiber_in_the'),"pairs":[["ome","brw",[[-167.5,64.75],[-168.25,65.5],[-168.25,67.25],[-164.75,71]]],["brw","anc",[[-154,70.6],[-148.4,70.25],[-148.7,68],[-147.7,64.8],[-149.1,63]]]]}, + {"id":"topaz","name":"Top-Hat","price":0.9,"age":"new","blurb":tr('cables.from_vancouver_island_straight_to_japan'),"pairs":[["van","tok",[[-123.25,48.25],[-124,48.25],[-124.25,48.5],[-125.75,48.5],[-136.18,49.88],[-142.34,50.23],[-148.55,50.25],[-155.49,49.88],[-163,49],[-174.36,48.79],[-182.51,47.93],[-190.99,46.37],[-199.55,44.01],[-204.45,42.27],[-209.64,40.07],[-214.49,37.65],[-219.5,34.75],[-220,34.75],[-220.25,35]]]]}, + {"id":"ccoast","name":"Connected Coast-er","price":0.8,"age":"new","blurb":tr('cables.fiber_along_british_columbia_s_coast'),"pairs":[["prr","van",[[-131,53.75],[-127,49],[-123.25,48.25]]]]}, + {"id":"skm","name":"SKM (Salmon, Kamchatka, More salmon)","price":1.2,"age":"mid","blurb":tr('cables.sakhalin_to_kamchatka_and_magadan_laid'),"pairs":[["uus","pkc",[[156.75,50.25],[159,52]]],["uus","gdx",[[144.75,48.5]]]]}, + {"id":"rjcn","name":"RJCN (Rather Jolly Cable to Niigata)","price":1.0,"age":"mid","blurb":tr('cables.nakhodka_to_niigata_across_the_sea'),"pairs":[["vvo","tok",[[133,42.6],[136,40],[138.2,37.3]]]]}, + {"id":"hscs","name":"Hokkaido Hop","price":1.0,"age":"mid","blurb":tr('cables.a_short_hop_from_sakhalin_to'),"pairs":[["uus","tok",[[143.5,46.75],[146,43.5],[141.5,35.75],[140.5,34.75],[139.75,35]]]]}, + {"id":"chuk","name":"Chukchi Chuckle Line","price":1.3,"age":"new","blurb":tr('cables.petropavlovsk_to_anadyr_finished_in'),"pairs":[["pkc","dyr",[[160.25,53],[168.84,57.88],[179,61.75],[180.25,62.75],[178.5,64.5]]]]}, + {"id":"ecl","name":"EC-Link-ed","price":1.0,"age":"mid","blurb":tr('cables.cura_ao_to_trinidad_along_the'),"pairs":[["cur","pos",[[-68.5,12.4],[-64,12],[-61.7,10.9]]]]}, + {"id":"havsil","name":"HAVSIL-ent Night","price":0.85,"age":"new","blurb":tr('cables.kristiansand_to_jutland_a_quiet_short'),"pairs":[["krs","ebj",[[7.5,56]]]]}, + {"id":"skagen","name":"Skagen-Dazs","price":0.85,"age":"new","blurb":tr('cables.oslo_fjord_to_the_tip_of'),"pairs":[["osl","ebj",[[10.5,58.75],[7.5,56.5],[7.75,55.5]]]]}, + {"id":"norfest","name":"Nor-Feast","price":0.8,"age":"new","blurb":tr('cables.a_buffet_of_landings_down_norway'),"pairs":[["svg","krs",[[5,59],[6,58]]],["krs","osl",[[10.25,58.5]]]]}, + {"id":"e4","anchor":true,"name":"E4-ward Thinking","price":0.75,"age":"new","blurb":tr('cables.germany_to_bornholm_and_copenhagen_then'),"pairs":[["ber","cph",[[13.25,54.75]]],["cph","sto",[[13,55.25],[14.5,55.25],[16.25,55.75],[18.5,58.75]]]]}, + {"id":"elight","anchor":true,"name":"Eastern Light-weight","price":0.8,"age":"mid","blurb":tr('cables.stockholm_to_helsinki_across_the_archipelago'),"pairs":[["sto","hel",[[23,59]]]]}, + {"id":"elisa","anchor":true,"name":"Elisa-bet","price":0.7,"age":"mid","blurb":tr('cables.helsinki_to_tallinn_and_cut_by'),"pairs":[["hel","tll",[[24.7,59.53]]]]}, + {"id":"lvse","anchor":true,"name":"Ventspils Venting","price":0.85,"age":"mid","blurb":tr('cables.latvia_to_gotland_and_stockholm_cut'),"pairs":[["rix","sto",[[22,59]]]]}, + {"id":"bcs","anchor":true,"name":"BCS (Baltic Cable Snapped)","price":1.1,"age":"old","blurb":tr('cables.lithuania_to_gotland_since_1997_and'),"pairs":[["rix","sto",[[22,59]]]]}, + {"id":"sjc2","name":"SJC2: Electric Boogaloo","price":0.8,"age":"new","blurb":tr('cables.the_sequel_singapore_to_hong_kong'),"pairs":[["sin","hkg",[[104.75,1.75],[109.75,11.5]]],["hkg","tpe",[[116.5,22.25],[120.75,25.25]]],["tpe","osa",[[134.25,32.75]]],["osa","icn",[[134.5,33],[130.5,30.5],[125.75,34.5],[125.75,36.5]]]]}, + {"id":"adc","name":"ADC (A Direct Cable, Mostly)","price":0.85,"age":"new","blurb":tr('cables.singapore_thailand_hong_kong_manila_and'),"pairs":[["sin","bkk",[[104.75,1.75],[104.75,2.75],[100.5,12.75]]],["sin","hkg",[[104.75,1.75],[109.75,11.5]]],["hkg","mnl",[[120,14.25]]],["hkg","tok",[[116.5,22.25],[127,30],[130.75,30.5],[139,34.5]]]]}, + {"id":"ase","name":"ASE-y Does It","price":0.95,"age":"mid","blurb":tr('cables.japan_to_singapore_by_way_of'),"pairs":[["tok","mnl",[[139,34.5],[128.03,26.23],[119.5,18],[119.25,15.25],[120,14.25]]],["mnl","hkg",[[120,14.25]]],["hkg","sin",[[109.75,11.5],[104.75,1.75]]],["sin","kul",[[102.75,1.25]]]]}, + {"id":"apcn2","name":"APCN-2 Fast 2 Furious","price":1.2,"age":"old","blurb":tr('cables.a_ring_round_east_asia_from'),"pairs":[["sin","kul",[[102.75,1.25]]],["kul","hkg",[[101.75,2.5],[102.5,1.5],[103.5,0.75],[103.75,0.75],[104.75,1.75],[109.75,11.5],[113.75,22]]],["hkg","mnl",[[120,14.25]]],["mnl","tpe",[[120,14.25],[119.25,15.25],[119.5,24],[120.75,25.25]]],["tpe","sha",[[122.5,29.25],[122.25,30.75]]],["sha","icn",[[126,37.25]]],["icn","tok",[[125.75,36.5],[125.75,34.5],[130.5,30.5],[139,34.5]]],["tok","tpe",[[139,34],[130.37,30.02]]]]}, + {"id":"c2c","name":"EAC-C2C (Every Asian City, Coast to Coast)","price":1,"age":"mid","blurb":tr('cables.another_ring_round_east_asia_this'),"pairs":[["sin","hkg",[[104.75,1.75],[109.75,11.5]]],["hkg","mnl",[[120,14.25]]],["hkg","tpe",[[116.5,22.25],[120.75,25.25]]],["tpe","sha",[[122.5,29.25],[122.25,30.75]]],["sha","icn",[[126,37.25]]],["icn","tok",[[125.75,36.5],[125.75,34.5],[130.5,30.5],[139,34.5]]],["tok","tpe",[[139,34],[130.37,30.02]]],["mnl","sin",[[112.4,7.97]]]]}, + {"id":"flag","name":"FLAG-pole Europe-Asia","price":1.35,"age":"old","blurb":tr('cables.cornwall_to_japan_the_long_way'),"pairs":[["bde","pmo",[[-5,51],[-6,50],[-10,43],[-10,38],[-8,36],[-2,36.25],[6.25,38.25]]],["pmo","cai",[[12,38],[13.25,36.75],[29.5,31.5]]],["cai","jed",[[32.5,29.75],[33,28.75]]],["jed","fuj",[[39,21.5],[38.75,21.25],[38.75,21],[38.99,20.56],[39.24,20.13],[39.48,19.69],[39.72,19.26],[39.95,18.82],[40.19,18.38],[40.43,17.95],[40.66,17.51],[40.89,17.07],[41.13,16.63],[41.36,16.19],[41.59,15.76],[41.82,15.32],[42.05,14.88],[42.27,14.44],[42.5,14],[42.75,13.75],[43,13.5],[43.25,13.25],[43.25,13],[43.25,12.75],[43.5,12.5],[43.75,12.25],[44,12],[44.5,12],[45.5,12.38],[46.5,12.75],[47.5,13.13],[48.5,13.5],[49.5,13.88],[50.5,14.25],[50.95,14.48],[51.39,14.71],[51.84,14.93],[52.29,15.16],[52.74,15.39],[53.19,15.61],[53.64,15.83],[54.09,16.06],[54.55,16.28],[55,16.5],[55.41,16.79],[55.83,17.09],[56.24,17.38],[56.66,17.67],[57.08,17.96],[57.5,18.25],[58.25,19],[58.5,19.39],[58.74,19.78],[58.99,20.17],[59.24,20.56],[59.49,20.95],[59.74,21.34],[59.99,21.72],[60.24,22.11],[60.5,22.5],[59.75,23.25],[59,24],[58,24.5],[57,25],[56.75,25],[56.5,25]]],["fuj","bom",[[56.5,25],[56.75,25],[57,25],[57.5,24.84],[58.01,24.67],[58.51,24.5],[59.01,24.33],[59.51,24.16],[60.01,23.99],[60.5,23.82],[61,23.64],[61.49,23.46],[61.99,23.29],[62.48,23.11],[62.97,22.92],[63.46,22.74],[63.94,22.56],[64.43,22.37],[64.92,22.18],[65.4,21.99],[65.88,21.8],[66.36,21.61],[66.84,21.42],[67.32,21.22],[67.8,21.03],[68.27,20.83],[68.75,20.63],[69.22,20.43],[69.69,20.23],[70.16,20.03],[70.63,19.83],[71.1,19.62],[71.57,19.42],[72.04,19.21],[72.5,19],[72.75,19]]],["bom","kul",[[72.75,19],[72.5,19],[72.25,18.5],[72.38,18.04],[72.5,17.58],[72.63,17.13],[72.75,16.67],[72.88,16.21],[73,15.75],[73.21,15.3],[73.41,14.85],[73.61,14.4],[73.82,13.95],[74.02,13.5],[74.22,13.05],[74.42,12.6],[74.62,12.15],[74.82,11.7],[75.02,11.25],[75.21,10.8],[75.41,10.35],[75.61,9.9],[75.8,9.45],[76,9],[76.5,8.5],[77,8],[78,7],[78.36,6.75],[78.72,6.5],[79.07,6.25],[79.43,6],[79.79,5.75],[80.14,5.5],[80.5,5.25],[81,5.28],[81.5,5.31],[82,5.34],[82.5,5.37],[83,5.4],[83.5,5.43],[84,5.46],[84.5,5.49],[85,5.52],[85.5,5.55],[86,5.58],[86.5,5.6],[87,5.63],[87.5,5.66],[88,5.68],[88.5,5.71],[89,5.73],[89.5,5.76],[90,5.78],[90.5,5.81],[91,5.83],[91.5,5.85],[92,5.87],[92.5,5.9],[93,5.92],[93.5,5.94],[94,5.96],[94.5,5.98],[95,6],[95.5,6],[96,6],[96.5,6],[97,6],[97.5,6],[98,6],[98.35,5.66],[98.69,5.31],[99.03,4.97],[99.38,4.63],[99.72,4.28],[100.06,3.94],[100.41,3.59],[100.75,3.25],[101,3.25],[101.25,3.25]]],["kul","hkg",[[101.75,2.5],[102.5,1.5],[103.5,0.75],[103.75,0.75],[104.75,1.75],[109.75,11.5],[113.75,22]]],["hkg","sha",[[116.5,22.25],[120.25,25.5],[122.5,29.25],[122,31]]],["sha","icn",[[126,37.25]]],["icn","tok",[[125.75,36.5],[125.75,34.5],[130.5,30.5],[139,34.5]]]]}, + {"id":"flagnal","name":"FLAG Loop-de-Loop","price":1,"age":"mid","blurb":tr('cables.hong_kong_taipei_seoul_and_tokyo_in'),"pairs":[["hkg","tpe",[[116.5,22.25],[120.75,25.25]]],["tpe","icn",[[122.5,29.25],[122.5,32.25],[126,37.25]]],["icn","tok",[[125.75,36.5],[125.75,34.5],[130.5,30.5],[139,34.5]]]]}, + {"id":"smw5","name":"SEE-ME-WAVE 5","price":0.95,"age":"new","blurb":tr('cables.marseille_to_singapore_with_a_stop'),"pairs":[["jed","sah",[[38.8,21],[40.8,17.6],[42.7,15]]],["mrs","pmo",[[5.25,42.75],[9,38.25]]],["pmo","cai",[[12,38],[13.25,36.75],[29.5,31.5]]],["cai","jed",[[32.5,29.75],[33,28.75]]],["jed","jib",[[38.75,21],[43,13],[44,12]]],["jib","mct",[[43.25,11.75],[43.5,11.75],[43.97,11.91],[44.45,12.08],[44.92,12.24],[45.4,12.4],[45.88,12.56],[46.35,12.72],[46.83,12.88],[47.31,13.03],[47.79,13.19],[48.27,13.35],[48.75,13.5],[49.21,13.72],[49.67,13.93],[50.14,14.15],[50.6,14.36],[51.07,14.58],[51.53,14.79],[52,15],[52.43,15.22],[52.85,15.43],[53.28,15.65],[53.71,15.86],[54.14,16.08],[54.57,16.29],[55,16.5],[55.92,17.17],[56.83,17.83],[57.75,18.5],[58.5,19.25],[58.75,19.67],[58.99,20.08],[59.24,20.5],[59.49,20.92],[59.75,21.33],[60,21.75],[60,22],[60,23],[59,23.75],[58.75,23.75],[58.5,23.75]]],["mct","fuj",[[58.25,24.25]]],["mct","khi",[[58.75,24]]],["khi","cbo",[[66.75,24.75],[66.75,24.25],[68.95,20.9],[71.05,17.52],[73.32,13.7],[76,9],[78,7],[79.75,7]]],["cbo","dac",[[79.25,7.5],[79,8],[79,9],[79.5,9.25],[79.5,9.5],[89.5,21.5],[89.5,22]]],["cbo","kul",[[79.5,6.25],[80.5,5.25],[98,6],[100.75,3.25]]],["kul","sin",[[102.75,1.25]]]]}, + {"id":"unity","name":"Unity-corn","price":1,"age":"mid","blurb":tr('cables.tokyo_to_los_angeles_built_by'),"pairs":[["tok","lax",[[139.75,35],[140.5,34.75],[150.01,37.72],[161.78,39.95],[178.71,40.93],[180.02,40.91],[189.14,40.3],[198,39],[207.61,39.2],[217.79,38.54],[229.47,36.65],[241,33.5]]]]}, + {"id":"tgn","name":"Tata’s Got Network","price":1,"age":"mid","blurb":tr('cables.singapore_to_tokyo_via_vietnam_and'),"pairs":[["sin","sgn",[[104.75,1.75],[107,9]]],["sgn","hkg",[[108,10],[109.75,11.5]]],["hkg","tok",[[116.5,22.25],[127,30],[130.75,30.5],[139,34.5]]]]}, + {"id":"tpe2","name":"TPE (Totally Pacific Express)","price":1,"age":"mid","blurb":tr('cables.seattle_straight_to_shanghai_seoul_and'),"pairs":[["sea","sha",[[-122.75,48.25],[-125.75,48.5],[-141.15,52.06],[-150.82,53.1],[-159.95,53.33],[-169.84,52.8],[-179.32,51.47],[-180.08,51.33],[-186,50],[-218.5,45.75],[-231,34.5]]],["sea","icn",[[-122.75,48.25],[-124,48.25],[-124.25,48.5],[-125.75,48.5],[-135.32,49.97],[-142.99,50.55],[-149.99,50.62],[-217.5,46],[-217.75,45.75],[-218.5,45.75],[-231,34.5],[-233,34],[-234,34],[-234.25,34.5],[-234.25,36.5]]],["sea","tpe",[[-122.75,48.25],[-125.75,48.5],[-141.15,52.06],[-150.82,53.1],[-159.95,53.33],[-169.84,52.8],[-179.32,51.47],[-180.08,51.33],[-186,50],[-218.5,45.75],[-224.75,40.02]]]]}, + {"id":"hkg2","name":"Hong Kong–Guam Gong","price":0.9,"age":"new","blurb":tr('cables.hong_kong_to_guam_where_the'),"pairs":[["hkg","gum",[[130.5,18.2]]]]}, + {"id":"mist","name":"MIST-ery Tour","price":0.85,"age":"new","blurb":tr('cables.mumbai_and_chennai_to_malaysia_and'),"pairs":[["bom","maa",[[72.75,19],[72.5,19],[72.25,18.5],[72.38,18.04],[72.5,17.58],[72.63,17.13],[72.75,16.67],[72.88,16.21],[73,15.75],[73.21,15.3],[73.41,14.85],[73.61,14.4],[73.82,13.95],[74.02,13.5],[74.22,13.05],[74.42,12.6],[74.62,12.15],[74.82,11.7],[75.02,11.25],[75.21,10.8],[75.41,10.35],[75.61,9.9],[75.8,9.45],[76,9],[76.63,8.25],[77.25,7.5],[77.75,7.75],[78,8],[79,9],[79.25,9],[79.5,9.25],[79.5,9.5],[80.5,10.5],[80.58,11.25],[80.67,12],[80.75,12.75],[80.75,13],[80.5,13.25]]],["maa","kul",[[88,13],[100.75,3.25]]],["kul","sin",[[102.75,1.25]]]]}, + {"id":"iax","name":"IAX-cellent","price":0.85,"age":"new","blurb":tr('cables.mumbai_to_singapore_with_a_stop'),"pairs":[["bom","mle",[[72.75,19],[72.5,19],[72.25,18.5],[72.3,18.01],[72.34,17.52],[72.39,17.03],[72.43,16.53],[72.48,16.04],[72.52,15.55],[72.56,15.06],[72.61,14.57],[72.65,14.08],[72.7,13.59],[72.74,13.1],[72.78,12.6],[72.83,12.11],[72.87,11.62],[72.91,11.13],[72.95,10.64],[73,10.15],[73.04,9.66],[73.08,9.16],[73.12,8.67],[73.17,8.18],[73.21,7.69],[73.25,7.2],[73.29,6.71],[73.33,6.22],[73.38,5.72],[73.42,5.23],[73.46,4.74],[73.5,4.25]]],["mle","maa",[[78.75,8.5],[80.5,10.5],[80.75,12.75]]],["maa","kul",[[88,13],[100.75,3.25]]],["kul","sin",[[102.75,1.25]]]]}, + {"id":"tic","name":"TIC-Tac","price":1,"age":"mid","blurb":tr('cables.chennai_to_singapore_in_one_short'),"pairs":[["maa","sin",[[80.75,13.5],[82.61,12.7],[98,5.5],[102.75,1.25]]]]}, + {"id":"tw1","name":"TW1-light","price":1.1,"age":"mid","blurb":tr('cables.the_emirates_oman_and_pakistan_on'),"pairs":[["fuj","mct",[[58.25,24.25]]],["mct","khi",[[58.75,24]]]]}, + {"id":"mct1","name":"MCT (Malaysia, Cambodia, Tuk-tuks)","price":0.95,"age":"new","blurb":tr('cables.malaysia_to_thailand_round_the_gulf'),"pairs":[["kul","bkk",[[101.75,2.5],[102.5,1.5],[103.5,0.75],[103.75,0.75],[104.75,1.75],[104.75,2.75],[100.5,12.75]]]]}, + {"id":"kjcn","name":"KJCN (Kimchi-Japan Cable Network)","price":1,"age":"mid","blurb":tr('cables.busan_to_kyushu_the_shortest_way'),"pairs":[["icn","fuk",[[126,36.75],[126,34],[130,34]]]]}, + {"id":"pdscn","name":"Pan de Sal Cable Network","price":0.9,"age":"new","blurb":tr('cables.the_philippines_longest_domestic_cable_fresh'),"pairs":[["mnl","ceb",[[120.6,14.4],[120.45,13.95],[120.85,13.6],[121.9,12.9],[122.7,12.3],[123.6,11.6],[124.2,11.2],[124.15,10.5]]],["ceb","dvo",[[124.05,10.2],[124.1,9.6],[124.5,8.9],[124.62,8.55]]],["mnl","dvo",[[121.6,13.85],[122.1,13.2],[122.9,12.45],[123.75,11.7],[124.3,11.1],[124.25,10.3],[124.1,9.6],[124.5,8.9],[124.62,8.55]]]]}, + {"id":"dfon","name":"Philippines Long Distance Relationship","price":1.1,"age":"mid","blurb":tr('cables.the_incumbent_s_own_line_south'),"pairs":[["mnl","ceb",[[121.6,13.85],[122.1,13.2],[122.9,12.45],[123.75,11.7],[124.3,11.1],[124.2,10.45]]],["ceb","dvo",[[123.95,10.05],[124.4,9.5],[124.75,9.05]]]]}, + {"id":"vismin","name":"Diverge VisMin Express","price":0.9,"age":"new","blurb":tr('cables.the_upstart_s_own_cable_from'),"pairs":[["ceb","dvo",[[124.15,10.9],[124.25,10.2],[124.4,9.3],[124.65,8.6]]]]}, + {"id":"sgscs","name":"Sure-Guy Cable System","price":1.2,"age":"mid","blurb":tr('cables.trinidad_to_guyana_and_suriname_along'),"pairs":[["pos","geo",[[-61,11],[-59.5,9.5]]],["geo","pbm",[[-57.5,7.2],[-56,6.4]]]]}, + {"id":"dbo","name":"Deep Blue Phone","price":0.9,"age":"new","blurb":tr('cables.the_newest_glass_along_the_guianas'),"pairs":[["pos","geo",[[-60.7,11.2],[-59.2,9.7]]],["geo","pbm",[[-57.4,7.4],[-55.9,6.6]]]]}, + {"id":"xlnk","name":"X-Linked","price":1.1,"age":"new","blurb":tr('cables.guyana_straight_to_barbados_skipping'),"pairs":[["geo","bgi",[[-57.5,8.5],[-59,11.5]]]]}, + {"id":"fibl","name":"Fibra-Linguine","price":1.3,"age":"mid","blurb":tr('cables.haiti_to_jamaica_across_the_windward'),"pairs":[["pap","kin",[[-73,18.8],[-75,18.3]]]]}, + {"id":"bdsn","name":"Bahama-Drama Sub Net","price":1.3,"age":"mid","blurb":tr('cables.the_bahamas_island_chain_with_a'),"pairs":[["nas","pap",[[-76,24],[-73.6,21],[-72.8,19]]]]}, + {"id":"mlsc","name":"Sicily Shuttle","price":1.1,"age":"mid","blurb":tr('cables.malta_s_three_operators_each_lay'),"pairs":[["mla","pmo",[[14.2,36.05],[12.3,37.2],[12.7,38.25]]]]}, + {"id":"cadm","name":"Cad-Moss","price":1.2,"age":"old","blurb":tr('cables.cyprus_to_beirut_a_short_hop'),"pairs":[["nic","bey",[[33.9,34.7],[35.2,34]]]]}, + {"id":"ugar","name":"U-Got-It","price":1.3,"age":"old","blurb":tr('cables.cyprus_to_syria_s_one_port'),"pairs":[["nic","dam",[[34,34.9],[35.7,34.9]]]]}, + {"id":"emc","name":"East Micro-Nation Cable","price":1.3,"age":"new","blurb":tr('cables.tarawa_nauru_and_pohnpei_on_one'),"pairs":[["trw","inu",[[171,0.8],[168.5,-0.1]]],["inu","pni",[[164,2.5],[160.5,5.6]]]]}, + {"id":"vaka","name":"Vaka-tion Cable","price":1.3,"age":"new","blurb":tr('cables.a_branch_down_to_funafuti_off'),"pairs":[["fun","suv",[[179.6,-12],[179,-16.5]]]]}, + {"id":"icn1","name":"Inter-Change-Purse","price":1.2,"age":"mid","blurb":tr('cables.port_vila_to_suva_the_cable'),"pairs":[["vli","suv",[[170.5,-18.3],[176.5,-18.5]]]]}, + {"id":"tlssc","name":"Timor-row Cable","price":1.2,"age":"new","blurb":tr('cables.timor_leste_s_first_cable_down'),"pairs":[["dil","drw",[[125.8,-8.9],[127.8,-10.5],[130,-12]]]]}, + {"id":"ceiba","name":"Ceiba-Siesta","price":1.3,"age":"mid","blurb":tr('cables.malabo_across_to_the_mainland_and'),"pairs":[["ssg","dla",[[9.1,3.9],[9.5,3.8]]]]} +]; +const CAB=Object.fromEntries(CABLES.map(c=>[c.id,c])); +const CABLE_PAIRS=CABLES.flatMap(c=>c.pairs.map(([a,b,mid])=>{const A=CITY[a],B=CITY[b];const near=(x,ref)=>x+W*Math.round((ref-x)/W); + const mp=mid.map(q=>proj(q[0],q[1]));const pts=[[near(A.x,mp[0][0]),A.y]].concat(mp,[[near(B.x,mp[mp.length-1][0]),B.y]]); + const ll=[[A.lon,A.lat]].concat(mid,[[B.lon,B.lat]]);let L=0;for(let i=1;iS.day&&[a,b].includes(S.ev.landban.city);if(ban)return [];const rl=S&&S.scn&&S.scn.rules,bp=rl&&rl.banPairs,bc=rl&&rl.banCities;return bp||bc?cablesFor(a,b).filter(c=>!(bp&&(bp.includes(c.cid+':'+c.a+'-'+c.b)||bp.includes(c.cid+':'+c.b+'-'+c.a)))&&!(bc&&(bc.includes(c.a)||bc.includes(c.b)))):cablesFor(a,b);} +function cablesFor(a,b){return CABLE_PAIRS.filter(c=>(c.a===a&&c.b===b)||(c.a===b&&c.b===a));} +function cablePair(cid,a,b){const c=CABLE_PAIRS.find(x=>x.cid===cid&&((x.a===a&&x.b===b)||(x.a===b&&x.b===a)));if(!c)return null;return c.a===a?c:{...c,pts:c.pts.slice().reverse()};} +const ALLC=CITIES.filter(c=>!c.cn&&!c.ru&&!c.ixOnly).map(c=>c.id); +/* City density: a small city (P under 60) does not sit within 300 km of a bigger city in the same country, unless it + is a cable landing or a capital (tests/regions.test.js enforces it). Cities retired by that rule are marked off: + they stay in the data so old saves keep their POPs there, but new games never see them. */ +const cityOn=id=>{const c=CITY[id];return !!c&&(!c.off||!!(S&&(S.pops[id]||S.ixp[id]!==undefined)));}; +// No customer of any kind calls from North Korea: sanctions, and the whole country moves well under 1 Gbps. +const bizCity=c=>CITY[c].cc!=='KP'; +const OFFC=ALLC.filter(c=>!CITY[c].off&&bizCity(c)); +const ruCity=c=>!!CITY[c].ru; +const cnCity=c=>!!CITY[c].cn; +const BIGC=['man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','ruh','jed','doh','kyv','mel','bne','osa','kul','bkk','sgn','khi','dac','waw','prg','vie','bud','buh','ist','rio','bue','scl','bog','lim','del','maa','blr','hyd','tpe','cpt','auh','ber','zrh','nbo','cai','jkt','mnl','per','akl','dub','lax','tor','mex','dxb','cph','icn','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mrs','mad','sto','bom','sin','hkg','tok','syd','jnb','lag','lys']; +const MIDC=['man','bcn','mil','lis','atn','den','phx','bos','hou','mel','osa','kul','bkk','waw','vie','ist','rio','bue','scl','bog','del','maa','blr','tpe','auh','ber','zrh','jkt','mnl','dub','lax','tor','dxb','icn','sjc','ash','nyc','chi','dal','mia','lon','ams','fra','par','mad','sin','hkg','tok','syd','bom','sao','lys']; + diff --git a/src/game/20-world/70-cable-ships.js b/src/game/20-world/70-cable-ships.js new file mode 100644 index 0000000..c92f139 --- /dev/null +++ b/src/game/20-world/70-cable-ships.js @@ -0,0 +1,35 @@ +/* ---------- cable ships ---------- + About sixty ships in the world can lay or repair a subsea cable, and only a few dozen do mostly repairs. Cable owners + pay a yearly fee per km to a regional maintenance club, which keeps ships on standby in fixed ports, ready to sail + within a day. When every club ship is out, the next cut waits. A private charter jumps the queue, for millions. + The game keeps one or two ships at the real clubs' bases (Cornwall, Curaçao, Cape Town, the French Riviera, + Vancouver Island, Yokohama, Subic Bay, Singapore) and two private operators. Names are puns, as everywhere. */ +const SHIP_CLUBS={atl:{n:'Atlantic Splice Society'},med:{n:'Mediterranean Mending Club'},naz:{n:'North Pacific Patch Pact'},prv:{n:''},sea:{n:'SEA-IO Fix-It Club'},yok:{n:'Knot-a-hama Zone'}}; +const SHIPS=[ + {id:'buoy',n:'Buoy Oh Buoy',club:'naz',home:'van'}, + {id:'cguy',n:'Cable Guy',club:'atl',home:'cpt'}, + {id:'grap',n:'Grapnel Grandma',club:'sea',home:'mnl'}, + {id:'hook',n:'Hook, Line & Splicer',club:'sea',home:'sin'}, + {id:'joint',n:'Jointly Liable',club:'sea',home:'sin'}, + {id:'junk',n:'Junk Bond',club:'prv',home:'sha'}, + {id:'knot',n:'Knot Again',club:'atl',home:'bde'}, + {id:'loose',n:'Loose Ends',club:'yok',home:'tok'}, + {id:'mend',n:'Mend & Tonic',club:'med',home:'mrs'}, + {id:'reel',n:'Reel Deal',club:'atl',home:'cur'}, + {id:'saw',n:'Sea-Saw',club:'prv',home:'fuj'}, + {id:'splice',n:'Splice Girl',club:'atl',home:'bde'}, + {id:'spool',n:'Spool of Thought',club:'yok',home:'tok'}, + {id:'tea',n:'Spliced Tea',club:'med',home:'mrs'}, +]; +const SHIP=Object.fromEntries(SHIPS.map(s=>[s.id,s])); +// The installation fleet lays new cables (not the repair ships above): your own cable gets one, and a second can be booked. +const LAY_SHIPS=['HMS Unplugged','Knot Today','Lay-Z Susan','Long Haul Lass','Reel Estate','Seas the Day','Spoolhardy','Wet Willy']; +/* Real numbers, rounded: a cable ship cruises at 10 to 12 knots (about 500 km a day) and leaves within a day of the + call; a repair takes 3 to 5 days on site in shallow water and a week or two in deep water; most faults (anchors and + fishing gear) are in shallow water near the shore; some countries take weeks to grant a repair permit in their + waters. A repair costs $0.5M to $1M; jumping the queue with a private charter costs more. A lay ship lays a + transoceanic cable at roughly 150 km a day. */ +const SHIP_KMD=500,SHIP_MOB_D=1,SHIP_SHALLOW=300,LAY_KMD=150; +const SHIP_FIX=1000000,SHIP_FIX_KM=200,SHIP_MOB=3000000,LAY_DAY=150000; +// Days to get a repair permit in a country's waters, [fewest, most]; anywhere else the ship just goes. +const SHIP_PERMIT={CN:[14,28],EG:[7,21],ID:[21,42],IN:[21,42],VN:[14,28]}; diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js new file mode 100644 index 0000000..728d2a9 --- /dev/null +++ b/src/game/30-networks/10-networks.js @@ -0,0 +1,128 @@ +/* ================= NETWORKS ================= */ +const NETS=[ + {id:'lvl',name:'Level Tree',asn:3535,type:'t1',pol:'restrictive',share:.07,price:9,col:'#7B61FF',pops:['syd','hfx','bda','hnl','bde','man','edi','svg','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','cph','osl','tor','lax','mex','mtl','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','bio','rio','bue','scl','bog','lim','pan','waw','prg','vie','bud','buh','ist','kcy','cal','van','ott','bru','bet','ham','muc','cpq','gdl','mty','qro','was','mgm','lit','sac','hfd','dov','tlh','boi','spi','ind','dsm','top','fft','btr','aug','anp','lan','stp','jan','jef','hln','lnk','csn','con','ttn','saf','alb','rdu','bis','cmh','okc','sle','har','pvd','cae','pir','bna','aus','mpv','ric','olm','crw','msn','cys','lys'],ix:[],blurb:tr('networks.grew_from_a_seedling_into_a')}, + {id:'ntt',name:'Not That Telecom',asn:2941,type:'t1',pol:'restrictive',share:.06,price:8,col:'#4B3FC4',pops:['hnl','gum','man','mil','atn','den','bos','hou','phx','jkt','mnl','lax','dxb','icn','sea','sjc','dal','ash','nyc','lon','ams','fra','sin','hkg','tok','syd','tpe','del','maa','blr','hyd','osa','kul','bkk','sgn','kcy','dus','fuk'],ix:[],blurb:tr('networks.huge_in_asia_which_telecom_not')}, + {id:'tly',name:'Tell-Ya Carrier',asn:1229,type:'t1',pol:'restrictive',share:.05,price:8,col:'#9D4EDD',pops:['pdl','tci','svg','edi','man','mil','rom','pmo','ath','ber','osl','cph','hel','beg','sof','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','mrs','hkg','sin','tpe','tll','waw','vie','bud','buh','prg','kyv','van','bru','ham','muc','dus','krs','ebj','rix','zag','bts','got','mmx','hpa','lys'],ix:[],blurb:tr('networks.nordic_backbone_that_tells_you')}, + {id:'cog',name:'Cogentle',asn:714,type:'t1',pol:'restrictive',share:.04,price:3,col:'#B35CF0',pops:['hfx','bde','man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','hel','sof','beg','tor','lax','mex','cph','icn','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','bio','mrs','sto','sin','hkg','tok','rio','bue','scl','bog','lim','osa','waw','prg','vie','bud','buh','ist','kyv','kcy','van','ott','bru','oos','bet','ham','muc','dus','syd','per','was','sac','ind','stp','cmh','aus','bna','rdu','ric','okc','alb','pvd','hfd','har','msn','zag','vno','bts','lju','brn','pry','lys','tls','lil','bod','sxb'],ix:[],blurb:tr('networks.cheapest_transit_on_the_map_famously')}, + {id:'tat',name:'Ta-Ta Comms',asn:6543,type:'t1',pol:'restrictive',share:.04,price:9,col:'#6A4C93',pops:['tci','gum','mil','pmo','lis','nbo','cai','jkt','dxb','nyc','ash','lon','fra','mrs','lag','jnb','bom','sin','hkg','tok','del','maa','blr','hyd','cpt','fuj','auh','tpe','khi','dac','cbo','kul','bkk','jed','ruh','doh','jib','dar','mba','dkr'],ix:[],blurb:tr('networks.waves_goodbye_to_latency_across_the')}, + {id:'drz',name:'Drizzle Electric',asn:9369,type:'t2',pol:'open',share:.04,price:4,col:'#1E90FF',auIx:['syd','mel','bne','per'],pops:['man','chc','edi','svg','bde','bcn','mil','rom','pmo','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','nbo','akl','per','jkt','mnl','dub','rek','tor','mtl','lax','mex','sof','osl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','bio','hkg','sin','tok','syd','jnb','for','rio','bue','scl','lim','bog','pan','del','maa','blr','hyd','tpe','auh','cpt','mel','bne','osa','kul','bkk','sgn','khi','dac','cbo','waw','prg','vie','bud','buh','tll','ist','kyv','jed','ruh','doh','kcy','cal','van','ott','bru','oos','bet','ham','muc','ccs','lpb','alg','tun','cas','dkr','dus','was','sac','ind','stp','cmh','aus','bna','rdu','ric','okc','alb','dsm','msn','boi','yeg','ywg','yxe','yqb','tia','zag','vno','skp','bts','lju','pnh','wlg','lys'],ix:'ALL',blurb:tr('networks.will_peer_with_anyone_anywhere')}, + {id:'tng',name:'Tangerine Telecom',asn:5115,type:'t1',cc:['CD','CI','CM','EG','ES','FR','MA','MG','MQ','PL','RE','RO','SN','TN','MD','SK','JO','BF','CF','GN','GW','LR','ML','SL'],pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['tci','bcn','cai','nbo','dxb','fra','par','mrs','mad','bio','lon','ams','lag','jnb','waw','buh','dkr','abj','cas','tun','dla','fih','fdf','run','tnr','kiv','bts','amm','oua','cky','oxb','rob','bko','fna','bgf','ask','nsi','rba','lys','tls','lil','bod','sxb','rns','nte'],ix:['bcn','par','mrs','mad','lon','ams','lag','jnb','waw','dkr','abj','cas','tun','dla','fih','lys','tls','lil','sxb'],blurb:tr('networks.juicy_reach_into_europe_and_africa')}, + {id:'sgt',name:'SingTell',asn:7474,type:'t2',cc:'SG',pol:'selective',minIx:15,minPni:40,share:.03,price:7,col:'#00A6A6',pops:['jkt','mnl','per','akl','icn','sin','hkg','tok','syd','bom','tpe','maa','kul','bkk','sgn','mel','bne'],ix:['sin','hkg','tok','bom','tpe','maa','kul','bkk'],blurb:tr('networks.sings_your_packets_across_asia')}, + {id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',cc:['CD','CZ','DE','EG','ES','GB','GR','IE','MZ','NL','PT','QA','RO','TR','TZ','ZA','AL','LS'],pol:'paid',freeLv:7,paidFee:8000,share:.03,price:6,col:'#E63946',pops:['man','edi','mil','rom','lis','ath','nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa','ist','prg','bud','buh','doh','acc','dar','fih','mpm','dus','tia','msu','pry','dod'],ix:[],blurb:tr('networks.ended_free_peering_across_europe_and')}, + {id:'ctc',name:'China Telecomet',asn:4314,type:'t2',cc:'CN',pol:'restrictive',share:.02,price:22,premium:2.5,premAt:['hkg','mos'],premOnly:['mos'],cn:true,col:'#0B5CAD',pops:['pek','sha','hkg','sin','tok','lon','fra','nyc','sjc'],ix:[],blurb:tr('networks.the_biggest_network_in_china_its')}, + {id:'cun',name:'China Unicorn',asn:4837,type:'t2',cc:'CN',pol:'restrictive',share:.015,price:16,cn:true,col:'#D7000F',pops:['pek','sha','hkg','fra','sjc','lon'],ix:[],blurb:tr('networks.number_two_in_china_with_a')}, + {id:'cmb',name:'China Moble',asn:9880,type:'eye',cc:'CN',pol:'paid',freeLv:10,paidFee:12000,share:.01,cn:true,col:'#0085CA',pops:['pek','sha','hkg'],ix:[],blurb:tr('networks.the_largest_mobile_network_on_earth')}, + {id:'cmc',name:'Comecast',asn:7227,type:'eye',cc:'US',pol:'selective',minIx:10,minPni:30,share:.03,col:'#2C7A7B',pops:['atn','den','bos','hou','phx','slc','ash','nyc','chi','sjc','sea','mia'],ix:['atn','den','bos','ash','nyc','chi','sjc','sea'],blurb:tr('networks.huge_eyeball_network_come_for_the')}, + {id:'dtk',name:'Doitsche Telekomm',asn:3203,type:'t1',cc:'DE',pol:'paid',freeLv:6,paidFee:9000,share:.03,price:12,col:'#E20074',pops:['fra','ams','lon','ham','muc','dus'],ix:[],blurb:tr('networks.pink_eyeball_giant_peering_is')}, + {id:'nfx',name:'NetChill',asn:2906,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.15,cache:{name:'Open Couch',min:12},col:'#C8102E',auIx:['syd','mel'],pops:ALLC,ix:'ALL',blurb:tr('networks.streams_40_of_evening_traffic_hands')}, + {id:'ggl',name:'Goggle',asn:15961,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.13,cache:{name:'Goggle Global Cache',min:15},col:'#3A7BEA',auIx:['syd','mel'],pops:ALLC,ix:'ALL',blurb:tr('networks.search_video_and_goggles_mostly')}, + {id:'fbk',name:'Faceplant',asn:32943,type:'cdn',pol:'selective',minIx:5,minPni:25,share:.08,cache:{name:'Faceplant Node Thingy',min:10},col:'#3B5BDB',auIx:['syd','mel'],pops:BIGC,ix:'ALL',blurb:tr('networks.social_media_everyone_keeps_falling')}, + {id:'akm',name:'Akamaybe',asn:20490,type:'cdn',pol:'open',share:.07,cache:{name:'Akamaybe Box',min:6},col:'#0099CC',auIx:['syd','mel','bne','per','adl'],pops:ALLC,ix:'ALL',blurb:tr('networks.the_original_cdn_maybe_it_is')}, + {id:'cfl',name:'Crowdflare',asn:13353,type:'cdn',pol:'open',share:.05,cache:{name:'Rackstar',min:10},col:'#F48120',auIx:['syd','mel','bne','per','adl','cbr','hba'],pops:BIGC.concat(['hnl','gum','nou','ppt','dus']),ix:'ALL',blurb:tr('networks.shields_half_the_web_from_crowds')}, + {id:'amz',name:"Amazin' Web Services",asn:16590,type:'cdn',pol:'selective',minIx:8,minPni:30,share:.05,col:'#FF9900',auIx:['syd','mel','bne','per'],pops:MIDC.concat(['dus']),ix:'ALL',blurb:tr('networks.the_cloud_it_s_just_someone')}, + {id:'msf',name:'Microsnoft',asn:8705,type:'cdn',pol:'selective',minIx:5,minPni:25,share:.04,col:'#00A4EF',auIx:['syd','mel','bne','per'],pops:MIDC.concat(['dus']),ix:'ALL',blurb:tr('networks.updates_so_many_updates')}, + {id:'bdc',name:'BiteDance',asn:39669,type:'cdn',pol:'open',share:.03,col:'#111111',auIx:[],pops:MIDC.concat(['pek','sha','dus']),ix:'ALL',blurb:tr('networks.short_videos_very_long_traffic')}, + {id:'slw',name:'Slowly',asn:54311,type:'cdn',pol:'open',share:.02,col:'#E5383B',auIx:['syd','mel','bne','per','adl'],pops:MIDC,ix:'ALL',blurb:tr('networks.an_edge_cloud_that_is_despite')}, +]; +NETS.push( + {id:'tcs',name:'TenCents',asn:45900,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.02,cn:true,col:'#1AAD19',pops:['pek','sha','hkg','sin','tok','fra','sjc'],ix:['hkg','sin','tok','fra','sjc'],blurb:tr('networks.chat_games_and_payments_every')}, + {id:'abc',name:'AliBubble Cloud',asn:37936,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.015,cn:true,col:'#FF6A00',pops:['pek','sha','hkg','sin','tok','fra','sjc','syd'],ix:['hkg','sin','tok','fra','sjc'],blurb:tr('networks.shopping_festivals_that_melt_traffic')}, + {id:'byd',name:'Bye-du',asn:38635,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.01,cn:true,col:'#2932E1',pops:['pek','sha','hkg'],ix:['hkg'],blurb:tr('networks.search_maps_and_a_cheerful_goodbye')}); +NETS.push( + {id:'rtc',name:'Rostelecomedy',asn:12389,type:'t2',cc:'RU',pol:'selective',minIx:20,minPni:40,share:.01,price:6,col:'#7700FF',pops:['mos','hel','sto','fra','ams','mmk','vvo','uus','pkc','gdx','dyr','pvs','tik','dks'],ix:['mos','fra','ams'],blurb:tr('networks.the_national_carrier_and_the_longest')}, + {id:'ydx',name:'Yawndex',asn:13238,type:'cdn',pol:'open',share:.008,col:'#FC3F1D',pops:['mos','hel','fra','ams'],ix:['mos','hel','fra','ams'],blurb:tr('networks.search_taxis_and_maps_slightly')}, + {id:'vkl',name:'VKontakt-lens',asn:47541,type:'cdn',pol:'open',share:.006,col:'#0077FF',pops:['mos','hel'],ix:['mos','hel'],blurb:tr('networks.social_network_with_perfect_vision')}, + {id:'ets',name:'Etis-a-lot',asn:5384,type:'eye',cc:'AE',pol:'paid',freeLv:9,paidFee:8000,share:.006,col:'#719E19',pops:['dxb','mrs','lon','fra','sin','auh','fuj','doh'],ix:[],blurb:tr('networks.charges_a_lot_paid_peering_only')}, + {id:'tmx',name:'Tel-Mess',asn:8151,type:'eye',cc:'MX',pol:'paid',freeLv:8,paidFee:7000,share:.008,col:'#00A0DF',pops:['mex','dal','lax','mia','qro','mty','gdl'],ix:[],blurb:tr('networks.mexico_s_giant_paid_peering_only')}, + {id:'bcd',name:'Bell Canad-eh',asn:577,type:'eye',cc:'CA',pol:'selective',minIx:10,minPni:30,share:.01,col:'#00549A',pops:['hfx','tor','mtl','nyc','chi','ott','cal','van'],ix:['tor','mtl','ott'],blurb:tr('networks.polite_enormous_and_sorry_about_the')}); +NETS.push( + {id:'tsf',name:'Telkom-selfie',asn:7713,type:'eye',cc:'ID',pol:'selective',minIx:10,minPni:30,share:.01,col:'#E4002B',pops:['jkt','sin'],ix:['jkt','sin'],blurb:tr('networks.indonesia_s_mobile_giant_every')}, + {id:'pld',name:'PLDTea Time',asn:9299,type:'t2',cc:'PH',pol:'selective',up:['ntt','tat'],minIx:10,minPni:30,share:.008,price:7,col:'#D62027',pops:['mnl','ceb','dvo','hkg','sin'],ix:['hkg','mnl~3'],blurb:tr('networks.philippine_giant_peering_requests')}, + {id:'cvg',name:'Diverge',asn:17639,type:'eye',cc:'PH',pol:'open',up:['ntt','tat'],share:.005,col:'#F26B21',pops:['mnl','ceb','dvo','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('networks.the_fiber_upstart_from_the_provinces')}, + {id:'smt',name:'Smarty Pants',asn:10139,type:'eye',cc:'PH',pol:'selective',up:['pld'],minIx:10,minPni:30,share:.006,col:'#00A859',pops:['mnl'],ix:[],blurb:tr('networks.pldtea_time_s_mobile_sibling_buy')}, + {id:'dto',name:'Ditto',asn:139831,type:'eye',cc:'PH',pol:'open',up:['ntt','tat'],share:.002,col:'#B5121B',pops:['mnl'],ix:['mnl','mnl~2'],blurb:tr('networks.the_third_mobile_network_same_towers')}, + {id:'rsh',name:'RISE & Shine',asn:63927,type:'eye',cc:'PH',pol:'open',up:['ntt','tat'],share:.002,col:'#F5A623',pops:['mnl','ceb','dvo','sin','hkg','fra','ams','lon','sto'],ix:['mnl','mnl~2','mnl~3','ceb','dvo','sin','sin~2','hkg','hkg~2','fra','ams','lon','sto'],blurb:tr('networks.up_early_in_cebu_and_already')}, + {id:'spk',name:'Spark-le',asn:4771,type:'eye',cc:'NZ',pol:'open',share:.005,col:'#6A2C91',pops:['akl','syd','chc','ivc','wlg'],ix:['akl','syd','chc'],blurb:tr('networks.new_zealand_s_shiniest_isp')}, + {id:'tsy',name:'Telstraya',asn:1221,type:'t2',cc:'AU',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['hnl','gum','suv','pom','nou','hir','syd','per','sin','hkg','lax','tpe','mel','bne','drw','adl','cbr','hba','phe','tsv','asp'],ix:['gum','sin','hkg'],blurb:tr('networks.australia_s_big_one_g_day')}); +NETS.push( + {id:'liq',name:'Liquid Lunch Networks',asn:30846,type:'t2',cc:['ZW'],pol:'open',up:['tat','tly'],share:.006,price:6,col:'#00A0DF',pops:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh','gid','llw','pry'],ix:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],blurb:tr('networks.cape_to_cairo_fiber_across_a')}, + {id:'scm',name:'Sea-Comedy Networks',asn:37102,type:'t2',pol:'open',up:['ntt','tat'],share:.005,price:5,col:'#1C3F94',pops:['jnb','cpt','dur','mpm','dar','mba','nbo','kla','kgl','jib','cai','mrs','bom','lon','pry'],ix:['jnb','cpt','dur','mpm','dar','mba','nbo','kla','jib','mrs'],blurb:tr('networks.owns_the_cable_that_brought_east')}, + {id:'agc',name:'Angle-a Cables',asn:37470,type:'t2',pol:'open',up:['tly','cog'],share:.004,price:5,col:'#E30613',pops:['lad','fih','for','sao','mia','lon','pry'],ix:['lad','for','sao','mia'],blurb:tr('networks.owns_the_cables_from_luanda_to')}, + {id:'djt',name:'Djibouti Calling',asn:30992,type:'t2',cc:'DJ',pol:'selective',up:['tat','tly'],minIx:3,minPni:15,share:.003,price:8,col:'#0D7F3F',pops:['jib','add','mrs','bom','jed'],ix:['jib'],blurb:tr('networks.a_tiny_telco_in_a_country')}, + {id:'mtx',name:'Empty-N',asn:29977,type:'eye',cc:['NG','GH','CI','CM','UG','RW','ZA','ZM','BJ','LR','SD','SS','SZ','CG'],pol:'selective',up:['tat','lvl'],minIx:5,minPni:20,share:.008,col:'#FFCB05',pops:['lag','acc','abj','dla','kla','kgl','jnb','cpt','dur','lun','gbe','lad','pto','rob','qmn','jub','krt','abv','nsi','pry','bzv'],ix:['lag','acc','abj','dla','kla','kgl','jnb','cpt','dur','lun','gbe','lad'],blurb:tr('networks.africa_s_mobile_giant_in_a')}, + {id:'art',name:'Air-Tell Africa',asn:36928,type:'eye',cc:['NG','UG','RW','TZ','ZM','CD','KE','MG','SC','GA','MW','NE','TD','CG'],pol:'selective',up:['tat','tly'],minIx:4,minPni:18,share:.006,col:'#ED1C24',pops:['lag','kla','kgl','dar','lun','fih','nbo','tnr','sez','nim','ndj','lbv','llw','abv','dod','bzv'],ix:['lag','kla','kgl','dar','lun','fih','nbo'],blurb:tr('networks.mobile_money_and_prepaid_data_in')}, + {id:'eth',name:'Ethio-Tele-Calm',asn:24759,type:'eye',cc:'ET',pol:'selective',up:['tat'],minIx:2,minPni:12,share:.005,col:'#8DC63F',pops:['add'],ix:['add'],blurb:tr('networks.ethiopia_s_state_telco_a_hundred')}, + {id:'mrc',name:'Atlas Hold-the-Line Telecom',asn:36905,type:'eye',cc:['MA','BF','BJ','ML','TD','TG'],pol:'selective',up:['lvl','tly'],minIx:3,minPni:15,share:.004,col:'#F28C00',pops:['cas','abj','dkr','pto','oua','bko','lfw','ndj','rba'],ix:['cas'],blurb:tr('networks.morocco_s_incumbent_with_sister')}, + {id:'sfc',name:'Safari-Comic',asn:33771,type:'eye',cc:['KE','ET'],pol:'selective',minIx:5,minPni:20,share:.006,up:['cog','lvl','scm'],col:'#4CB848',pops:['nbo','mba','add'],ix:['nbo','mba','add'],blurb:tr('networks.kenya_s_mobile_giant_pays_you')}, + {id:'teg',name:'Tele-Comet Egypt',asn:8452,type:'t2',cc:'EG',pol:'selective',minIx:15,minPni:40,share:.006,price:8,col:'#5B2D8E',pops:['cai','mrs','fra','lon'],ix:['cai','mrs'],blurb:tr('networks.owns_the_land_crossing_every_red')}); +NETS.push( + {id:'clr',name:'Clarovision',asn:28537,type:'t2',cc:['AR','BR','CL','CO','CR','DO','EC','GT','PE','PR','PY','UY','HN','NI','SV'],pol:'paid',freeLv:11,paidFee:7000,share:.012,price:5,col:'#DA291C',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog','pan','mex','mia','sju','sdq','sal','tgu','mga'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog'],blurb:tr('networks.the_big_regional_carrier_sees')}, + {id:'viv',name:'Viva Vivo',asn:26959,type:'eye',cc:'BR',pol:'selective',minIx:8,minPni:25,share:.01,col:'#660099',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.brazil_s_mobile_giant_very_much')}, + {id:'oio',name:'Oi Oi',asn:7739,type:'eye',cc:'BR',pol:'selective',up:['lvl','tly'],minIx:6,minPni:20,share:.008,col:'#FFD000',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.says_oi_to_every_home_in')}, + {id:'tmt',name:'TIM-TIM Mobile',asn:26616,type:'eye',cc:'BR',pol:'selective',up:['skl'],minIx:6,minPni:20,share:.007,col:'#004691',pops:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],ix:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],blurb:tr('networks.a_mobile_network_named_after_the')}, + {id:'bsn',name:'Brisanada',asn:28127,type:'eye',cc:'BR',pol:'open',up:['lvl'],share:.004,col:'#F7941D',pops:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],ix:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],blurb:tr('networks.fiber_across_the_sertao_of_the')}, + {id:'mvs',name:'Moviestar',asn:12957,type:'t2',cc:['AR','CL','CO','EC','MX','PE','UY','VE'],pol:'selective',up:['tly','lvl'],minIx:8,minPni:25,share:.008,price:6,col:'#019DF4',pops:['mex','gua','bog','mde','uio','lim','lpb','scl','bue','cor','mvd','ccs','sao','mia'],ix:['bog','lim','scl','bue','mvd','ccs','sao'],blurb:tr('networks.a_spanish_carrier_starring_in_every')}, + {id:'llt',name:'Liberty Latte America',asn:23521,type:'t2',cc:['BB','BS','CR','CW','JM','PA','PR','TT','AG','DM','GD','KN','LC','VC'],pol:'open',up:['lvl','cog'],share:.005,price:5,col:'#6C2C91',pops:['mia','pan','sjo','gua','bog','mde','ccs','sju','kin','nas','pos','bgi','cur','anu','bas','dom','slu','svd','gnd'],ix:['pan','sjo','gua','bog','kin','pos'],blurb:tr('networks.cables_all_around_the_caribbean')}, + {id:'ant',name:'Antelope',asn:6058,type:'eye',cc:'UY',pol:'selective',up:['skl','tly'],minIx:3,minPni:15,share:.004,col:'#0072BC',pops:['mvd'],ix:['mvd'],blurb:tr('networks.uruguay_s_state_telco_fast')}, + {id:'tgo',name:'Tiger Mobile',asn:27743,type:'eye',cc:['PY','BO','GT','CR','PA','CO','HN','NI','SV'],pol:'selective',up:['lvl'],minIx:4,minPni:15,share:.005,col:'#00377B',pops:['asu','lpb','gua','sjo','pan','bog','mde','sal','tgu','mga'],ix:['asu','lpb','gua','sjo','bog'],blurb:tr('networks.prepaid_mobile_from_paraguay_to')}, + {id:'mlv',name:'Mercado Livre-ly',asn:52850,type:'cdn',pol:'open',share:.006,col:'#FFE600',pops:['sao','rio','bue','scl','bog','lim','mia'],ix:['sao','rio','bue','scl','bog','lim'],blurb:tr('networks.ships_parcels_and_packets_both')}, + {id:'jio',name:'Jio-graphy',asn:55863,type:'eye',cc:'IN',pol:'selective',minIx:10,minPni:30,share:.02,col:'#0F3CC9',pops:['bom','del','maa','blr','hyd'],ix:['bom','del','maa','blr','hyd'],blurb:tr('networks.gave_a_billion_people_cheap_data')}, + {id:'atl',name:'Airtel-tale',asn:9849,type:'t2',cc:'IN',pol:'selective',minIx:15,minPni:40,share:.01,price:7,col:'#E40000',pops:['bom','del','maa','blr','hyd','sin','lon','dxb','dac','cbo'],ix:['bom','del','maa','blr'],blurb:tr('networks.india_s_other_giant_every_outage')}, + {id:'cht',name:'Chunghwa Tele-calm',asn:3426,type:'t2',cc:'TW',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#00A0E9',pops:['tpe','hkg','tok','lax','sin'],ix:['tpe','hkg'],blurb:tr('networks.taiwan_s_incumbent_stays_calm_while')}, + {id:'duu',name:'Du-opoly',asn:15820,type:'eye',cc:'AE',pol:'paid',freeLv:11,paidFee:6000,share:.004,up:['tat','tly'],col:'#00A9CE',pops:['dxb','auh','fuj'],ix:[],blurb:tr('networks.the_other_half_of_the_uae')}); +NETS.push( + {id:'kdi',name:'KD-DIY',asn:2561,type:'t2',cc:'JP',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#E85D04',pops:['tok','osa','lax','sin','hkg','fuk'],ix:['tok','osa','fuk'],blurb:tr('networks.japanese_carrier_that_builds')}, + {id:'opt',name:'Floptus',asn:4804,type:'eye',cc:'AU',pol:'selective',minIx:8,minPni:25,share:.006,up:['sgt'],col:'#00837E',pops:['syd','mel','bne','per'],ix:[],blurb:tr('networks.australia_s_number_two_once_took')}, + {id:'tpr',name:'Toilet Paper Group',asn:7545,type:'eye',cc:'AU',pol:'selective',minIx:8,minPni:25,share:.0035,col:'#4E2A84',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.stockpiled_bandwidth_in_2020_and')}, + {id:'abb',name:'Aussie Boyband',asn:4764,type:'eye',cc:'AU',pol:'open',share:.002,col:'#00B140',pops:['syd','mel','bne','per','adl','cbr','drw','hba','tsv'],ix:['syd','mel','bne','per','adl','drw'],blurb:tr('networks.matching_outfits_perfect_harmonies')}, + {id:'voc',name:'Hocus Pocus',asn:4826,type:'t2',pol:'open',up:['ntt','tly'],share:.002,price:7,col:'#E4002B',pops:['syd','mel','bne','per','adl','cbr','drw','hba','sin','phe','tsv'],ix:['syd','mel','bne','per','adl','hba','drw','sin'],blurb:tr('networks.now_you_see_the_fibre_now')}, + {id:'ddo',name:'Doodoo',asn:9443,type:'eye',cc:'AU',pol:'open',up:['voc'],share:.0011,col:'#FFC20E',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.the_cheapest_plan_in_the_country')}, + {id:'stb',name:'Star-Blink',asn:14593,type:'eye',cc:'US',pol:'selective',minIx:3,minPni:10,share:.001,col:'#1B1F24',pops:['syd','mel','bne','per','drw','sea','lax','dal','chi','ash'],ix:['mel','bne','per','drw'],blurb:tr('networks.beams_the_outback_online_from_550')}, + {id:'spl',name:'Speedyloop',asn:38195,type:'t2',cc:'AU',pol:'open',up:['tly'],share:.001,price:6,col:'#FF5F00',pops:['syd','mel','bne','per','adl','sin','hkg','cbr','drw'],ix:['mel','bne','per','adl','hba','drw','sin','hkg'],blurb:tr('networks.speedy_by_name_owns_a_slice')}, + {id:'blg',name:'Beshort',asn:135887,type:'eye',cc:'AU',pol:'selective',minIx:8,minPni:25,up:['tsy'],share:.0005,col:'#FF5A00',pops:['syd','mel','bne'],ix:[],blurb:tr('networks.telstraya_s_budget_brand_cheaper')}, + {id:'spn',name:'Spin2wintel',asn:18390,type:'eye',cc:'AU',pol:'open',up:['voc'],share:.00015,col:'#0072CE',pops:['syd','mel','bne','per','adl'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.cheap_broadband_with_the_sales_pitch')}, + {id:'lpt',name:'Frogtel',asn:134090,type:'eye',cc:'AU',pol:'open',share:.0001,col:'#7AC143',pops:['syd','mel','bne','adl','per','drw'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.small_fast_and_always_leaping_to')}, + {id:'ext',name:'Lintel',asn:10143,type:'eye',cc:'AU',pol:'open',up:['spl'],share:.0001,col:'#F26522',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.bought_by_speedyloop_and_still')}, + {id:'tru',name:'Mostly-True Move',asn:7740,type:'eye',cc:'TH',pol:'selective',minIx:5,minPni:20,share:.006,col:'#E4002B',pops:['bkk'],ix:['bkk'],blurb:tr('networks.thailand_s_mobile_giant_its_coverage')}, + {id:'vtl',name:'Viet-tell',asn:7525,type:'t2',cc:['VN','KH','LA','MM','TL','BI'],pol:'selective',minIx:10,minPni:30,share:.005,price:7,col:'#EE0033',pops:['sgn','hkg','sin','pnh','vte','nyt','dil','han','gid'],ix:['sgn'],blurb:tr('networks.vietnam_s_giant_will_tell_you')}, + {id:'ptc',name:'PTC-hell',asn:17577,type:'t2',cc:'PK',pol:'selective',minIx:10,minPni:30,share:.004,price:8,col:'#00843D',pops:['khi','dxb','isb'],ix:['khi'],blurb:tr('networks.pakistan_s_incumbent_every_session')}, + {id:'tmy',name:'Telekom Malay-tency',asn:4877,type:'t2',cc:'MY',pol:'selective',minIx:10,minPni:30,share:.004,price:6,col:'#1F2A6B',pops:['kul','sin'],ix:['kul'],blurb:tr('networks.malaysia_s_incumbent_with_a_cable')}, + {id:'ttk',name:'Türk Tele-komik',asn:9211,type:'t2',cc:'TR',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#1D3F8F',pops:['ath','ist','fra','sof','lon','esb'],ix:['ist'],blurb:tr('networks.bridges_europe_and_asia_and')}, + {id:'dgi',name:'Digi-tally Cheap',asn:8798,type:'eye',cc:['ES','RO'],pol:'open',share:.006,col:'#2A5CAA',pops:['buh','bud','mad'],ix:['buh','bud','mad'],blurb:tr('networks.gigabit_to_every_flat_for_the')}, + {id:'ups',name:'UPC-You-Later',asn:6380,type:'eye',cc:['PL','CZ','AT','HU','CH'],pol:'selective',minIx:8,minPni:25,share:.006,col:'#D8001B',pops:['waw','prg','vie','bud','zrh','kyv'],ix:['waw','prg','vie','kyv'],blurb:tr('networks.cable_broadband_across_central')}); +NETS.push( + {id:'tlu',name:'Tell Us',asn:852,type:'eye',cc:'CA',pol:'selective',minIx:10,minPni:30,share:.008,up:['lvl','tly'],col:'#4B286D',pops:['van','cal','tor','mtl','ott','sea','prr'],ix:['van','cal','tor'],blurb:tr('networks.western_canada_s_incumbent_tell_us')}, + {id:'rgc',name:'Bodgers Communications',asn:812,type:'eye',cc:'CA',pol:'selective',minIx:10,minPni:30,share:.01,up:['cog','ntt'],col:'#DA291C',pops:['tor','ott','mtl','van','cal'],ix:['tor','ott','van'],blurb:tr('networks.canada_s_cable_giant_held_together')}); +NETS.push( + {id:'tny',name:'Telenyet',asn:6848,type:'eye',cc:'BE',pol:'selective',minIx:10,minPni:30,share:.008,up:['lvl'],col:'#FFC421',pops:['bru','oos','ams','fra','lon'],ix:['bru'],blurb:tr('networks.half_of_the_flanders_duopoly_on')}, + {id:'pxm',name:'Proxyminus',asn:5432,type:'eye',cc:'BE',pol:'selective',minIx:15,minPni:40,share:.008,up:['bgs','lvl'],col:'#5C2D91',pops:['bru','oos','ams'],ix:['bru'],blurb:tr('networks.the_other_half_of_the_duopoly')}, + {id:'bgs',name:'B.I.G.S.',asn:6774,type:'t2',pol:'selective',minIx:10,minPni:30,share:.005,price:5,up:['lvl'],col:'#7B2D8E',pops:['bru','bet','ams','fra','lon','par','mrs','nyc','sin'],ix:['bru','bet','ams','fra','lon','par'],blurb:tr('networks.proxyminus_s_wholesale_arm_present')}, + {id:'cit',name:'Citrus Belgium',asn:47377,type:'eye',cc:'BE',pol:'selective',minIx:10,minPni:30,share:.005,up:['lvl'],col:'#FF7900',pops:['bru','par'],ix:['bru'],blurb:tr('networks.tangerine_s_belgian_daughter_mobile')}, + {id:'pst',name:'Poste Restante',asn:6663,type:'eye',cc:'LU',pol:'selective',minIx:4,minPni:15,share:.001,up:['lvl','tly'],col:'#FFCC00',pops:['bet','fra','ams'],ix:['bet','fra'],blurb:tr('networks.luxembourg_s_post_office_which_also')}, + {id:'cms',name:'CityMess',asn:199095,type:'eye',cc:'BE',pol:'open',share:.002,up:['cog'],col:'#00B2A9',pops:['oos','bru'],ix:['bru'],blurb:tr('networks.private_5g_and_business_fiber_from')}); +NETS.push({id:'kys',name:'Kyiv Superstar',asn:15859,type:'eye',cc:'UA',pol:'selective',minIx:5,minPni:20,share:.006,up:['cog','tly'],col:'#0055B8',pops:['kyv','waw','fra'],ix:['kyv'],blurb:tr('networks.ukraine_s_biggest_mobile_network_has')}); +NETS.push({id:'stc',name:'Sticky Telecom',asn:39368,type:'t2',cc:['SA','BH','KW'],pol:'selective',minIx:10,minPni:30,share:.01,price:8,col:'#4F008C',pops:['ruh','jed','dxb','fra','lon','cai','kwi','bah'],ix:['ruh'],blurb:tr('networks.the_kingdom_s_incumbent_long_contracts')}, + {id:'ord',name:'Ooh-redoo',asn:8871,type:'eye',cc:['QA','OM','ID','IQ','KW'],pol:'paid',freeLv:11,paidFee:5000,share:.004,up:['tat','tly'],col:'#ED1C24',pops:['doh','dxb','jkt','mct','bgw','kwi'],ix:[],blurb:tr('networks.qatar_s_big_operator_paid_peering')}); +NETS.push( + {id:'tim',name:'TIM-Tam Italia',asn:3269,type:'eye',cc:['IT','SM'],pol:'selective',minIx:8,minPni:25,share:.008,up:['skl'],col:'#004691',pops:['mil','rom','pmo','smr'],ix:['mil','rom'],blurb:tr('networks.italy_s_incumbent_sweet_on_the')}, + {id:'skl',name:'Sparkly Seabone',asn:6762,type:'t1',pol:'restrictive',share:.04,price:6,col:'#5B2C83',pops:['pmo','mil','rom','ath','mrs','bcn','mad','bio','lis','par','lon','ams','fra','zrh','vie','bud','prg','waw','buh','sof','ist','ber','sto','nyc','ash','mia','atn','dal','chi','lax','sjc','tor','mex','pan','bog','lim','scl','bue','sao','rio','for','cai','jed','dxb','bom','sin','hkg','tok','hav','lys'],ix:[],blurb:tr('networks.the_tier_1_that_grew_up')}, + {id:'fwb',name:'Fast-Webby',asn:12874,type:'eye',cc:'IT',pol:'open',share:.004,col:'#FDC300',pops:['mil','rom'],ix:['mil','rom'],blurb:tr('networks.fiber_to_the_italian_home_with')}, + {id:'meo',name:'MEO-w Portugal',asn:3243,type:'eye',cc:'PT',pol:'selective',minIx:5,minPni:20,share:.004,col:'#00A3E0',pops:['pdl','lis','mad'],ix:['lis'],blurb:tr('networks.portugal_s_incumbent_purrs_when_you')}, + {id:'nos',name:'NOS-y Neighbour',asn:2860,type:'eye',cc:'PT',pol:'open',share:.003,col:'#111111',pops:['lis'],ix:['lis'],blurb:tr('networks.peers_with_anyone_and_wants_to')}, + {id:'cos',name:'Cosmo-Note',asn:6799,type:'eye',cc:'GR',pol:'selective',minIx:5,minPni:20,share:.004,col:'#7DC242',pops:['ath','sof'],ix:['ath'],blurb:tr('networks.greece_s_incumbent_takes_careful')}, + {id:'spc',name:'Spectre-um Cable',asn:20115,type:'eye',cc:'US',pol:'selective',minIx:12,minPni:35,share:.02,col:'#0099D8',pops:['nyc','lax','dal','chi','atn','den','phx','slc','hou','bos','sjc'],ix:['nyc','lax','dal','chi','atn','den'],blurb:tr('networks.cable_broadband_for_half_of_america')}, + {id:'vzn',name:'Very-Zone',asn:701,type:'eye',cc:'US',pol:'paid',paidFee:9000,share:.015,col:'#CD040B',pops:['nyc','ash','bos','dal','lax','chi','atn','mia'],ix:[],blurb:tr('networks.can_you_hear_me_now_only')}); +NETS.push( + {id:'att',name:'AT&Tease',asn:7018,type:'t1',pol:'restrictive',share:.02,price:8,col:'#00A8E0',pops:['nyc','ash','chi','dal','atn','lax','sjc','sea','mia','hou','lon','fra','ams','par','was','sac','aus','okc','lit','btr','jan','mgm','tlh','cae','rdu','bna','fft','ind','cmh','lan','msn','spi','jef','top','hfd'],ix:[],blurb:tr('networks.the_phone_company_s_favourite_child')}, + {id:'tmo',name:'Tee-Hee Mobile',asn:21928,type:'eye',cc:['US','PR'],pol:'selective',minIx:6,minPni:20,share:.01,up:['lvl','ntt'],col:'#E20074',pops:['nyc','bos','den','sea','sjc','lax','mia','chi','sju'],ix:['nyc','bos','den','sea','sjc','lax','mia','sju'],blurb:tr('networks.pink_loud_and_almost_entirely_ipv6')}, + {id:'cxc',name:'Coax Communications',asn:22773,type:'eye',cc:'US',pol:'selective',minIx:8,minPni:25,share:.006,up:['spc'],col:'#0072CE',pops:['ash','atn','bos','chi','dal','kcy','lax','nyc','sjc','phx'],ix:[],blurb:tr('networks.cable_broadband_for_the_sun_belt')}, + {id:'pes',name:'Pessimum',asn:6128,type:'eye',cc:'US',pol:'open',share:.005,up:['cog','lvl'],col:'#1A3D8F',pops:['nyc','ash','chi'],ix:['nyc','ash','chi'],blurb:tr('networks.expects_the_worst_from_every_link')}, + {id:'ftr',name:'Final Frontear',asn:5650,type:'eye',cc:'US',pol:'selective',minIx:6,minPni:20,share:.005,up:['vzn'],col:'#D2232A',pops:['ash','chi','dal','nyc','mia','lax'],ix:['ash','chi','dal','nyc','mia','lax'],blurb:tr('networks.fiber_to_30_million_homes_and')}, + {id:'gfb',name:'GFibber',asn:16591,type:'eye',cc:'US',pol:'open',share:.002,up:['lvl','cog'],col:'#34A853',pops:['kcy','ash','atn','chi','dal','den','nyc','phx','slc','sjc'],ix:['kcy','ash','atn','chi','dal','den','nyc','phx','slc','sjc'],blurb:tr('networks.started_in_kansas_city_in_2012')}, + {id:'snc',name:'Sonic Boomer',asn:46375,type:'eye',cc:'US',pol:'open',share:.0008,up:['cog','lvl'],col:'#F7A600',pops:['sjc'],ix:['sjc'],blurb:tr('networks.bay_area_fiber_with_an_old')}); +NETS.push( + {id:'npt',name:'Neptoon Internet',asn:151660,type:'eye',cc:'AU',pol:'open',share:.00008,col:'#3D5AFE',pops:['syd','mel','bne','per','adl'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.privacy_first_broadband_from_melbourne')}, + {id:'lnt',name:'Lawn-tel',asn:134697,type:'eye',cc:'AU',pol:'selective',minIx:2,minPni:10,share:.00015,col:'#3FA34D',pops:['hba','syd','mel','bne','per','adl'],ix:['hba','syd','mel','bne','per','adl'],blurb:tr('networks.tasmania_s_own_mowing_its_way')}, + {id:'pnt',name:'Pent-Up Net',asn:10214,type:'eye',cc:'AU',pol:'open',share:.0003,col:'#8E24AA',pops:['per','syd'],ix:['per','syd'],blurb:tr('networks.perth_wireless_and_fibre_pent_up')}, + {id:'mag',name:'Dive-Bomb Magpie',asn:58511,type:'t2',pol:'open',up:['ntt','cog'],share:.0003,price:7,col:'#212121',pops:['syd','mel','bne','per','adl','akl','sin','sjc','sea','lon','ams','fra','par'],ix:['syd','mel','bne','per','adl','akl','sin','sjc','sea','lon','ams','fra','par'],blurb:tr('networks.dive_bombs_every_exchange_in_the')}, + {id:'inp',name:'Internope',asn:4739,type:'eye',cc:'AU',pol:'restrictive',up:['tpr'],share:.0015,col:'#F57C00',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.once_the_nerds_favourite_isp_now')}); diff --git a/src/game/30-networks/20-rival-exchanges.js b/src/game/30-networks/20-rival-exchanges.js new file mode 100644 index 0000000..3abb2cc --- /dev/null +++ b/src/game/30-networks/20-rival-exchanges.js @@ -0,0 +1,33 @@ +/* Rival exchanges. Big metros rarely have just one IX: challengers undercut the incumbent and + share many members with it, but not all. The incumbent keeps the city id, challengers are 'city~n'. */ +const XIX=[ + {id:'jnb~2',c:'jnb',name:'JINXED-IX',cheap:.7,take:0.5,core:['drz','akm','cfl','tng'],blurb:tr('rival_exchanges.the_older_johannesburg_exchange_run')}, + {id:'fra~2',c:'fra',name:'KleyWrecks',cheap:.5,take:0.5,core:['drz','akm','cfl','slw','bdc','ydx'],blurb:tr('rival_exchanges.a_smaller_commercial_exchange_down')}, + {id:'fra~3',c:'fra',name:'Apfelwein-IX',cheap:0.3,take:0.3,blurb:tr('rival_exchanges.a_community_exchange_run_from_above')}, + {id:'ams~2',c:'ams',name:'NL-Nyx',cheap:0.6,take:0.6,blurb:tr('rival_exchanges.one_fabric_across_the_whole_country')}, + {id:'ams~3',c:'ams',name:'FRIES-IX',cheap:1,take:0.5,freeTo:1,core:['drz','akm','cfl','slw','msf'],blurb:tr('rival_exchanges.settlement_free_peering_with_frysian')}, + {id:'lon~2',c:'lon',name:'LO-NAPS',cheap:.6,take:0.5,core:['drz','akm','cfl','slw','bdc','msf','fbk'],blurb:tr('rival_exchanges.member_owned_and_not_for_profit')}, + {id:'par~2',c:'par',name:'Baguette-IX',cheap:0.55,take:0.5,blurb:tr('rival_exchanges.the_challenger_fresh_every_morning_a')}, + {id:'mad~2',c:'mad',name:'Paella-NIX',cheap:.6,take:0.5,core:['drz','akm','cfl','tng','bdc','slw','msf'],blurb:tr('rival_exchanges.the_long_established_madrid_exchange')}, + {id:'mil~2',c:'mil',name:'Aperitivo-IX',cheap:0.5,take:0.45,blurb:tr('rival_exchanges.opens_at_six_comes_with_free')}, + {id:'ber~2',c:'ber',name:'Club-Mate-IX',cheap:0.35,take:0.4,blurb:tr('rival_exchanges.run_by_hackers_on_caffeine_the')}, + {id:'waw~2',c:'waw',name:'Bigos-IX',cheap:0.45,take:0.5,blurb:tr('rival_exchanges.warsaw_has_more_exchanges_than')}, + {id:'waw~3',c:'waw',name:'Zapiekanka-IX',cheap:0.3,take:0.35,blurb:tr('rival_exchanges.open_faced_cheap_and_available_at')}, + {id:'prg~2',c:'prg',name:'Knedlík-IX',cheap:0.35,take:0.4,blurb:tr('rival_exchanges.dense_filling_and_very_cheap')}, + {id:'buh~2',c:'buh',name:'Mici-IX',cheap:0.35,take:0.45,blurb:tr('rival_exchanges.grilled_ports_served_with_mustard')}, + {id:'sto~2',c:'sto',name:'Fika-IX',cheap:0.5,take:0.5,blurb:tr('rival_exchanges.every_session_comes_with_a_coffee')}, + {id:'kyv~2',c:'kyv',name:'Kyiv-Cake-IX',cheap:0.35,take:0.45,blurb:tr('rival_exchanges.layered_resilient_and_somehow_always')}, + {id:'nyc~2',c:'nyc',name:'Bagel-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.a_community_exchange_in_a_hudson')}, + {id:'chi~2',c:'chi',name:'Deep-Dish-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.takes_forever_to_set_up_but')}, + {id:'sjc~2',c:'sjc',name:'Garage-IX',cheap:0.55,take:0.45,blurb:tr('rival_exchanges.started_in_somebody_s_garage_like')}, + {id:'lax~2',c:'lax',name:'Smog-IX',cheap:0.6,take:0.45,blurb:tr('rival_exchanges.you_can_t_see_the_fabric')}, + {id:'sin~2',c:'sin',name:'Kopi-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.strong_sweet_and_cheaper_than_the')}, + {id:'hkg~2',c:'hkg',name:'Dim-Sum-IX',cheap:0.6,take:0.5,blurb:tr('rival_exchanges.lots_of_small_sessions_on_little')}, + {id:'mnl~2',c:'mnl',name:'Bayanihan-IX',cheap:0.3,take:0.4,blurb:tr('rival_exchanges.the_whole_neighbourhood_carries_the')}, + {id:'mnl~3',c:'mnl',name:'In-Vitro-IX',cheap:4.4,take:0.2,core:['pld','smt'],blurb:tr('rival_exchanges.grown_in_a_lab_by_the')}, + {id:'tok~2',c:'tok',name:'Bento-IX',cheap:0.65,take:0.5,core:['drz','akm','cfl','sgt','msf','amz'],blurb:tr('rival_exchanges.tokyo_has_more_exchanges_than_anyone')}, + {id:'syd~2',c:'syd',name:'At-The-Edge IX',cheap:.7,take:0.5,core:['drz','nfx','ggl','fbk','akm','cfl','amz','msf','bdc','slw','abb','voc','stb','spl','lpt','npt','mag'],blurb:tr('rival_exchanges.the_challenger_to_ix_straya_pops')}, + {id:'bom~2',c:'bom',name:'Vada-Pav-IX',cheap:0.45,take:0.45,blurb:tr('rival_exchanges.mumbai_s_street_food_exchange_fast')}, + {id:'dxb~2',c:'dxb',name:'Shawarma-IX',cheap:0.6,take:0.4,blurb:tr('rival_exchanges.the_challenger_to_the_de_kicks')}, +]; +const XIXM=Object.fromEntries(XIX.map(x=>[x.id,x])); diff --git a/src/game/30-networks/30-long-tail.js b/src/game/30-networks/30-long-tail.js new file mode 100644 index 0000000..2f2e5c4 --- /dev/null +++ b/src/game/30-networks/30-long-tail.js @@ -0,0 +1,130 @@ +/* The long tail: odd little networks with a sliver of traffic each, on one or two exchanges. */ +const TAIL=[ + ['Grandma’s Basement Hosting','cdn',['fra'],tr('long_tail.three_servers_one_dehumidifier_and_a')], + ['Hamster Wheel Networks','eye',['ams'],tr('long_tail.powered_by_renewable_rodents_uptime')], + ['Fjordnet Kooperativ','eye',['osl'],tr('long_tail.a_fiber_co_op_for_one')], + ['Kebab-Link','eye',['ber','fra'],tr('long_tail.an_isp_run_from_the_back')], + ['Mesh Collective e.V.','eye',['ber','fra'],tr('long_tail.volunteers_with_rooftop_antennas_and')], + ['Village Fibre Co-op','eye',['lon'],tr('long_tail.dug_the_trench_themselves_one_field')], + ['Tiny Swiss Bank Shield','cdn',['zrh'],tr('long_tail.hosts_exactly_one_website_and_three')], + ['Clockwork ISP','eye',['zrh'],tr('long_tail.packets_leave_on_time_to_the')], + ['LAN-Party Federation','cdn',['ams','fra'],tr('long_tail.game_servers_energy_drinks_and_a')], + ['Former Church Datacenter','cdn',['ams'],tr('long_tail.racks_in_the_nave_cooling_in')], + ['WISP on a Silo','eye',['dal','chi'],tr('long_tail.wireless_internet_from_the_top_of')], + ['Cornfield Broadband','eye',['chi'],tr('long_tail.rural_fiber_that_follows_the_tractor')], + ['Moose Lake Telephone Co-op','eye',['tor','mtl'],tr('long_tail.has_served_the_lake_since_1912')], + ['Surf Shop Networks','cdn',['lax'],tr('long_tail.hosting_for_surfboard_shops_closed')], + ['Ski Lift Fiber','eye',['den','zrh'],tr('long_tail.fiber_strung_along_the_chairlifts')], + ['Tumbleweed Telecom','eye',['phx','dal'],tr('long_tail.covers_a_lot_of_empty_ground')], + ['Crypto Bro Colo','cdn',['ash','mia'],tr('long_tail.ten_thousand_gpus_and_a_podcast')], + ['Ye Olde University Network','eye',['bos','lon'],tr('long_tail.has_had_a_8_since_before')], + ['Mom & Pop Packet Shop','eye',['nyc'],tr('long_tail.family_run_since_dial_up_still')], + ['Space Cowboy Broadband','eye',['hou','dal'],tr('long_tail.yee_haw_and_low_earth_orbit')], + ['Fry Sauce Fibre','eye',['slc'],tr('long_tail.utah_s_dipping_sauce_of_an')], + ['Sauna Uplink Oy','cdn',['hel','sto'],tr('long_tail.servers_cooled_by_the_lake_then')], + ['Reindeer Relay','eye',['sto','osl','hel'],tr('long_tail.wireless_links_across_the_tundra')], + ['Pierogi Hosting','cdn',['waw'],tr('long_tail.cheap_filling_hosting_ask_for_the')], + ['Sunflower Uplink','eye',['kyv','waw'],tr('long_tail.kept_the_lights_on_in_its')], + ['Tram Line Telecom','eye',['prg','vie'],tr('long_tail.fiber_laid_under_the_tram_tracks')], + ['Paprika Peering','eye',['bud'],tr('long_tail.spicy_pricing_mild_latency')], + ['Dracula Datacenter','cdn',['buh'],tr('long_tail.only_comes_online_at_night')], + ['Bosphorus Ferry Net','eye',['ist'],tr('long_tail.wi_fi_on_every_ferry_backhaul')], + ['Gondola Gigabit','eye',['mil','rom'],tr('long_tail.started_in_venice_upgraded_to_land')], + ['Nonna’s Pasta Pipes','cdn',['rom','pmo'],tr('long_tail.hosting_for_every_family_restaurant')], + ['Tram 28 Telecom','eye',['lis'],tr('long_tail.slow_on_the_hills_fast_on')], + ['Olive Grove Online','eye',['ath'],tr('long_tail.rural_broadband_for_the_islands_one')], + ['Siesta Server Hotel','cdn',['mad'],tr('long_tail.down_from_2_to_5_p')], + ['Bouillabaisse Bits','cdn',['mrs','par'],tr('long_tail.a_rich_mix_of_everything_the')], + ['Baguette Bandwidth Associés','eye',['par'],tr('long_tail.delivered_fresh_every_morning')], + ['Pub Quiz Internet','eye',['dub','lon'],tr('long_tail.founded_after_a_pub_quiz_by')], + ['Gaming Café Net','eye',['lag'],tr('long_tail.internet_cafe_turned_isp_the_gamers')], + ['Matatu Mobile Mesh','eye',['nbo'],tr('long_tail.wi_fi_on_minibuses_and_the')], + ['Load-Shedding Survivors','eye',['jnb','cpt'],tr('long_tail.has_more_batteries_than_customers')], + ['Bollywood Buffer','cdn',['bom','del'],tr('long_tail.three_hour_films_zero_second_start')], + ['Hawker Centre Hosting','cdn',['sin','kul'],tr('long_tail.cheap_fast_and_open_late')], + ['Karaoke Box Networks','cdn',['tok','osa','icn'],tr('long_tail.lyrics_servers_low_latency_high')], + ['Night Market Net','eye',['tpe','hkg'],tr('long_tail.comes_alive_after_dark')], + ['Kangaroo Courier','eye',['syd','mel','bne'],tr('long_tail.packets_hop_sometimes_backwards')], + ['Hobbit Hole Hosting','cdn',['akl'],tr('long_tail.cosy_racks_under_a_hill_second')], + ['Capybara Connect','eye',['sao','poa','bue'],tr('long_tail.gets_along_with_every_other_network')], + ['Llama Link','eye',['lim','scl','bog'],tr('long_tail.mountain_wireless_will_spit_at_bad')], + ['Supercar Hosting','cdn',['dxb'],tr('long_tail.gold_plated_servers_valet_parking')], + ['Tango Transit Co-op','eye',['bue','cor'],tr('long_tail.it_takes_two_to_peer')], + ['Bánh Mì Broadband','eye',['sgn'],tr('long_tail.crispy_on_the_outside_cheap_on')], + ['Jeepney Jumpnet','eye',['mnl'],tr('long_tail.colourful_crowded_and_gets_you_there')], + ['Game Server Gremlins','cdn',['fra','ams','lon','nyc','sjc'],tr('long_tail.hosts_every_game_you_play_at'),0.003], + ['Discord-ant Voice Relay','cdn',['ams','fra','ash'],tr('long_tail.voice_chat_for_millions_of_gamers'),0.003], + ['Mastodon Instance Herd','cdn',['ber','ams','par'],tr('long_tail.a_thousand_tiny_social_networks_on')], + ['Dutch Bike Fibre','eye',['ams'],tr('long_tail.fiber_laid_along_the_bike_lanes')], + ['Chip Fab Cleanroom Net','cdn',['tpe','phx'],tr('long_tail.bunny_suits_mandatory_in_the_server')], + ['Volunteer Fire Brigade Wi-Fi','eye',['vie','zrh'],tr('long_tail.runs_the_village_network_between')], + ['Peach State Hosting','cdn',['atn'],tr('long_tail.sweet_fuzzy_and_surprisingly')], + ['Chowder Hosting','cdn',['bos'],tr('long_tail.thick_comforting_and_very_new')], +]; +/* Who the long tail buys transit from (#85): small networks almost always buy it from a big carrier where they sit, + usually the cheapest Tier 1 in town or two of them. One or two of the founding five Tier 1s with a PoP in their home + cities, picked by name so it never changes; where none sits (Auckland), a carrier there that buys from them. */ +const TAIL_UP=['cog','lvl','tly','ntt','tat']; +function tailUp(name,home){const h=hstr(name+'|up'),t1=TAIL_UP.filter(id=>{const n=NETS.find(x=>x.id===id);return home.some(c=>n.pops.includes(c));}); + if(!t1.length)return NETS.filter(n=>n.price&&n.up&&n.up.some(u=>TAIL_UP.includes(u))&&home.some(c=>n.pops.includes(c))).map(n=>n.id).slice(0,1); + const a=t1[h%t1.length],b=t1[(h>>>8)%t1.length];return t1.length>1&&(h>>>16)%100<50&&b!==a?[a,b]:[a];} +function ixStatic(c){const o=[];if(CITY[c]&&CITY[c].ix)o.push(c);for(const x of XIX)if(x.c===c)o.push(x.id);return o;} +TAIL.forEach(([name,type,home,blurb,sh],i)=>{const h=hstr(name),cand=home.flatMap(ixStatic),ix=[]; + if(cand.length){ix.push(cand[h%cand.length]);if(cand.length>1&&(h>>>8)%100<40){const o=cand[(h>>>12)%cand.length];if(!ix.includes(o))ix.push(o);}} + const sel=(h>>>4)%10>=8; + NETS.push({id:'tail'+i,name,asn:200000+(h%190000),type,tail:true,up:tailUp(name,home),pol:sel?'selective':'open',...(sel?{minIx:1+(h>>>16)%3,minPni:6+(h>>>18)%8}:{}),share:sh||+(0.0006+((h>>>20)%15)*0.0001).toFixed(4),col:`hsl(${h%360} 55% 46%)`,pops:home.slice(),ix,blurb});}); +NETS.push( + {id:'ktt',name:'Kay-Tea',asn:4766,type:'eye',cc:'KR',pol:'paid',paidFee:5000,perG:90,kr:true,share:.012,col:'#E4002B',pops:['icn','hkg','tok','lax'],ix:[],blurb:tr('long_tail.korea_s_incumbent_sender_pays_every')}, + {id:'skb',name:'SK Broadbandit',asn:9318,type:'eye',cc:'KR',pol:'paid',paidFee:4000,perG:110,kr:true,share:.01,col:'#EA002C',pops:['icn','hkg','sjc'],ix:[],blurb:tr('long_tail.took_a_streaming_giant_to_court')}, + {id:'lgu',name:'LG You-Pay-Plus',asn:3786,type:'eye',cc:'KR',pol:'paid',paidFee:3000,perG:80,kr:true,share:.008,col:'#E6007E',pops:['icn','tok'],ix:[],blurb:tr('long_tail.the_plus_is_a_usage_fee')}); +NETS.push( + {id:'btt',name:'Bee-Tee',asn:2856,type:'eye',cc:'GB',pol:'selective',minIx:10,minPni:30,share:.012,col:'#5514B4',pops:['lon','man','edi','bde'],ix:['lon','man'],blurb:tr('long_tail.the_uk_s_incumbent_buzzes_politely')}, + {id:'sky',name:'Sky-High Broadband',asn:5607,type:'eye',cc:['GB','IE'],pol:'selective',minIx:6,minPni:25,share:.008,up:['tly','lvl'],col:'#0072C9',pops:['lon','man','edi','dub'],ix:['lon','man','edi'],blurb:tr('long_tail.football_films_and_a_router_that')}, + {id:'vmo',name:'Virgin Mediocre',asn:5089,type:'eye',cc:'GB',pol:'selective',minIx:6,minPni:25,share:.007,up:['lvl','ntt'],col:'#E10A0A',pops:['lon','man','edi'],ix:['lon','man'],blurb:tr('long_tail.cable_broadband_for_half_of_britain')}, + {id:'tnr',name:'Tele-Nor-Way',asn:2119,type:'eye',cc:['NO','SE'],pol:'selective',minIx:5,minPni:20,share:.006,up:['tly','lvl'],col:'#00A9E0',pops:['osl','svg','sto','cph','krs','got','mmx'],ix:['osl','svg','got'],blurb:tr('long_tail.norway_s_incumbent_neither_yes_nor')}); +NETS.push( + {id:'hwt',name:'Hawaiian Telecombo',asn:36149,type:'eye',cc:'US',pol:'selective',minIx:3,minPni:15,share:.004,up:['ntt','lvl'],col:'#5B2A86',pops:['hnl'],ix:['hnl'],blurb:tr('long_tail.hawaii_s_incumbent_every_plan_comes')}, + {id:'gtg',name:'Grand Theft Teleguam',asn:9246,type:'t2',cc:'GU',pol:'open',share:.002,price:8,up:['ntt','tat'],col:'#0072CE',pops:['gum','ror','maj','hnl','tok'],ix:['gum','hnl'],blurb:tr('long_tail.guam_s_incumbent_and_the_way')}, + {id:'dcp',name:'Docomoco Pacific',asn:3605,type:'eye',cc:'GU',pol:'selective',minIx:2,minPni:10,share:.002,up:['ntt'],col:'#E4002B',pops:['gum','ror'],ix:['gum'],blurb:tr('long_tail.guam_s_mobile_network_rice_a')}, + {id:'dsp',name:'Digi-Sell Pacific',asn:38442,type:'t2',cc:['FJ','PG','TO','WS','NR','VU'],pol:'open',share:.005,price:9,up:['ntt','tat'],col:'#E2001A',pops:['pom','suv','tbu','apw','syd','inu','vli'],ix:['suv'],blurb:tr('long_tail.phones_on_every_island_from_papua')}, + {id:'fnt',name:'FINTEL-ligent',asn:9241,type:'t2',pol:'open',share:.002,price:8,up:['ntt','tly'],col:'#00A3AD',pops:['suv','tbu','apw','ppg','syd','hnl'],ix:['suv'],blurb:tr('long_tail.fiji_s_international_gateway_very')}, + {id:'pft',name:'Postes et Télé-Croissant',asn:56055,type:'t2',cc:['NC','PF'],pol:'selective',minIx:3,minPni:15,share:.003,price:10,up:['tly','cog'],col:'#F7B500',pops:['nou','ppt','syd','lax'],ix:['nou'],blurb:tr('long_tail.runs_the_post_the_phones_and')}, + {id:'tkp',name:'Telly-Kom PNG',asn:17828,type:'eye',cc:'PG',pol:'selective',minIx:2,minPni:10,share:.003,up:['tat'],col:'#C8102E',pops:['pom'],ix:[],blurb:tr('long_tail.papua_new_guinea_s_state_telco')}, + {id:'otk',name:'Ours-Truly Telekom',asn:45891,type:'eye',cc:'SB',pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#00843D',pops:['hir'],ix:['hir'],blurb:tr('long_tail.the_solomon_islands_incumbent_on')}, + {id:'tcc',name:'Tongue-in-Cheek Comms',asn:38201,type:'eye',cc:'TO',pol:'selective',minIx:1,minPni:8,share:.001,up:['ntt'],col:'#C10230',pops:['tbu'],ix:[],blurb:tr('long_tail.tonga_s_own_telco_lived_through')}, + {id:'bsk',name:'Blue-Sky-Pie Samoa',asn:17993,type:'eye',cc:['WS','AS'],pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#0096D6',pops:['apw','ppg'],ix:[],blurb:tr('long_tail.samoa_s_broadband_promised_with_a')}, + {id:'pnc',name:'PNC-See',asn:17893,type:'eye',cc:'PW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#1B75BB',pops:['ror'],ix:[],blurb:tr('long_tail.palau_s_telco_snorkel_down_and')}, + {id:'nta',name:'Never Too Atoll',asn:24439,type:'eye',cc:'MH',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#2E8B57',pops:['maj'],ix:[],blurb:tr('long_tail.the_marshall_islands_telco_two')}); +NETS.push( + {id:'onc',name:'One Commotion',asn:3855,type:'eye',cc:'BM',pol:'selective',minIx:1,minPni:8,share:.001,up:['lvl','tly'],col:'#E4007C',pops:['bda'],ix:[],blurb:tr('long_tail.bermuda_s_phones_tv_and_internet')}, + {id:'cvt',name:'Curriculum Vitae Telecom',asn:37517,type:'t2',cc:'CV',pol:'open',share:.002,price:8,up:['tat','tly'],col:'#004B87',pops:['rai','lis','for','dkr'],ix:['rai'],blurb:tr('long_tail.cape_verde_s_incumbent_and_the')}, + {id:'pss',name:'Pretty Sure South Atlantic',asn:210841,type:'t2',cc:'SH',pol:'open',share:.0005,price:12,up:['tat'],col:'#7D2B8B',pops:['jam','cpt'],ix:[],blurb:tr('long_tail.the_telco_for_st_helena_ascension')}, + {id:'bst',name:'Beastlink',asn:11260,type:'eye',cc:'CA',pol:'selective',minIx:2,minPni:10,share:.002,up:['cog','lvl'],col:'#EE3124',pops:['hfx','tor'],ix:['hfx'],blurb:tr('long_tail.atlantic_canada_s_cable_company')}); +NETS.push( + {id:'dgc',name:'Digi-Sell Caribbean',asn:40786,type:'eye',cc:['JM','TT','BB','MQ','CW','AG','DM','GD','GY','HT','KN','LC','SR','VC'],pol:'open',share:.002,up:['tly','lvl'],col:'#E2001A',pops:['kin','pos','bgi','fdf','cur','mia','anu','bas','dom','slu','svd','gnd','geo','pap','pbm'],ix:['kin'],blurb:tr('long_tail.the_same_phone_company_as_in')}, + {id:'wnt',name:'Whirled Net',asn:11367,type:'eye',cc:'PR',pol:'open',share:.0005,up:['lvl'],col:'#1F6FB2',pops:['sju'],ix:['sju'],blurb:tr('long_tail.puerto_rico_s_own_business_isp')}, + {id:'cbh',name:'Cable Bahamamama',asn:15146,type:'eye',cc:'BS',pol:'selective',minIx:2,minPni:10,share:.0008,up:['lvl','cog'],col:'#00A3AD',pops:['nas','mia'],ix:[],blurb:tr('long_tail.cable_tv_and_broadband_for_the')}, + {id:'etc',name:'Etecs-ah',asn:27725,type:'eye',cc:'CU',pol:'open',share:.002,up:['skl'],col:'#0055A4',pops:['hav'],ix:[],blurb:tr('long_tail.cuba_s_state_telco_and_only')}, + {id:'tst',name:'TSTT (This Should Take Time)',asn:5639,type:'eye',cc:'TT',pol:'selective',minIx:2,minPni:10,share:.001,up:['lvl'],col:'#C8102E',pops:['pos'],ix:['pos'],blurb:tr('long_tail.trinidad_and_tobago_s_incumbent_your')}, + {id:'cwt',name:'Curaçao Teal-ecom',asn:27660,type:'eye',cc:'CW',pol:'open',share:.0004,up:['tly'],col:'#00A6A6',pops:['cur'],ix:['cur'],blurb:tr('long_tail.the_island_s_own_telco_the')}, + {id:'cnp',name:'Canal Minus',asn:21351,type:'eye',cc:['MQ','RE'],pol:'selective',minIx:2,minPni:8,share:.0006,up:['tly'],col:'#111111',pops:['fdf','run','par'],ix:['run'],blurb:tr('long_tail.french_pay_tv_that_also_runs')}, + {id:'zeo',name:'Zealot',asn:37002,type:'eye',cc:'RE',pol:'open',share:.0005,up:['tly'],col:'#7A1FA2',pops:['run'],ix:['run'],blurb:tr('long_tail.r_union_s_fiber_challenger_very')}, + {id:'srr',name:'Signal Frequently Ruined',asn:49902,type:'eye',cc:'RE',pol:'selective',minIx:1,minPni:8,share:.0005,up:['tly'],col:'#E2001A',pops:['run'],ix:['run'],blurb:tr('long_tail.mobile_and_broadband_on_r_union')}, + {id:'mtc',name:'Dodo Telecom',asn:23889,type:'t2',cc:'MU',pol:'open',share:.001,price:9,up:['tat','tly'],col:'#D52B1E',pops:['mru','run','tnr','jnb','mrs'],ix:['mru'],blurb:tr('long_tail.the_island_s_incumbent_and_a')}, + {id:'emt',name:'Em-Tell',asn:30999,type:'eye',cc:'MU',pol:'open',share:.0004,up:['tat'],col:'#00953B',pops:['mru'],ix:['mru'],blurb:tr('long_tail.mauritius_number_two_telling_everyone')}, + {id:'tlm',name:'Telmaybe',asn:37054,type:'t2',cc:'MG',pol:'open',share:.0015,price:10,up:['tat','tly'],col:'#FFCC00',pops:['tnr','run','mru','jnb'],ix:['tnr'],blurb:tr('long_tail.madagascar_s_incumbent_and_the_only')}, + {id:'cws',name:'Cable & Witless Seychelles',asn:36958,type:'t2',cc:'SC',pol:'open',share:.0003,price:12,up:['tat'],col:'#E4007C',pops:['sez','mba'],ix:[],blurb:tr('long_tail.the_seychelles_old_telco_open_to')}, + {id:'acs',name:'Alaska Commotions',asn:7782,type:'eye',cc:'US',pol:'open',share:.0008,up:['lvl','cog'],col:'#0072CE',pops:['anc','jnu','sea'],ix:['anc'],blurb:tr('long_tail.alaska_s_old_phone_company_and')}, + {id:'gci',name:'Glacier Comms Inc.',asn:8047,type:'t2',cc:'US',pol:'open',share:.0015,price:11,up:['lvl','ntt'],col:'#00467F',pops:['anc','jnu','ome','brw','dut','sea'],ix:['sea'],blurb:tr('long_tail.alaska_s_biggest_network_from_anchorage')}, + {id:'mgf',name:'MegaPhone',asn:31133,type:'eye',cc:['RU','TJ'],pol:'selective',minIx:4,minPni:15,share:.003,up:['rtc'],col:'#00B956',pops:['mos','vvo','uus','pkc','mmk','gdx','dyu'],ix:['mos','vvo'],blurb:tr('long_tail.one_of_russia_s_big_mobile')}, + {id:'ert',name:'Er-Um Telecom',asn:9049,type:'eye',cc:'RU',pol:'open',share:.002,up:['rtc'],col:'#E30613',pops:['mos','vvo'],ix:['mos','vvo'],blurb:tr('long_tail.broadband_in_dozens_of_russian_cities')}); +NETS.push( + {id:'tet',name:'Tet-à-Tête',asn:12578,type:'eye',cc:'LV',pol:'selective',minIx:2,minPni:10,share:.001,up:['tly'],col:'#3F2A56',pops:['rix','sto'],ix:['rix'],blurb:tr('long_tail.latvia_s_incumbent_peers_face_to')}, + {id:'omt',name:'Omantell',asn:8529,type:'t2',cc:'OM',pol:'selective',minIx:3,minPni:12,share:.002,price:9,up:['tat','tly'],col:'#2F6E3B',pops:['mct','fuj','mrs','lon','bom'],ix:['mct'],blurb:tr('long_tail.oman_s_incumbent_and_owner_of')}, + {id:'dhr',name:'Dhiraa-goo',asn:7642,type:'t2',cc:'MV',pol:'open',share:.0003,price:12,up:['tat'],col:'#E2231A',pops:['mle','cbo'],ix:[],blurb:tr('long_tail.the_maldives_telco_on_islands_one')}); +// The far north and Canada's regional incumbents: the carriers that sell transit where the big ones never went. +NETS.push( + {id:'bal',name:'Bell Alien',asn:855,type:'t2',cc:'CA',pol:'selective',minIx:2,minPni:10,share:.0012,price:8,up:['bcd','lvl'],col:'#00549A',pops:['yfc','yyg','yyt','hfx','mtl'],ix:[],blurb:tr('long_tail.atlantic_canada_s_phone_company_landed')}, + {id:'nwt',name:'Northwest Passage Tel',asn:22573,type:'t2',cc:'CA',pol:'open',share:.0004,price:12,up:['bcd','lvl'],col:'#0067B1',pops:['yxy','yzf','yeg','van'],ix:[],blurb:tr('long_tail.the_north_s_only_carrier_fiber')}, + {id:'skt',name:'SaskTell-Tale',asn:803,type:'t2',cc:'CA',pol:'selective',minIx:2,minPni:10,share:.0012,price:8,up:['lvl','tly'],col:'#00A0DF',pops:['yqr','yxe','cal'],ix:[],blurb:tr('long_tail.saskatchewan_s_own_phone_company_still')}, + {id:'tus',name:'Too Sassy',asn:8818,type:'t2',cc:'GL',pol:'open',share:.0002,price:14,up:['tly'],col:'#C8102E',pops:['nuk','qaq','sis','aas'],ix:[],blurb:tr('long_tail.greenland_s_one_telco_answers_back')}); diff --git a/src/game/30-networks/32-homegrown-eyeballs.js b/src/game/30-networks/32-homegrown-eyeballs.js new file mode 100644 index 0000000..2f079b2 --- /dev/null +++ b/src/game/30-networks/32-homegrown-eyeballs.js @@ -0,0 +1,167 @@ +/* Homegrown eyeballs: every country on the map has at least two consumer networks of its own (gameplay rule W2, + tests/gameplay-rules.test.js). Each is a real operator of that country, with its real ASN, a traffic share scaled by + subscribers like the rest, presence where it really peers, and a realistic upstream (a big carrier where it sits, or + its group's own carrier), so it sits in a founding Tier 1's customer cone: Tier 1 is no harder for anyone, old saves included, + and older saves reach them by the courtesy route for their first 60 days (sanitize(), S.seen). One per line, sorted by id. + Sits before 40-traffic-shares.js, which indexes NETS. */ +NETS.push( + {id:'a1b',name:'A-Wan Bulgaria',asn:8717,type:'eye',cc:'BG',pol:'open',share:.0015,up:['aat'],col:'#DA291C',pops:['sof','vie'],ix:['sof'],blurb:tr('homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister')}, + {id:'aat',name:'A-Wan Telekom',asn:8447,type:'eye',cc:['AT','BY','HR','MK','SI'],pol:'selective',minIx:6,minPni:20,share:.003,up:['tly','lvl'],col:'#DA291C',pops:['vie','fra','prg','bud','msq','zag','skp','lju'],ix:['vie'],blurb:tr('homegrown_eyeballs.austria_s_incumbent_first_in_line')}, + {id:'adt',name:'Andorable Telecom',asn:6752,type:'t2',cc:'AD',pol:'open',share:.0002,price:11,up:['tng','cog'],col:'#E2001A',pops:['ala','bcn','par','tls'],ix:[],blurb:tr('homegrown_eyeballs.andorra_s_only_telco_by_law')}, + {id:'afc',name:'Afri-Sell',asn:37524,type:'eye',cc:['GM','SL'],pol:'open',share:.0006,up:['tng','cog'],col:'#6B2C91',pops:['bjl','fna'],ix:['bjl','fna'],blurb:tr('homegrown_eyeballs.a_mobile_group_from_the_gambia')}, + {id:'aft',name:'Afghan Tele-Pass',asn:55330,type:'t2',cc:'AF',pol:'open',share:.0008,price:13,up:['uzt','tta'],col:'#00843D',pops:['kbl','tas'],ix:['kbl'],blurb:tr('homegrown_eyeballs.afghanistan_s_state_telco_finds_transit')}, + {id:'agt',name:'Algérie Comme-Ci Comme-Ça',asn:36947,type:'eye',cc:'DZ',pol:'selective',minIx:2,minPni:12,share:.003,up:['tly','cog'],col:'#0B7A3E',pops:['alg','mrs'],ix:['alg'],blurb:tr('homegrown_eyeballs.algeria_s_state_incumbent_so_so')}, + {id:'ais',name:'AIS-cream',asn:45430,type:'eye',cc:'TH',pol:'selective',minIx:4,minPni:15,share:.006,up:['ntt','tat'],col:'#B5D334',pops:['bkk','sin','hkg'],ix:['bkk'],blurb:tr('homegrown_eyeballs.thailand_s_biggest_mobile_network_cool')}, + {id:'alb',name:'Altibox of Chocolates',asn:29695,type:'eye',cc:'NO',pol:'open',share:.002,up:['tly','cog'],col:'#2D2A6E',pops:['osl','svg','krs'],ix:['osl','svg'],blurb:tr('homegrown_eyeballs.norwegian_fibre_from_the_power_company')}, + {id:'alt',name:'Alt-Ctrl-Dominicana',asn:28118,type:'eye',cc:'DO',pol:'selective',minIx:2,minPni:10,share:.0015,up:['lvl','cog'],col:'#1A1A1A',pops:['sdq','mia'],ix:[],blurb:tr('homegrown_eyeballs.the_dominican_republic_s_other_big')}, + {id:'arb',name:'Are-Beeba',asn:37612,type:'eye',cc:'GN',pol:'open',share:.0006,up:['mtx'],col:'#FFCC00',pops:['cky'],ix:['cky'],blurb:tr('homegrown_eyeballs.guinea_s_old_mtn_network_now')}, + {id:'ast',name:'Pay-Go Pay-Go Telecom',asn:9751,type:'eye',cc:'AS',pol:'selective',minIx:1,minPni:8,share:.0004,up:['fnt','tly'],col:'#00539B',pops:['ppg'],ix:[],blurb:tr('homegrown_eyeballs.american_samoa_s_own_telco_prepaid')}, + {id:'athk',name:'Atoll-H Kiribati',asn:134783,type:'t2',cc:'KI',pol:'open',share:.0002,price:14,up:['dsp'],col:'#E60000',pops:['trw','suv'],ix:[],blurb:tr('homegrown_eyeballs.kiribati_s_telco_spread_over_more')}, + {id:'awc',name:'AW-CC-Shucks',asn:138322,type:'eye',cc:'AF',pol:'open',share:.0008,up:['uzt','rtc','drz'],col:'#E4002B',pops:['kbl'],ix:['kbl'],blurb:tr('homegrown_eyeballs.afghanistan_s_first_mobile_network_still')}, + {id:'azc',name:'Azer-Sell',asn:31721,type:'eye',cc:'AZ',pol:'open',share:.0012,up:['azt'],col:'#6E2C8F',pops:['gyd'],ix:[],blurb:tr('homegrown_eyeballs.azerbaijan_s_biggest_mobile_network_it')}, + {id:'azt',name:'Aztec-om',asn:34170,type:'t2',cc:'AZ',pol:'selective',minIx:2,minPni:10,share:.001,price:10,up:['tly','skl','drz'],col:'#0054A6',pops:['gyd','tbs','fra'],ix:[],blurb:tr('homegrown_eyeballs.azerbaijan_s_state_telco_no_pyramids')}, + {id:'bat',name:'Bat-elco',asn:5416,type:'t2',cc:'BH',pol:'selective',minIx:2,minPni:10,share:.0008,price:9,up:['omt','cog','stc'],col:'#E31E24',pops:['bah','dxb','lon'],ix:['bah'],blurb:tr('homegrown_eyeballs.bahrain_s_old_telco_hangs_upside')}, + {id:'bel',name:'Belize It Or Not',asn:10269,type:'t2',cc:'BZ',pol:'open',share:.0003,price:10,up:['llt','lvl'],col:'#0072BC',pops:['bcv','mia'],ix:[],blurb:tr('homegrown_eyeballs.belize_s_old_phone_company_still')}, + {id:'bht',name:'Herze-Go-Fast',asn:9146,type:'t2',cc:'BA',pol:'open',share:.0008,price:9,up:['tly','lvl','cog'],col:'#004C97',pops:['sjj','vie'],ix:['sjj'],blurb:tr('homegrown_eyeballs.sarajevo_s_telco_on_the_exchange')}, + {id:'bhu',name:'Gross National Happiness Telecom',asn:17660,type:'t2',cc:'BT',pol:'open',share:.0003,price:11,up:['ntt','drz','tat'],col:'#F2A900',pops:['pbh','del'],ix:['pbh'],blurb:tr('homegrown_eyeballs.bhutan_s_state_telco_measures_its')}, + {id:'bit',name:'Bitė Me',asn:13194,type:'eye',cc:'LT',pol:'open',share:.0008,up:['tat','cog','lvl'],col:'#F7D117',pops:['vno','sto'],ix:['vno'],blurb:tr('homegrown_eyeballs.lithuania_s_bee_buzzes_louder_than')}, + {id:'blt',name:'Belt & Braces Telecom',asn:6697,type:'t2',cc:'BY',pol:'selective',minIx:3,minPni:12,share:.002,price:9,up:['tly','cog','rtc'],col:'#0055A4',pops:['msq','fra','mos'],ix:['msq'],blurb:tr('homegrown_eyeballs.belarus_s_state_telco_and_one')}, + {id:'bmo',name:'To Be Mobile',asn:132462,type:'eye',cc:'SB',pol:'open',share:.0002,up:['tly'],col:'#E4007C',pops:['hir'],ix:['hir'],blurb:tr('homegrown_eyeballs.the_solomon_islands_mobile_challenger_to')}, + {id:'btc',name:'Botswana Tele-cow',asn:14988,type:'eye',cc:'BW',pol:'selective',minIx:1,minPni:8,share:.0006,up:['liq'],col:'#0072BC',pops:['gbe','jnb'],ix:['gbe'],blurb:tr('homegrown_eyeballs.botswana_s_incumbent_with_more_towers')}, + {id:'bzi',name:'Be-Quick International',asn:8551,type:'t2',cc:'IL',pol:'selective',minIx:3,minPni:12,share:.002,price:8,up:['drz','tly','cog','lvl','tat'],col:'#00A0DF',pops:['jer','fra','lon','nyc'],ix:[],blurb:tr('homegrown_eyeballs.israel_s_international_carrier_always_in')}, + {id:'cbn',name:'Cable-Not',asn:35432,type:'eye',cc:'CY',pol:'open',share:.0004,up:['skl','tly','drz'],col:'#00A651',pops:['nic'],ix:['nic'],blurb:tr('homegrown_eyeballs.cyprus_s_cable_challenger_despite_the')}, + {id:'cgo',name:'Tele-Conga',asn:37451,type:'t2',cc:'CG',pol:'open',share:.0003,price:12,up:['tng','cog'],col:'#009543',pops:['bzv','fih','lag'],ix:['bzv','fih'],blurb:tr('homegrown_eyeballs.the_republic_of_congo_s_state')}, + {id:'cgt',name:'Crno-Gorgeous Telekom',asn:8585,type:'t2',cc:'ME',pol:'open',share:.0004,price:10,up:['mgt','mts'],col:'#E20074',pops:['tgd','bud'],ix:[],blurb:tr('homegrown_eyeballs.montenegro_s_old_telekom_magenta_and')}, + {id:'clc',name:'Seldom-Digi',asn:10030,type:'eye',cc:'MY',pol:'selective',minIx:4,minPni:15,share:.003,up:['ntt','tat'],col:'#0019FF',pops:['kul','sin'],ix:['kul'],blurb:tr('homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom')}, + {id:'cnl',name:'Can’t’L',asn:17480,type:'eye',cc:'NC',pol:'open',share:.0003,up:['pft','tly'],col:'#E30613',pops:['nou'],ix:['nou'],blurb:tr('homegrown_eyeballs.new_caledonia_s_cable_operator_can')}, + {id:'cpc',name:'Cen-Pac-Man',asn:55722,type:'t2',cc:'NR',pol:'open',share:.0001,price:14,up:['gtg'],col:'#FFCC00',pops:['inu'],ix:[],blurb:tr('homegrown_eyeballs.nauru_s_fixed_line_operator_eating')}, + {id:'cst',name:'Cocoa-Santomense Tele',asn:328191,type:'t2',cc:'ST',pol:'open',share:.0001,price:14,up:['agc'],col:'#00843D',pops:['tms','lbv'],ix:[],blurb:tr('homegrown_eyeballs.s_o_tom_s_telco_on_two')}, + {id:'ctv',name:'Can’t-V',asn:8048,type:'eye',cc:'VE',pol:'selective',minIx:2,minPni:10,share:.002,up:['tly','lvl'],col:'#0055A5',pops:['ccs','mia'],ix:['ccs'],blurb:tr('homegrown_eyeballs.venezuela_s_state_telco_stretched')}, + {id:'cyt',name:'Cyte-Seeing',asn:6866,type:'t2',cc:'CY',pol:'selective',minIx:2,minPni:10,share:.0008,price:9,up:['tly','skl','lvl'],col:'#003F87',pops:['nic','ath','mrs'],ix:['nic'],blurb:tr('homegrown_eyeballs.cyprus_s_state_telco_lands_cables')}, + {id:'dcm',name:'Docomo Arigato',asn:9605,type:'eye',cc:'JP',pol:'selective',minIx:6,minPni:20,share:.008,up:['ntt'],col:'#CC0033',pops:['tok','osa','fuk'],ix:['tok','osa'],blurb:tr('homegrown_eyeballs.japan_s_biggest_mobile_network_bows')}, + {id:'djz',name:'Djezzy Does It',asn:327931,type:'eye',cc:'DZ',pol:'open',share:.002,up:['tly'],col:'#E2001A',pops:['alg'],ix:['alg'],blurb:tr('homegrown_eyeballs.algeria_s_biggest_mobile_network_easy')}, + {id:'dlg',name:'Inner Dialog',asn:18001,type:'eye',cc:'LK',pol:'open',share:.0015,up:['tat','ntt'],col:'#E5202E',pops:['cbo'],ix:['cbo'],blurb:tr('homegrown_eyeballs.sri_lanka_s_biggest_mobile_network_talks')}, + {id:'dna',name:'DNA Test Results',asn:16086,type:'eye',cc:'FI',pol:'open',share:.002,up:['tly'],col:'#FF4F00',pops:['hel'],ix:['hel'],blurb:tr('homegrown_eyeballs.finnish_broadband_and_mobile_it_s')}, + {id:'ecn',name:'Eco-Neat',asn:33567,type:'eye',cc:['BI','LS'],pol:'open',share:.0005,up:['liq'],col:'#0072CE',pops:['gid','msu'],ix:['msu'],blurb:tr('homegrown_eyeballs.econet_s_mobile_networks_in_burundi')}, + {id:'ele',name:'Für Elisa Eesti',asn:2586,type:'eye',cc:'EE',pol:'open',share:.0008,up:['els'],col:'#0068B4',pops:['tll'],ix:['tll'],blurb:tr('homegrown_eyeballs.fur_elisa_across_the_gulf_of')}, + {id:'els',name:'Für Elisa',asn:719,type:'eye',cc:'FI',pol:'selective',minIx:5,minPni:20,share:.003,up:['tly','cog'],col:'#0068B4',pops:['hel','sto'],ix:['hel'],blurb:tr('homegrown_eyeballs.finland_s_biggest_mobile_network_unlimited')}, + {id:'ent',name:'Entel-ligence',asn:6568,type:'eye',cc:'BO',pol:'selective',minIx:2,minPni:10,share:.0012,up:['tly','lvl'],col:'#0033A0',pops:['lpb'],ix:['lpb'],blurb:tr('homegrown_eyeballs.bolivia_s_state_telco_thinking_hard')}, + {id:'ept',name:'Swazi Post & Tele-Pole',asn:19711,type:'t2',cc:'SZ',pol:'open',share:.0003,price:12,up:['agc','mtx'],col:'#1C3F94',pops:['qmn','jnb'],ix:[],blurb:tr('homegrown_eyeballs.eswatini_s_post_office_and_telco')}, + {id:'eri',name:'Eri-Tell-Me-More',asn:30987,type:'t2',cc:'ER',pol:'restrictive',share:.0001,price:18,up:['tng','cog'],col:'#418FDE',pops:['asm'],ix:[],blurb:tr('homegrown_eyeballs.eritrea_s_one_state_network_on')}, + {id:'erl',name:'Earth-Linky',asn:50710,type:'t2',cc:'IQ',pol:'open',share:.0015,price:12,up:['ttk','stc','cog'],col:'#1D70B8',pops:['bgw'],ix:['bgw'],blurb:tr('homegrown_eyeballs.iraq_s_biggest_home_isp_down')}, + {id:'fet',name:'Far EasTone-Deaf',asn:9674,type:'eye',cc:'TW',pol:'selective',minIx:3,minPni:12,share:.003,up:['ntt'],col:'#E60012',pops:['tpe','hkg'],ix:['tpe'],blurb:tr('homegrown_eyeballs.taiwan_s_number_three_never_hears')}, + {id:'fl1',name:'FL-One-Liner',asn:20634,type:'t2',cc:'LI',pol:'open',share:.0002,price:10,up:['lvl','aat'],col:'#9F1D35',pops:['vdz','zrh'],ix:['vdz'],blurb:tr('homegrown_eyeballs.liechtenstein_s_telecom_short_enough_for')}, + {id:'fre',name:'Free as in Beer',asn:12322,type:'eye',cc:'FR',pol:'selective',minIx:6,minPni:20,share:.006,up:['cog','lvl'],col:'#CD1E25',pops:['par','mrs','ams','lon','fra','lys','tls','lil','bod','sxb','rns','nte'],ix:['par','mrs','lys','tls','lil','bod'],blurb:tr('homegrown_eyeballs.the_challenger_that_made_french_broadband')}, + {id:'frs',name:'Oh Yas Sénégal',asn:37649,type:'eye',cc:['SN','KM'],pol:'open',share:.0008,up:['tat','tly'],col:'#FFD100',pops:['dkr','hah'],ix:['dkr'],blurb:tr('homegrown_eyeballs.senegal_s_number_two_freshly_renamed')}, + {id:'fsm',name:'Island-Hop Micronesia',asn:10130,type:'t2',cc:'FM',pol:'open',share:.0001,price:14,up:['gtg'],col:'#0072CE',pops:['pni','gum'],ix:[],blurb:tr('homegrown_eyeballs.micronesia_s_only_telco_noodling_across')}, + {id:'gbt',name:'Gabon Tele-Calm',asn:16058,type:'t2',cc:'GA',pol:'open',share:.0004,price:11,up:['mrc','tng'],col:'#F7941D',pops:['lbv','cas'],ix:['lbv'],blurb:tr('homegrown_eyeballs.gabon_s_old_telco_now_part')}, + {id:'gdc',name:'Global Disconnect',asn:31027,type:'t2',pol:'open',share:.0008,price:5,up:['tly','cog'],col:'#00B2A9',pops:['sto','got','mmx','hpa','cph','osl','hel','ber'],ix:['sto','got','cph','osl','hel'],blurb:tr('homegrown_eyeballs.the_nordic_fibre_carrier_whose_superfibre')}, + {id:'get',name:'GET-ESA Going',asn:37173,type:'t2',cc:'GQ',pol:'open',share:.0002,price:14,up:['agc'],col:'#3E9A3D',pops:['ssg','dla'],ix:[],blurb:tr('homegrown_eyeballs.equatorial_guinea_s_state_telco_finally')}, + {id:'glb',name:'Globe-Trotter Telecom',asn:4775,type:'t2',cc:'PH',pol:'selective',minIx:3,minPni:15,share:.006,price:6,up:['ntt','tat'],col:'#0056A2',pops:['mnl','ceb','dvo','hkg','sin'],ix:['mnl','mnl~2','hkg','sin'],blurb:tr('homegrown_eyeballs.the_philippines_other_mobile_giant_roaming')}, + {id:'gmt',name:'Gam-Tell',asn:25250,type:'t2',cc:'GM',pol:'open',share:.0003,price:12,up:['skl','cog'],col:'#0072BC',pops:['bjl','dkr'],ix:['bjl'],blurb:tr('homegrown_eyeballs.the_gambia_s_state_telco_and')}, + {id:'gom',name:'GO-Getter',asn:15735,type:'t2',cc:'MT',pol:'open',share:.0005,price:10,up:['skl','tly','cog'],col:'#E3001B',pops:['mla','pmo'],ix:[],blurb:tr('homegrown_eyeballs.malta_s_old_telco_with_its')}, + {id:'gph',name:'Grameen Machine',asn:24389,type:'eye',cc:'BD',pol:'selective',minIx:3,minPni:12,share:.004,up:['tat','ntt'],col:'#19AAF8',pops:['dac','sin'],ix:['dac'],blurb:tr('homegrown_eyeballs.bangladesh_s_biggest_mobile_network_a')}, + {id:'gyt',name:'Gee Tee Tea',asn:19863,type:'t2',cc:'GY',pol:'open',share:.0004,price:11,up:['llt','drz','tat'],col:'#00843D',pops:['geo','pos'],ix:[],blurb:tr('homegrown_eyeballs.guyana_s_telephone_and_telegraph_company')}, + {id:'hkb',name:'Ding-Ding Broadband',asn:9269,type:'eye',cc:'HK',pol:'open',share:.002,up:['ntt','cog'],col:'#6A2C91',pops:['hkg'],ix:['hkg'],blurb:tr('homegrown_eyeballs.fibre_to_every_tower_block_rung')}, + {id:'hkt',name:'Net-Vigour HK',asn:4760,type:'eye',cc:'HK',pol:'selective',minIx:5,minPni:20,share:.004,up:['ntt','tat'],col:'#00A0E1',pops:['hkg','sin','tok','lax'],ix:['hkg'],blurb:tr('homegrown_eyeballs.hong_kong_s_incumbent_broadband_full')}, + {id:'hoi',name:'Hoi Polloi Internet',asn:35223,type:'eye',cc:'LI',pol:'open',share:.0001,up:['fl1'],col:'#3A7D44',pops:['vdz'],ix:['vdz'],blurb:tr('homegrown_eyeballs.fibre_for_the_rest_of_liechtenstein')}, + {id:'hrm',name:'Hormoody',asn:37371,type:'t2',cc:'SO',pol:'open',share:.0006,price:13,up:['scm','cog'],col:'#008C45',pops:['mgq','mba'],ix:[],blurb:tr('homegrown_eyeballs.somalia_s_biggest_telco_moody_but')}, + {id:'hrt',name:'Cravat Telekom',asn:5391,type:'t2',cc:'HR',pol:'selective',minIx:3,minPni:12,share:.0015,price:9,up:['dtk','cog','skl','tly'],col:'#E20074',pops:['zag','vie','fra'],ix:['zag'],blurb:tr('homegrown_eyeballs.croatia_s_telekom_tied_to_magenta')}, + {id:'jaz',name:'All That Jazz',asn:45669,type:'eye',cc:'PK',pol:'selective',minIx:2,minPni:10,share:.004,up:['tat'],col:'#ED1C24',pops:['khi','dxb'],ix:['khi'],blurb:tr('homegrown_eyeballs.pakistan_s_biggest_mobile_network_improvising')}, + {id:'kcl',name:'K-Sell',asn:29355,type:'eye',cc:'KZ',pol:'open',share:.0015,up:['kzt'],col:'#7B2C8F',pops:['nqz'],ix:['nqz'],blurb:tr('homegrown_eyeballs.kazakhstan_s_first_mobile_network_selling')}, + {id:'kgt',name:'Yurt-elecom',asn:12997,type:'t2',cc:'KG',pol:'open',share:.0005,price:11,up:['kzt','rtc'],col:'#0072BC',pops:['fru'],ix:['fru'],blurb:tr('homegrown_eyeballs.kyrgyzstan_s_old_telco_packs_up')}, + {id:'kmt',name:'Comores Tele-Calm',asn:36939,type:'t2',cc:'KM',pol:'open',share:.0002,price:13,up:['bgs','tng'],col:'#3A75C4',pops:['hah','dar'],ix:[],blurb:tr('homegrown_eyeballs.the_comoros_old_telco_calm_on')}, + {id:'kpn',name:'Kay-Pea-Nuts',asn:1136,type:'eye',cc:'NL',pol:'selective',minIx:6,minPni:20,share:.005,up:['lvl','tly'],col:'#00C300',pops:['ams','fra','lon'],ix:['ams'],blurb:tr('homegrown_eyeballs.the_dutch_incumbent_peers_for_peanuts')}, + {id:'kzt',name:'Steppe-by-Steppe Telecom',asn:9198,type:'t2',cc:'KZ',pol:'selective',minIx:2,minPni:10,share:.002,price:10,up:['rtc','mgf','cog'],col:'#00A3E0',pops:['nqz','mos','fra'],ix:['nqz'],blurb:tr('homegrown_eyeballs.kazakhstan_s_state_telco_crossing_the')}, + {id:'lfc',name:'Half-Life-cell',asn:34058,type:'eye',cc:'UA',pol:'open',share:.002,up:['cog','tly'],col:'#FFCC00',pops:['kyv','waw','fra'],ix:['kyv'],blurb:tr('homegrown_eyeballs.ukraine_s_third_mobile_network_kept')}, + {id:'lmt',name:'Let Me Talk',asn:12847,type:'eye',cc:'LV',pol:'selective',minIx:2,minPni:8,share:.0008,up:['tly'],col:'#4E2C82',pops:['rix','sto'],ix:['rix'],blurb:tr('homegrown_eyeballs.latvia_s_mobile_leader_let_me')}, + {id:'ltc',name:'Lao-d and Clear',asn:9873,type:'t2',cc:'LA',pol:'open',share:.0005,price:11,up:['drz','tly'],col:'#C8102E',pops:['vte','bkk'],ix:[],blurb:tr('homegrown_eyeballs.laos_s_state_telco_loud_and')}, + {id:'ltt',name:'Libya Tele-Tech',asn:21003,type:'t2',cc:'LY',pol:'open',share:.0008,price:11,up:['skl','tly'],col:'#239E46',pops:['tip','pmo'],ix:[],blurb:tr('homegrown_eyeballs.libya_s_fixed_isp_on_the')}, + {id:'lyb',name:'Libyana-Joneses',asn:328286,type:'eye',cc:'LY',pol:'open',share:.0008,up:['ltt'],col:'#E2001A',pops:['tip'],ix:[],blurb:tr('homegrown_eyeballs.libya_s_biggest_mobile_network_keeping')}, + {id:'mbc',name:'Mobi-Khan',asn:55805,type:'t2',cc:'MN',pol:'open',share:.0005,price:11,up:['tly','drz','ntt'],col:'#E4002B',pops:['uln','pek','hkg'],ix:['uln'],blurb:tr('homegrown_eyeballs.mongolia_s_first_mobile_network_ruling')}, + {id:'mca',name:'MT-Sea',asn:37009,type:'eye',cc:'NA',pol:'selective',minIx:1,minPni:8,share:.0005,up:['liq'],col:'#0067B1',pops:['wdh'],ix:['wdh'],blurb:tr('homegrown_eyeballs.namibia_s_mobile_network_lots_of')}, + {id:'mci',name:'Hamrah-on',asn:197207,type:'eye',cc:'IR',pol:'selective',minIx:2,minPni:10,share:.003,up:['tci'],col:'#00A3E0',pops:['thr'],ix:['thr'],blurb:tr('homegrown_eyeballs.iran_s_first_mobile_network_hamrah')}, + {id:'mdt',name:'Moldy Telecom',asn:8926,type:'t2',cc:'MD',pol:'open',share:.0008,price:9,up:['cog','lvl','tly'],col:'#0072BC',pops:['kiv','buh','fra'],ix:['kiv'],blurb:tr('homegrown_eyeballs.moldova_s_state_telco_aged_like')}, + {id:'mgc',name:'Magic-com',asn:16010,type:'eye',cc:'GE',pol:'open',share:.0008,up:['skn','tly'],col:'#E2001A',pops:['tbs'],ix:['tbs'],blurb:tr('homegrown_eyeballs.georgia_s_biggest_mobile_network_pulls')}, + {id:'mgt',name:'Magenta Paprika',asn:5483,type:'eye',cc:['HU','ME','MK'],pol:'selective',minIx:4,minPni:15,share:.003,up:['dtk','tly'],col:'#E20074',pops:['bud','vie','fra','tgd','skp'],ix:['bud'],blurb:tr('homegrown_eyeballs.doitsche_telekomm_s_hungarian_daughter_pink')}, + {id:'mlt',name:'Melitamin',asn:12709,type:'eye',cc:'MT',pol:'open',share:.0004,up:['lvl','tly','ntt'],col:'#7A2B8F',pops:['mla','pmo'],ix:[],blurb:tr('homegrown_eyeballs.malta_s_cable_company_with_a')}, + {id:'mnc',name:'Monte-Carlo-Bits',asn:6758,type:'t2',cc:'MC',pol:'open',share:.0002,price:11,up:['tly','cog','vdp'],col:'#C8102E',pops:['mco','mrs','nic','mla'],ix:[],blurb:tr('homegrown_eyeballs.monaco_s_one_telco_and_its')}, + {id:'mni',name:'Muni-Cipal',asn:37337,type:'eye',cc:'GQ',pol:'open',share:.0001,up:['get'],col:'#FF6600',pops:['ssg'],ix:[],blurb:tr('homegrown_eyeballs.equatorial_guinea_s_second_mobile_network')}, + {id:'mob',name:'Mobily-zation',asn:35819,type:'eye',cc:'SA',pol:'selective',minIx:3,minPni:12,share:.004,up:['tat','tly'],col:'#00A7E1',pops:['ruh','jed','dxb','fra'],ix:['ruh'],blurb:tr('homegrown_eyeballs.the_kingdom_s_challenger_always_mobilising')}, + {id:'mpt',name:'Empty Telecom',asn:9988,type:'t2',cc:'MM',pol:'open',share:.0012,price:12,up:['atl','tat'],col:'#0072BC',pops:['nyt','sin'],ix:[],blurb:tr('homegrown_eyeballs.myanmar_s_state_telco_its_initials')}, + {id:'mrt',name:'Mauri-Tell',asn:29544,type:'t2',cc:'MR',pol:'open',share:.0004,price:12,up:['tng','tly','cog'],col:'#F7941D',pops:['nkc','cas'],ix:[],blurb:tr('homegrown_eyeballs.mauritania_s_old_telco_with_moroccan')}, + {id:'msc',name:'Mascot Wireless',asn:37014,type:'eye',cc:'BW',pol:'open',share:.0006,up:['liq'],col:'#008FD5',pops:['gbe'],ix:['gbe'],blurb:tr('homegrown_eyeballs.botswana_s_biggest_mobile_network_with')}, + {id:'mts',name:'Serve-ia Telekom',asn:8400,type:'eye',cc:['RS','BA','ME'],pol:'selective',minIx:3,minPni:12,share:.003,up:['tly','cog'],col:'#E2001A',pops:['beg','fra','sof','sjj','tgd'],ix:[],blurb:tr('homegrown_eyeballs.serbia_s_incumbent_at_your_service')}, + {id:'mtt',name:'Mat-Tell',asn:37508,type:'eye',cc:'MR',pol:'open',share:.0003,up:['tng','cog'],col:'#00A651',pops:['nkc'],ix:[],blurb:tr('homegrown_eyeballs.mauritania_s_first_mobile_network_flat')}, + {id:'mvc',name:'Movi-Sell',asn:37081,type:'eye',cc:'AO',pol:'open',share:.0008,up:['agc'],col:'#F7941D',pops:['lad'],ix:['lad'],blurb:tr('homegrown_eyeballs.angola_s_number_two_always_on')}, + {id:'mvt',name:'Movie-Tell',asn:37342,type:'eye',cc:'MZ',pol:'open',share:.0006,up:['liq'],col:'#E30613',pops:['mpm'],ix:['mpm'],blurb:tr('homegrown_eyeballs.mozambique_s_rural_mobile_network_towers')}, + {id:'ncl',name:'N-Sell',asn:38565,type:'eye',cc:'NP',pol:'open',share:.0008,up:['atl','tat'],col:'#7E2D8F',pops:['ktm'],ix:['ktm'],blurb:tr('homegrown_eyeballs.nepal_s_biggest_private_mobile_network')}, + {id:'nov',name:'Super-Nova hf.',asn:43571,type:'eye',cc:'IS',pol:'open',share:.0004,up:['tly','cog'],col:'#ED1F7F',pops:['rek'],ix:[],blurb:tr('homegrown_eyeballs.iceland_s_mobile_challenger_burning_bright')}, + {id:'nrl',name:'Northern Lights Out',asn:8273,type:'eye',cc:'DK',pol:'open',share:.002,up:['tly','cog'],col:'#00A651',pops:['cph','ebj'],ix:['cph'],blurb:tr('homegrown_eyeballs.danish_fibre_from_the_power_company')}, + {id:'ntc',name:'Not-Com',asn:52260,type:'t2',cc:'HT',pol:'open',share:.0008,price:12,up:['llt','cog'],col:'#F7941D',pops:['pap','mia'],ix:[],blurb:tr('homegrown_eyeballs.haiti_s_national_telco_rebuilt_by')}, + {id:'ntg',name:'Niger Tele-Goes',asn:37385,type:'t2',cc:'NE',pol:'open',share:.0004,price:13,up:['mtx'],col:'#E05206',pops:['nim','lag'],ix:[],blurb:tr('homegrown_eyeballs.niger_s_state_telco_reaching_the')}, + {id:'ntl',name:'Ne-Pal Telecom',asn:23752,type:'t2',cc:'NP',pol:'selective',minIx:2,minPni:10,share:.001,price:10,up:['atl','tat'],col:'#003893',pops:['ktm','del'],ix:['ktm'],blurb:tr('homegrown_eyeballs.nepal_s_state_telco_everybody_s_pal')}, + {id:'ocl',name:'Ocean Wink',asn:132486,type:'eye',cc:'KI',pol:'open',share:.0001,up:['athk'],col:'#00A9E0',pops:['trw'],ix:[],blurb:tr('homegrown_eyeballs.kiribati_s_second_mobile_network_winking')}, + {id:'ogr',name:'Ogre-o',asn:42020,type:'t2',cc:'LB',pol:'selective',minIx:2,minPni:10,share:.001,price:11,up:['tng','lvl'],col:'#ED1C24',pops:['bey','mrs'],ix:['bey'],blurb:tr('homegrown_eyeballs.lebanon_s_state_network_the_ogre')}, + {id:'omv',name:'Ooh-redoo Atolls',asn:55944,type:'eye',cc:'MV',pol:'open',share:.0003,up:['ord','tat'],col:'#ED1C24',pops:['mle'],ix:[],blurb:tr('homegrown_eyeballs.ooh_redoo_s_maldives_branch_four')}, + {id:'onk',name:'Oh Really!',asn:47237,type:'eye',cc:'KG',pol:'open',share:.0005,up:['kgt'],col:'#E6007E',pops:['fru'],ix:['fru'],blurb:tr('homegrown_eyeballs.kyrgyzstan_s_biggest_mobile_network_named')}, + {id:'onl',name:'Won Albania',asn:42313,type:'eye',cc:'AL',pol:'open',share:.0008,up:['skl','cog','tly'],col:'#E4002B',pops:['tia'],ix:['tia'],blurb:tr('homegrown_eyeballs.albania_s_biggest_mobile_network_it')}, + {id:'onz',name:'Won New Zealand',asn:4768,type:'eye',cc:'NZ',pol:'selective',minIx:3,minPni:12,share:.002,up:['ntt','tly'],col:'#E4002B',pops:['akl','chc','syd','wlg'],ix:['akl','chc'],blurb:tr('homegrown_eyeballs.new_zealand_s_number_two_renamed')}, + {id:'otn',name:'Ooh-redoo Tunisie',asn:37693,type:'eye',cc:'TN',pol:'open',share:.0012,up:['ord','tly'],col:'#ED1C24',pops:['tun','mrs'],ix:['tun'],blurb:tr('homegrown_eyeballs.ooh_redoo_s_tunisian_network_mint')}, + {id:'p3t',name:'Out-of-Phase Telecom',asn:37148,type:'t2',cc:'NG',pol:'open',share:.0003,price:12,up:['mtx','tat'],col:'#2E7D32',pops:['abv','lag'],ix:[],blurb:tr('homegrown_eyeballs.nigeria_s_wholesale_backbone_strung_along')}, + {id:'pmc',name:'Pal-O-Mine Mobile',asn:58932,type:'eye',cc:'PW',pol:'open',share:.0002,up:['ntt'],col:'#0099CC',pops:['ror'],ix:[],blurb:tr('homegrown_eyeballs.palau_s_mobile_challenger_your_pal')}, + {id:'prm',name:'Paradise Lost Mobile',asn:55159,type:'eye',cc:'BM',pol:'open',share:.0003,up:['lvl'],col:'#00B2A9',pops:['bda'],ix:[],blurb:tr('homegrown_eyeballs.bermuda_s_newest_mobile_network_the')}, + {id:'prt',name:'Pardner',asn:12400,type:'eye',cc:'IL',pol:'open',share:.0015,up:['cog','lvl','drz'],col:'#00B5E2',pops:['jer','fra','lon'],ix:[],blurb:tr('homegrown_eyeballs.israel_s_mobile_and_fibre_network')}, + {id:'rob',name:'Robi-n Hood',asn:24432,type:'eye',cc:'BD',pol:'open',share:.002,up:['tat'],col:'#E2231A',pops:['dac'],ix:['dac'],blurb:tr('homegrown_eyeballs.takes_from_the_big_carriers_and')}, + {id:'sax',name:'Smart Axe-iata',asn:45498,type:'eye',cc:'KH',pol:'open',share:.0008,up:['drz','tat'],col:'#00A651',pops:['pnh'],ix:['pnh'],blurb:tr('homegrown_eyeballs.cambodia_s_biggest_mobile_network_chopping')}, + {id:'sbn',name:'Celtiis Me More',asn:28683,type:'t2',cc:'BJ',pol:'open',share:.0005,price:11,up:['mtx','tng','cog'],col:'#E3B505',pops:['pto','lag'],ix:[],blurb:tr('homegrown_eyeballs.benin_s_state_network_and_its')}, + {id:'sdn',name:'Sudani-ly',asn:15706,type:'t2',cc:'SD',pol:'open',share:.0008,price:12,up:['stc','lvl','cog'],col:'#00A3E0',pops:['krt','jed'],ix:['krt'],blurb:tr('homegrown_eyeballs.sudan_s_national_telco_which_moved')}, + {id:'sft',name:'Sahel-ebrity Fiber',asn:328594,type:'t2',cc:'TD',pol:'open',share:.0003,price:14,up:['mtx'],col:'#C99700',pops:['ndj','dla'],ix:['ndj'],blurb:tr('homegrown_eyeballs.chad_s_busiest_network_the_wholesaler')}, + {id:'skn',name:'Silk Road Net',asn:35805,type:'t2',cc:'GE',pol:'selective',minIx:2,minPni:10,share:.0008,price:10,up:['tly','lvl','drz'],col:'#E30613',pops:['tbs','sof','fra'],ix:['tbs'],blurb:tr('homegrown_eyeballs.georgia_s_incumbent_on_the_old')}, + {id:'slk',name:'Slow-vak Telekom',asn:6855,type:'t2',cc:'SK',pol:'selective',minIx:3,minPni:12,share:.0015,price:9,up:['dtk','tly'],col:'#E20074',pops:['bts','vie','fra'],ix:['bts'],blurb:tr('homegrown_eyeballs.slovakia_s_telekom_never_actually_slow')}, + {id:'slt',name:'SLT-and-Pepper',asn:9329,type:'eye',cc:'LK',pol:'selective',minIx:2,minPni:10,share:.0015,up:['tat'],col:'#0070C0',pops:['cbo','sin'],ix:['cbo'],blurb:tr('homegrown_eyeballs.sri_lanka_s_incumbent_adds_a')}, + {id:'sml',name:'Som-Tell',asn:328469,type:'eye',cc:'SO',pol:'open',share:.0004,up:['scm','art'],col:'#0055A4',pops:['mgq'],ix:[],blurb:tr('homegrown_eyeballs.somalia_s_second_telco_telling_it')}, + {id:'smn',name:'Símon Says',asn:215793,type:'eye',cc:'IS',pol:'selective',minIx:1,minPni:8,share:.0006,up:['tly'],col:'#4A2B83',pops:['rek','lon'],ix:[],blurb:tr('homegrown_eyeballs.iceland_s_incumbent_when_simon_says')}, + {id:'spt',name:'Smarty Pants',asn:266762,type:'eye',cc:'BZ',pol:'open',share:.0002,up:['bel'],col:'#E4002B',pops:['bcv'],ix:[],blurb:tr('homegrown_eyeballs.belize_s_mobile_challenger_quick_with')}, + {id:'ste',name:'Damask Telecom',asn:29256,type:'t2',cc:'SY',pol:'open',share:.0008,price:14,up:['cyt','teg'],col:'#007A3D',pops:['dam'],ix:[],blurb:tr('homegrown_eyeballs.syria_s_state_telco_woven_through')}, + {id:'sth',name:'StarHubble',asn:4657,type:'eye',cc:'SG',pol:'selective',minIx:4,minPni:15,share:.003,up:['ntt','tat'],col:'#68B030',pops:['sin','hkg'],ix:['sin'],blurb:tr('homegrown_eyeballs.singapore_s_number_two_with_a')}, + {id:'stj',name:'Star Gazer JV',asn:131279,type:'t2',cc:'KP',pol:'restrictive',share:.0001,price:20,up:['cun','rtc'],col:'#C8102E',pops:['fnj'],ix:[],blurb:tr('homegrown_eyeballs.the_one_network_of_north_korea')}, + {id:'swc',name:'Swiss-Cheese-com',asn:3303,type:'eye',cc:'CH',pol:'selective',minIx:8,minPni:25,share:.004,up:['lvl','tly'],col:'#001155',pops:['zrh','fra'],ix:['zrh'],blurb:tr('homegrown_eyeballs.switzerland_s_incumbent_the_holes_in')}, + {id:'syt',name:'Syria-tell',asn:48065,type:'eye',cc:'SY',pol:'open',share:.0008,up:['ste'],col:'#E30613',pops:['dam'],ix:[],blurb:tr('homegrown_eyeballs.syria_s_biggest_mobile_network_telling')}, + {id:'tcg',name:'Tele-Sell Ghana',asn:29614,type:'eye',cc:'GH',pol:'selective',minIx:2,minPni:10,share:.0015,up:['tat','tly'],col:'#E30613',pops:['acc','lag'],ix:['acc'],blurb:tr('homegrown_eyeballs.ghana_s_number_two_a_new')}, + {id:'tch',name:'Out of Touch',asn:38999,type:'eye',cc:'LB',pol:'open',share:.0006,up:['ogr'],col:'#A3238E',pops:['bey'],ix:['bey'],blurb:tr('homegrown_eyeballs.one_of_lebanon_s_two_state')}, + {id:'tci',name:'Tea-See-Eye',asn:58224,type:'t2',cc:'IR',pol:'selective',minIx:2,minPni:10,share:.002,price:14,up:['rtc','ttk','cog'],col:'#0D6EB4',pops:['thr'],ix:['thr'],blurb:tr('homegrown_eyeballs.iran_s_fixed_incumbent_steeped_in')}, + {id:'tcl',name:'Tele-Sell Group',asn:37526,type:'eye',cc:['BF','CF','GW'],pol:'open',share:.0004,up:['mtx'],col:'#E2231A',pops:['oua','bgf','oxb'],ix:['oua'],blurb:tr('homegrown_eyeballs.an_african_mobile_group_selling_in')}, + {id:'tdc',name:'YouSee-Me-Now',asn:3292,type:'eye',cc:'DK',pol:'selective',minIx:5,minPni:20,share:.003,up:['tly'],col:'#0B2D71',pops:['cph','ebj','sto','ham'],ix:['cph'],blurb:tr('homegrown_eyeballs.denmark_s_incumbent_you_see_it')}, + {id:'tee',name:'Tell-Ya Eesti',asn:3249,type:'eye',cc:'EE',pol:'selective',minIx:3,minPni:12,share:.001,up:['tly'],col:'#990AE3',pops:['tll','hel','sto'],ix:['tll'],blurb:tr('homegrown_eyeballs.tell_ya_s_estonian_daughter_e')}, + {id:'tel',name:'Tel-One-derful',asn:37204,type:'eye',cc:'ZW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['liq'],col:'#0D4C92',pops:['hre'],ix:['hre'],blurb:tr('homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_with')}, + {id:'tfl',name:'Telecom Fidget',asn:45349,type:'eye',cc:'FJ',pol:'selective',minIx:1,minPni:8,share:.0004,up:['fnt','ntt'],col:'#00A3E0',pops:['suv'],ix:['suv'],blurb:tr('homegrown_eyeballs.fiji_s_fixed_line_incumbent_never')}, + {id:'tgc',name:'Togo-Go',asn:24691,type:'t2',cc:'TG',pol:'selective',minIx:1,minPni:8,share:.0005,price:11,up:['cog','bgs','tat','drz'],col:'#00A651',pops:['lfw','acc','lag'],ix:['lfw'],blurb:tr('homegrown_eyeballs.togo_s_telco_on_the_cable')}, + {id:'tgd',name:'Tango Two-Step',asn:48526,type:'eye',cc:'LU',pol:'selective',minIx:2,minPni:8,share:.0005,up:['bgs'],col:'#FF6600',pops:['bet'],ix:['bet'],blurb:tr('homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg')}, + {id:'tjt',name:'Tojik Tock',asn:51346,type:'t2',cc:'TJ',pol:'open',share:.0004,price:12,up:['rtc','uzt'],col:'#00843D',pops:['dyu'],ix:['dyu'],blurb:tr('homegrown_eyeballs.tajikistan_s_state_telco_counting_the')}, + {id:'tks',name:'Slove-Nice Telekom',asn:5603,type:'t2',cc:'SI',pol:'selective',minIx:2,minPni:10,share:.001,price:9,up:['lvl','skl','cog'],col:'#0066B3',pops:['lju','vie'],ix:['lju'],blurb:tr('homegrown_eyeballs.slovenia_s_state_telco_very_nice')}, + {id:'tkt',name:'Darvaza Telecom',asn:20661,type:'t2',cc:'TM',pol:'selective',minIx:1,minPni:8,share:.0003,price:15,up:['rtc','uzt'],col:'#007A33',pops:['asb'],ix:[],blurb:tr('homegrown_eyeballs.turkmenistan_s_one_gateway_named_after')}, + {id:'tlt',name:'Tele-Two-Many',asn:1257,type:'eye',cc:'SE',pol:'selective',minIx:4,minPni:15,share:.003,up:['tly','cog'],col:'#000000',pops:['sto','cph','osl','got','mmx'],ix:['sto','got'],blurb:tr('homegrown_eyeballs.sweden_s_challenger_that_took_on')}, + {id:'tlv',name:'Tell-Ya Lietuva',asn:8764,type:'eye',cc:'LT',pol:'selective',minIx:2,minPni:10,share:.0012,up:['tly','cog'],col:'#990AE3',pops:['vno','sto'],ix:['vno'],blurb:tr('homegrown_eyeballs.telia_s_lithuanian_arm_still_telling')}, + {id:'tnm',name:'Tele-Namib',asn:36996,type:'eye',cc:'NA',pol:'open',share:.0004,up:['liq','tat'],col:'#00529B',pops:['wdh'],ix:['wdh'],blurb:tr('homegrown_eyeballs.namibia_s_state_incumbent_wired_across')}, + {id:'tnw',name:'Telekom Networks Mal-away',asn:37294,type:'eye',cc:'MW',pol:'open',share:.0005,up:['liq','mtx'],col:'#00A0DF',pops:['llw'],ix:['llw'],blurb:tr('homegrown_eyeballs.malawi_s_own_mobile_network_never')}, + {id:'tsh',name:'Tashi Delek-Cell',asn:38740,type:'eye',cc:'BT',pol:'open',share:.0002,up:['drz','tly','tat','ntt'],col:'#E4002B',pops:['pbh'],ix:['pbh'],blurb:tr('homegrown_eyeballs.bhutan_s_private_mobile_network_greeting')}, + {id:'tsm',name:'Titano-Net',asn:196874,type:'eye',cc:'SM',pol:'open',share:.0001,up:['tim','cog'],col:'#5EB6E4',pops:['smr'],ix:[],blurb:tr('homegrown_eyeballs.san_marino_s_little_fibre_isp')}, + {id:'tsr',name:'Tele-Sure Thing',asn:27775,type:'t2',cc:'SR',pol:'open',share:.0004,price:11,up:['tng','llt'],col:'#E30613',pops:['pbm','pos'],ix:['pbm'],blurb:tr('homegrown_eyeballs.suriname_s_state_telco_absolutely_certain')}, + {id:'tta',name:'Dream Team Telecom',asn:12297,type:'t2',cc:'AM',pol:'selective',minIx:2,minPni:10,share:.0008,price:10,up:['tat','tly','drz'],col:'#FF6600',pops:['evn','tbs','fra'],ix:['evn'],blurb:tr('homegrown_eyeballs.armenia_s_old_telco_now_a')}, + {id:'ttc',name:'Too-Valuable Telecom',asn:23917,type:'t2',cc:'TV',pol:'open',share:.0001,price:15,up:['fnt'],col:'#00A0DF',pops:['fun','suv'],ix:[],blurb:tr('homegrown_eyeballs.tuvalu_s_only_telco_for_eleven')}, + {id:'ttl',name:'Timor-row Telecom',asn:38077,type:'t2',cc:'TL',pol:'open',share:.0003,price:12,up:['tly','tsy'],col:'#E2001A',pops:['dil','drw'],ix:[],blurb:tr('homegrown_eyeballs.timor_leste_s_first_telco_which')}, + {id:'tvl',name:'Vanu-Two Telecom',asn:9249,type:'t2',cc:'VU',pol:'open',share:.0002,price:12,up:['dsp'],col:'#E60000',pops:['vli','suv'],ix:['vli'],blurb:tr('homegrown_eyeballs.vanuatu_s_old_telco_one_of')}, + {id:'ucm',name:'You-Come',asn:8932,type:'eye',cc:'AM',pol:'open',share:.0005,up:['lvl','cog','drz'],col:'#00AEEF',pops:['evn'],ix:[],blurb:tr('homegrown_eyeballs.armenia_s_fibre_and_mobile_challenger')}, + {id:'unn',name:'UN-Natural Networks',asn:10094,type:'t2',cc:'BN',pol:'open',share:.0004,price:11,up:['ntt','tat','drz'],col:'#FFCD00',pops:['bwn','sin'],ix:['bwn'],blurb:tr('homegrown_eyeballs.brunei_s_one_state_network_which')}, + {id:'unt',name:'Bee-Lined',asn:41202,type:'eye',cc:'UZ',pol:'open',share:.0012,up:['uzt'],col:'#FFC800',pops:['tas'],ix:['tas'],blurb:tr('homegrown_eyeballs.uzbekistan_s_biggest_mobile_network_flying')}, + {id:'unv',name:'Yurt-o-Vision',asn:17882,type:'eye',cc:'MN',pol:'open',share:.0004,up:['mbc'],col:'#00A0E9',pops:['uln'],ix:['uln'],blurb:tr('homegrown_eyeballs.mongolia_s_tv_and_fibre_network')}, + {id:'utl',name:'Unitel-ly Yours',asn:37119,type:'eye',cc:['AO','ST'],pol:'selective',minIx:3,minPni:12,share:.002,up:['agc'],col:'#F28C00',pops:['lad','lis','tms'],ix:['lad'],blurb:tr('homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours')}, + {id:'utp',name:'Unitel T-Plus-Plus',asn:37575,type:'eye',cc:'CV',pol:'open',share:.0003,up:['cvt','tat'],col:'#F28C00',pops:['rai'],ix:['rai'],blurb:tr('homegrown_eyeballs.cape_verde_s_challenger_one_more')}, + {id:'uzt',name:'Uz & Them Telecom',asn:28910,type:'t2',cc:'UZ',pol:'selective',minIx:2,minPni:10,share:.0015,price:10,up:['rtc','lvl','cog'],col:'#0072BC',pops:['tas','mos','fra'],ix:['tas'],blurb:tr('homegrown_eyeballs.uzbekistan_s_state_telco_and_the')}, + {id:'vin',name:'Vini Vidi Vici',asn:9471,type:'eye',cc:'PF',pol:'open',share:.0003,up:['pft','tly'],col:'#E2001A',pops:['ppt'],ix:[],blurb:tr('homegrown_eyeballs.french_polynesia_s_mobile_network_came')}, + {id:'vnp',name:'VNPT (Very Nice Packet Times)',asn:45899,type:'eye',cc:'VN',pol:'selective',minIx:3,minPni:12,share:.004,up:['ntt','tat'],col:'#0066B3',pops:['sgn','hkg','sin','han'],ix:['sgn'],blurb:tr('homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant')}, + {id:'vvc',name:'Viva la Vidacom',asn:8866,type:'eye',cc:'BG',pol:'selective',minIx:4,minPni:15,share:.002,up:['tly','cog'],col:'#E2001A',pops:['sof','fra'],ix:['sof'],blurb:tr('homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida')}, + {id:'yet',name:'Not Yettel',asn:31042,type:'eye',cc:'RS',pol:'open',share:.0015,up:['tly'],col:'#B4FF00',pops:['beg'],ix:[],blurb:tr('homegrown_eyeballs.the_mobile_network_formerly_known_as')}, + {id:'ymn',name:'Mocha-Net',asn:30873,type:'t2',cc:'YE',pol:'open',share:.0005,price:15,up:['omt','tly'],col:'#4B2C20',pops:['sah'],ix:[],blurb:tr('homegrown_eyeballs.yemen_s_one_gateway_named_after')}, + {id:'zai',name:'Zany Telecom',asn:42961,type:'eye',cc:['BH','IQ','JO','KW','SD','SS'],pol:'selective',minIx:2,minPni:10,share:.003,up:['omt','tly'],col:'#00A0AF',pops:['kwi','bgw','amm','bah','krt','jub'],ix:['kwi','bgw','bah'],blurb:tr('homegrown_eyeballs.kuwait_s_mobile_group_across_the')}); diff --git a/src/game/30-networks/35-glowball-sakura-lager.js b/src/game/30-networks/35-glowball-sakura-lager.js new file mode 100644 index 0000000..c45b8de --- /dev/null +++ b/src/game/30-networks/35-glowball-sakura-lager.js @@ -0,0 +1,31 @@ +/* Glowball Sakura Lager: a Tier 2 that buys transit from three Tier 1s and resells it, with open peering wherever it + is. Its PoPs are the real network's (Netify, Oct 2026: 38 cities in 17 countries) that are on our map: Asia-Pacific + and New Zealand, the US and a handful of European hubs, and nothing in Africa or South America. It sits in four + Australian cities and peers on their big exchanges, but is not one of the AU_SELLERS: like the Pacific carriers it + sells Australians nothing, so Australia stays as hard as it was. Far from its US and European core it costs more + (far), so it never undercuts the locals there. Sits before 40-traffic-shares.js, which indexes NETS. */ +const GSL_POPS=['adl','akl','ams','bne','bom','chi','dal','fra','hkg','icn','ist','jkt','lax','lon','mel','mia','mil','mnl','nyc','osa','par','per','phx','sin','syd','tok','waw']; +NETS.push( + {id:'gsl',name:'Glowball Sakura Lager',asn:137409,type:'t2',pol:'open',up:['lvl','cog','ntt'],share:.02,price:5,far:{AS:1.6,OC:2},col:'#C94F7C',auIx:['syd','mel','bne','per'],pops:GSL_POPS,ix:GSL_POPS.filter(c=>CITY[c].ix),blurb:tr('glowball_sakura_lager.on_tap_in_the_big_hubs')}); +/* Its downstreams: networks that buy their transit from it, so a PNI with it reaches them too. Only where it has + PoPs itself, and no Australians: a PNI with it is no back door into Australia. One per line, sorted within each. */ +const GSL_DOWN=[ + // Asia + 'dhr', // Dhiraa-goo + 'ptc', // PTC-hell + 'tru', // Mostly-True Move + 'vtl', // Viet-tell + // Europe + 'cms', // CityMess + 'dgi', // Digi-tally Cheap + 'fwb', // Fast-Webby + 'nos', // NOS-y Neighbour + // North America + 'dgc', // Digi-Sell Caribbean + 'pes', // Pessimum + 'snc', // Sonic Boomer + 'wnt', // Whirled Net + // New Zealand + 'spk', // Spark-le +]; +for(const id of GSL_DOWN){const n=NETS.find(x=>x.id===id);n.up=(n.up||[]).concat('gsl');} diff --git a/src/game/30-networks/38-france.js b/src/game/30-networks/38-france.js new file mode 100644 index 0000000..8f978b2 --- /dev/null +++ b/src/game/30-networks/38-france.js @@ -0,0 +1,8 @@ +/* France beyond Paris and Marseille: the second and third mobile operators and the two big French clouds, with real ASNs. + Orange (Tangerine Telecom) and Free (Free as in Beer) reach the new cities too; Andorable Telecom comes up to Toulouse. + Sits before 40-traffic-shares.js, which indexes NETS. */ +NETS.push( + {id:'sfe',name:'SF-Error Telecom',asn:15557,type:'eye',cc:'FR',pol:'selective',minIx:6,minPni:20,share:.005,up:['cog','lvl','tly'],col:'#E4002B',pops:['par','mrs','lys','tls','lil','bod','sxb','rns','nte','lon','ams','fra'],ix:['par','mrs','lys','tls','lil','bod','sxb'],blurb:tr('france.france_s_number_two_it_bought_a')}, + {id:'byg',name:'Boy-Egg Telecom',asn:5410,type:'eye',cc:'FR',pol:'selective',minIx:6,minPni:20,share:.004,up:['cog','lvl','tng'],col:'#0072CE',pops:['par','mrs','lys','tls','lil','bod','sxb','rns','nte','lon','ams','fra'],ix:['par','mrs','lys','tls','lil','sxb'],blurb:tr('france.the_builder_that_became_a_mobile')}, + {id:'ovh',name:'Ov-Hatch Cloud',asn:16276,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.004,col:'#123F6D',pops:['par','lil','sxb','lon','fra','ams','waw','sin','syd'],ix:['par','sxb','lon','fra','ams','sin'],blurb:tr('france.europe_s_biggest_hosting_cloud_from')}, + {id:'sca',name:'Scale-Away',asn:12876,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.002,col:'#4F0599',pops:['par','ams','waw'],ix:['par'],blurb:tr('france.the_cloud_arm_of_the_free_group')}); diff --git a/src/game/30-networks/40-traffic-shares.js b/src/game/30-networks/40-traffic-shares.js new file mode 100644 index 0000000..3f525c4 --- /dev/null +++ b/src/game/30-networks/40-traffic-shares.js @@ -0,0 +1,36 @@ +const NET=Object.fromEntries(NETS.map(n=>[n.id,n])),NET_IDS=NETS.map(n=>n.id); +/* Customer cones (#85): a network announces to its peers itself and everyone who buys transit from it, and their + customers in turn. So a PNI or a session with a network reaches its whole cone, and peering with every Tier 1 brings + their customers along. Built once at load: CONE[id] lists the network first, then its cone; CONE_S is the same as a + Set, and DOWN[id] holds the cone without the network itself (empty for most). */ +/* Who buys from whom follows the real networks' upstreams (bgp.he.net, CAIDA AS Rank, Oct 2026). Added in 2.0: Kyiv + Superstar (Cogentle, Tell-Ya), Ooh-redoo and Du-opoly (Ta-Ta, Tell-Ya), Safari-Comic (Cogentle, Level Tree, Sea-Comedy), + PLDTea Time (Not That, Ta-Ta), TIM-Tam (its sibling Sparkly Seabone), Floptus (its parent SingTell), Sky-High and + Tele-Nor-Way (Tell-Ya, Level Tree), Virgin Mediocre (Level Tree, Not That), and the long tail (tailUp()). The rest stay + islands because they are too: the content giants, the transit-free incumbents (Doitsche, Comecast, Jio-graphy, Bee-Tee), + China and Korea, and Australia's big ISPs, which buy only from Australian carriers. Smaller Australians do sit in Tier 1 + cones: Kangaroo Courier buys from Cogentle, Doodoo and Spin2wintel from Hocus Pocus (Not That, Tell-Ya), Lintel from + Speedyloop (Tell-Ya). */ +const CONE={},CONE_S={},DOWN={}; +{const dn={};for(const n of NETS)for(const u of n.up||[])(dn[u]||(dn[u]=[])).push(n.id); + for(const n of NETS){const s=new Set([n.id]),q=[n.id];while(q.length){for(const y of dn[q.pop()]||[])if(!s.has(y)){s.add(y);q.push(y);}} + CONE[n.id]=[...s];CONE_S[n.id]=s;DOWN[n.id]=CONE[n.id].slice(1);}} +// ANC[id]: every network whose cone holds it, nearest upstream first (who brings it along, for the panels). +const ANC={};for(const n of NETS){const o=[],q=(n.up||[]).slice();while(q.length){const u=q.shift();if(o.includes(u)||!NETS.some(x=>x.id===u))continue;o.push(u);q.push(...(NETS.find(x=>x.id===u).up||[]));}ANC[n.id]=o;} +// The networks a PNI with each network reaches: its customer cone. CONE_RANK: where routing tries a peer's cone. +const PNI_NETS=CONE,CONE_RANK=2.5; +/* PNIs and IX ports are both peering (#298): traffic leaves at the nearest one, not over the ocean to a PNI. At the same + distance the PNI goes first: an IX port counts as this much further away, far below any link's weight. */ +const PNI_TIE=1e-3; +for(const X of XIX){X.members=NETS.filter(n=>Array.isArray(n.ix)&&n.ix.includes(X.id)||!n.tail&&(X.core?X.core.includes(n.id):(n.ix==='ALL'||Array.isArray(n.ix)&&n.ix.includes(X.c))&&hstr(n.id+'|'+X.id)%100<(n.ix==='ALL'?72:X.take*100))).map(n=>n.id);} +const NSH={}; {const t=NETS.reduce((a,n)=>a+n.share,0); NETS.forEach(n=>NSH[n.id]=n.share/t);} +// After Glitch leaves Korea, Seoul viewers watch half as much of it and the rest moves to everyone else. +const NSH_KRX={}; {const w=id=>NSH[id]*(id==='amz'?0.5:1),t=NETS.reduce((a,n)=>a+w(n.id),0); NETS.forEach(n=>NSH_KRX[n.id]=w(n.id)/t);} +const CN_W={ctc:.2,cun:.14,cmb:.08,tcs:.22,abc:.14,byd:.08,bdc:.08,akm:.02,msf:.02,amz:.01,drz:.01}; +const RU_W={ydx:.24,vkl:.12,rtc:.14,ggl:.12,bdc:.08,akm:.05,cfl:.06,msf:.04,amz:.03,tly:.02,cog:.02,drz:.01}; +const NSH_RU={}; {const t=Object.values(RU_W).reduce((a,b)=>a+b,0); for(const k in RU_W)NSH_RU[k]=RU_W[k]/t;} +const NSH_CN={}; {const t=Object.values(CN_W).reduce((a,b)=>a+b,0); for(const k in CN_W)NSH_CN[k]=CN_W[k]/t;} +const CN_BLOCKED=NETS.filter(n=>!CN_W[n.id]&&n.type==='cdn').map(n=>n.name); +const TYPE_L={t1:tr('common.tier_1'),t2:tr('common.tier_2'),cdn:tr('common.cdn_content'),eye:tr('common.eyeballs')}; +const initials=n=>n.name.replace(/[^A-Za-z ]/g,'').split(' ').filter(Boolean).map(w=>w[0]).join('').slice(0,3).toUpperCase(); + diff --git a/src/game/30-networks/45-home-markets.js b/src/game/30-networks/45-home-markets.js new file mode 100644 index 0000000..2ba0f77 --- /dev/null +++ b/src/game/30-networks/45-home-markets.js @@ -0,0 +1,30 @@ +/* Where each network's users live (#48). A network that sells to homes lists its home markets (cc, see W2), and that is + where its eyeballs are. People mostly talk to people near them, so a POP's traffic to the networks that sell to homes + goes mostly to the ones at home: a New York POP sends a lot to Comecast and little to Doitsche Telekomm, Frankfurt + the other way round. Together those networks keep the share the city's table gives them; only how it splits between + them follows geography. Content and carriers without home markets are everywhere and keep their shares. + Routing is unchanged: traffic leaves at the nearest exit (hot potato), so an eyeball peered with in the cities its + users are in takes that traffic off your backbone where it starts, and one peered with in two cities has it hauled + there from everywhere else. */ +const LOC_HOME=1,LOC_REG=0.3,LOC_FAR=0.08; +const LOC_NIX=new Map(NETS.map((n,j)=>[n.id,j])); +// Per network index: its home countries and the regions they are in, or null (no home market: everywhere). +let LOC_NET=null; +function locNets(){if(LOC_NET)return LOC_NET;const ccReg=new Map(); + for(const c of CITIES){let s=ccReg.get(c.cc);if(!s)ccReg.set(c.cc,s=new Set());s.add(c.reg);} + LOC_NET=NETS.map(n=>{if(!n.cc)return null;const cc=new Set(Array.isArray(n.cc)?n.cc:[n.cc]),reg=new Set();for(const k of cc)for(const r of ccReg.get(k)||[])reg.add(r);return {cc,reg};}); + return LOC_NET;} +// How near a city is to a network's users: at home, on the same continent, or far away. +const locW=(h,C)=>h.cc.has(C.cc)?LOC_HOME:h.reg.has(C.reg)?LOC_REG:LOC_FAR; +/* A city's shares in table T (by network index), localised. The tables and the map never change after load, so each + city's array is made once per table and kept. */ +const LOC_SH=new Map(); +function locSh(T,c){let m=LOC_SH.get(T);if(!m)LOC_SH.set(T,m=new Map());let a=m.get(c);if(a)return a; + const L=locNets(),C=CITY[c],NN=NETS.length;a=new Float64Array(NN);let g=0,gw=0; + for(let j=0;j0){const f=g/gw;for(let j=0;j!(S&&(S.mode==='puzzle'||S.pz||S.ar||S.scn)); +function cityShares(T,c){if(locOn())return locSh(T,c);let a=LOC_PLAIN.get(T);if(!a)LOC_PLAIN.set(T,a=Float64Array.from(NETS,n=>T[n.id]||0));return a;} diff --git a/src/game/40-progress/10-businesses.js b/src/game/40-progress/10-businesses.js new file mode 100644 index 0000000..dc45c81 --- /dev/null +++ b/src/game/40-progress/10-businesses.js @@ -0,0 +1,84 @@ +/* ================= BUSINESSES ================= */ +const BIZ_T={ + dia:{l:tr('common.enterprise_dia'),opts:[1,2,5,10],rate:600}, + game:{l:tr('common.game_servers'),gaming:true,opts:[5,10,20,40],rate:120}, + host:{l:tr('common.hosting'),opts:[10,20,40,80],rate:60}, + isp:{l:tr('businesses.downstream_isp_buys_transit'),opts:[100,200,400,800],rate:15,lv:2}, + l2vpn:{l:tr('common.l2vpn_circuit'),opts:[1,10,40,100],rate:0,l2:true,km:1,lv:1}, + fabip:{l:tr('businesses.customer_on_a_fabric_transit_over'),opts:[1,5,10,25],rate:110,nni:true,lv:2}, + fabl2:{l:tr('businesses.fabric_circuit_to_one_of_your'),opts:[1,5,10],rate:0,l2:true,nni:true,km:0.8,lv:2}, + stream:{l:tr('common.streaming_startup'),opts:[50,100,200],rate:80,lv:2}, + edu:{l:tr('common.university_network'),opts:[20,50,100],rate:90,lv:2}, + gpu:{l:tr('businesses.ai_gpu_data_center'),opts:[200,400,800],rate:70,lv:3,names:['Neural Noodles AI','GPUs R Us','Hallucination Labs','Transformers & Sons','Token Burners Inc.','Very Large Language Co.','Prompt Engineering Ltd','DeepThought Farms','Parameter Pastures','Gradient Descent Diner','Attention Is All We Need LLC','Overfit Analytics']}, + onramp:{l:tr('businesses.cloud_on_ramp'),opts:[100,200,400],rate:0,l2:true,km:0.7,lv:3,names:["Amazin' Web Services on-ramp","Microsnoft Azzure on-ramp",'Goggle Cloud on-ramp','AliBubble Cloud on-ramp','Miracle Cloud on-ramp']}, + ai:{l:tr('businesses.ai_training_interconnect'),opts:[400,800,1600],rate:0,l2:true,div:true,km:0.9,lv:4,names:['Skynot Compute','Galaxy Brain Training Run','Megawatt Minds','The Big Model Co.','Infinite Context Corp','Sentient Spreadsheet Inc.']}, + hyper:{l:tr('common.hyperscaler_dci'),opts:[1600,3200,6400],rate:0,l2:true,div:true,km:0.5,lv:4,names:["Amazin' Web Services DCI","Microsnoft Azzure DCI",'Goggle Cloud DCI','Faceplant Infra DCI','AliBubble Cloud DCI']}, + hft:{l:tr('businesses.high_frequency_trading_link'),opts:[1,5,10],rate:0,l2:true,lat:true,km:6,lv:2,names:['Flash Boys Capital','Nanosecond Nancy Trading','Speed of Light Securities','Arbitrage & Sons','Front-Run Fund','Microwave Tower Capital','Tick-Tock Quant','Low Latency Larry LLC']}, + bulk:{l:tr('businesses.bulk_backup_transfer_latency_does'),opts:[100,200,400],rate:0,l2:true,scenic:true,km:0.1,lv:2,names:['Glacier Slow Storage','Tape Backup Tortoise','Scenic Route Archives','Cold Storage Cold Cuts','Sloth Sync','Eventually Consistent Inc.','Snail Mail Data Co.']}, + event:{l:tr('common.event_network'),opts:[100,200,400,800,1600,3200],rate:0,event:true,lv:2,names:['Carnaval Parade','Diwali Streaming Night','The Big Football Final','NANOG 99','APRICOT 2027','DENOG 18','UKNOF 56','RIPE 94','DKNOG 16','Burning Router Festival','Euro-Pop Song Contest','Formula Ping Grand Prix','The Big Game','Olympic Pings','A Pop Megastar Stadium Tour','LAN Party of the Century','The Keynote (One More Thing)','Gamer-Con Expo','Oktoberfest Livestream']}, + sdwan:{l:tr('businesses.sd_wan_for_a_chain'),opts:[1,2,5,10],rate:0,l2:true,sdwan:true,km:0,lv:2,names:['Kebab Kingdom','Pretzel Palace','Burger Router Inc.','Café Latte-ncy','Hardware Hut Stores','Pharma-See Pharmacies','Bank of Tiny Branches','Supermarket Superhighway','Fitness Pings Gyms','Hotel Hops Group','Doughnut Data Diners']}, + wwave:{l:tr('common.wholesale_wave'),opts:[1],rate:0,fiber:true,lv:2,names:['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','G&T (Gin and Transit)','A Hyperscaler Who Shall Not Be Named','Megapork','youNetworks']}, + // A managed wave (the capacity market): carved out of capacity you lit; b.g is its size (100 or 400G), b.slots how many. + mwave:{l:tr('market.managed_wave'),opts:[1],rate:0,fiber:true,lv:2,names:['Lambda Lambda Lambda','Coherent Thoughts Inc.','Photon Express','Transponder Tribe','Sea Change Networks','Spectrum Spectacle','Wavelength Wanderers','Muxed Signals Ltd.']}, + dfpair:{l:tr('businesses.dark_fiber_pair_lease'),opts:[1],rate:0,fiber:true,lv:3,names:['A Hyperscaler Who Shall Not Be Named','Goggle Fiber Division','Faceplant Infra','Amazin’ Backbone Team','A Very Secretive Trading Firm']}, + scrub:{l:tr('businesses.ddos_protection_dia'),opts:[1,5,10,20],rate:900}, + aiwan:{l:tr('businesses.ai_wan_between_two_ai_factories'),opts:[3200,6400,12800],rate:0,l2:true,div:true,mega:true,km:0.45,lv:4,names:['Fairweather AI WAN','Planet-Scale Superfactory Link','Two Brains One Model Inc.','Distributed Godlike Compute','The Gigawatt Handshake']}, + mtrain:{l:tr('businesses.multi_site_training_run'),opts:[1600,3200,6400],rate:0,l2:true,sdwan:true,mega:true,lv:4,names:['Gem-in-Eye Ultra Training Run','Frontier Model 9000','The Very Big Model','Checkpoint-Free Training Co.','Model Too Big For One Building']}, + ingest:{l:tr('businesses.dataset_ingest_elephant_flow'),opts:[1600,3200,6400],rate:0,event:true,mega:true,lv:3,names:['Scrape-the-Whole-Web Ingest','Checkpoint Sync Storm','Video Dataset Firehose','Every Book Ever (allegedly licensed)','Synthetic Data Tsunami']}, + pairs:{l:tr('businesses.hundreds_of_fiber_pairs'),opts:[1],rate:0,fiber:true,mega:true,lv:4,names:['A Hyperscaler Who Shall Not Be Named','Planet-Scale AI WAN Team','The Fiber-Hungry Giant','Project Very Long Glass']}, + esport:{l:tr('businesses.esports_world_final'),opts:[400,800,1600,3200],rate:0,event:true,lv:5,names:['League of Lag Finals','Counter-Ping Major','Fortnightly World Cup','Dota Two Many Viewers','Rocket Leak Championship','Street Frighter Evo']}, + sov:{l:tr('businesses.sovereign_cloud_region'),opts:[400,800,1600],rate:0,l2:true,div:true,km:0.6,lv:6,names:['Gaia-Ex Sovereign Cloud','Bundeswolke (Very Secure)','Le Cloud Souverain','Datenschutz Deluxe','Your Data Stays Here, Probably','A Cloud With a Flag on It','Data Residency Is a State of Mind']}, + // Strict latency contracts (#137): a carrier or market-data network buys big capacity on one route with a latency SLA, + // the premium paid for the guaranteed milliseconds (km), credits paid for every day over it (38-latency-contracts.js), + // and never more than max: one customer cannot carry a whole level. + lowlat:{l:tr('businesses.low_latency_wholesale_route'),opts:[1600,3200],max:3200,rate:0,l2:true,lat:true,sla:true,km:2,lv:7,names:['Great Circle Clearing House','Straight Line Settlements','Millisecond Markets Exchange','Photon Arbitrage Partners','Shortest Path Securities','Tick Feed Torrent Co.','Matching Engine Mirror Ltd','Speed-of-Glass Replication','Order Book Express','Consolidated Tape Worm']}, + cgame:{l:tr('businesses.cloud_gaming_platform'),gaming:true,opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, + metav:{l:tr('common.metaverse_platform'),opts:[1600,3200,6400],rate:35,lv:9,names:['Meh-taverse','Second Second Life','Horizon Worlds Apart','The Oasis (Ready Player Done)','Legs Finally Shipped Inc.','Decentra-landlocked']}, + agi:{l:tr('businesses.agi_lab_allegedly'),opts:[12800,25600],rate:0,l2:true,div:true,mega:true,km:0.4,lv:11,names:['Almost General Intelligence Inc.','Superintelligence Pending','The Lab That Said Two More Years','Paperclip Maximizer Labs','Deep Thought Two','Benevolent Overlord Research']}, + mars:{l:tr('businesses.mars_mission_ground_station'),opts:[100,200,400],rate:0,l2:true,lat:true,km:4,lv:13,names:['Red Planet Relay','Ares Ground Segment','Olympus Mons Uplink','Mars or Bust Mission Control','Interplanetary Ping Society','Light-Minute Logistics','RFC 1149 Avian Carriers (Mars Division)']}, + // Orbit terminals (35-pie-paths.js): no POP of theirs, landed on a pie dish. Priced per Gbps of busy-hour capacity, which a + // satellite operator oversubscribes two hundredfold (two hundred homes at $100 a month share one Gbps). The prices set + // the payback of a full crust (rule O7: never under 5 years, 6 to 10 for a strong network). + // share: the most of the sky's market (pieMarket()) that kind may hold; there are only so many airlines. + pizza:{l:tr('businesses.pizza_homes_and_boats_on_orbit'),opts:[50,100,200,400],rate:25000,orbit:true,lv:1,names:['Deep Dish Rural Broadband','Crust Mile Connect','Topping Off Telecom','Extra Cheese Islands Net','Slice of Life Homesteads','Calzone Ranch Wi-Fi','Thin Crust Tundra Net','Margherita Marina Moorings','Anchovy Atoll Online','Stuffed Crust Station Hands']}, + flywifi:{l:tr('businesses.flywifi_airline_wi_fi'),opts:[20,50,100,200],rate:36000,orbit:true,las:true,share:0.2,lv:1,names:['Jet Lag Wi-Fi','Wi-Fly Away','Seatback Streaming Co.','Tray Table Upright Telecom','Cabin Pressure Networks','Mile High Megabits','Overhead Bin Broadband','Turbulence Tolerant Transit']}, + boat:{l:tr('businesses.cruise_ship_connectivity'),opts:[100,200,400,800],rate:27500,orbit:true,lv:1,names:['Buffet Overboard Cruises','The Love Bandwidth','Poop Deck Packets','Midnight Buffet Mbps','Shuffleboard Shipping Lines','All-You-Can-Stream Cruises','Iceberg Ahead Voyages']}, + marsorb:{l:tr('businesses.mars_mission_over_your_pies'),opts:[50,100,200],rate:44000,orbit:true,las:true,share:0.05,lv:13,names:['Red Planet Relay (Orbital)','Olympus Mons Uplink (Orbital)','Light-Minute Logistics (Orbital)','Interplanetary Ping Society (Orbital)','Rover Over Pies']}, + provedor:{l:tr('businesses.provedor_small_regional_isp'),opts:[5,10,20,40],rate:20,br:true,names:['Provedor Capivara Net','Fibra do Sertão','Rapidinho Telecom','Net Jabuticaba','Caipirinha Online','Wi-Fi do Zé','Pão de Queijo Fibra','Açaí Net','Tucano Telecom','Forró Fibra','Saci Net','Brigadeiro Banda Larga','Mandioca Online','Churrasco Connect']}, +}; +const LEVELS=[ + {n:tr('common.local_isp'),q:tr('businesses.your_network_diagram_is_a_photo'),req:tr('common.start_here'),unlock:tr('businesses.enterprises_game_servers_hosting')}, + {n:tr('common.regional_player'),q:tr('businesses.you_now_have_a_change_freeze'),req:tr('businesses.peak_200_gbps_and_3_pops'),unlock:tr('businesses.downstream_isps_streaming_startups')}, + {n:tr('common.serious_backbone'),q:tr('businesses.it_s_not_dns_there_s'),req:tr('businesses.peak_1_tbps_and_6_pops'),unlock:tr('businesses.ai_gpu_data_centers_and_cloud')}, + {n:tr('common.big_league'),q:tr('businesses.your_mtu_is_9000_on_every'),req:tr('businesses.peak_3_tbps_10_pops_3'),unlock:tr('businesses.ai_training_interconnects_and')}, + {n:tr('common.continental_carrier'),q:tr('businesses.your_noc_has_a_chat_channel'),req:tr('businesses.peak_6_tbps_15_pops_4'),era:1.15,unlock:tr('businesses.esports_world_finals_and_the_4k')}, + {n:tr('common.transcontinental'),q:tr('businesses.you_joined_the_outages_mailing_list'),req:tr('businesses.peak_9_tbps_and_20_pops'),unlock:tr('businesses.sovereign_cloud_regions_and_a_free')}, + {n:tr('common.global_backbone'),q:tr('businesses.your_asn_now_shows_up_in'),req:tr('businesses.peak_12_tbps_25_pops_5'),unlock:tr('businesses.low_latency_routes_and_a_free_pni')}, + {n:tr('common.packet_empire'),q:tr('businesses.your_maintenance_window_is_2_a'),req:tr('businesses.peak_16_tbps_and_32_pops'),era:1.15,unlock:tr('businesses.cloud_gaming_platforms_and_the_cloud')}, + {n:tr('businesses.six_continent_carrier'),q:tr('businesses.somewhere_on_every_continent_a'),req:tr('businesses.peak_21_tbps_40_pops_6'),unlock:tr('businesses.metaverse_platforms_it_finally_took')}, + {n:tr('businesses.backbone_of_backbones'),q:tr('businesses.your_routing_table_needs_its_own'),req:tr('businesses.peak_26_tbps_and_50_pops'),era:1.2,unlock:tr('businesses.the_vr_era_eyeballs_want_20')}, + {n:tr('businesses.internet_weather_system'),q:tr('businesses.when_your_bgp_sneezes_a_small'),req:tr('businesses.peak_33_tbps_and_60_pops'),unlock:tr('businesses.agi_labs_allegedly_wanting_ai_wans')}, + {n:tr('businesses.too_big_to_route'),q:tr('businesses.your_last_fat_fingered_route_leak'),req:tr('businesses.peak_40_tbps_and_70_pops'),era:1.25,unlock:tr('businesses.the_ai_agent_era_eyeballs_want')}, + {n:tr('common.the_internet'),q:tr('businesses.people_phone_you_to_ask_if'),req:tr('businesses.peak_50_tbps_and_80_pops'),unlock:tr('businesses.mars_mission_ground_stations_gear')}, +]; +// What each level asks for (peak Gbps, POPs, continents). Continents carry over to the levels above. +const LV_REQ=[null,{pk:200,pops:3},{pk:1000,pops:6},{pk:3000,pops:10,reg:3},{pk:6000,pops:15,reg:4},{pk:9000,pops:20},{pk:12000,pops:25,reg:5},{pk:16000,pops:32},{pk:21000,pops:40,reg:6},{pk:26000,pops:50},{pk:33000,pops:60},{pk:40000,pops:70},{pk:50000,pops:80}]; +const lvReg=i=>Math.max(0,...LV_REQ.slice(1,i+1).map(q=>q.reg||0)); +// Open gates (sandbox, puzzles): every level's unlocks are there from the start. +const lvl=()=>S&&S.rules&&S.rules.gates==='open'?LEVELS.length:(S&&S.lvl)||1; +// Lower-case just the first word for mid-sentence use, so names like Tel-Mess or AGI keep their capitals. +const lc1=t=>/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t; +function custLevel(){const pops=Object.keys(S.pops).length,pk=S.stats.peak,rc=regionsCount();let lv=1;for(let i=1;i=q.pk&&pops>=q.pops&&rc>=lvReg(i))lv=i+1;else break;}return lv;} +// Traffic eras: some levels bring a new reason to watch more video, and every city's eyeballs grow toward more. +const eraMul=()=>LEVELS.slice(0,lvl()).reduce((a,L)=>a*(L.era||1),1); +const eyeP=c=>CITY[c].P*eraMul(); +// Network operators' meetings only meet where they really do; any other event name goes anywhere. APRICOT is Asia +// Pacific with Oceania, but not mainland China or Hong Kong, nor the Middle East, Central Asia and Russia (RIPE's). +const RIPE_AS=['AE','AM','AZ','BH','GE','IL','IQ','IR','JO','KG','KW','KZ','LB','OM','QA','RU','SA','SY','TJ','TM','TR','UZ','YE']; +const NOG_AT={NANOG:C=>C.cc==='US',APRICOT:C=>(C.reg==='AS'||C.reg==='OC')&&!['CN','HK','KP','US'].includes(C.cc)&&!RIPE_AS.includes(C.cc), + DENOG:C=>C.cc==='DE',UKNOF:C=>C.cc==='GB',RIPE:C=>C.reg==='EU'||C.reg==='AF'||RIPE_AS.includes(C.cc),DKNOG:C=>C.id==='cph'}; +const nogOk=(name,c)=>{const f=NOG_AT[name.split(' ')[0]];return !f||f(CITY[c]);}; +// New broadband starts small, but never above what the town can grow to (St Helena has 4,500 people). +const bbStart=c=>Math.min(eyeP(c),Math.max(8,CITY[c].P*0.03)); +const BIZ_N=['Byte-Size Bakery','Hamster Wheel Power Co.','Llama Logistics','Cloud Nine Hosting','Rural Rabbit Broadband','Tiny Telco','Pixel Pirates Games','Moo-Moo Dairy Corp','Snack Overflow','Git Happens Ltd','Kernel Sanders Fried Code','Lag-Free Llamas','404 Bistro','Ping Pong Sports','Null Pointer Pets','Buffer Bloat Boats','Packet Pizza','Latency Lattes','Ctrl-Alt-Deli','Sudo Sandwiches','Cache Me Outside','Hertz So Good Radio','Jitterbug Dance Hall','Bit Barn Hosting','Fiber Optimists','The Daily Ping','Squirrel Mesh Wireless','Spam & Eggs Diner','Router Rooter Plumbing','Kilobyte Kebab','Gigglebit Studios','Uptime Funk Records','Ohm Sweet Ohm','Dial-Up Nostalgia Club','Two-Factor Tacos']; + diff --git a/src/game/40-progress/20-goals.js b/src/game/40-progress/20-goals.js new file mode 100644 index 0000000..72624ce --- /dev/null +++ b/src/game/40-progress/20-goals.js @@ -0,0 +1,38 @@ +/* ================= GOALS ================= */ +const GOALS=[ + {id:'bb',t:tr('goals.light_up_your_first_customers'),d:tr('goals.open_your_home_city_and_press'),r:5000,ok:()=>Object.values(S.pops).some(p=>p.bb)}, + {id:'tr',t:tr('goals.reach_the_whole_internet'),d:tr('goals.your_eyeballs_want_everything_buy_ip'),r:5000,ok:()=>S.transit.length>0}, + {id:'ix',t:tr('goals.join_an_internet_exchange'),d:tr('goals.get_a_port_at_an_ix'),r:7500,ok:()=>Object.keys(S.ixp).length>0}, + {id:'p5',t:tr('goals.make_5_peering_friends'),d:tr('goals.on_the_peering_tab_request_sessions'),r:10000,ok:()=>R.sessions>=5}, + {id:'ln',t:tr('goals.lay_your_first_fiber'),d:tr('goals.drag_from_your_pink_router_to'),r:10000,ok:()=>S.links.length>0}, + {id:'bz',t:tr('goals.sign_a_business_customer'),d:tr('goals.businesses_show_up_with_a_bubble'),r:12500,ok:()=>S.biz.some(b=>!b.scripted)}, + {id:'rd',t:tr('goals.survive_a_failure'),d:tr('goals.things_break_all_the_time_build'),r:12500,ok:()=>S.stats.survived>0}, + {id:'ca',t:tr('goals.host_an_embedded_cache'),d:tr('goals.big_cdns_give_you_free_cache'),r:12500,ok:()=>S.caches.length>0}, + {id:'pn',t:tr('goals.set_up_a_pni'),d:tr('goals.a_private_cross_connect_to_one'),r:15000,ok:()=>S.pni.some(pniOn)}, + {id:'scrub',t:tr('goals.stand_up_ddos_defences'),d:tr('goals.build_a_scrubbing_center_from_a'),r:20000,ok:()=>hasScrub()}, + {id:'c3',t:tr('common.go_global'),d:tr('goals.have_pops_on_3_continents_subsea'),r:50000,ok:()=>regionsCount()>=3}, + {id:'t2',t:tr('goals.become_a_tier_2'),d:tr('goals.5_pops_ports_on_3_ixs'),r:50000,ok:()=>isTier2()}, + {id:'tb',t:tr('goals.serve_1_tbps'),d:tr('goals.a_terabit_per_second_of_happy'),r:75000,ok:()=>R.served>=1000}, + {id:'df',t:tr('goals.light_your_own_dark_fiber'),d:tr('goals.lease_or_dig_dark_fiber_put'),r:40000,ok:()=>S.links.some(l=>l.kind==='df'&&dfCap(l)>0)}, + {id:'m2',t:tr('goals.be_in_two_buildings_at_once'),d:tr('goals.add_a_second_site_in_a'),r:30000,ok:()=>Object.values(S.pops).some(p=>p.site2)}, + {id:'c5',t:tr('common.five_continents'),d:tr('goals.pops_in_five_of_the_six'),r:100000,ok:()=>regionsCount()>=5}, + {id:'gi',t:tr('goals.sign_a_giant'),d:tr('goals.land_an_ai_wan_a_multi'),r:150000,ok:()=>S.biz.some(b=>BIZ_T[b.type]&&BIZ_T[b.type].mega&&!BIZ_T[b.type].event)}, + {id:'t10',t:tr('goals.serve_10_tbps'),d:tr('goals.ten_terabits_per_second_of_happy'),r:250000,ok:()=>R.served>=10000}, + {id:'t1',t:tr('common.go_transit_free_tier_1'),d:tr('goals.peer_with_every_tier_1_their_customers'),r:0,win:true,ok:()=>isTier1()}, +]; +// The Cable broker's goals (#300): light glass, sell it, lay cables across the oceans, and end as a Glass Baron +// (37-cable-broker.js). Ids of their own, so a save keeps the ladder it ran. Rewards are larger: glass costs more. +const BROKER_GOALS=[ + {id:'bk_df',t:tr('goals.light_your_own_dark_fiber'),d:tr('broker.goal_df_d'),r:25000,ok:()=>S.links.some(l=>l.kind==='df'&&dfCap(l)>0)}, + {id:'bk_wave',t:tr('broker.goal_wave'),d:tr('broker.goal_wave_d'),r:40000,ok:()=>S.biz.some(b=>b.type==='wwave'||b.type==='mwave'||b.type==='capw'&&!capPend(b))}, + {id:'bk_pair',t:tr('broker.goal_pair'),d:tr('broker.goal_pair_d'),r:50000,ok:()=>S.biz.some(b=>(b.type==='dfpair'||b.type==='pairs'||b.type==='capfib')&&!capPend(b))}, + {id:'bk_sea',t:tr('broker.goal_sea'),d:tr('broker.goal_sea_d'),r:150000,ok:()=>S.links.some(l=>ownGlassL(l)&&l.sub)}, + {id:'bk_deal',t:tr('broker.goal_deal'),d:tr('broker.goal_deal_d'),r:100000,ok:()=>(S.stats.capDone||0)>0}, + {id:'bk_10k',t:tr('broker.goal_10k'),d:tr('broker.goal_10k_d'),r:200000,ok:()=>glassKm()>=10000}, + {id:'bk_16t',t:tr('broker.goal_16t'),d:tr('broker.goal_16t_d'),r:250000,ok:()=>glassChain(1600)}, + {id:'bk_c4',t:tr('broker.goal_c4'),d:tr('broker.goal_c4_d'),r:400000,ok:()=>cableConts()>=4}, + {id:'bk_10t',t:tr('broker.goal_10t'),d:tr('broker.goal_10t_d'),r:600000,ok:()=>capSoldG()>=10000}, + {id:'bk_win',t:tr('broker.glass_baron'),d:tr('broker.goal_win_d'),r:0,win:true,baron:true,ok:()=>baronOk()}, +]; +// The ladder this network runs: the broker's, or the classic one every other charter and mode plays. +const goals=()=>broker()?BROKER_GOALS:GOALS; diff --git a/src/game/40-progress/30-rules.js b/src/game/40-progress/30-rules.js new file mode 100644 index 0000000..0586a76 --- /dev/null +++ b/src/game/40-progress/30-rules.js @@ -0,0 +1,56 @@ +/* ---------- The ruleset: one game, many doors ---------- + Every network carries its own rules (S.rules), picked when it starts and locked from then on. Modes are presets of + these rules, not separate code: Normal comes as Change Freeze, On-call (the classic game) and BGP at 3 a.m.; + Sandbox and Puzzles are presets too. Saves without rules load as On-call, so nothing changes for them. + Scenarios and the weekly challenge run on On-call plus their own S.scn.rules (scnRule()). */ +// sea: cable ships sail out to subsea cuts, or (timer) a cut mends on its own clock. confs: conference season. +// broke: deep in the red ends the game, or (rescue) a state loan keeps it going. moods: patient customers sour half as fast. +// pnis: PNIs and their augments wait for the other network's team, or (instant) are up the moment they are ordered. +// ip4: IPv4 is scarce (#150, 33-address-space.js): customers need addresses, homes share them behind CGNAT. +const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder',sea:'ships',confs:true,broke:'lose',moods:'normal',pnis:'wait',ip4:true,mods:[]}; +const RULE_LATE=['sea','confs','broke','moods','pnis','ip4']; +const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],money:['normal','infinite'],gates:['ladder','open'],sea:['ships','timer'],confs:[true,false],broke:['lose','rescue'],moods:['normal','patient'],pnis:['wait','instant'],ip4:[true,false]}; +// i: icon, n: name, d: the one-line joke, x: what is different, in small print. +const PRESETS={ + soft:{i:'☕',n:tr('rules.best_effort'),d:tr('rules.no_sla_no_pager_no_promises'),x:tr('rules.rare_outages_no_ddos_pnis_at_once'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',sea:'timer',confs:false,broke:'rescue',moods:'patient',pnis:'instant',ip4:false}, + freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos_pnis'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',ip4:false}, + oncall:{i:'📟',n:tr('rules.on_call'),d:tr('rules.the_real_thing_your_pager_has'),x:tr('rules.real_lead_times_real_outages_a_real'),clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder'}, + bgp:{i:'🔥',n:tr('rules.bgp_at_3_a_m'),d:tr('rules.everything_is_on_fire_and_it'),x:tr('rules.more_and_longer_outages_more_ddos'),clock:true,chaos:'spicy',lead:'real',market:true,money:'normal',gates:'ladder'}, + sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,money:'infinite',gates:'open',ip4:false}, + puzzle:{i:'🧩',n:tr('rules.puzzle'),d:tr('rules.one_small_network_one_tricky_goal'),x:tr('rules.no_clock_no_bills_nothing_breaks'),clock:false,chaos:'none',lead:'quick',market:false,money:'normal',gates:'open',ip4:false}, +}; +const NORMAL_PRESETS=['soft','freeze','oncall','bgp']; +// How often things break, against the classic game. Spicy outages also last half as long again. +const CHAOS={none:{i:'😴',n:tr('rules.chaos_none'),d:tr('rules.nothing_ever_breaks'),m:0},calm:{i:'🧊',n:tr('rules.chaos_calm'),d:tr('rules.a_cut_now_and_then'),m:0.35},normal:{i:'📟',n:tr('rules.chaos_normal'),d:tr('rules.like_the_real_game'),m:1},spicy:{i:'🔥',n:tr('rules.chaos_spicy'),d:tr('rules.your_pager_never_sleeps'),m:1.8}}; +const SPICY_LONG=1.5,LEAD_QUICK=10; +function rule(k){const r=S&&S.rules;return r&&r[k]!==undefined?r[k]:RULE_DEF[k];} +function rulePreset(){const p=S&&S.rules&&S.rules.preset;return p&&Object.prototype.hasOwnProperty.call(PRESETS,p)?p:'oncall';} +const shipsOn=()=>rule('sea')!=='timer',confsOn=()=>rule('confs')!==false; +function gatesOpen(){return rule('gates')==='open';} +function chaosMul(){const c=CHAOS[rule('chaos')];return c?c.m:1;} +// Days until something ordered arrives: as quoted, or a tenth of it (at least a day) with quick lead times. +function leadDays(n){return rule('lead')==='quick'?Math.max(1,Math.round(n/LEAD_QUICK)):n;} +// A fresh, valid rules object: the preset's values, with any valid overrides on top. +function makeRules(preset,o){const p=Object.prototype.hasOwnProperty.call(PRESETS,preset)?preset:'oncall',P=PRESETS[p],r={preset:p};o=o&&typeof o==='object'?o:{}; + // The later rules are written only where they differ from the classic game, so older networks' rules stay as they were. + for(const k of Object.keys(RULE_OK)){const d=P[k]!==undefined?P[k]:RULE_DEF[k],v=RULE_OK[k].includes(o[k])?o[k]:d;if(!RULE_LATE.includes(k)||v!==RULE_DEF[k])r[k]=v;} + r.mods=Array.isArray(o.mods)?[...new Set(o.mods.filter(m=>typeof m==='string'&&/^[a-z0-9_-]{1,24}$/.test(m)))].slice(0,16):[]; + return r;} +// What the HUD and the share card say about the rules. On-call says nothing: it is the game. +function ruleTag(){const p=rulePreset();if(S&&S.mode==='sandbox'){const c=CHAOS[rule('chaos')];return tr('common.sandbox')+(c&&rule('chaos')!=='none'?' '+c.i:'');} + return p==='oncall'||p==='sandbox'?'':PRESETS[p].i+' '+PRESETS[p].n;} +/* Spicy outages last longer: stretch a fresh incident by half, and exactly what it holds down (found by its ref, as + clearInc() finds it), never something else that happens to end the same day. */ +function stretchInc(i){if(rule('chaos')!=='spicy'||!i||!(i.until>S.day)||i.start!==S.day)return;const U=i.until,V=S.day+Math.ceil((U-S.day)*SPICY_LONG);if(V===U)return;i.until=V; + const f=(o,k)=>{if(o&&o[k]===U)o[k]=V;},E=S.ev,T=i.type,r=i.ref,L=()=>S.links.find(l=>l.id===r); + if(T==='cut'||T==='redsea'){for(const l of S.links)if((l.trench||l.id)===r)f(l,'cut');} + else if(T==='fatwave'||T==='label')f(L(),'cut'); + else if(T==='ctrlplane'){for(const id of Array.isArray(i.links)?i.links:[])f(S.links.find(l=>l.id===id),'cut');} + else if(T==='amp'||T==='roadmff')f(L(),'eqDown');else if(T==='mtu')f(L(),'deg');else if(T==='loss')f(L()?.loss,'until');else if(T==='optic')f(L()?.chFail,'until'); + else if(['crash','power','oops','cleaner','maint','shutdown'].includes(T))f(S.pops[r],'down'); + else if(T==='ring')f(S.pops[r],'ringcut');else if(T==='ac')f(S.pops[r],'hot'); + else if(T==='transit'||T==='prepend')f(S.transit.find(t=>t.id===r),'down'); + else if(T==='ixloop'&&E.ixdown)f(E.ixdown,r);else if(T==='fabric'&&E.fab)f(E.fab,r);else if(T==='leostorm')f(E,'sky'); + else if(T==='lacp'){const [k,...x]=String(r).split(':'),id=x.join(':');f(k==='ix'?E.ixlacp&&E.ixlacp[id]:(k==='t'?S.transit:S.pni).find(o=>o.id===id)?.lacp,'until');} + else if(T==='rpki'||T==='hijack')f(E.rpki,'until');else if(T==='leak'||T==='pmtud')f(E[T],'until');else if(T==='krroute'||T==='depeer')f(E,T); + else if(T==='ddos')f(ddosAll(S,false).find(a=>a.id===i.atk),'until');} diff --git a/src/game/50-state.js b/src/game/50-state.js new file mode 100644 index 0000000..6375302 --- /dev/null +++ b/src/game/50-state.js @@ -0,0 +1,9 @@ +/* ================= STATE ================= */ +let S=null, R=emptyR(); +const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false,clockLocked:false}; +/* Where tools that are not part of the game (the development page's agent, src/agent/) may hook in. Empty in the page + players get, and the game only ever calls into it with ?.(), so nothing changes there. clockLocked: the clock is not + the player's (an agent drives): no pause, no speed buttons, no auto-pause, and the speed is HOOKS.speed()'s. */ +const HOOKS={}; +let uidN=1; const uid=()=>'i'+(Date.now()%1e7).toString(36)+(uidN++); +function emptyR(){return {nt:{},cone:{},reachNT:0,teBlack:0,tNet:{},egT:{},netEg:{},l2lat:{},nodeLoad:{},nodeCap:{},div:{},l2:{},gfwLost:0,gfwCross:0,ef:{},egDesc:{},p95:{},peered:0,peerShare:0,load:{},useT:{},useIx:{},usePni:{},useCache:{},cityDem:{},citySrv:{},cityEye:{},latF:{},latFar:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{},ddos:[],haul:[],tgtF:{},bbF:{},fsUse:{},ddosHot:{}};} diff --git a/src/game/60-features/10-banks.js b/src/game/60-features/10-banks.js new file mode 100644 index 0000000..12aaeb7 --- /dev/null +++ b/src/game/60-features/10-banks.js @@ -0,0 +1,135 @@ +/* ================= BANKS & LOANS ================= + Lenders make offers now and then (more often when you are broke). Each loan + is a fixed monthly payment that shows up in your costs; conditions are checked + daily and breaking one costs a penalty. */ +const BANKS={ + gs:{name:'Goldman Sacks',col:'#6F8FAF',min:'AA',apr:[.07,.11],amt:[4,9],term:[24,48],covs:['peer30','continents2','golf','yacht'],blurb:tr('banks.only_lends_to_people_who_do')}, + db:{name:'Deutsche Bankrupt',col:'#0018A8',min:'A',apr:[.08,.13],amt:[3,7],term:[18,36],covs:['nocog','gen','fax'],blurb:tr('banks.very_solid_mostly')}, + jpm:{name:'JP Morgain',col:'#5B4636',min:'A',apr:[.09,.14],amt:[3,6],term:[12,36],covs:['uptime','logo','nephew'],blurb:tr('banks.lends_you_money_and_also_a')}, + cs:{name:'Credit Sweaty',col:'#7A9CC6',min:'BBB',apr:[.11,.17],amt:[2,5],term:[12,30],covs:['cash50','nochina'],blurb:tr('banks.nervous_but_enthusiastic')}, + wf:{name:'Wells Far-Gone',col:'#D71E28',min:'BB',apr:[.12,.18],amt:[2,4],term:[12,24],covs:['nosub','logo','reach99'],blurb:tr('banks.opened_three_accounts_for_you_while')}, + spk:{name:'Spätzle-Sparkasse',col:'#E30613',min:'B',apr:[.05,.08],amt:[1,3],term:[24,60],covs:['spaetzle','kehrwoche'],blurb:tr('banks.cheap_patient_and_very_particular')}, + rev:{name:'Revoloot',col:'#191C1F',min:'B',apr:[.13,.2],amt:[1,3],term:[6,18],covs:['app'],blurb:tr('banks.instant_approval_instant_regret')}, + gov:{name:'Ministry of Tubes',col:'#2E7D32',min:'CCC',apr:[.01,.02],amt:[1,2],term:[36,60],covs:['rural','forms'],blurb:tr('banks.cheap_state_money_for_connecting_the')}, + crypto:{name:'Crypto Bros Capital',col:'#F7931A',min:'CCC',apr:[.15,.25],amt:[2,6],term:[6,18],covs:['hodl','tier3'],crypto:true,blurb:tr('banks.pays_out_in_tubecoin_value_may')}, + vult:{name:'Venture Vultures',col:'#8E44AD',min:'CCC',amt:[6,12],share:[.1,.15],covs:['blitz'],equity:true,blurb:tr('banks.no_repayments_ever_just_a_slice')}, + balloon:{name:'Ballooney Brothers',col:'#E91E63',min:'B',apr:[.1,.15],amt:[2,6],term:[12,24],covs:['oddpops'],model:'balloon',blurb:tr('banks.no_payments_at_all_until_the')}, + storm:{name:'Stormy Weather Lending',col:'#546E7A',min:'BB',apr:[.04,.06],amt:[2,5],term:[12,36],covs:['nogen'],model:'storm',blurb:tr('banks.cheap_while_the_sun_shines_every')}, + ppp:{name:'Peer Pressure Partners',col:'#00897B',min:'B',amt:[2,5],term:[24,36],covs:['nocache'],model:'transit',blurb:tr('banks.you_repay_with_30_of_your')}, + astro:{name:'Horoscope Holdings',col:'#5E35B1',min:'CCC',apr:[.02,.3],amt:[1,4],term:[12,24],covs:['friday','nobude'],model:'astro',blurb:tr('banks.your_rate_is_set_by_the')}, + pizza:{name:'Papa Pizza Capital',col:'#FF7043',min:'BB',apr:[.03,.05],amt:[1,3],term:[12,24],covs:['pizza'],blurb:tr('banks.the_cheapest_money_in_town_there')}, + // The rocket company's state lender: never calls on its own, offered in Pie Control (99-pie-subsidies.js), sized there. + exim:{name:'Ex-Im Pie Bank',col:'#1565C0',min:'C',apr:[.015,.025],amt:[0,0],term:[60,60],covs:['pielaunch','piedish'],pie:true,blurb:tr('banks.exim_blurb')}, + shark:{name:'Loan Shark Telecom Finance',col:'#37474F',min:'C',apr:[.6,.9],amt:[1,2],term:[4,8],covs:[],shark:true,blurb:tr('banks.always_open_ask_no_questions_do')}, +}; +const RATINGS=['C','CCC','B','BB','BBB','A','AA','AAA']; +const COVS={ + peer30:{l:tr('banks.keep_your_peering_ratio_above_30'),ok:()=>(R.peerShare||0)>=0.3}, + continents2:{l:tr('banks.keep_pops_on_at_least_2'),ok:()=>regionsCount()>=2}, + golf:{l:tr('banks.your_ceo_plays_golf_with_our'),ok:()=>true}, + nocog:{l:tr('banks.no_cogentle_transit_anywhere_our_ceo'),ok:()=>!S.transit.some(t=>t.net==='cog')}, + gen:{l:tr('banks.every_pop_needs_a_backup_generator'),ok:()=>Object.values(S.pops).every(p=>p.gen)}, + fax:{l:tr('banks.send_us_your_monthly_report_by'),ok:()=>true}, + uptime:{l:tr('banks.deliver_at_least_95_of_what'),ok:()=>!R.demand||R.served/R.demand>=0.95}, + logo:{l:tr('banks.our_logo_goes_on_every_router'),ok:()=>true}, + cash50:{l:tr('banks.never_let_cash_drop_below_50k'),ok:()=>S.cash>=50000}, + nochina:{l:tr('banks.stay_out_of_mainland_china'),ok:()=>!Object.keys(S.pops).some(cnCity)}, + nosub:{l:tr('banks.no_new_subsea_links_while_this'),ok:l=>S.links.filter(seaLink).length<=(l.base&&l.base.sub||0)}, + spaetzle:{l:tr('banks.peer_at_the_spatzle_ix_in'),ok:()=>S.ixp.stg!==undefined}, + kehrwoche:{l:tr('banks.do_the_kehrwoche_keep_your_noc'),ok:()=>!S.inc.some(i=>S.day-i.start>7)}, + app:{l:tr('banks.download_our_app_and_enable_all'),ok:()=>true}, + rural:{l:tr('banks.run_home_broadband_somewhere'),ok:()=>Object.keys(S.pops).some(c=>S.pops[c].bb&&['AS','AF','OC','SA'].includes(CITY[c].reg))}, + forms:{l:tr('banks.fill_in_form_t_17b_in'),ok:()=>true}, + hodl:{l:tr('banks.never_sell_your_tubecoin_diamond'),ok:()=>true}, + oddpops:{l:tr('banks.always_run_an_odd_number_of'),ok:()=>Object.keys(S.pops).length%2===1}, + nobude:{l:tr('banks.never_build_in_bude_the_loan'),ok:()=>!S.pops.bde}, + nogen:{l:tr('banks.no_diesel_generators_anywhere_our'),ok:()=>!Object.values(S.pops).some(p=>p.gen)}, + friday:{l:tr('banks.no_new_links_on_a_friday'),ok:l=>!S.links.some(x=>(x.day||0)>=l.start&&(x.day||0)%7===4)}, + nocache:{l:tr('banks.no_goggle_cache_boxes_our_chairman'),ok:()=>!S.caches.some(c=>c.net==='ggl')}, + reach99:{l:tr('banks.reach_99_of_the_internet_at'),ok:()=>(R.reach||0)>=0.99}, + tier3:{l:tr('banks.stay_tier_3_number_go_up'),ok:()=>tierLabel()==='Tier 3'}, + nephew:{l:tr('banks.give_our_ceo_s_nephew_a'),fee:3000,ok:()=>true}, + yacht:{l:tr('banks.our_chairman_needs_a_yacht_for'),fee:8000,ok:()=>true}, + pizza:{l:tr('banks.pizza_for_the_whole_noc_after'),each:400,ok:()=>true}, + // The Ex-Im Pie Bank's space covenants: their numbers live on the loan (l.pie). + pielaunch:{l:l=>l&&l.pie?tr('banks.exim_launch_n_pies_by',{n:l.pie.n,d:dateStr(l.pie.by),f:Math.min(l.pie.flown,l.pie.n)}):tr('banks.exim_launch_pies'),ok:l=>pieEximLaunchOk(l)}, + piedish:{l:l=>tr('banks.exim_keep_a_dish_in',{a:l&&l.pie?pieLicCountry(l.pie.cc):'?'}),ok:l=>pieEximDishOk(l)}, + blitz:{l:tr('banks.open_a_new_pop_at_least'),ok:l=>S.day-Math.max(l.start,...Object.values(S.pops).map(p=>p.day||0))<=90}, +}; +// Conditions read with their price filled in; some cost money every month, one costs money per incident. +const covLabel=(c,l)=>{const C=COVS[c];return !C?c:typeof C.l==='function'?C.l(l):C.l.replace('{price}',fmt$(C.fee||C.each||0));}; +const loanFees=l=>(l.covs||[]).reduce((a,c)=>a+((COVS[c]&&COVS[c].fee)||0),0); +// Good terms are for good credit: every notch below AAA adds to the rate. +const RATE_PREM={AAA:0,AA:.005,A:.01,BBB:.02,BB:.04,B:.07,CCC:.12,C:.2}; +// A loan worth more than this many months of revenue also wants a slice of revenue until it is repaid. +const BIG_LOAN=5; +const STAR_SIGNS=[N_('common.mercury'),N_('common.saturn'),N_('common.venus'),N_('banks.your_rising_sign'),N_('common.the_moon'),N_('banks.pluto_which_is_not_even_a')]; +function niceAmt(v){const m=Math.pow(10,Math.floor(Math.log10(Math.max(1,v)))-1);return Math.max(50000,Math.round(v/m)*m);} +function rating(){if(!S)return 'BB';const rev=R.revMo||0,pay=(R.cost&&R.cost.loans)||0;let sc=2; + if(rev>100000)sc++;if(rev>500000)sc++;if(rev>2000000)sc++;if(R.revMo>R.costMo)sc++;else sc--;if(rev&&(R.revMo-R.costMo)/rev>=0.25)sc++; + if(S.cash<0)sc-=2;if(rev&&pay/rev>0.3)sc--;if(rev&&pay/rev>0.6)sc--;sc-=Math.min(3,S.loanStrikes||0); + return RATINGS[clamp(sc,0,RATINGS.length-1)];} +const rIdx=r=>RATINGS.indexOf(r); +function annuity(P,apr,n){const r=apr/12;return r?P*r/(1-Math.pow(1+r,-n)):P/n;} +function spawnLoanOffer(emergency){ + const rt=rating(),keys=Object.keys(BANKS).filter(k=>rIdx(rt)>=rIdx(BANKS[k].min)&&!S.loanOffers.some(o=>o.bank===k)&&!(BANKS[k].equity&&S.loans.some(l=>l.bank===k))&&!BANKS[k].pie); + let pool=emergency?keys.filter(k=>['shark','gov','crypto','vult','rev','spk','astro','balloon'].includes(k)):keys.filter(k=>k!=='shark');if(!pool.length)pool=keys;if(!pool.length)return; + const k=pick(pool),B=BANKS[k],base=Math.max(60000,R.revMo||0),ra=(a)=>a[0]+Math.random()*(a[1]-a[0]); + const amount=niceAmt(base*ra(B.amt)*(emergency?0.6:1)),o={id:uid(),bank:k,amount,exp:S.day+(emergency?10:25),covs:B.covs.slice()}; + if(B.equity){o.share=+ra(B.share).toFixed(3);} + else if(B.model==='transit'){o.model='transit';o.cut=0.3;o.term=Math.round(ra(B.term)/6)*6||6;o.owe=Math.round(amount*1.3);o.apr=0;o.pay=0;} + else{o.apr=+(ra(B.apr)+(RATE_PREM[rt]||0)).toFixed(3);o.term=Math.round(ra(B.term)/6)*6||6;o.pay=B.model==='balloon'?0:Math.round(annuity(amount,o.apr,o.term));if(B.model)o.model=B.model;} + if(!B.equity&&amount>BIG_LOAN*base)o.share=+Math.min(0.08,0.02+0.01*(amount/base-BIG_LOAN)).toFixed(3); + S.loanOffers.push(o); + toast(tr('banks.bank_would_like_to_lend_you',{bank:esc(B.name),amount:fmt$(amount)})+'
'+(emergency?tr('banks.they_heard_you_might_be_in'):tr('banks.terms_apply_several_terms')),emergency?'bad':'goal',[{l:tr('common.open_bank'),act:'bank',args:{}}]); +} +/* Good credit can pick up the phone (#251), from AA up. The rate and the limit follow from the rating alone, so calling again + gets nothing better and rolls no dice. Bankers being bankers, weird conditions apply: this week's quirk (CALL_ODD, turning + over every 7 days) comes on top of the usual ones. What you owe already uses up the limit, and the limit replaces the + revenue share of a BIG_LOAN. */ +const CALL_AMTS=[1e5,5e5,1e6,5e6,1e7],CALL_MONTHS=36; +const CALL_TERMS={AA:{bank:'gs',apr:.075,x:6,covs:['golf','continents2'],odd:2},AAA:{bank:'gs',apr:.06,x:8,covs:['golf'],odd:1}}; +const CALL_ODD=['yacht','oddpops','friday','nephew','nobude','kehrwoche','forms','app']; +const callOdd=T=>{const w=Math.floor(S.day/7)*3;return Array.from({length:T.odd},(_,i)=>CALL_ODD[(w+i)%CALL_ODD.length]);}; +const loanDebt=()=>S.loans.reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.bal),0); +const callLimit=T=>Math.max(0,(R.revMo||0)*T.x-loanDebt()); +// The new offer replaces an earlier called one; offers that came by themselves stay. +function callOffer(amount){const T=CALL_TERMS[rating()];if(!T||!CALL_AMTS.includes(amount)||S.cash>=RICH_NO_LOANS||amount>callLimit(T))return null; + const o={id:uid(),bank:T.bank,amount,exp:S.day+25,covs:T.covs.concat(callOdd(T)),apr:T.apr,term:CALL_MONTHS,pay:Math.round(annuity(amount,T.apr,CALL_MONTHS)),call:1}; + S.loanOffers=S.loanOffers.filter(x=>!x.call);S.loanOffers.push(o);return o;} +// Best Effort has no game over: deep in the red, the Ministry of Tubes lends what it takes to be back in the black, +// cheap, over five years, no conditions. The repayments are still yours. +const RESCUE_APR=0.02,RESCUE_TERM=60; +function rescueLoan(){const amount=niceAmt(Math.max(250000,-S.cash+Math.max(150000,(R.costMo||0)*2))); + S.cash+=amount;S.stats.rescues=(S.stats.rescues||0)+1;S.neg=0; + S.loans.push({id:uid(),bank:'gov',start:S.day,amount,got:amount,bal:amount,apr:RESCUE_APR,apr0:RESCUE_APR,pay:Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)),left:RESCUE_TERM,term:RESCUE_TERM,share:0,covs:[],base:{sub:S.links.filter(seaLink).length}}); + track('rescue');toast(`${tr('banks.bank_stepped_in',{bank:esc(BANKS.gov.name)})}
${tr('banks.a_rescue_loan_of_amount_keeps',{amount:fmt$(amount),pay:fmt$(Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)))})}`,'bad',[{l:tr('common.open_bank'),act:'bank',args:{}}]);sfx('coin');} +function loanTick(d){ + // conditions: 15-day grace, then a penalty every 30 days while broken + for(const l of S.loans){const B=BANKS[l.bank]; + const broken=l.covs.filter(c=>COVS[c]&&!COVS[c].ok(l)); + if(d-l.start<15||!broken.length){l.breach=0;continue;} + l.breach=(l.breach||0)+1; + if(l.breach===1)toast(tr('banks.bank_is_unhappy_you_broke_a',{bank:esc(B.name),cond:esc(covLabel(broken[0],l))}),'bad',[{l:tr('common.open_bank'),act:'bank',args:{}}]); + if(l.breach===10||(l.breach>10&&(l.breach-10)%30===0)){ + if(B.equity){l.share=+(l.share+0.02).toFixed(3);toast(tr('banks.bank_are_circling_they_now_take',{bank:esc(B.name),pct:pct(l.share)}),'bad');} + else{const fee=Math.round(l.bal*0.05);l.bal+=fee;l.pay=Math.round(annuity(l.bal,l.apr,Math.max(1,l.left)));S.loanStrikes=(S.loanStrikes||0)+1;toast(tr('banks.penalty_from_bank_fee_added_to',{bank:esc(B.name),fee:fmt$(fee),pay:fmt$(l.pay)}),'bad');if(B.pie)pieEximBreach(l,broken);} + sfx('err');}} + // monthly statement: payments already leave your cash daily as part of costs + for(const l of S.loans.slice()){const B0=BANKS[l.bank];if(B0.equity||!monthiversary(l.start,d))continue; + if(l.model==='transit')l.bal=Math.max(0,l.bal-Math.round(((R.cost&&R.cost.transit)||0)*(l.cut||0.3)));else l.bal=Math.max(0,l.bal*(1+l.apr/12)-l.pay);l.left--; + // A balloon, or what a transit-free network never paid, is due in one go at the end. + if(l.left<=0&&l.bal>=1&&(l.model==='balloon'||l.model==='transit')){S.cash-=Math.round(l.bal);toast(tr('banks.bank_the_balloon_popped_the',{bank:esc(B0.name),price:fmt$(l.bal)}),'bad');sfx('err');l.bal=0;} + if(l.left>0&&l.bal>=1){if(l.model==='storm'){l.apr=+((l.apr0||0)+0.02*S.inc.length).toFixed(3);l.pay=Math.round(annuity(l.bal,l.apr,l.left));} + else if(l.model==='astro'){const a=+(0.02+Math.random()*0.28).toFixed(3);if(Math.abs(a-l.apr)>=0.08)toast(tr('banks.bank_sign_is_in_retrograde_your',{bank:esc(B0.name),sign:tr(pick(STAR_SIGNS)),apr:(a*100).toFixed(1)}),a>l.apr?'bad':'good');l.apr=a;l.pay=Math.round(annuity(l.bal,l.apr,l.left));}} + if(l.left<=0||l.bal<1){S.loans=S.loans.filter(x=>x!==l);track('loan_repaid');toast(tr('banks.loan_from_bank_paid_off_they',{bank:esc(BANKS[l.bank].name)}),'good');sfx('coin');}} + // the shark's collectors come by when you are broke + if(S.cash<0&&S.loans.some(l=>BANKS[l.bank].shark)&&Math.random()<0.03){const c=pick(Object.keys(S.pops));const p=S.pops[c];p.down=Math.max(p.down||0,d+1);const en=N_('banks.two_very_large_gentlemen_from_loan');addInc({type:'shutdown',ref:c,until:d+1,msg:tr(en,{city:CITY[c].name}),cost:0},en);toast(tr('banks.the_loan_shark_sent_a_reminder',{city:CITY[c].name}),'bad');sfx('alert');} + // offers: now and then, and much more often when you are in trouble + S.loanOffers=S.loanOffers.filter(o=>o.exp>d); + const broke=S.cash<0; + // With half a billion in the vault, loan offers are just noise (#52): banks stop calling, open offers lapse. + if(S.cash>=RICH_NO_LOANS){if(S.loanOffers.length||!S.richTold){S.loanOffers=[];if(!S.richTold&&S.mode!=='sandbox'){S.richTold=1;toast(tr('banks.the_banks_have_stopped_calling_you',{cash:fmt$(RICH_NO_LOANS)}),'good');}}return;} + if(S.loanOffers.length<4&&(broke?Math.random()<0.25:(d-S.day0>20&&Math.random()<1/40)))spawnLoanOffer(broke); +} +const RICH_NO_LOANS=5e8; diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js new file mode 100644 index 0000000..0ae8ca5 --- /dev/null +++ b/src/game/60-features/20-scenarios.js @@ -0,0 +1,74 @@ +/* Seeded games (scenarios, weekly challenge) draw every random number from S.rng, so the same seed + gives the same world. Free play keeps using the browser's Math.random. */ +const _rand=Math.random; +Math.random=function(){if(S&&typeof S.rng==='number'){let t=(S.rng=(S.rng+0x6D2B79F5)|0);t=Math.imul(t^t>>>15,1|t);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}return _rand();}; +const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='sat'?l.g:l.kind==='xp'?xpHopG(l):l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g; +function fastPath(a,b,g){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l)||hopG(l)S.scn.wk?wsTxt(S.scn.wk.name):S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name; +const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>seaLink(l)&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size; +// Ports count only on POPs your backbone joins to São Paulo: islands of POPs with a port each skipped the Amazon (playtest). +const FTTB_G=500; +// Gangnam Style Peering: traffic, how well Seoul is served (delivered and fast) and a monthly profit. +const GN_G=700,GN_Q=0.92; +const brIxN=()=>CITIES.filter(c=>c.br&&S.ixp[c.id]!==undefined&&(c.id==='sao'||pathExists('sao',c.id))).length; +// Days and cash were tuned in the 2.0.0 playtest (tests/scenarios-playtest.test.js): a reference player wins each one in +// roughly a fifth to a half of its days, and the obvious shortcut does not win. The 1.6T scenarios start with enough cash to +// build the whole chain on day 0 and still last until the traffic goal. +const SCN=[ + {id:'stg',n:tr('scenarios.only_spatzle_ix'),city:'stg',cash:400000,days:365,rules:{noTransit:true,local:true},d:tr('scenarios.start_in_stuttgart_where_nobody'),goal:tr('scenarios.reach_50_of_the_internet_and'),ok:()=>R.reach>=0.5&&R.served>=300}, + {id:'redsea',n:tr('scenarios.red_sea_crisis'),city:'mrs',cash:2500000,days:365,rules:{banCities:['cai','jed'],banPairs:['eig:dxb-mrs','gbi:fuj-mrs','smw4:khi-mrs','smw6:mrs-bom','smw6:mrs-sin','peace:mrs-sin','aae:mrs-hkg','twoaf:mrs-bom','medn:cai-mrs','medn:ist-mrs','twoaf:jnb-mrs','eassy:nbo-mrs']},d:tr('scenarios.every_cable_through_the_red_sea'),goal:tr('scenarios.a_path_from_marseille_to_singapore'),ok:()=>pathExists('mrs','sin')&&(S.stats.asiaRun||0)>=RS_DAYS}, + {id:'spat',n:tr('scenarios.the_cogentle_spat'),city:'nyc',cash:700000,days:240,rules:{spat:true},d:tr('scenarios.cogentle_and_goggle_are_not_speaking'),goal:tr('scenarios.99_reach_and_150_gbps_served'),ok:()=>R.reach>=0.99&&R.served>=150}, + {id:'carnaval',n:tr('common.carnaval'),city:'rio',cash:600000,days:100,rules:{},setup:()=>{S.biz.push({id:uid(),scripted:true,city:'rio',city2:null,reqs:[],name:'Carnaval Parade in Rio de Janeiro',type:'event',bw:400,rate:0,mood:100,since:0,start:90,dur:5,fee:400*5*70});},d:tr('scenarios.rio_from_scratch_carnaval_starts_in'),goal:tr('scenarios.deliver_carnaval_in_full'),ok:()=>(S.stats.evFull||0)>=1}, + // Connected, not just present: four island POPs with local transit won on day 40 without crossing anything (playtest). + {id:'darien',n:tr('common.mind_the_gap'),city:'pan',cash:900000,days:180,rules:{},d:tr('scenarios.start_in_panama_city_nothing_crosses'),goal:tr('scenarios.connect_panama_city_to_bogota_lima'),ok:()=>['bog','lim','scl','sao'].every(c=>pathExists('pan',c))&&R.served>=150}, + // Lagos and Nairobi on the network too: one long wave to Cairo plus two empty POPs was not a network across Africa. + {id:'c2c',n:tr('scenarios.cape_to_cairo'),city:'cpt',cash:2000000,days:365,rules:{},d:tr('scenarios.cape_town_build_a_network_across'),goal:tr('scenarios.a_path_from_cape_town_to_cairo_lagos'),ok:()=>pathExists('cpt','cai')&&pathExists('cpt','lag')&&pathExists('cpt','nbo')&&R.served>=150}, + {id:'ixbr',n:tr('scenarios.order_and_progress'),city:'sao',cash:600000,days:240,rules:{},d:tr('scenarios.sao_paulo_brazil_is_a_continent'),goal:tr('scenarios.ports_on_15_ix_brrr_exchanges_backbone'),ok:()=>brIxN()>=15&&S.ixp.mao!==undefined&&R.served>=200}, + // Sender pays, turned up: with Korea at the usual prices broadband swamped every bill and Seoul alone won on day 73 + // (playtest). Now Seoul transit is dear, the incumbents want a paid PNI and Korean users mind every far exit. + {id:'gangnam',n:tr('scenarios.gangnam_style_peering'),city:'icn',cash:900000,days:240,rules:{sender:true},d:tr('scenarios.seoul_sender_pays_d'),goal:tr('scenarios.seoul_sender_pays_goal',{g:GN_G,q:Math.round(GN_Q*100)}),ok:()=>R.reach>=0.99&&R.served>=GN_G&&sfOf(R,'icn')>=GN_Q&&R.revMo>=R.costMo}, + {id:'flood',n:tr('common.flood_season'),city:'ams',cash:2000000,days:365,rules:{ddos:true},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.amsterdam_hosting_capital_of_europe'),goal:tr('scenarios.hold_20_floods_5_terabit'),ok:()=>(S.stats.ddosOk||0)>=20&&(S.stats.ddosOkBig||0)>=5}, + // Traffic served too: broadband in five cities and two cables were bought on day 1 and won on day 2 (playtest). + {id:'fttb',n:tr('scenarios.fibre_to_the_basement'),city:'syd',cash:1500000,days:365,rules:{levy:true},d:tr('scenarios.sydney_2013_the_toilet_paper_group'),goal:tr('scenarios.broadband_in_sydney_melbourne_served'),ok:()=>AU_BB.every(c=>S.pops[c]&&S.pops[c].bb)&&auExits()>=2&&R.served>=FTTB_G}, + // Nobody sells transit in Tallinn here: with local transit, a network that never crossed the water won (playtest). + {id:'baltic',n:tr('common.anchors_away'),city:'tll',cash:500000,days:365,rules:{anchors:3,noTransitIn:['tll']},d:tr('scenarios.tallinn_nobody_sells_transit_anchors'),goal:tr('scenarios.90_days_in_a_row_with'),ok:()=>(S.stats.clean||0)>=90}, + {id:'pac',n:tr('common.stepping_stones'),city:'hnl',cash:5000000,days:240,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.honolulu_in_the_middle_of_the'),goal:tr('scenarios.a_path_from_los_angeles_to'),ok:()=>fastPath('lax','syd',1600)&&pathExists('lax','tok')&&R.served>=150}, + {id:'atl',n:tr('scenarios.mid_atlantic_accent'),city:'pdl',cash:5000000,days:240,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.ponta_delgada_azores_lisbon_lagos'),goal:tr('scenarios.1_6t_on_every_hop_from'),ok:()=>fastPath('mia','mad',1600)&&fastPath('lis','lag',1600)&&R.served>=100}, +]; +const WEEK_CITIES=['fra','ams','lon','nyc','ash','sjc','sin','tok','syd','sao','jnb','bom','waw','ist','scl','hkg']; +const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chaos',n:tr('scenarios.twice_the_failures')},{id:'poor',n:tr('scenarios.start_with_only_100k')},{id:'boom',n:tr('scenarios.eyeballs_grow_50_faster')},{id:'dk',n:tr('scenarios.every_ix_is_run_by_de')},{id:'sharks',n:tr('scenarios.shark_season_subsea_cuts_twice_as')}]; +// The in-browser weekly, when no published scenario came: same weeks as the published one (Sunday 06:00 Berlin). +function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};} +const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); +function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} +function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew(); + beginState(nm,city,{...o,asn:+(UI.asnTxt||UI.asnSug||0)});UI.asnSug=null;beginShow(city,o);} +/* A new network in two halves. beginState() makes S (no screen, no storage, no slot), so a server can build a network + the way the page does; o.asn is the AS number the player typed, kept when asnOk(). beginShow() puts it on screen and + starts it: speed, camera, welcome, charter, tutorial. o.srv: the server built this network (beginState, compute, + beginHello) and set S.tut, so the page neither routes it (its R comes from the server), nor says welcome again, nor + starts the tutorial: it only shows the coach where S.tut is. */ +function beginState(nm,city,o={}){newGame(nm,city);if(asnOk(o.asn))S.asn=o.asn;S.mode=o.mode||'normal'; + // A multiplayer session (89-multiplayer.js): the server's AS number, and its seed, so every player starts in the same world. + if(o.mp&&S.mode==='normal'){const m=o.mp;S.mp={code:m.code,pid:m.pid,asn:m.asn,seed:m.seed,preset:m.preset,color:m.color,title:m.title,seq:0};S.asn=m.asn;S.rng=m.seed|0;} + // The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules. + {const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);} + if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}} + if(o.scn){const sc=o.scn;S.scn={id:sc.id,rules:sc.rules||{},days:sc.days,name:sc.n||tr('features.weekly_challenge_key',{key:sc.key}),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';S.asn=200000+Math.floor(Math.random()*15000); + if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup(); + for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}} + // o.day: a network of a server session begins on the session's date (81-late-joiners.js), after its rules are locked. + if(S.mp&&S.mode==='normal'&&Number.isInteger(o.day)&&o.day>0)lateStart(Math.min(o.day,1e7));} +// The welcome line: in the log, and on screen. +function beginHello(o={}){toast(S.scn?`${esc(S.scn.name)}
${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(S.name),asn:S.asn,city:CITY[S.home].name}),'goal'); + if(lateIs())lateHello();} +function beginShow(city,o={}){ + // Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen. + UI.lastSpeed=rule('clock')?0.5:0;setSpeed(UI.lastSpeed);UI.resumeSpeed=null; + track('game_new');UI.started=true;closeModal();if(!o.srv)compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city); + if(!o.srv)beginHello(o); + // A Normal game asks for its charter first; the tutorial starts once it is signed. + renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(o.srv)renderCoach();else if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();} + if(S.mp)mpStartTell();} diff --git a/src/game/60-features/30-conferences.js b/src/game/60-features/30-conferences.js new file mode 100644 index 0000000..fd63b3f --- /dev/null +++ b/src/game/60-features/30-conferences.js @@ -0,0 +1,29 @@ +/* ---------- conference season ---------- */ +const CONFS=[{n:'PTC',c:'hnl',m:0,cap:1},{n:'NANOG',c:'chi',m:1},{n:'APRICOT',c:'sin',m:1},{n:'Peering Days',c:'waw',m:2},{n:'DKNOG',c:'cph',m:2,j:N_('conferences.the_hallway_track_moved_to_a')},{n:'UKNOF',c:'lon',m:3},{n:'MENOG',c:'dxb',m:3},{n:'NZNOG',c:'akl',m:3},{n:'RIPE',c:'ams',m:4},{n:'NANOG',c:'sea',m:5},{n:'IX Forum',c:'tok',m:6},{n:'AfPIF',c:'nbo',m:7},{n:'AusNOG',c:'syd',m:8},{n:'NLNOG Day',c:'ams',m:8},{n:'LACNOG',c:'sao',m:9},{n:'NANOG',c:'ash',m:9},{n:'Capacity Europe',c:'lon',m:9,cap:1},{n:'DENOG',c:'fra',m:10},{n:'RIPE',c:'ber',m:10},{n:'PTT Forum',c:'sao',m:11},{n:'PacNOG',c:'suv',m:11}]; +const CONF_COST=8000,CONF_DAYS=45; +// Sponsoring (#168) puts your logo on the lanyards: more customers call from that region while the glow lasts. +// Only some meetings sell sponsorships, the same ones every time you look. Capacity conferences are where carriers buy in bulk. +const CONF_SP=40000,CAP_COST=30000,CAP_LV=3; +const confSp=cf=>!cf.cap&&[...cf.key].reduce((a,ch)=>(a*31+ch.charCodeAt(0))>>>0,7)%3!==0; +const confCost=cf=>cf.cap?CAP_COST:CONF_COST; +const confDay=(cf,y)=>dayOf(y+1,cf.m,10); +function confKey(cf,y){return cf.n+'@'+cf.c+'@'+y;} +// No conference season in Best Effort: nothing to register for, nothing in the panel, no invitations. +function upcomingConfs(within){if(!confsOn())return [];const y0=cal(S.day).y-1,out=[];for(const y of [y0,y0+1])for(const cf of CONFS){const d=confDay(cf,y);if(d>=S.day&&d-S.day<=within)out.push({...cf,day:d,key:confKey(cf,y)});}return out.sort((a,b)=>a.day-b.day);} +function confBoost(id){const cb=S.conf;if(!cb||!(cb.until>S.day))return 1;const n=NET[id];return n&&n.pops.some(c=>CITY[c]&&CITY[c].reg===cb.reg)?0.5:1;} +// Once you have made Tier 1, conferences go quiet (#101): no reminders and no reports, only the Deals panel. +const confQuiet=()=>!!(S.done&&S.done.t1!==undefined); +function confTick(d){S.confReg=S.confReg||{};const q=confQuiet(); + for(const cf of upcomingConfs(30)){if(!q&&cf.day-d===30&&!S.confReg[cf.key])toast(tr('conferences.conf_comes_to_city_in_30',{conf:esc(cf.n),city:esc(CITY[cf.c].name)}),'goal',[{l:tr('common.show_me'),act:'leftTab',args:{t:'deals'}}]);} + for(const cf of upcomingConfs(0)){if(cf.day!==d||!S.confReg[cf.key])continue;const reg=CITY[cf.c].reg,sp=S.confReg[cf.key]==='sp';S.conf={until:d+CONF_DAYS,reg,name:cf.n,sp};S.stats.confs=(S.stats.confs||0)+1;if(sp)S.stats.confSp=(S.stats.confSp||0)+1; + if(cf.cap)S.capDeal={at:d+4+Math.floor(Math.random()*5),c:cf.c}; + const r=Math.random();let extra='';if(r<0.3){const cash=5000+Math.floor(Math.random()*4)*5000;S.cash+=cash;extra=' '+tr('conferences.you_also_won_the_raffle_cash',{cash:fmt$(cash)});}else if(r<0.5)extra=' '+tr('conferences.someone_from_goggle_bought_you_a');if(cf.j)extra=' '+tr(cf.j)+(r<0.3?extra:''); + if(!q){toast(tr('conferences.conf_in_city_you_shook_a',{conf:esc(cf.n),city:esc(CITY[cf.c].name),n:CONF_DAYS,region:esc(REG[reg])})+(sp?' '+tr('conferences.your_logo_was_on_every_lanyard',{region:esc(REG[reg])}):'')+(cf.cap?' '+tr('conferences.carriers_took_your_card_expect_big'):'')+extra,'goal');sfx('coin');}} + capDealTick(d);} +function confSection(){const up=upcomingConfs(75).slice(0,3),cb=S.conf&&S.conf.until>S.day?S.conf:null;if(!up.length&&!cb)return ''; + return `

${tr('common.conferences')}

${cb?`
${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}
${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}${cb.sp?' '+tr('conferences.as_a_sponsor_you_also_get',{region:esc(REG[cb.reg])}):''}
`:''}${up.map(confRow).join('')}`;} +function confRow(cf){const reg=S.confReg&&S.confReg[cf.key],open=cf.day>S.day,sp=confSp(cf),cost=confCost(cf),lk=cf.cap&&glassLvl()'+tr('conferences.sponsor')+'':reg?''+tr('common.registered')+'':open?'':''+tr('common.registration_closed')+''); + const btns=!open||reg==='sp'?'':(reg?'':lk?btn(tr('sites_and_service.level_n',{n:CAP_LV}),'confGo',{key:cf.key},'sm',true):btn(tr('conferences.attend_cost',{cost:fmt$(cost)}),'confGo',{key:cf.key},'sm',S.cash
${esc(cf.n)} · ${esc(CITY[cf.c].name)}
${cf.day===S.day?tr('common.today'):tr('conferences.in_n_days',{n:cf.day-S.day})} · ${esc(REG[CITY[cf.c].reg])}${cf.cap?' · '+tr('conferences.capacity_conference_carriers_buy_in'):sp&&open&®!=='sp'?' · '+tr('conferences.sponsorships_available'):''}
${tags}${btns?`
${btns}
`:''}
`;} + diff --git a/src/game/60-features/33-address-space.js b/src/game/60-features/33-address-space.js new file mode 100644 index 0000000..c90cb37 --- /dev/null +++ b/src/game/60-features/33-address-space.js @@ -0,0 +1,112 @@ +/* ---------- Address space (#150): IPv6 is free for everyone, IPv4 ran out years ago ---------- + The network holds IPv4 blocks in real CIDR sizes (/24 to /16): its first allocation from the RIR, blocks bought on + the transfer market and blocks leased in by the month. Owned blocks can be leased out (a broker finds the tenant) or + sold, once two years have passed since they last moved (the RIRs' holding period, which also stops flipping). + Business customers on IP service take a public block each, sized by kind and port (a /29 for a small DIA port, a /23 + for a big hosting company); broadband homes take what is left, and the homes that do not fit share addresses behind + CGNAT at the player's ratio. CGNAT costs a little per Gbps it carries (IPv6 goes around the box) and some gamers want + their money back. An offer that needs more than is free, with every home already behind CGNAT, cannot be signed, and a + customer renewing bigger stays at its size when the bigger block is not free (clGrow). + Nothing is stored per customer: what each one needs follows from its kind and size, so growing customers and old saves + need no new fields. On in On-call and BGP at 3 a.m. (rule ip4), off in the gentler presets, sandbox and puzzles; + scenarios only when they opt in (S.scn.rules.ip4). No random draws: the market price is a function of the day. + The first allocation is a /21: one transit's worth of broadband levels off at about 1,300 homes in every start city, + so the first months fit with room for a few customers (gameplay rule F1). */ +// IP4_BLK: the most blocks a network holds; buying and leasing stop there, and a save keeps that many. +const IP4_START=21,IP4_MIN=16,IP4_MAX=24,IP4_HOLD=730,IP4_NAT=[8,16,32,64],IP4_NAT0=16,IP4_BLK=256; +// Public addresses per Gbps of busy-hour broadband (a home each), and the part of it CGNAT still carries on day 0: the rest +// is IPv6. The world moves on, two points a year to a floor that never goes (ip4V4). +const IP4_BB=10,IP4_V4=0.55,IP4_V4_YR=0.02,IP4_V4_MIN=0.2,IP4_CGN=2; +// IPv6-only homes (464XLAT, 34-ipv6-only.js) have no address of their own: their IPv4 shares a NAT64 pool, at a wider ratio +// than CGNAT can take. Only what still needs IPv4 notices (consoles, IPv4-only VPNs): a share of the bill comes back, well +// under CGNAT's at the same ratio, and shrinking as the world goes IPv6. +const IP4_N64=[64,128,256],IP4_N640=128,IP4_ANNOY64={64:0.006,128:0.01,256:0.016}; +// The market: dollars per address, flat for half a year, then +3% a year on a slow four-year swing. Leases are by the +// month (a broker keeps a cut of what yours earn, and investors on a revenue share take theirs: computeMoney), sales pay +// 92% of the price after the broker's fee. +const IP4_PX=38,IP4_FREE=180,IP4_YR=0.03,IP4_IN=0.5,IP4_OUT=0.4,IP4_SELL=0.92; +// Of the bill of a home behind CGNAT, the share that comes back as refunds (gamers, mostly): more homes per address, more +// grumbling. Homes squeezed past the ratio (port exhaustion) are worse. +const IP4_ANNOY={8:0.01,16:0.015,32:0.025,64:0.04},IP4_SQZ=0.15; +// Per kind of customer: addresses per Gbps of port, and the smallest block it takes. Circuits, waves and fiber carry no +// addresses of yours; downstream ISPs and universities bring their own (universities sit on legacy /16s); orbit +// terminals sit behind the satellite operator's own CGNAT. +const IP4_BIZ={cgame:[0.5,256],dia:[2,8],fabip:[2,8],game:[2,16],gpu:[0.5,64],host:[4,64],metav:[0.25,256],scrub:[2,8],stream:[1,32]}; +const ip4Sz=len=>2**(32-len),ip4LenOk=len=>Number.isInteger(len)&&len>=IP4_MIN&&len<=IP4_MAX; +const ip4Cidr=n=>'/'+(32-Math.ceil(Math.log2(Math.max(1,n)))),ip4N=n=>Math.round(n).toLocaleString(); +function ip4On(){return !!S&&!!S.ip4&&rule('ip4')===true&&(S.scn?scnRule('ip4'):S.mode==='normal');} +function ip4Need(b){const k=b&&IP4_BIZ[b.type];if(!k||!(b.bw>0))return 0;return Math.min(4096,2**Math.ceil(Math.log2(Math.max(k[1],b.bw*k[0]))));} +/* Who uses what. T: usable addresses (owned and leased in, without what is leased out); B: business customers; H: homes, + of them H6 IPv6-only (Hd dual stack); p6: the NAT64 pool; cg: dual-stack homes behind CGNAT; over: the share of homes + that do not fit even at the ratios; need: the least the homes can live with; free: what a new customer can have with + every dual-stack home behind CGNAT. The NAT64 pool comes right after business customers: its homes gave their own + addresses up already and cannot fall back on anything, while dual-stack homes still can (behind CGNAT). */ +function ip4Use(s=S){const I=s.ip4,r=I.nat,r6=I.n64||IP4_N640;let own=0,inn=0,out=0,B=0,H=0,H6=0; + for(const b of I.b){const n=ip4Sz(b.len);if(b.k==='in')inn+=n;else if(b.out)out+=n;else own+=n;} + for(const b of s.biz)B+=ip4Need(b); + // Island Wi-Fi homes (46-wisp-zones.js) are IPv6-only from day one: their IPv4 shares the NAT64 pool. + for(const c in s.pops){const p=s.pops[c];if(p.bb){const h=p.bb.d*IP4_BB;H+=h;if(p.bb.v6)H6+=h*p.bb.v6;}if(p.wisp)for(const z in p.wisp){const h=p.wisp[z].d*IP4_BB;H+=h;H6+=h;}} + H=Math.ceil(H);H6=Math.min(H,Math.ceil(H6));const Hd=H-H6,T=own+inn,A=Math.max(0,T-B),p6=Math.ceil(H6/r6),min=Math.ceil(Hd/r),need=p6+min,A2=A-p6;let cg=0,over=0; + if(A2=min)cg=Math.min(Hd,Math.ceil((Hd-A2)*r/(r-1)));else{cg=Hd;over=need?1-A/need:0;}} + return {T,own,inn,out,B,H,H6,Hd,p6,cg,over,need,free:T-B-need,r,r6};} +const ip4Fits=o=>!ip4On()||ip4Need(o)<=Math.max(0,ip4Use().free); +// Which sharing is left to stretch when space runs out, for the advice: CGNAT (0, no IPv6-only homes), the NAT64 pool alone +// (1, every home IPv6-only) or both (2). +const ip4Pools=u=>!u.H6?0:u.Hd?2:1; +// A customer renewing at bw: does the bigger block it needs fit what is free? +const ip4GrowOk=(b,bw)=>!ip4On()||ip4Need({type:b.type,bw})-ip4Need(b)<=Math.max(0,ip4Use().free); +const ip4Full=()=>S.ip4.b.length>=IP4_BLK; +// What you announce, as the AS box shows it: your blocks by prefix length, without the ones leased out to others. +const ip4Pfx=()=>{const c={};for(const b of S.ip4.b)if(!b.out)c[b.len]=(c[b.len]||0)+1;return Object.keys(c).sort((a,b)=>a-b).map(l=>`${c[l]} × /${l}`).join(', ');}; +// Would giving this block up (selling, leasing it out, handing it back) still leave room for everyone? +const ip4Spare=b=>ip4Use().free>=ip4Sz(b.len); +const ip4Held=b=>b.k!=='in'&&S.day-b.dMath.round(ip4Sz(len)*ip4Px()*(1-0.015*(IP4_MAX-len))/100)*100; +const ip4Value=len=>Math.round(ip4Cost(len)*IP4_SELL/100)*100; +const ip4InMo=len=>Math.round(ip4Sz(len)*IP4_IN*ip4Px()/IP4_PX),ip4OutMo=len=>Math.round(ip4Sz(len)*IP4_OUT*ip4Px()/IP4_PX); +// The IPv4 share of home traffic on day d: 55% on day 0 (so nothing changes at the start), two points less a year, never +// under a fifth (old consoles, old VPNs, old everything). +const ip4V4=(d=S.day)=>Math.max(IP4_V4_MIN,IP4_V4-IP4_V4_YR*Math.max(0,d)/365.2425); +/* The month's IPv4 bill: leases in and out, CGNAT boxes and NAT64 gateways (the same price per Gbps of IPv4 they carry), + refunds (eye: what broadband earns a month). NAT64 refunds shrink with the IPv4 share: in an IPv6-only home only what + still needs IPv4 meets the NAT at all. s: the network as ip4Use() takes it (a city panel asks about one that might be). */ +function ip4Bill(eye,s=S){const u=ip4Use(s),v4=ip4V4();let lin=0,lout=0;for(const b of s.ip4.b){if(b.k==='in')lin+=b.mo||0;else if(b.out)lout+=b.mo||0;} + const cgS=u.H?u.cg/u.H:0,v6S=u.H?u.H6/u.H:0; + return {u,lin,lout,v4,box:u.cg/IP4_BB*v4*IP4_CGN,box64:u.H6/IP4_BB*v4*IP4_CGN,refund:eye*(cgS*IP4_ANNOY[u.r]+v6S*IP4_ANNOY64[u.r6]*v4/IP4_V4+u.over*IP4_SQZ)};} +// What homes pay a month (broadband and island Wi-Fi), which the refunds scale with: from computeMoney's V, or R. +const ip4Eye=(V=R&&R.rev)=>V?(V.eyeballs||0)+(V.wisp||0):0; +// computeMoney: only what is there, so a network with nothing to pay keeps its money rows as they were. +function ip4Money(C,V){if(!ip4On())return;const b=ip4Bill(ip4Eye(V)),c=Math.round(b.lin+b.box+b.box64+b.refund);if(c>0)C.ip4=c;if(b.lout>0)V.ip4=b.lout;} +/* A new network gets its /21 from the RIR. An older save gets what it already uses registered to it and a quarter more to + grow into (about a month for a big, fast-growing network), rounded up to /24s in real CIDR blocks (a /21 at the + least), so nothing changes on load; those blocks move like any other two years on. + Their ids are fixed (rir0, rir1…), not uid(): a new game draws no id, so every id after it stays as it was. */ +function ip4Grant(s){const d=s.day||0,b=[],add=len=>b.push({id:'rir'+b.length,len,k:'rir',d});let need=0; + for(const x of s.biz||[])need+=ip4Need(x); + for(const c in s.pops||{}){const p=s.pops[c];if(p&&p.bb&&p.bb.d>0)need+=p.bb.d*IP4_BB;if(p&&p.wisp&&typeof p.wisp==='object')for(const z in p.wisp)need+=Math.max(0,num(p.wisp[z]&&p.wisp[z].d,0))*IP4_BB;} + need=Math.max(ip4Sz(IP4_START),Math.ceil(need*1.25/256)*256); + while(need>=ip4Sz(IP4_MIN)&&b.length<200){add(IP4_MIN);need-=ip4Sz(IP4_MIN);} + for(let len=IP4_MIN+1;len<=IP4_MAX;len++)if(need>=ip4Sz(len)){add(len);need-=ip4Sz(len);} + return {b,nat:IP4_NAT0,n64:IP4_N640,w:0};} +const ip4New=()=>ip4Grant({}); +function ip4Fix(s){const I=s.ip4&&typeof s.ip4==='object'&&!Array.isArray(s.ip4)?s.ip4:null;if(!I){s.ip4=ip4Grant(s);return;} + const day=Math.max(0,num(s.day,0)),mo=v=>Math.round(Math.min(1e8,Math.max(0,num(v,0)))); + const b=(Array.isArray(I.b)?I.b:[]).filter(x=>x&&typeof x==='object'&&ip4LenOk(x.len)&&['rir','buy','in'].includes(x.k)).slice(0,IP4_BLK).map(x=>{ + const o={id:typeof x.id==='string'&&x.id&&x.id.length<=40?x.id:uid(),len:x.len,k:x.k,d:int(x.d,0,day,0)}; + if(x.k==='in')o.mo=mo(x.mo);else if(x.out===true){o.out=true;o.mo=mo(x.mo);}return o;}); + s.ip4={b,nat:IP4_NAT.includes(I.nat)?I.nat:IP4_NAT0,n64:IP4_N64.includes(I.n64)?I.n64:IP4_N640,w:int(I.w,0,3,0)};} +/* Once a day: say so when homes go behind CGNAT (a percent of them at least), and when even CGNAT cannot fit them all + (w: what was said). Each rearms only with room to spare again, so homes hovering at the limit hear it once. */ +function ip4Day(d){if(!ip4On())return;ip6Day(d);const I=S.ip4,u=ip4Use(),A=u.T-u.B,go=[{l:tr('ip4.section'),act:'ip4Open'}]; + if(u.cg>=Math.max(1,u.H*0.01)){if(!(I.w&1)){I.w|=1;toast(tr('ip4.toast_cgnat',{p:pct(u.cg/u.H)}),'',go);}}else if(A-u.p6>=u.Hd*1.05)I.w&=~1; + if(u.over>0){if(!(I.w&2)){I.w|=2;const k=ip4Pools(u);toast(k===1?tr('ip4.toast_out_v6',{r:u.r6}):k?tr('ip4.toast_out_both',{r:u.r,r6:u.r6}):tr('ip4.toast_out',{r:u.r}),'bad',go);sfx('err');}} + else if(A>=u.need*1.1)I.w&=~2;} +// Your customers need the addresses: what to stretch or get instead (ip4Busy, the bank's block rows). +function ip4InUse(u=ip4Use()){const k=ip4Pools(u);return k===1?tr('ip4.in_use_v6'):k?tr('ip4.in_use_both'):tr('ip4.in_use');} +// Renewals that wanted a bigger block than is free (clGrow, [customer, bandwidth]): they stay as they are, and hear why. +function ip4News(l=[]){for(const [b,bw] of l.slice(0,3))toast(tr('ip4.no_grow',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(bw)}),'',[{l:tr('ip4.section'),act:'ip4Open'}]);} +// The line under an offer that cannot be signed for want of addresses. +function ip4Why(o){if(ip4Fits(o))return '';const n=ip4Need(o); + return `
${tr('ip4.offer_needs',{p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))})} ${btn(tr('ip4.section'),'ip4Open',{},'ghost sm')}
`;} diff --git a/src/game/60-features/34-ipv6-only.js b/src/game/60-features/34-ipv6-only.js new file mode 100644 index 0000000..6be1db7 --- /dev/null +++ b/src/game/60-features/34-ipv6-only.js @@ -0,0 +1,64 @@ +/* ---------- IPv6-only broadband (464XLAT), city by city, next to CGNAT (33-address-space.js) ---------- + A broadband city can go IPv6-only: every home router is swapped for one with a CLAT, and the network runs NAT64/DNS64 + for whatever still needs IPv4. Those homes hold no IPv4 address of their own: their IPv4 shares the NAT64 pool at the + player's NAT64 ratio (S.ip4.n64), which ip4Use() sets aside right after business customers. CGNAT costs nothing to + start; this costs a home router per home, paid as each one goes in, and some days per city. + p.bb.v6: the share of the city's homes that are IPv6-only (absent: none, dual stack, as in every older save); + p.bb.v6e: the day the swap finishes, while it runs. Homes that join a city that is swapping or done get the new router + from the start, at the same price (ip6Grow): a city that goes IPv6-only the day it launches pays for every home it grows + into, as one that switches years later does. Stop halfway and the swapped ones stay, the new ones come dual stack + again. A POP closed and rebuilt starts dual stack: its homes, and the routers they had, left with it. Rule ip4, like + the rest of the address space. */ +// Dollars per home router; a swap takes IP6_D0 days plus one for every IP6_PER homes, IP6_DMAX at most. +const IP6_CPE=4,IP6_D0=30,IP6_PER=200,IP6_DMAX=180; +const ip6Pop=c=>own(S.pops,c)?S.pops[c]:null; +// Dual-stack homes still to swap in a city. +const ip6Homes=p=>p&&p.bb?Math.max(0,p.bb.d*IP4_BB*(1-(p.bb.v6||0))):0; +const ip6Cost=c=>{const n=ip6Homes(ip6Pop(c));return n>0?Math.max(100,Math.round(n*IP6_CPE/100)*100):0;}; +const ip6Days=c=>Math.min(IP6_DMAX,IP6_D0+Math.ceil(ip6Homes(ip6Pop(c))/IP6_PER)); +// To start, the first day's routers on hand: the rest is paid as they go in, and the swap waits while cash is short. +const ip6First=c=>ip6Cost(c)/Math.max(1,ip6Days(c)); +// The network as it would be with every home here IPv6-only (p: the city's POP, with broadband). +const ip6If=(c,p)=>({ip4:S.ip4,biz:S.biz,pops:{...S.pops,[c]:{...p,bb:{...p.bb,v6:1}}}}); +// Exactly what going IPv6-only here frees for new customers: the address space counted again with every home here on it. +function ip6Free(c){const p=ip6Pop(c);if(!p||!p.bb)return 0;return ip4Use(ip6If(c,p)).free-ip4Use().free;} +/* And what it does to the month's IPv4 bill, counted the same way (eye: what broadband earns a month): NAT64 gateways and + refunds against the CGNAT boxes and refunds it saves. While no home is behind CGNAT it only adds. */ +function ip6Mo(c,eye){const p=ip6Pop(c);if(!p||!p.bb)return 0;const m=b=>b.box+b.box64+b.refund;return m(ip4Bill(eye,ip6If(c,p)))-m(ip4Bill(eye));} +// A city the build standard's IPv6-only row would start (bstdPlan()): broadband with dual-stack homes, no swap running. +const ip6Todo=c=>{const p=ip6Pop(c);return !!p&&!!p.bb&&!p.bb.v6e&&!(p.bb.v6>=1)&&ip6Homes(p)>0;}; +// What the swaps under way still have to pay for, router by router: the build standard's button starts a job, and the +// intern's orders anything, only with that much on top of its own price (above the cash floor), since a swap pays as it +// goes and the cash has not moved yet. Nothing while IPv4 is plentiful: the swaps wait then (ip6Day()). +const ip6Owed=()=>{if(!ip4On())return 0;let n=0;for(const c in S.pops){const b=S.pops[c].bb;if(b&&b.v6e)n+=ip6Homes(S.pops[c])*IP6_CPE;}return n;}; +// Why this city cannot start a swap now ('' when it can). +function ip6Why(c){const p=ip6Pop(c);if(!ip4On())return tr('ip4.off');if(!p||!p.bb)return tr('ip6.no_bb');if(p.bb.v6e)return tr('ip6.busy');if(p.bb.v6>=1)return tr('ip6.already');return '';} +// Today's routers: an even share of what is left, so the swap ends on its day however the city grows meanwhile. +const ip6Left=(b,d)=>Math.max(1,b.v6e-d+1),ip6Slice=(b,d)=>b.d*IP4_BB*(1-(b.v6||0))/ip6Left(b,d)*IP6_CPE; +/* Once a day (from ip4Day): every running swap does its share of the homes and pays for their routers. Short of cash, + the crews wait a day and the end slides with them, so a swap never pushes the network into the red. */ +function ip6Day(d){if(!ip4On())return;for(const c in S.pops){const b=S.pops[c].bb;if(!b||!b.v6e)continue; + const k=ip6Left(b,d),cost=ip6Slice(b,d);if(cost>Math.max(0,S.cash)){b.v6e++;continue;} + S.cash-=cost;const v=b.v6||0;b.v6=k<=1?1:Math.min(1,v+(1-v)/k); + if(k<=1){delete b.v6e;toast(tr('ip6.done',{city:esc(CITY[c].name)}),'good',[{l:tr('ip4.section'),act:'ip4Open'}]);}}} +/* The day's new homes (d0: demand before it grew): while swapping or done each gets the new router, IP6_CPE like a swapped + one, dual stack after a stop. The swap of old routers is a project and waits for cash; a home that signs up today + needs its router today, so that is spent like any running cost (homes only join where the service is good, and they + pay it back within days). */ +function ip6Grow(b,d0){if(!ip4On()||!(b.d>d0))return;const v=b.v6||0; + if(b.v6e||v>=1){S.cash-=(b.d-d0)*IP4_BB*IP6_CPE;if(v<1)b.v6=1-(1-v)*d0/b.d;}else if(v>0)b.v6=v*d0/b.d;} +// Saves: v6 is a share (none at all is no field, so a dual-stack city saves as it always did); v6e a day, gone once done. +function ip6Fix(b,day){if(b.v6!==undefined){const v=num(b.v6,0);if(v>0)b.v6=Math.min(1,v);else delete b.v6;} + if(b.v6e!==undefined){if(b.v6>=1||!Number.isFinite(b.v6e))delete b.v6e;else b.v6e=int(b.v6e,day,day+3650,day);}} +// The city panel's Home broadband: where the city stands, and the swap to start or stop. +function ip6Html(c){if(!ip4On())return '';const p=ip6Pop(c),b=p&&p.bb;if(!b)return '';const v=b.v6||0,r=S.ip4.n64||IP4_N640; + let h=`
${tr('ip6.title')}${v>=1?tr('ip6.every_home'):v>0||b.v6e?tr('ip6.share_homes',{p:pct(v)}):tr('ip6.dual_stack')}
`; + if(b.v6e){const wait=ip6Slice(b,S.day+1)>Math.max(0,S.cash); + h+=`

${tr('ip6.swapping_home_routers_paid',{cost:fmt$(IP6_CPE),date:dateStr(b.v6e)})}

${wait?`

${tr('ip6.waiting')}

`:''}
${btn(tr('ip6.stop'),'ip6Stop',{city:c},'ghost sm')}
`;} + else if(v>=1)h+=`

${tr('ip6.new_homes_get_a_clat',{cost:fmt$(IP6_CPE),r})}

`; + else{const n=Math.ceil(ip6Homes(p)),cost=ip6Cost(c),f=Math.max(0,ip6Free(c)),mo=Math.round(ip6Mo(c,ip4Eye())); + // Before the player commits: what the month costs after it too, and that it buys nothing yet while IPv4 still fits. + const bill=mo>0?tr('ip6.your_ipv4_bill_goes_up',{price:fmt$(mo)})+(ip4Use().cg?'':' '+tr('ip6.no_home_is_behind_cgnat')):mo<0?tr('ip6.your_ipv4_bill_goes_down',{price:fmt$(-mo)}):''; + h+=`

${v>0?tr('ip6.part_note',{p:pct(v)}):tr('ip6.pitch',{r})} ${tr('ip6.what',{routers:trn('ip6.n_routers',n,{n:ip4N(n)}),days:ip6Days(c),addr:trn('ip4.n_addresses',f,{n:ip4N(f)})})} ${tr('ip6.homes_that_join_later',{cost:fmt$(IP6_CPE)})}${bill?' '+bill:''}

+
${btn(tr('ip6.go',{cost:fmt$(cost)}),'ip6Go',{city:c},'sm',S.cash`;} + return h+'
';} diff --git a/src/game/60-features/35-capacity-deals.js b/src/game/60-features/35-capacity-deals.js new file mode 100644 index 0000000..bdb5c51 --- /dev/null +++ b/src/game/60-features/35-capacity-deals.js @@ -0,0 +1,48 @@ +/* ---------- capacity deals and sponsored conferences (#168) ---------- */ +// A capacity conference ends with carriers asking for bulk: waves, subsea capacity or whole fiber pairs on a route. +// You sign first and build afterwards, like a real pre-sale: it pays nothing until it is delivered, and missing +// the date costs a penalty and the deal. +Object.assign(BIZ_T,{ + capw:{l:tr('capacity_deals.wholesale_waves'),opts:[8,16,32],rate:0,l2:true,cap:true,km:0.45,lv:CAP_LV,names:['Lambda Llama Carriers','Wavelength Wholesalers','Big Pipe Partners','Rainbow Lambda Ltd','Tera Firma Networks']}, + capsub:{l:tr('capacity_deals.subsea_capacity'),opts:[1600,3200,6400],rate:0,l2:true,cap:true,km:0.35,lv:CAP_LV,names:['Seven Seas Capacity Co.','Petabyte Pirates','Deep Blue Bandwidth','Cable Guy Consortium','Kraken Transit Holdings']}, + capfib:{l:tr('capacity_deals.fiber_pairs'),opts:[2,4,8],rate:0,fiber:true,cap:true,lv:CAP_LV,names:['Glass Half Full Fiber','Hyperscale Hydra','A Hyperscaler Who Shall Not Be Named','Strand Theft Auto','Pair-a-Dice Networks']}, +}); +// The routes each capacity conference talks about. PTC is a Pacific crowd; Capacity Europe is the Atlantic and Europe. +const CAP_ROUTES={ + hnl:[['syd','lax','capsub'],['tok','sea','capsub'],['hnl','lax','capsub'],['sin','hkg','capsub'],['syd','per','capw'],['dal','ash','capw'],['syd','akl','capfib'],['lax','sea','capfib']], + lon:[['bde','nyc','capsub'],['lis','for','capsub'],['mrs','sin','capsub'],['lon','fra','capw'],['chi','ash','capw'],['fra','ams','capw'],['chi','ash','capfib'],['mad','mrs','capfib']], +}; +const SP_OFFERS=1.8,SP_REGION=0.6,CAP_PEN=2; +const confSpOn=()=>!!(S.conf&&S.conf.sp&&S.conf.until>S.day); +// While a sponsored glow lasts, most new customers come from that region. +function spMine(mine){if(!confSpOn()||Math.random()>=SP_REGION)return mine;const r=mine.filter(c=>CITY[c].reg===S.conf.reg);return r.length?r:mine;} +const capPend=b=>!!(BIZ_T[b.type]&&BIZ_T[b.type].cap&&b.due!==undefined&&!b.live); +const capN=b=>b.type==='capw'?Math.round(b.bw/400):b.type==='capfib'?(b.slots||1):0; +function capWhat(o){return o.type==='capw'?trn('capacity_deals.n_400g_waves',capN(o)):o.type==='capfib'?trn('capacity_deals.n_fiber_pairs',capN(o)):tr('capacity_deals.bw_of_subsea_capacity',{bw:fmtG(o.bw)});} +function capTerms(o){const price=fmt$(bizMo(o)),what=capWhat(o); + if(o.due===undefined)return tr('capacity_deals.what_price_mo_deliver_within_n',{what,price,n:o.win}); + return o.live?tr('capacity_deals.what_price_mo',{what,price}):tr('capacity_deals.what_price_mo_due_date',{what,price,date:dateStr(o.due)});} +function capOffer(a,b,t,nm){const T=BIZ_T[t],km=kmBetween(a,b),n=pick(T.opts),o={id:uid(),city:a,city2:b,name:nm(),type:t,reqs:[],exp:S.day+30}; + if(t==='capfib'){o.bw=1;o.slots=n;o.rate=Math.round(dfLeaseMo(km)*n*1.5);o.win=dfBuildDays(km)+150;} + else{o.bw=t==='capw'?n*400:n;o.rate=Math.round((150+km*0.08)*T.km);o.win=t==='capsub'?300+Math.floor(Math.random()*121):180+Math.floor(Math.random()*91);} + return o;} +function capDealTick(d){const q=S.capDeal;if(!q||q.at!==d)return;S.capDeal=null;seatConf(q.c);const pool=(CAP_ROUTES[q.c]||[]).filter(r=>isCity(r[0])&&isCity(r[1])).slice(),out=[]; + while(out.length<3&&pool.length){const [a,b,t]=pool.splice(Math.floor(Math.random()*pool.length),1)[0],T=BIZ_T[t]; + const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;};out.push(capOffer(a,b,t,nm));} + if(!out.length)return;S.offers.push(...out); + toast(trn('capacity_deals.n_carriers_from_the_conference',out.length),'goal',[{l:tr('common.show_me'),act:'leftTab',args:{t:'deals'}}]);sfx('coin');} +// A signed deal waits for its route. Fiber pairs need a fiber of your own between the two cities. +function capFibLink(b){return S.links.find(l=>l.kind==='df'&&l.own&&l.ready<=S.day&&!(l.cut>S.day)&&((l.a===b.city&&l.b===b.city2)||(l.a===b.city2&&l.b===b.city))&&!S.biz.some(x=>x!==b&&(x.type==='pairs'||x.type==='capfib'||x.type==='dfpair')&&x.link===l.id));} +function capPendTick(b,d){if(!capPend(b))return false; + if(b.type==='capfib'){const l=capFibLink(b);if(l)b.link=l.id;} + if(bizSf(b)>=0.95&&reqOk(b)){b.live=true;b.since=d;b.mood=100;S.stats.capDone=(S.stats.capDone||0)+1; + toast(tr('capacity_deals.delivered_name_now_pays_price_mo',{name:esc(b.name),price:fmt$(bizMo(b))}),'goal');sfx('coin');return true;} + if(b.type==='capfib'&&b.link&&!capFibLink(b))b.link=undefined; + if(d>=b.due){const pen=Math.round(bizMo(b)*CAP_PEN);S.cash-=pen;S.biz=S.biz.filter(x=>x!==b); + toast(tr('capacity_deals.name_walked_away_you_missed_the',{name:esc(b.name),pen:fmt$(pen)}),'bad');sfx('err');return true;} + if(b.due-d===30)toast(tr('capacity_deals.name_is_due_in_30_days',{name:esc(b.name),what:capWhat(b),a:CITY[b.city].name,b:CITY[b.city2].name}),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]); + return true;} +// What a pending deal still needs, for the customer list. +function capWhy(b){if(!capPend(b))return [];const left=b.due-S.day; + if(b.type==='capfib')return [tr('capacity_deals.build_your_own_fiber_a_b',{a:CITY[b.city].name,b:CITY[b.city2].name,n:left})]; + return [tr('capacity_deals.carrying_p_of_it_n_days',{p:pct(bizSf(b)),n:left})];} diff --git a/src/game/60-features/36-specialist.js b/src/game/60-features/36-specialist.js new file mode 100644 index 0000000..a9e5880 --- /dev/null +++ b/src/game/60-features/36-specialist.js @@ -0,0 +1,113 @@ +/* ---------- Specialist play (#187, #173) ---------- + You do not have to grow everywhere to grow up. Customers call when your network can already serve them, not only + when your level says so; gear one level ahead comes early as a vendor demo unit at a premium; a seat on a + consortium cable is the way onto your own subsea glass before Tier 1; and a charter picks what you set out to be. */ +const FIN=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash']; +// What a capability brings in, and why the offer says it came. +const SPOT_W={lat:N_('specialist.spotted_your_ms_ms_a_b_path'),df:N_('specialist.spotted_your_cap_of_dark_fiber'),div:N_('specialist.spotted_your_two_diverse_paths_a'),eye:N_('specialist.spotted_your_broadband_in_a_one')}; +const SPOT_BIG=12,SPOT_DF=0.75; +const latMaxOf=(a,b)=>+(kmBetween(a,b)/200*1.35).toFixed(1); +let BIGEYE=null;const bigEye=()=>BIGEYE||(BIGEYE=CITIES.slice().sort((x,y)=>y.P-x.P).slice(0,SPOT_BIG).map(c=>c.id)); +// Worked out at most once a day (and again when the network changes shape): offers spawn far less often than that. +let SPOTC=null; +function spots(){const lv=lvl(),k=S.day+'|'+lv+'|'+S.links.length+'|'+Object.keys(S.pops).length+'|'+charter();if(SPOTC&&SPOTC.s===S&&SPOTC.k===k)return SPOTC.v;const v=spots0(lv);SPOTC={s:S,k,v};return v;} +function spots0(lv){const out=[];if(gatesOpen()||S.scn)return out;const up=t=>BIZ_T[t].lv>lv,mine=Object.keys(S.pops).filter(bizCity); + if(up('hft'))for(const [a,b,ms] of latPairs(FIN.filter(c=>S.pops[c])))if(ms<=latMaxOf(a,b))out.push({t:'hft',a,b,k:'lat',n:+ms.toFixed(1)}); + const dci=['onramp','ai','hyper'].filter(up); + if(dci.length)for(const l of S.links){if(l.kind!=='df'||l.sub||l.ready>S.day||linkDown(l))continue;const g=dfCap(l); + for(const t of dci){const T=BIZ_T[t];if(g>=T.opts[0]*SPOT_DF&&(!T.div||reqCan('diverse',{city:l.a,city2:l.b})))out.push({t,a:l.a,b:l.b,k:'df',n:g});}} + if(up('sov')){const by={};for(const c of mine)(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c); + const g=divGraph();for(const cs of Object.values(by))for(let i=0;i=0.95)out.push({t:'cgame',a:c,b:null,k:'eye',n:0}); + return out;} +// A spotted customer starts at the smallest size its type comes in; your level makes them bigger and more frequent. +function spawnSpot(t,s){const T=BIZ_T[t],list=T.names.filter(n=>!S.usedNames.includes(n)),name=list.length?pick(list):pick(T.names);useName(name); + const o={id:uid(),city:s.a,city2:s.b,name,type:t,bw:T.opts[0],reqs:[],exp:S.day+40,spot:{k:s.k,n:s.n}}; + o.rate=T.l2?Math.round((150+kmBetween(s.a,s.b)*0.08)*T.km*(T.lat?latPay():1)*(T.div?1+REQS.diverse.bonus:1)):T.rate; + if(T.lat){o.reqs=['lat'];o.latMax=latMaxOf(s.a,s.b);}else if(T.div)o.reqs=['diverse']; + S.offers.push(o);} +function spotWhy(o){const s=o&&o.spot;if(!s||!own(SPOT_W,s.k))return ''; + return `
🔭 ${tr(SPOT_W[s.k],{ms:s.n,cap:fmtCap(s.n),a:CITY[o.city].name,b:o.city2?CITY[o.city2].name:''})}
`;} + +/* Vendor demo units: gear one level above yours, early, at a markup and after a short wait. Never two levels ahead. */ +const DEMO_MUL=1.6,DEMO_DAYS=14; +function demoItem(k,id){return k==='rg'?RG[+id]||null:k==='sys'?(own(DF_SYS,id)?DF_SYS[id]:null):k==='opt'?(own(OPT,id)?OPT[id]:null):null;} +const demoAt=(k,id)=>{const d=S&&S.demo&&S.demo[k+':'+id];return d===undefined?null:d;}; +const demoCan=L=>!gatesOpen()&&L===lvl()+1; +function techOk(k,id,L){if(L<=(k==='rg'?(rgGlass(+id)?LEVELS.length:lvl()):k==='sys'||k==='opt'?glassLvl():lvl()))return true;const d=demoAt(k,id);return demoCan(L)&&d!==null&&d<=S.day;} +const techMul=L=>L>glassLvl()?DEMO_MUL:1; +function demoBtn(k,id,L,lock,cls){const d=demoAt(k,id);if(!demoCan(L))return btn(lock,'demoAsk',{k,id},cls,true); + if(d!==null&&d>S.day)return btn(tr('specialist.demo_unit_ships_in_n_days',{n:d-S.day}),'demoAsk',{k,id},cls,true); + return btn(tr('specialist.ask_for_a_demo_unit_p_n',{p:Math.round((DEMO_MUL-1)*100),n:leadDays(DEMO_DAYS)}),'demoAsk',{k,id},cls);} +const sysCost=k=>Math.round(DF_SYS[k].cost*techMul(DF_SYS[k].lvl)); +// Digging your own fiber before level 3: the pioneer pays for the permits nobody has asked for yet. +const PIONEER=1.6; +const digMul=()=>glassLvl()>=3?1:PIONEER,digCost=km=>Math.round(dfBuildCost(km)*digMul()); + +/* A seat on a consortium cable (#173): pay your share of the build, wait for the ship, and own fiber pairs on it, + lit with your own optics like your own cable. Capacity conferences offer them, and now and then a consortium calls. */ +const SEAT_ROUTES={ + lon:[['nyc','bde','Amity Ville'],['lis','for','Ella Fitz-Link'],['mrs','sin','Sea, Me, We, Us, Them'],['lon','lag','Equi-Not']], + hnl:[['syd','lax','Southern Double-Cross'],['tok','sea','Kuro-Show'],['sin','hkg','Dim Sum Express'],['syd','akl','Tasman Devil']], +}; +const SEAT_N=[1,2,4],SEAT_SHARE=10,SEAT_LV=2,SEAT_ODDS=240,SEAT_EXP=30; +const seatKm=(a,b)=>Math.round(kmBetween(a,b)*1.2),seatCost=(km,n)=>Math.round(ownCabCost(km)*n/SEAT_SHARE),seatMo=(km,n)=>Math.round(ownCabMo(km)*n/SEAT_SHARE),seatDays=km=>Math.max(1,Math.round(ownCabDays(km)*0.6)); +const seatRoute=name=>Object.values(SEAT_ROUTES).flat().find(r=>r[2]===name); +// A conference names its own routes; a cold call is about a route with one of your POPs at an end. Picked by a hash, not +// by the dice, so the rest of the game rolls exactly as before. +function seatOffer(c,d){const rs=(c?SEAT_ROUTES[c]||[]:Object.values(SEAT_ROUTES).flat()).filter(r=>isCity(r[0])&&isCity(r[1])&&(c||S.pops[r[0]]||S.pops[r[1]])&&!S.links.some(l=>l.seat&&l.cname===r[2])); + if(!rs.length)return null;const r=rs[hstr(S.asn+'|seat|'+d)%rs.length];return {a:r[0],b:r[1],name:r[2],km:seatKm(r[0],r[1]),exp:d+SEAT_EXP};} +function seatConf(c){if(S.seatOff||lvl()!S.pops[c]).reduce((x,c)=>x+newPopCost(c),0); + return `
🚢 ${tr('specialist.consortium_seat_name',{name:esc(o.name)})}
${tr('specialist.a_b_km_km_ready_in',{a:CITY[o.a].name,b:CITY[o.b].name,km:o.km.toLocaleString(),n:seatDays(o.km),ms:linkLat({kind:'df',own:true,sub:true,km:o.km,seaDesign:'standard'}).toFixed(1)})} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
+
${tr('specialist.your_own_fiber_pairs_on_a')}${pop?' '+tr('specialist.includes_pops_at_the_landings_price',{price:fmt$(pop)}):''}
+
${SEAT_N.map(n=>{const c=seatCost(o.km,n)+pop;return btn(`${trn('specialist.n_fiber_pairs',n)} ${fmt$(c)} · ${tr('common.price_mo',{price:fmt$(seatMo(o.km,n))})}`,'seatBuy',{n},'sm',S.cash
`;} +function seatPanel(l){if(!l.seat)return '';return `
${tr('specialist.consortium_seat')}${esc(l.cname||'')} · ${trn('specialist.n_fiber_pairs',Math.max(1,l.pairs|0))}

${tr('specialist.the_consortium_runs_the_cable_your')}

`;} + +/* Charters: what the network sets out to be, picked once when a Normal game starts, in a popup that waits for an + answer. Global backbone is the game as it always was; the Low-latency boutique sells speed to traders and has its own + win, Speed of Light; the Cable broker (#300) lays and lights glass on land and under the sea from day one, at the + usual prices, sells it, and has its own goals and win, Glass Baron (37-cable-broker.js). */ +const CHARTERS={global:{i:'🌐',n:N_('specialist.global_backbone'),d:N_('specialist.the_classic_game_grow_everywhere_and')},boutique:{i:'⚡',n:N_('specialist.low_latency_boutique'),d:N_('specialist.trading_firms_and_other_latency_customers')},broker:{i:'🚢',n:N_('specialist.cable_broker'),d:N_('specialist.cable_broker_desc')}}; +const CHARTER_DAYS=30,LAT_PAY=1.4,SOL_ROUTES=3,SOL_CUST=2; +const charter=()=>S&&!S.scn&&S.mode==='normal'&&(S.charter==='boutique'||S.charter==='broker')?S.charter:'global'; +const broker=()=>charter()==='broker'; +// The level glass is judged at: fiber, line systems, optics, pairs and subsea gear. A broker has all of it from day one. +const glassLvl=()=>broker()?LEVELS.length:lvl(); +// The router class the fastest optics need: a broker may buy every router up to it, so all its optics can be lit. +const RG_GLASS=Math.max(...Object.values(OPT).map(o=>o.rg)),rgGlass=g=>broker()&&!!RG[g]&&RG[g].cls<=RG_GLASS,rgOpen=g=>!!RG[g]&&(RG[g].lvl<=lvl()||rgGlass(g)); +const latPay=()=>charter()==='boutique'?LAT_PAY:1; +// The fastest a leased wave or fiber gets between two cities: overland, or the quickest cable on the route. +function leasedLat(a,b){let best=isSub(a,b)?Infinity:kmBetween(a,b)*1.25/200;for(const c of cablesFor(a,b))best=Math.min(best,c.km*Math.min(CAB[c.cid].lat||1,1.25)/200);return best;} +const ownGlass=l=>l.kind==='df'&&l.own&&dfOn(l); +let SOLC=null; +function solRoutes(){const k=S.day+'|'+S.links.length+'|'+S.links.reduce((n,l)=>n+(l.ch||[]).length,0);if(SOLC&&SOLC.s===S&&SOLC.k===k)return SOLC.v; + const f=FIN.filter(c=>S.pops[c]),v=[];if(S.links.some(ownGlass))for(const [a,b,o] of latPairs(f,ownGlass)){const l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&oS.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].lat&&b.mood>=50&&reqOk(b)).length; +// What each charter promises, as the picker and the agent's docs say it. +const charterDesc=C=>tr(C.d,{p:Math.round((LAT_PAY-1)*100),r:SOL_ROUTES,c:SOL_CUST,n:BARON_CONT,m:fmt$(BARON_MO)}); +/* The picker: when a Normal game starts (and when a save that never picked loads), before anything else. It pauses the + clock like any open window and cannot be closed without a choice; the tutorial waits for it. Seeded tests skip it unless + they ask (window.__TUBES_CHARTER__), as they skip the tutorial: they sign a charter with ACT.charter when they need one. */ +const charterDue=()=>!!(S&&UI.started&&!S.lost&&!S.scn&&S.mode==='normal'&&!S.chartSet&&!pzOn()); +function charterPickHtml(){return `
${esc(S.name)} · AS${S.asn}

${tr('specialist.what_are_you_building')}

${tr('specialist.your_charter_sets_your_goals')}

` + +Object.entries(CHARTERS).map(([k,C])=>``).join('')+`
`;} +function charterAsk(){if(!charterDue()||!$('modal').hidden||window.__TUBES_TEST__&&!window.__TUBES_CHARTER__)return;openModal(charterPickHtml(),'charter');} +function charterCard(){if(S.scn||S.mode!=='normal')return ''; + if(broker())return baronCard(); + if(charter()!=='boutique')return ''; + if(S.solWon)return `
⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.won_on_date_your_own_glass',{date:dateStr(S.solWon)})}
`; + const r=solRoutes();return `
⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.routes_r_of_n_beat_the',{r:Math.min(r.length,SOL_ROUTES),n:SOL_ROUTES,c:Math.min(solCust(),SOL_CUST),m:SOL_CUST})}
${r.slice(0,SOL_ROUTES).map(x=>`
✓ ${CITY[x.a].name} ⇄ ${CITY[x.b].name}: ${tr('common.ms_ms_one_way',{ms:x.o.toFixed(1)})} < ${x.l.toFixed(1)}
`).join('')}
`;} +// Once a day: seats expire or call, the boutique checks its win and carriers call the broker. +function specDay(d){if(broker())brokerDay(d);if(S.seatOff&&S.seatOff.exp<=d)S.seatOff=null; + if(!S.seatOff&&!S.scn&&S.mode!=='puzzle'&&lvl()>=SEAT_LV&&hstr(S.asn+'|seatcall|'+d)%SEAT_ODDS===0)seatConf(null); + if(charter()==='boutique'&&!S.solWon&&solRoutes().length>=SOL_ROUTES&&solCust()>=SOL_CUST){S.solWon=Math.max(1,d);track('win_sol');toast(`⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.your_own_glass_beats_every_leased')}`,'goal');sfx('coin');checkBadges();}} +// Saves: the charter, demo orders, a seat on offer and the boutique's and the broker's wins. Old saves are Global +// backbone, picked; one still in its first month that never picked is asked again. +function specSanitize(s){s.charter=(s.charter==='boutique'||s.charter==='broker')&&s.mode==='normal'&&!s.scn?s.charter:'global';s.chartSet=s.chartSet===false&&s.day-(s.day0|0)<=CHARTER_DAYS?false:true; + const dm={};if(s.demo&&typeof s.demo==='object'&&!Array.isArray(s.demo))for(const key of Object.keys(s.demo).slice(0,64)){const [k,id]=key.split(':');if(demoItem(k,id)&&Number.isFinite(+s.demo[key]))dm[key]=Math.round(+s.demo[key]);}s.demo=dm; + const o=s.seatOff;s.seatOff=o&&typeof o==='object'&&typeof o.name==='string'&&seatRoute(o.name)&&seatRoute(o.name)[0]===o.a&&seatRoute(o.name)[1]===o.b?{a:o.a,b:o.b,name:o.name,km:seatKm(o.a,o.b),exp:num(o.exp,0)}:null; + s.solWon=Number.isFinite(+s.solWon)&&+s.solWon>0?Math.round(+s.solWon):0;s.baronWon=Number.isFinite(+s.baronWon)&&+s.baronWon>0?Math.round(+s.baronWon):0; + for(const l of s.links)if(l.seat!==undefined){if(l.seat===true&&l.kind==='df'&&l.own&&l.sub)l.pairs=Math.max(1,Math.min(Math.max(...SEAT_N),l.pairs|0));else delete l.seat;} + for(const b of [...s.biz,...s.offers])if(b.spot!==undefined){const x=b.spot;if(x&&typeof x==='object'&&own(SPOT_W,x.k))b.spot={k:x.k,n:num(x.n,0)};else delete b.spot;}} diff --git a/src/game/60-features/37-cable-broker.js b/src/game/60-features/37-cable-broker.js new file mode 100644 index 0000000..0da3aad --- /dev/null +++ b/src/game/60-features/37-cable-broker.js @@ -0,0 +1,34 @@ +/* ---------- The Cable broker (#300) ---------- + A charter for building glass and selling it. Dark fiber, every line system and optic, digging, own subsea cables, + their upgrades and more pairs are open from day one at the usual prices (glassLvl, rgGlass in 36-specialist.js); the + rest of the game unlocks by level as always. Carriers call for capacity, the goals are about glass (BROKER_GOALS), and + the win is Glass Baron: your own cables land on five continents while carriers pay you $1M a month for capacity. */ +const BARON_CONT=5,BARON_MO=1000000,BROKER_CALL=120,BROKER_CALL_FROM=60; +// Your own glass: fiber you dug and cables you laid, once ready. A leased IRU is someone else's; so is a consortium seat. +const ownGlassL=l=>l.kind==='df'&&l.own&&!l.seat&&l.ready<=S.day; +const glassKm=()=>S.links.reduce((a,l)=>a+(ownGlassL(l)?l.km:0),0); +// The continents your own subsea cables land on. +function cableConts(){const r=new Set();for(const l of S.links)if(ownGlassL(l)&&l.sub)for(const c of [l.a,l.b])r.add(CITY[c].reg);return r.size;} +// Capacity other carriers buy from you: alien waves, fiber pairs and capacity deals (once delivered). +const CAP_TYPES=['wwave','mwave','dfpair','pairs','capw','capsub','capfib']; +const capSold=b=>CAP_TYPES.includes(b.type)&&!capPend(b); +const capSalesMo=()=>S.biz.reduce((a,b)=>a+(capSold(b)?bizMo(b):0),0); +// Lit capacity sold, in Gbps: waves (400G each) and subsea capacity. A dark pair is the buyer's to light. +const capSoldG=()=>S.biz.reduce((a,b)=>a+(!capSold(b)?0:b.type==='wwave'?(b.slots||1)*400:b.type==='mwave'?(b.slots||1)*(b.g||100):b.type==='capw'||b.type==='capsub'?b.bw:0),0); +// Two hops of your own glass through one city, each lit to at least g. +function glassChain(g){const by={};for(const l of S.links)if(ownGlassL(l)&&dfCap(l)>=g)for(const [c,o] of [[l.a,l.b],[l.b,l.a]])(by[c]=by[c]||new Set()).add(o); + return Object.values(by).some(s=>s.size>=2);} +const baronOk=()=>cableConts()>=BARON_CONT&&capSalesMo()>=BARON_MO; +// On the goals tab, under the charter: how far Glass Baron is. +function baronCard(){if(S.baronWon)return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.won_on_date',{date:dateStr(S.baronWon)})}
`; + return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.progress',{c:Math.min(cableConts(),BARON_CONT),n:BARON_CONT,mo:fmt$(capSalesMo()),m:fmt$(BARON_MO)})}
`;} +function showBaronWin(){openModal(`

🌊 ${tr('broker.glass_baron')}

${tr('broker.win_text',{name:esc(S.name),asn:S.asn,days:netAge(),n:BARON_CONT,mo:fmt$(capSalesMo())})}

${btn(tr('help.share_my_network'),'share',{},'pink')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost')}
`);} +/* Carriers call the broker now and then (about three times a year, from day 60) with a capacity deal on a route the + capacity conferences trade: the same deals at the same terms, without the trip. Picked by a hash of the day, so a + broker's other dice roll as they would. */ +function brokerDay(d){if(d-S.day0isCity(r[0])&&isCity(r[1])&&!S.offers.some(o=>o.city===r[0]&&o.city2===r[1]&&o.type===r[2]));if(!pool.length)return; + const [a,b,t]=pool[hstr(S.asn+'|caproute|'+d)%pool.length],T=BIZ_T[t]; + const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;}; + const o=capOffer(a,b,t,nm);S.offers.push(o); + toast(tr('broker.a_carrier_calls',{name:esc(o.name),what:capWhat(o),a:CITY[a].name,b:CITY[b].name}),'goal',[{l:tr('common.show_me'),act:'leftTab',args:{t:'deals'}}]);sfx('coin');} diff --git a/src/game/60-features/37-customer-paths.js b/src/game/60-features/37-customer-paths.js new file mode 100644 index 0000000..032457f --- /dev/null +++ b/src/game/60-features/37-customer-paths.js @@ -0,0 +1,75 @@ +/* ---------- moving a customer to another path between the same two POPs ---------- */ +/* Fiber customers (an alien wave, leased pairs) sit on one fiber, b.link, so they move to a parallel one. Circuits have + no link of their own: routing picks their path every day. Moving one pins it to a list of cities, b.pin. While a link + on the pin is down it follows routing, as a protected wave would, and it comes back by itself. */ +const PATH_ALT=3,PATH_FAR=1000; +const pathKind=b=>{const T=BIZ_T[b.type];if(pzOn()||!T||capPend(b)||!b.city2)return '';return T.fiber?(b.link?'fiber':''):T.l2&&!b.sites?'circuit':'';}; +const trenchOf=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); +const pathCity=c=>CITY[c].name,pathStr=p=>p.map(pathCity).join(' → '); +const samePair=(l,a,b)=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a); +const fibLab=l=>tr('customer_paths.fiber_label',{name:l.cname?esc(l.cname):capName(l),km:Math.round(l.km).toLocaleString()}); +// Why this fiber cannot take this customer, in the same terms as the market that sold it: waves only where the broker +// could sell them, after the share kept back for your own traffic. +function fiberNo(b,l){const n=b.slots||1,hold=S.cm.hold; + if(b.type==='wwave'){const free=freeCh(l),spare=cmSpare(l,'spec');return spare>=n?'':free=n*g?'':tr('customer_paths.not_enough_spare_capacity',{free:fmtCap(free),g:fmtCap(n*g),hold});} + if(!l.own)return tr('customer_paths.only_your_own_fiber_rents_pairs'); + if(b.type==='dfpair')return pairFree(l)?'':tr('customer_paths.its_spare_pairs_are_taken'); + return S.biz.some(x=>x!==b&&x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type))?tr('customer_paths.its_spare_pairs_are_taken'):'';} +// The working fibers it could go to, those on another trench first. +function fiberTargets(b){const cur=S.links.find(l=>l.id===b.link),t=cur?trenchOf(cur):''; + return S.links.filter(l=>l.kind==='df'&&l.id!==b.link&&samePair(l,b.city,b.city2)&&l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day)) + .map(l=>({l,diverse:trenchOf(l)!==t,no:fiberNo(b,l)})).sort((x,y)=>(y.diverse-x.diverse)||(!!x.no-!!y.no)||x.l.km-y.l.km);} +// The live backbone by city pair, as compute() sees it: every link of a pair is one edge. +function pathEdges(){const E={},N={};for(const l of S.links){if(linkDown(l)||!popUp(l.a)||!popUp(l.b))continue;const k=edgeKey(l);let e=E[k]; + if(!e){e=E[k]={k,a:l.a,b:l.b,w:Infinity,km:Infinity,lat:Infinity,cap:0,load:0,ts:new Set()};(N[l.a]=N[l.a]||[]).push(e);(N[l.b]=N[l.b]||[]).push(e);} + // An express (65-express.js) runs in the trench of every fiber it rides. + e.w=Math.min(e.w,pairW(k,l.km));e.km=Math.min(e.km,l.km);e.lat=Math.min(e.lat,linkLat(l));e.cap+=capOf(l);e.load+=(R.load&&R.load[l.id])||0;if(l.kind==='xp')for(const t of xpRisk(l))e.ts.add(t);else e.ts.add(trenchOf(l));} + return {E,N};} +const hopKey=(a,b)=>a{const o=[];for(let i=1;i{const c=PIN_G;if(!c||c.R!==R||c.S!==S||c.d!==S.day||c.n!==S.links.length)PIN_G={R,S,d:S.day,n:S.links.length,G:pathEdges()};return PIN_G.G;}; +const pinUp=b=>!!pathHops(pinG(),b.pin); +// Where the circuit runs today. Scenic circuits remember it; the others take the shortest path of their kind. +function pathNow(b,G){if(b.pin&&pathHops(G,b.pin))return b.pin; + const r=R.l2route&&R.l2route[b.id+'>'+b.city+'>'+b.city2];if(r&&r[0]){const p=r[0].ns.slice();if(p[0]!==b.city)p.reverse();if(pathHops(G,p))return p;} + return pathWalk(G,b.city,b.city2,b.route==='fast'?e=>e.lat+0.05:e=>e.w);} +// Paths that avoid what is in use: each one is priced as if every trench already used were nearly unusable, so the next +// one is the most diverse there is, sharing a trench only if there is no way round it. +function circuitTargets(b){const G=pathEdges(),now=pathNow(b,G);if(!now)return {now:null,alts:[]}; + const hops=pathHops(G,now)||[],used=new Set(),seen=new Set([now.join()]),own=new Set(hops.map(e=>e.k)),got=R.l2&&R.l2[b.id]||0,alts=[]; + const nowT=new Set();for(const e of hops)for(const t of e.ts){nowT.add(t);used.add(t);} + for(let i=0;i{for(const t of e.ts)if(used.has(t))return (e.w+1)*PATH_FAR;return e.w+1;});if(!p)break; + const h=pathHops(G,p);for(const e of h)for(const t of e.ts)used.add(t);if(seen.has(p.join()))continue;seen.add(p.join()); + alts.push({p,shared:h.filter(e=>[...e.ts].some(t=>nowT.has(t))).length,km:h.reduce((a,e)=>a+e.km,0),lat:h.reduce((a,e)=>a+e.lat+0.05,0), + room:Math.max(0,Math.min(...h.map(e=>e.cap-e.load+(own.has(e.k)?got:0))))});} + alts.sort((x,y)=>x.shared-y.shared||x.lat-y.lat);return {now,alts};} +// The pin as compute() walks it. Null while a link on it is down, and routing takes over. +function pinRoute(p,edges){const path=[];for(let i=1;iCIDX[x]),share:1};} +// Under a customer in the panels. +function pathCtl(b){if(!pathKind(b))return ''; + const pin=b.pin?`
${tr('customer_paths.pinned_to_path',{path:esc(pathStr(b.pin))})}${pinUp(b)?'':` · ${tr('customer_paths.that_path_is_down')}`}
`:''; + return `${pin}
${btn(tr('customer_paths.move_to_another_path'),'pathOpen',{id:b.id},'ghost sm')}
`;} +function pathModal(b){const a=pathCity(b.city),z=pathCity(b.city2),k=pathKind(b);let h=`

${tr('customer_paths.move_name',{name:esc(b.name)})}

`; + const row=(nm,meta,tag,button)=>`
${nm}${tag?` ${tag}`:''}
${meta?`
${meta}
`:''}
${button}
`; + if(k==='fiber'){const cur=S.links.find(l=>l.id===b.link),T=fiberTargets(b); + h+=`

${tr('customer_paths.this_customer_rides_one_fiber',{a,b:z})}

`; + if(cur)h+=`
${tr('customer_paths.now_on')}${fibLab(cur)}
`; + if(!T.length)h+=`

${tr('customer_paths.no_other_working_fiber',{a,b:z})}

`; + for(const t of T)h+=row(fibLab(t.l),t.no,t.diverse?tr('customer_paths.fully_diverse'):tr('customer_paths.same_trench'),btn(tr('customer_paths.move'),'pathMove',{id:b.id,link:t.l.id},'sm',!!t.no));} + else{const {now,alts}=circuitTargets(b); + h+=`

${tr('customer_paths.routing_chooses_this_circuit',{a,b:z})}

`; + if(now)h+=`
${tr('customer_paths.now_on')}${esc(pathStr(now))}
`; + if(b.pin)h+=`
${btn(tr('customer_paths.let_routing_choose_again'),'pathAuto',{id:b.id},'ghost sm')}
`; + if(!alts.length)h+=`

${tr('customer_paths.no_other_path',{a,b:z})}

`; + for(const t of alts){const warn=[t.room${tr('customer_paths.fits_only_g_of_bw',{g:fmtG(t.room),bw:fmtG(b.bw)})}
`:'',b.latMax&&t.lat>b.latMax?`${tr('customer_paths.over_the_ms_budget',{ms:b.latMax})}`:''].filter(Boolean).join(' · '); + h+=row(esc(pathStr(t.p)),tr('customer_paths.path_facts',{km:Math.round(t.km).toLocaleString(),ms:t.lat.toFixed(1)})+(warn?' · '+warn:''),t.shared?trn('customer_paths.shares_n_spans',t.shared):tr('customer_paths.fully_diverse'),btn(tr('customer_paths.move'),'pathPin',{id:b.id,via:t.p.join()},'sm'));}} + openModal(h);} diff --git a/src/game/60-features/37-fiber-broker.js b/src/game/60-features/37-fiber-broker.js new file mode 100644 index 0000000..ac03cea --- /dev/null +++ b/src/game/60-features/37-fiber-broker.js @@ -0,0 +1,25 @@ +/* ---------- the capacity broker: a listing that sells as the market wants (#203) ---------- + You list some alien waves (and, on your own build, spare pairs) on a dark fiber; the broker keeps the listing and + sells it off over the months, as carriers between those two cities want capacity. A route's market is how many 400G + waves other carriers want there, sized by the eyeballs at both ends (a landing town counts the big city it serves), + and everything you already rent out between those cities fills it: a busy route sells in days, a road to nowhere + maybe once. The broker keeps 10% of the monthly price, as before. l.list = {w: waves left to sell, p: pairs}. */ +const BR_DIV=40,BR_MAX=48,BR_PAIR=8,BR_NEAR=350; +// What a city weighs for the market: its own eyeballs, or half of a big city's within reach of its backhaul. +const BR_W=new Map(); +function brWeight(c){let b=BR_W.get(c);if(b===undefined){const C=CITY[c];b=C.P; + for(const D of CITIES)if(D.id!==c&&!D.off&&D.land===C.land&&kmBetween(c,D.id)<=BR_NEAR)b=Math.max(b,D.P*0.5);BR_W.set(c,b);} + return b*eraMul();} +// 400G waves carriers want between two cities, and how many of them you already rent out there (a pair counts as 8). +const brMarket=(a,b)=>clamp(Math.round(Math.sqrt(brWeight(a)*brWeight(b))/BR_DIV),1,BR_MAX); +function brSold(a,b){const k=edgeKey({a,b});let n=0;const ls=new Set(S.links.filter(l=>l.kind==='df'&&edgeKey(l)===k).map(l=>l.id)); + for(const x of S.biz)if(ls.has(x.link))n+=x.type==='wwave'?(x.slots||0):x.type==='dfpair'?BR_PAIR:0;return n;} +const brFree=l=>Math.max(0,brMarket(l.a,l.b)-brSold(l.a,l.b)); +/* What a carrier pays for one alien wave (#203): a share of what the fiber itself costs a month (lease plus amplifiers), + since a buyer would not pay more than leasing and lighting it. Each wave sold between the two cities makes the next + one cheaper, down to 40% of the first once the route's market is full: a full route earns a few times its lease. */ +const WW_SHARE=0.3,WW_FALL=0.6; +function wwRate(l,n,cut=1){const F=dfLeaseMo(l.km)+ampCount(l.km)*AMP_MO,M=brMarket(l.a,l.b),s=brSold(l.a,l.b);let r=0; + for(let i=0;icmDay(S.day); diff --git a/src/game/60-features/37-fiber-market.js b/src/game/60-features/37-fiber-market.js new file mode 100644 index 0000000..3bad457 --- /dev/null +++ b/src/game/60-features/37-fiber-market.js @@ -0,0 +1,190 @@ +/* ---------- the capacity market: what carriers want on each route, today and tomorrow ---------- + Every route you hold dark fiber on has buyers for spectrum (an alien wave, the buyer brings the optics), managed + 100G, 400G, 800G and 1.6T waves (carved out of capacity you lit yourself), and dark pairs on fiber you dug (an IRU: a + big sum up front, then a little upkeep a month). How much each route wants moves all the time, as it does in real + life: a slow cycle of its own, weeks of noise, and news (a cable cut next door, a hyperscaler breaking ground, a rival + lighting new glass). Underneath, it grows: carriers want more every year, and bigger waves as the years go by (100G + gives way to 400G, then 800G and 1.6T), and carriers already on your glass ask to move up a size. Hot routes pay more + and fill faster; a short, straight route sells waves at a premium, and a long one costs more because its fiber does. The broker keeps 10% (3% for a Cable broker, who also sees where + each route is heading). S.cm: hold (share kept for your own traffic), p (per product: auto on, min demand, price + floor), off (routes left alone), sh (shocks), news, seen (incidents already turned into news). */ +const CM_P=['spec','w100','w400','w800','w1600','iru'],CM_W=['w100','w400','w800','w1600']; +const CM_L={spec:'w',w100:'m1',w400:'m4',w800:'m8',w1600:'m16',iru:'p'},CM_G={w100:100,w400:400,w800:800,w1600:1600}; +const CM_HOLD=[0,10,25,50],CM_FLOOR=[60,80,100,120],CM_MIN={spec:[1,2,4,8],w100:[1,4,8,16],w400:[1,2,4,8],w800:[1,2,4,8],w1600:[1,2,4],iru:[1,2]}; +const CM_DEF={spec:{on:false,min:2,floor:80},w100:{on:false,min:4,floor:80},w400:{on:false,min:2,floor:80},w800:{on:false,min:1,floor:80},w1600:{on:false,min:1,floor:80},iru:{on:false,min:1,floor:100}}; +// A wave's price against a 100G one, on land and on subsea: 2.7x and 3.8x for 400G (real markets in 2025), and the +// price of a bit keeps falling as waves grow. +const CM_X={w100:[1,1],w400:[2.7,3.8],w800:[4.6,6.6],w1600:[7.8,11]}; +// Cities where trading firms sit: a short route between two of them pays the most for a fast wave. +const CM_FIN=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash']; +const CM_HMAX=2.5; +const cmNew=()=>({hold:25,p:JSON.parse(JSON.stringify(CM_DEF)),off:{},sh:[],news:[],seen:[]}); +const cmCut=()=>broker()?0.97:0.9; +/* A fiber's listing, l.list: {w: spectrum slots, p: pairs} as it always was, plus m1/m4/m8/m16 (managed 100G to 1.6T + waves) when any are listed, and hw/hp: how many of w/p you listed by hand, which the broker's thresholds never take + back (#340). cmClean() checks one (a save, or after a day of sales) and returns null when nothing is left. */ +const cmLs=l=>l.list||(l.list={w:0,p:0}); +const CM_HAND={w:'hw',p:'hp'}; +function cmClean(L){if(!L||typeof L!=='object'||Array.isArray(L))return null;const x={w:int(L.w,0,256,0),p:int(L.p,0,2,0)};let any=x.w||x.p; + for(const k in CM_HAND){const v=Math.min(x[k],int(L[CM_HAND[k]],0,256,0));if(v)x[CM_HAND[k]]=v;} + for(const p of CM_W){const v=int(L[CM_L[p]],0,256,0);if(v){x[CM_L[p]]=v;any=1;}}return any?x:null;} +// What you listed by hand of a product on a fiber (only alien waves and pairs can be). +const cmHand=(l,lk)=>(CM_HAND[lk]&&l.list&&l.list[CM_HAND[lk]])||0; +// A stable number in [0,1) for a route and a question, different in every game. +const cmU=(k,q)=>hstr(k+'|'+q+'|'+((S&&S.asn)||0))%100000/100000; +/* How hot a route is (1 = its usual self). Its own slow cycle (two waves of 4 to 10 and 1.5 to 3 months) is what a + forecast can see; the weeks of noise on top and news nobody has heard yet are not. */ +function cmCycle(k,d){const p1=120+180*cmU(k,'p1'),p2=40+50*cmU(k,'p2');return 1+0.25*Math.sin(2*Math.PI*(d/p1+cmU(k,'f1')))+0.15*Math.sin(2*Math.PI*(d/p2+cmU(k,'f2')));} +function cmNoise(k,d){const i=Math.floor(d/15),t=(d-i*15)/15,u=t*t*(3-2*t),v=j=>0.85+0.3*cmU(k,'n'+j);return v(i)*(1-u)+v(i+1)*u;} +// News: a shock ramps up over a week, holds, and fades over the last 40% of its time. +const cmShockF=(x,d)=>d=x.until?0:Math.max(0,Math.min(1,(d-x.from+1)/7,(x.until-d)/Math.max(1,(x.until-x.from)*0.4))); +const cmHits=(x,r)=>x.k?x.k===r.k:x.c?x.c===r.a||x.c===r.b:!!x.sub&&r.sub; +function cmShock(r,p,d){let m=1;for(const x of S.cm.sh)if(cmHits(x,r)&&(!x.p||x.p.includes(p))){const f=cmShockF(x,d);if(f)m*=1+(x.m-1)*f;}return m;} +function cmHeat(r,p,d,fc){return clamp(cmCycle(r.k,d)*(fc?1:cmNoise(r.k,d))*cmShock(r,p,d),0.3,CM_HMAX);} +// What a route is: its cities, its fiber (yours, if any), how far and how fast. Without fiber, as you could dig it +// (straight, at your own fiber's 1.1 path factor). +function cmRoute(a,b,ls=[]){const k=al.km)):kmBetween(a,b),sub=ls.length?ls.some(l=>l.sub):isSub(a,b); + const lat=ls.length?Math.min(...ls.map(linkLat)):kmBetween(a,b)*1.1/200,gc=kmBetween(a,b)/200,st=gc>0?lat/gc:2,fin=CM_FIN.includes(a)&&CM_FIN.includes(b); + // Latency is dominated by the length of the route: a short, straight one sells fast waves at a premium (up to +50%, + // +80% between two trading cities). + const lp=1+0.5*clamp((1.5-st)/0.4,0,1)*(fin?1.6:1); + return {k,a,b,ls,km,sub,lat,st,lp,fin,dc:MEGA.some(m=>m.c===a||m.c===b)};} +// The routes you hold ready dark fiber on. +function cmRoutes(){const by=new Map();for(const l of S.links)if(l.kind==='df'&&l.ready<=S.day){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} + const rs=new Map();for(const [k,ls] of by){const [a,b]=k.split('|');rs.set(k,cmRoute(a,b,ls));}return rs;} +/* Growth: carriers want about 15% more every year (non-AI traffic grows about that fast, AI traffic faster), up to 8 + times what they wanted at the start. */ +const cmGrowth=d=>Math.min(8,Math.pow(1.15,Math.max(0,d)/365)); +/* Which wave sizes buyers want: each size catches on along an S-curve over game years plus the network era, and takes + over from the one before (100G, then 400G, 800G from about year 5, 1.6T from about year 9; a later network era + brings each a little sooner). */ +const CM_ADOPT={w400:1.5,w800:5,w1600:9}; +const cmA=(p,d)=>1/(1+Math.exp(-(Math.max(0,d)/365+0.15*lvl()-CM_ADOPT[p])/1.3)); +function cmShare(p,d){const a4=cmA('w400',d),a8=cmA('w800',d),a16=cmA('w1600',d);return p==='w100'?1-a4:p==='w400'?a4-a8:p==='w800'?a8-a16:a16;} +/* What a route wants of a product, in units: spectrum slots, waves of that size, dark pairs. The size comes from the + eyeballs at both ends (brMarket(), as before) and growth; managed waves split by the sizes buyers want now, fast + waves from latency, the big ones and dark pairs from data centers at either end; dark pairs are mostly bought for + shorter hauls. */ +function cmDem(r,p,d,fc){const M=brMarket(r.a,r.b),H=cmHeat(r,p,d,fc),g=cmGrowth(d); + if(p==='spec')return M*0.5*Math.pow(g,0.7)*H; + if(p==='iru')return Math.min(2,M/12*(r.dc?2:1)*clamp(900/r.km,0.35,1.5))*Math.sqrt(g)*H; + const dc=r.dc&&p!=='w100'?(p==='w400'?1.3:1.6):1;return M*160*Math.sqrt(r.lp)*g*cmShare(p,d)*dc*H/CM_G[p];} +// What carriers already rent on a route, by product, in the same units. +const cmWP=g=>CM_W.find(p=>CM_G[p]===g)||'w100'; +function cmSold(rs){const m=new Map(),ids=new Map();for(const r of rs.values()){m.set(r.k,Object.fromEntries(CM_P.map(p=>[p,0])));for(const l of r.ls)ids.set(l.id,r.k);} + for(const b of S.biz){const k=b.link&&ids.get(b.link);if(!k)continue;const s=m.get(k); + if(b.type==='wwave')s.spec+=b.slots||0;else if(b.type==='mwave')s[cmWP(b.g)]+=b.slots||0;else if(b.type==='dfpair')s.iru++;} + return m;} +/* List prices, before the market index (mkt()) and the broker's cut: spectrum is 30% of what the fiber costs a month + (as before, #203); a managed 100G wave 30% of that times the latency premium, bigger ones by CM_X; a dark pair two + years of its lease up front, then 15% of it a month. */ +const cmF=r=>dfLeaseMo(r.km)+ampCount(r.km)*AMP_MO; +function cmList(r,p){return p==='spec'?cmF(r)*WW_SHARE:p==='iru'?dfLeaseMo(r.km)*0.15:cmF(r)*WW_SHARE*0.3*r.lp*CM_X[p][r.sub?1:0];} +const cmUpList=r=>dfLeaseMo(r.km)*0.9*24; +/* The price of the i-th unit from now, as a share of list: heat pushes it up or down (hot routes pay off), and each + unit sold on the route makes the next one cheaper, down to 40% once its market is full. */ +function cmIdx(r,p,s,i,d,fc){const D=cmDem(r,p,d,fc),H=cmHeat(r,p,d,fc);return clamp(Math.pow(H,0.6),0.7,1.35)*(1-WW_FALL*Math.min(1,D>0?(s+i)/D:1));} +// Managed waves sold on a fiber, in Gbps: they come off what your own traffic gets (dfCap0()). +let CM_MW=null,CM_V=0; +function mwG(l){if(!S||!S.biz)return 0;if(!CM_MW||CM_MW.b!==S.biz||CM_MW.n!==S.biz.length||CM_MW.v!==CM_V){const m=new Map(); + for(const b of S.biz)if(b.type==='mwave'&&b.link)m.set(b.link,(m.get(b.link)||0)+(b.slots||0)*(b.g||100));CM_MW={b:S.biz,n:S.biz.length,v:CM_V,m};} + return CM_MW.m.get(l.id)||0;} +// How much of a product a fiber has spare, after the share kept back for your own traffic (spectrum slots, or lit +// capacity your traffic is not using). A wave rides one channel, so an 800G or 1.6T one needs an optic that big. A pair +// is never kept back: it is glass you are not lighting. +const cmFreeG=(l,hold=S.cm.hold)=>dfCap0(l)-(R.load[l.id]||0)*1.05-hold/100*dfLit(l); +const cmOptG=l=>Math.max(0,...(l.ch||[]).map(c=>optG(c,l))); +function cmSpare(l,p,hold=S.cm.hold){ + if(p==='spec')return Math.max(0,freeCh(l)-Math.ceil(hold/100*chMax(l))); + if(p==='iru')return l.own&&pairFree(l)&&!(l.cut>S.day)?1:0; + return cmOptG(l)p==='spec'?wwWhat(l,n):p==='iru'?tr('requirements.a_spare_fiber_pair_in_your',{a:CITY[l.a].name,b:CITY[l.b].name}):trn('market.n_g_wave_on',n,{g:fmtCap(CM_G[p]),a:CITY[l.a].name,b:CITY[l.b].name}); +// A sale: a new carrier on this fiber, or more of the same product for one that already rents here. +function cmSell(l,p,n,rate,up){const t=p==='spec'?'wwave':p==='iru'?'dfpair':'mwave',T=BIZ_T[t],nm=()=>{const list=T.names.filter(x=>!S.usedNames.includes(x)),x=list.length?pick(list):pick(T.names);useName(x);return x;}; + const g=CM_G[p],name=nm(),more=t!=='dfpair'&&S.biz.find(b=>b.type===t&&b.link===l.id&&b.name===name&&(t!=='mwave'||b.g===g)); + if(more){more.slots=(more.slots||0)+n;more.rate+=rate;more.what=cmWhat(l,p,more.slots);} + else{const o={id:uid(),city:l.a,city2:l.b,link:l.id,slots:t==='dfpair'?0:n,what:cmWhat(l,p,n),name,type:t,bw:1,rate,reqs:[],exp:S.day+30};const b=clSign(offerCustomer(o));if(g)b.g=g;S.biz.push(b);} + CM_V++;if(up)S.cash+=up;S.stats.cmSold=(S.stats.cmSold||0)+1; + toast(up?tr('market.sold_pair',{name:esc(name),what:esc(cmWhat(l,p,n)),up:fmt$(up),price:fmt$(rate)}):tr('broker.sold',{name:esc(name),what:esc(cmWhat(l,p,n)),price:fmt$(rate)}),'good'); + floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('common.signed'),'#16A866');} +// What one fiber can still sell of a product right now, whatever is listed: free spectrum, lit capacity your traffic +// is not using, a free pair. +function cmCan(l,p){if(!fiberOk({link:l.id,type:p==='iru'?'dfpair':'wwave'}))return 0;return p==='spec'?Math.max(0,freeCh(l)):p==='iru'?cmSpare(l,'iru'):cmSpare(l,p,0);} +/* News: incidents that cut glass become news the next morning, and every so often something happens on its own. + Each one is a shock on a route, around a city, or on every subsea route, for some products, for a while. */ +const CM_NEWS={ + cut:{m:1.6,days:45,p:null,t:N_('market.news_cut')},redsea:{m:1.8,days:90,p:null,t:N_('market.news_redsea')}, + dc:{m:2,days:150,p:['w400','w800','w1600','iru'],t:N_('market.news_dc_big')},ai:{m:2.5,days:70,p:['w400','w800','w1600'],t:N_('market.news_ai_big')}, + glut:{m:0.6,days:120,p:null,t:N_('market.news_glut')},exch:{m:1.7,days:60,p:CM_W,t:N_('market.news_exch')}, + merge:{m:0.75,days:90,p:null,t:N_('market.news_merge')},boom:{m:1.4,days:60,p:['spec','w100'],t:N_('market.news_boom')}}; +function cmNews(why,x,d){const N=CM_NEWS[why],s={why,from:d,until:d+N.days,m:N.m,...x};if(N.p)s.p=N.p.slice();S.cm.sh.push(s); + S.cm.news.unshift({d,why,a:x.a||x.c||null,b:x.b||null});S.cm.news.length=Math.min(S.cm.news.length,8); + const rs=cmRoutes();if([...rs.values()].some(r=>cmHits(s,r)))toast(cmNewsText(S.cm.news[0]),N.m>1?'info':'warn',[{l:tr('market.open'),act:'marketOpen',args:{}}]);} +const cmNewsText=n=>tr(CM_NEWS[n.why].t,{a:n.a?CITY[n.a].name:'',b:n.b?CITY[n.b].name:''}); +function cmShocks(d){const C=S.cm;C.sh=C.sh.filter(x=>x.until>d); + for(const i of S.inc)if(LINKCUT_TR.includes(i.type)&&!C.seen.includes(i.id)){C.seen.push(i.id);if(C.seen.length>40)C.seen.shift(); + if(i.type==='redsea'){cmNews('redsea',{sub:1},d);continue;} + const l=S.links.find(x=>x.id===i.ref||x.trench===i.ref);if(l)cmNews('cut',{c:hstr(String(i.id))%2?l.a:l.b,a:l.a,b:l.b},d);} + // Without dark fiber there is no market to move, and no random number is drawn (the rest of the day stays as it was). + const rs=[...cmRoutes().values()],cs=[...new Set(rs.flatMap(r=>[r.a,r.b]))];if(!rs.length||Math.random()>=1/10)return; + const why=pick(['dc','ai','glut','exch','merge','boom','boom','dc']),r=pick(rs),c=pick(cs); + if(why==='dc'||why==='boom')cmNews(why,{c},d); + else if(why==='exch'){const f=cs.filter(x=>CM_FIN.includes(x));if(f.length){const x=pick(f);cmNews(why,{c:x},d);}} + else cmNews(why,{k:r.k,a:r.a,b:r.b},d);} +/* Once a day: news, then on every route the broker lists what your thresholds allow (spare after the share kept back, + while demand is at least your minimum and the price at least your floor) or takes it off, then each listing may + find a buyer: the more room the route has left and the hotter it is, the sooner; the fastest fiber sells first. */ +function cmList1(r,p,s,d){const c=S.cm.p[p],lk=CM_L[p];if(!c.on||S.cm.off[r.k])return;const ok=cmDem(r,p,d)>=c.min&&cmIdx(r,p,s,0,d)*100>=c.floor; + // What you listed by hand stays listed on top of what the thresholds allow, up to what the fiber has free. + for(const l of r.ls){const h=cmHand(l,lk),n=Math.min(ok?cmSpare(l,p)+h:h,h?(p==='spec'?freeCh(l):1):Infinity);if(n>0)cmLs(l)[lk]=n;else if(l.list)l.list[lk]=0;}} +// The listings as the thresholds want them right now (after you change a setting), without selling anything. +function cmRelist(){const rs=cmRoutes(),sold=cmSold(rs);for(const r of rs.values())for(const p of CM_P)cmList1(r,p,sold.get(r.k)[p],S.day);cmTidy();} +const cmTidy=()=>{for(const l of S.links)if(l.list){const L=cmClean(l.list);if(L)l.list=L;else delete l.list;}}; +function cmDay(d=S.day){const C=S.cm;cmShocks(d);const rs=cmRoutes(),sold=cmSold(rs); + for(const r of rs.values()){const s=sold.get(r.k); + for(const p of CM_P){const lk=CM_L[p];cmList1(r,p,s[p],d); + // Room rounds to the nearest unit: a road to nowhere that wants about one wave sells one. + const D=cmDem(r,p,d),room=Math.round(D-s[p]);if(room<1)continue; + const ls=r.ls.filter(l=>l.list&&l.list[lk]>0&&cmCan(l,p)>0).sort((x,y)=>linkLat(x)-linkLat(y));if(!ls.length)continue; + if(Math.random()>=Math.min(0.35,0.06+0.25*room/Math.max(1,D))*(p==='iru'?0.08:1)*(p==='spec'?1:Math.sqrt(r.lp)))continue; + const l=ls[0];let n=p==='iru'?1:Math.max(1,Math.min(l.list[lk],cmCan(l,p),room,1+Math.floor(Math.random()*(p==='spec'||p==='w100'?4:2)))); + // Never below your floor: fewer units, or none. + while(n>0&&cmIdx(r,p,s[p],n-1,d)*100l.list[lk])l.list[CM_HAND[lk]]=l.list[lk];}} + cmGrow(d);cmTidy();} +/* What the next 30 and 90 days look like on a route, for a Cable broker: the route's own cycle and the news already + out, but not the noise or news still to come. */ +const cmFc=(r,p,t)=>cmDem(r,p,S.day+t,true); +/* Growth inside contracts: once the next size is common (15% of what buyers want), a carrier on a managed wave asks + now and then to move all its waves up one size. With room on the fiber (after what you keep back) it moves at once + and pays more (a bigger wave, at a lower price per bit); without, it tells you, at most twice a year. */ +function cmGrow(d){for(const b of S.biz){if(b.type!=='mwave')continue;const i=CM_W.indexOf(cmWP(b.g)),q=CM_W[i+1];if(!q||cmShare(q,d)<0.15||Math.random()>=1/300)continue; + const l=S.links.find(x=>x.id===b.link);if(!l||!fiberOk(b))continue;const g1=CM_G[q],extra=(g1-b.g)*(b.slots||1),sub=l.sub?1:0,arg={name:esc(b.name),n:b.slots||1,g0:fmtCap(b.g),g1:fmtCap(g1),a:CITY[l.a].name,b:CITY[l.b].name}; + if(cmOptG(l)>=g1&&cmFreeG(l)>=extra){const p0=cmWP(b.g);b.rate=Math.round(b.rate*CM_X[q][sub]/CM_X[p0][sub]*0.85);b.g=g1;b.what=cmWhat(l,q,b.slots||1);CM_V++; + toast(tr('market.upgraded',{...arg,price:fmt$(b.rate)}),'good');} + else if(!(b.gw>d-180)){b.gw=d;toast(tr('market.wants_more',arg),'warn',[{l:tr('lease_swaps.open_your_fiber'),act:'dashLink',args:{id:l.id}}]);}}} +// How many more spectrum slots a fiber's route wants today (the fiber panel's market line). +function cmRoomSpec(l){const rs=cmRoutes(),r=rs.get(edgeKey(l));if(!r)return 0;return Math.max(0,Math.round(cmDem(r,'spec',S.day)-cmSold(rs).get(r.k).spec));} +// Routes a Cable broker could build between two of its POPs, the most wanted first. +function cmScout(n=6){const ps=Object.keys(S.pops),have=new Set(S.links.filter(l=>l.kind==='df').map(edgeKey)),out=[]; + for(let i=0;i1500||!dfAllowed(a,b))continue;const r=cmRoute(a,b); + out.push({r,v:CM_P.reduce((s,p)=>s+cmDem(r,p,S.day)*cmList(r,p),0)});} + return out.sort((x,y)=>y.v-x.v).slice(0,n).map(x=>x.r);} +// Saves: everything checked, old saves get the defaults. +function cmFix(s){const c=s.cm&&typeof s.cm==='object'&&!Array.isArray(s.cm)?s.cm:{},n=cmNew(); + n.hold=CM_HOLD.includes(+c.hold)?+c.hold:25; + for(const p of CM_P){const x=c.p&&c.p[p]||{};n.p[p]={on:!!x.on,min:CM_MIN[p].includes(+x.min)?+x.min:CM_DEF[p].min,floor:CM_FLOOR.includes(+x.floor)?+x.floor:CM_DEF[p].floor};} + if(c.off&&typeof c.off==='object')for(const k in c.off){const [a,b]=k.split('|');if(c.off[k]&&isCity(a)&&isCity(b)&&ax&&own(CM_NEWS,x.why)&&(x.k?typeof x.k==='string'&&x.k.split('|').every(isCity):x.c?isCity(x.c):!!x.sub)).slice(-24).map(x=>{ + const y={why:x.why,from:int(x.from,-1e6,1e7,0),until:int(x.until,-1e6,1e7,0),m:clamp(num(x.m,1),0.3,3)};if(x.k)y.k=x.k;else if(x.c)y.c=x.c;else y.sub=1; + if(isCity(x.a))y.a=x.a;if(isCity(x.b))y.b=x.b;if(Array.isArray(x.p)){const p=x.p.filter(q=>CM_P.includes(q));if(p.length)y.p=p;}return y;}); + if(Array.isArray(c.news))n.news=c.news.filter(x=>x&&own(CM_NEWS,x.why)).slice(0,8).map(x=>({d:int(x.d,-1e6,1e7,0),why:x.why,a:isCity(x.a)?x.a:null,b:isCity(x.b)?x.b:null})); + if(Array.isArray(c.seen))n.seen=c.seen.filter(x=>typeof x==='string').slice(-40); + s.cm=n; + for(const l of s.links){if(l.kind!=='df'||!l.list)continue;const L=cmClean(l.list);if(L)l.list=L;else delete l.list;} + for(const b of s.biz)if(b.type==='mwave'){b.g=CM_W.some(p=>CM_G[p]===b.g)?b.g:100;b.slots=Math.max(1,Math.round(b.slots||1));if(b.gw!==undefined)b.gw=int(b.gw,-1e6,1e7,0);}} diff --git a/src/game/60-features/38-latency-contracts.js b/src/game/60-features/38-latency-contracts.js new file mode 100644 index 0000000..d430c54 --- /dev/null +++ b/src/game/60-features/38-latency-contracts.js @@ -0,0 +1,25 @@ +/* ---------- Strict latency contracts (#137) ---------- + Late in the game, carriers and market-data networks buy 1.6 or 3.2T on one route with a latency SLA, the way real + low-latency wholesale is sold: a premium per Gbps for guaranteed milliseconds, and a service credit for every day the + circuit runs over them. They are an ordinary customer type (BIZ_T.lowlat) with the latency requirement every trading + link has (REQS.lat on R.l2lat, the one-way path latency compute() measures), offered from customer level LC_LV, and + never bigger than BIZ_T.lowlat.max: one contract cannot carry a level on its own. */ +const LC_LV=BIZ_T.lowlat.lv,LC_MOOD=3,LC_GRACE=15; +// Once a day for each customer, from the mood check: a latency customer over its SLA after the provisioning grace is +// credited that day's fee and loses patience faster than for a bandwidth problem alone. Returns that extra mood lost. +function lcBreach(b,d){const T=BIZ_T[b.type];if(!T||!T.sla)return 0; + if(d-(b.since||0)0)||REQS.lat.ok(b)){delete b.lcB;return 0;} + const cr=Math.round(bizMo(b)/monLen(d));S.cash-=cr;b.lcCr=(b.lcCr||0)+cr; + if(!b.lcB){b.lcB=1;const v=R.l2lat[b.id]; + toast(tr('latency_contracts.over_sla',{name:esc(b.name),a:CITY[b.city].name,b:CITY[b.city2].name,ms:isFinite(v)?v.toFixed(1):'∞',max:b.latMax,price:fmt$(cr)}),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);} + return LC_MOOD;} +// The contract, on its offer and customer rows (bRisk()). +function lcNote(b){const T=BIZ_T[b.type];if(!T||!T.sla)return ''; + return `
⏱️ ${tr('latency_contracts.sla_terms',{ms:b.latMax,max:fmtG(T.max)})}${b.lcCr>0?' · '+tr('latency_contracts.credits_paid',{price:fmt$(b.lcCr)}):''}
`;} +// Saves: credits paid and the breach flag are numbers and a flag; a contract is never bigger than its type allows. +function lcSanitize(s){for(const b of [...s.biz,...s.offers]){const T=BIZ_T[b.type]; + if(b.lcCr!==undefined){const v=Math.round(+b.lcCr);if(Number.isFinite(v)&&v>0)b.lcCr=v;else delete b.lcCr;} + if(b.lcB!==undefined){if(b.lcB)b.lcB=1;else delete b.lcB;} + if(T&&T.max)b.bw=Math.min(T.max,Math.max(T.opts[0],b.bw)); + if(T&&T.sla&&Array.isArray(b.reqs)&&!b.reqs.includes('lat'))b.reqs.unshift('lat'); + if(T&&T.sla&&!(b.latMax>0)&&isCity(b.city)&&b.city2&&isCity(b.city2))b.latMax=latMaxOf(b.city,b.city2);}} diff --git a/src/game/60-features/38-sales-desk.js b/src/game/60-features/38-sales-desk.js new file mode 100644 index 0000000..bdff745 --- /dev/null +++ b/src/game/60-features/38-sales-desk.js @@ -0,0 +1,79 @@ +/* ---------- The sales desk: one salesperson, three kinds you meet in this industry ---------- + Next to the NOC intern, you can put one person in charge of sales. Each brings deals in their own way and leaves + their mark on the customers they sign (b.by), which the contracts (75-customer-lifecycle.js) remember at renewal. + - The engineer turned salesdroid goes to every network operators' meeting (you pay the ticket), brings plenty of + small and mid deals and never the huge ones, and only sells what the network can do: their customers stay longer, + the nerdy ones most of all. They haggle badly. + - The shark brings the biggest deals at a higher price and takes a commission, but oversells: many come with a + promise your network does not keep yet. Ignores the nerds: no technical customers, no meetings, and peering desks + want more traffic from you. Wins most haggles. + - The CEO runs sales himself, for free: now and then a huge deal signed on the golf course at a discount, with a + promise nobody checked, the odd declined offer signed anyway, and opinions. He cannot be fired; the board can + be asked for a VP of Sales instead. + Every roll is a hash of the day and the deal, so a game without a salesperson keeps its random stream. */ +const SALES={ + eng:{i:'🤓',n:N_('sales.eng_n'),s:N_('sales.eng_s'),d:N_('sales.eng_d'),mo:9000}, + shark:{i:'🦈',n:N_('sales.shark_n'),s:N_('sales.shark_s'),d:N_('sales.shark_d'),mo:15000}, + ceo:{i:'👔',n:N_('sales.ceo_n'),s:N_('sales.ceo_s'),d:N_('sales.ceo_d'),mo:0}, +}; +const SALES_LV=2,SALES_VP=50000,SALES_VP_DAYS=30; +// The ones the engineer never lands, and the nerds the shark never calls back. +const salesBig=t=>{const T=BIZ_T[t];return !!T&&(!!T.mega||(T.lv||1)>=4);}; +const SALES_NERDS=['hft','edu','isp','l2vpn','bulk','provedor','fabl2','wwave','mwave','dfpair']; +const SALES_SAY=[N_('sales.ceo_say_synergy'),N_('sales.ceo_say_golf'),N_('sales.ceo_say_blockchain'),N_('sales.ceo_say_napkin'),N_('sales.ceo_say_mbps'),N_('sales.ceo_say_airport')]; +const slP=()=>S&&S.sales&&own(SALES,S.sales.p)?S.sales.p:null; +const slName=(long)=>{const p=slP();return p?tr(long?SALES[p].n:SALES[p].s):'';}; +// The short name at the start of a sentence: Dave, Chad, The CEO. +const slCap=()=>{const t=slName();return t?t[0].toUpperCase()+t.slice(1):'';}; +const slR=q=>(hstr(((S&&S.asn)||0)+'|sales|'+q)%100000)/100000; +// What a deal is, not its id: ids come from the clock, so a roll on them would differ every time the same game is played. +const slKey=o=>[o.type,o.city,o.city2||'',o.name,o.bw,o.exp].join('|'); +const salesMo=()=>{const p=slP();return p?SALES[p].mo:0;}; +const salesCanHire=()=>lvl()>=SALES_LV; +// How often offers come in: the engineer brings more, half as many again while a meeting's glow lasts. +function salesSpawn(){const p=slP();if(p==='eng')return 1.4*(S.conf&&S.conf.until>S.day?1.5:1);if(p==='shark')return 1.2;return 1;} +// What the salesperson does to the offers that just came in (from index n0): who brought them, which they drop, +// and how the shark dresses them up. +function salesShape(n0){const p=slP();if(!p)return;for(let i=S.offers.length-1;i>=n0;i--){const o=S.offers[i],T=BIZ_T[o.type];if(!T||o.ref)continue; + if(p==='eng'&&salesBig(o.type)){S.offers.splice(i,1);continue;} + if(p==='shark'&&SALES_NERDS.includes(o.type)){S.offers.splice(i,1);continue;} + o.by=p; + if(p==='shark'&&!T.event&&!T.cap){const up=(T.opts||[]).find(x=>x>o.bw);if(up&&!T.fiber)o.bw=up;o.rate=Math.round(o.rate*1.25); + if(slR('over|'+slKey(o))<0.5){const k=salesPromise(o);if(k)o.reqs=(o.reqs||[]).concat(k);}}}} +// A promise nobody checked: a requirement this deal can have, that the network does not meet today. +function salesPromise(o){const T=BIZ_T[o.type],pool=Object.keys(REQS).filter(k=>!(o.reqs||[]).includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,o)).sort(); + const no=pool.filter(k=>{try{return !REQS[k].ok(o);}catch(e){return false;}});return no.length?no[Math.floor(slR('promise|'+slKey(o))*no.length)]:null;} +// Their mark at renewal: how much likelier the customers they signed are to leave. The engineer's orbit customers, sold +// only where a dish had room to spare, stay like the nerds do. +function salesLeaveMul(b){if(b.by==='eng')return SALES_NERDS.includes(b.type)||BIZ_T[b.type].orbit?0.5:0.75;if(b.by==='shark')return 1.5;if(b.by==='ceo')return 1.25;return 1;} +// Haggles with whoever is at the desk now: how deep the discount they ask, and how often meeting halfway works. +const salesAsk=()=>slP()==='eng'?0.72:0.8; +const salesMeet=()=>({shark:0.9,eng:0.5,ceo:0.55})[slP()]||0.65; +// Peering desks notice who you send to meetings: with the shark, selective networks want a quarter more traffic. +const salesPeerMul=()=>slP()==='shark'?1.25:1; + +/* A day at the sales desk: the engineer books the next meeting (30 days ahead, the same day the invitation comes), + the CEO plays golf and has opinions, and a VP of Sales takes over from him when the board says so. */ +function salesDay(d){const L=S.sales;if(!L)return; + if(L.vp&&d>=L.vp){L.p=null;L.vp=null;toast(tr('sales.vp_arrived'),'good',[{l:tr('sales.desk'),act:'salesOpen',args:{}}]);return;} + const p=slP();if(!p)return; + if(p==='eng')for(const cf of upcomingConfs(30)){if(cf.cap||cf.day-d!==30||(S.confReg||{})[cf.key])continue; + if(S.cash>=CONF_COST){S.cash-=CONF_COST;(S.confReg=S.confReg||{})[cf.key]=true;if(!confQuiet())toast(tr('sales.eng_booked',{name:esc(slCap()),conf:esc(cf.n),city:esc(CITY[cf.c].name),cost:fmt$(CONF_COST)}),'');}} + if(p==='ceo'){if(!(L.golf>=d))L.golf=d+50+Math.floor(slR('golf|'+d)*30);else if(d===L.golf){salesGolf(d);L.golf=d+50+Math.floor(slR('golf|'+d)*30);} + if(!(L.say>=d))L.say=d+20+Math.floor(slR('say|'+d)*15);else if(d===L.say){toast(tr('sales.ceo_says',{say:tr(SALES_SAY[Math.floor(slR('sayl|'+d)*SALES_SAY.length)])}),'');L.say=d+20+Math.floor(slR('say|'+d)*15);}}} +// The golf course: the biggest internet customer this network can take, in its biggest city, at 30% off, signed on the spot. +// With a rocket company, every other game is with the Founder, and in orbit (pieGolf, 99-pie-sales.js). +const SALES_GOLF=['metav','cgame','gpu','stream','isp','edu','host','dia']; +function salesGolf(d){if(pieGolf(d))return;const mine=Object.keys(S.pops).filter(c=>popUp(c)&&bizCity(c));if(!mine.length)return; + const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name); + const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40}; + const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';if(clOn(b))b.mk=mkt();S.biz.push(clSign(b)); + toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');} +// Declining an offer the CEO likes: about one in three, he already shook hands on it. +function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||!ip4Fits(o)||slR('veto|'+slKey(o))>=0.33)return false; + const b=offerCustomer(o);if(o.mk&&clOn(b))b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;} +// Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer. +function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null; + s.sales={p:own(SALES,L.p)?L.p:null,hired:n(L.hired)||0,vp:L.p==='ceo'?n(L.vp):null,golf:n(L.golf),say:n(L.say)}; + for(const x of [...s.biz,...s.offers])if(x.by!==undefined&&!own(SALES,x.by))delete x.by;slAutoFix(s);} diff --git a/src/game/60-features/39-req-fix.js b/src/game/60-features/39-req-fix.js new file mode 100644 index 0000000..a9276b0 --- /dev/null +++ b/src/game/60-features/39-req-fix.js @@ -0,0 +1,21 @@ +/* ---------- Buy what a customer asks for, on signing (#241) ---------- + Some requirements are hardware at a POP you already have: a backup generator, a second router, a second building. + An offer that asks for them gets a second button that buys exactly what is missing and signs, with the price on it. + Never silent: the player presses it, and nothing is bought unless the deal can be signed right after. */ +const REQ_FIX=['gen','routers','metro']; +// What is missing for this offer, priced as the Infra tab's own buttons price it: [{k, city, cost, mo}], with totals. +function reqFix(o){if(!o||!bHas(o)||pzOn())return null;const items=[],cs=[o.city,o.city2].filter(Boolean); + for(const k of o.reqs||[]){if(!REQ_FIX.includes(k)||!REQS[k]||REQS[k].ok(o))continue; + for(const c of k==='routers'?[o.city]:cs){const p=S.pops[c];if(!p||items.some(x=>x.k===k&&x.city===c))continue; + if(k==='gen'&&!p.gen)items.push({k,city:c,cost:GEN_COST,mo:GEN_MO}); + else if(k==='metro'&&!p.site2)items.push({k,city:c,cost:SITE2_COST,mo:SITE2_MO}); + else if(k==='routers'&&(p.routers||1)<2){const g=p.rgen||0;items.push({k,city:c,cost:routerCost(g,p.routers||1),mo:routerMo(g)});}}} + if(!items.length)return null;return {items,cost:items.reduce((a,x)=>a+x.cost,0),mo:items.reduce((a,x)=>a+x.mo,0)};} +// Whether accept() would sign this offer now: the same checks, so money is never spent on a deal that then refuses. +// IPv4 too (#150): an offer whose address block does not fit is refused at signing, so nothing is bought for it. +const reqFixCanSign=o=>bHas(o)&&ip4Fits(o)&&!(BIZ_T[o.type].event&&S.day>=o.start); +const REQ_FIX_L={gen:N_('req_fix.generator_in_city'),routers:N_('req_fix.second_router_in_city'),metro:N_('req_fix.second_site_in_city')}; +// The button and one line saying what it buys. sm: the button size the list around it uses. +function reqFixHtml(o){const q=reqFix(o);if(!q||!reqFixCanSign(o))return ''; + return `
${tr('req_fix.buys_list',{list:q.items.map(x=>tr(REQ_FIX_L[x.k],{city:CITY[x.city].name})).join(', '),cost:fmt$(q.cost),mo:fmt$(q.mo)})}
+
${btn(tr('req_fix.buy_and_sign',{cost:fmt$(q.cost)}),'acceptFix',{id:o.id,cost:q.cost},'pink sm',S.cash`;} diff --git a/src/game/60-features/39-sales-auto.js b/src/game/60-features/39-sales-auto.js new file mode 100644 index 0000000..029d288 --- /dev/null +++ b/src/game/60-features/39-sales-auto.js @@ -0,0 +1,51 @@ +/* ---------- The sales desk signs deals for you ---------- + Deals belong to Sales, not to the NOC intern. With someone at the desk, the player can let them sign offers once a + game day (S.slAuto.on) and decline the ones that pay less than a minimum (S.slAuto.min). How they sign is who they are: + - the engineer signs only what the network can serve: #185's trial (autoOffer, a full routing pass), at most + SL_TRIALS a day, and an offer that did not fit waits SL_RETRY days; + - the shark signs every offer whose POPs are up the moment it lands, promises and all: no trial, an unkept promise is + the customer's problem. The commission is paid as on any shark deal, so only while the cash covers it; + - the CEO signs like the engineer, and a decline is a handshake away (salesOverride: about one in three he signs anyway). + Orbit offers need no routing pass: the dish they land on (pieServe) must have room, except for the shark. + Nobody at the desk, nothing automatic: every deal is signed by hand. No random numbers are drawn here. */ +const SL_MINS=[0,2000,5000,10000,25000,50000],SL_TRIALS=1,SL_RETRY=7; +const slAutoNew=()=>({on:false,min:0,wk:null,rep:null}); +// Is the desk signing or declining anything today? +const slAutoOn=()=>!!(S&&S.slAuto&&slP()&&(S.slAuto.on||S.slAuto.min)); +// A week's tally: {w: week, p: who was at the desk, n: signed, rev: what they pay a month, x: declined, y: of those, signed anyway}. +function slWkOk(x){if(!x||typeof x!=='object'||Array.isArray(x)||!own(SALES,x.p))return null;const n=v=>int(v,0,1e6,0);return {w:n(x.w),p:x.p,n:n(x.n),rev:int(x.rev,0,1e10,0),x:n(x.x),y:n(x.y)};} +const slWkAny=x=>!!x&&(x.n>0||x.x>0); +function slAutoFix(s){const a=s.slAuto&&typeof s.slAuto==='object'&&!Array.isArray(s.slAuto)?s.slAuto:{}; + s.slAuto={on:a.on===true,min:SL_MINS.includes(a.min)?a.min:0,wk:slWkOk(a.wk),rep:slWkOk(a.rep)};if(a.ren===true)s.slAuto.ren=true;} +// An old save whose intern ran the sales order: the same switch and minimum, now at the sales desk (they run once someone is there). +function slAutoFrom(s,on,p){if(!on||(s.slAuto&&typeof s.slAuto==='object'))return;s.slAuto={on:p.acc!==false,min:SL_MINS.includes(p.min)?p.min:0,wk:null,rep:null};} +// "This week Dave signed 3 customers (+$41k/mo), declined 17 tiny offers." +function slWeekLine(x,last){const parts=[];if(x.n)parts.push(trn('sales.w_signed',x.n,{rev:opsMo$(x.rev)}));if(x.x)parts.push(trn('sales.w_declined',x.x));if(x.y)parts.push(trn('sales.w_anyway',x.y)); + const v={name:tr(SALES[x.p].s),list:parts.join(', ')};return last?tr('sales.w_last',v):tr('sales.w_now',v);} +// An orbit offer fits where its dish has room for it; used: what this shift already signed on each dish. +function slSkyOk(o,used){const L=pieServe(o.city,o.type);if(!L)return null;const k=L.cr+'|'+L.k;return slP()==='shark'||L.left-(used.get(k)||0)>=o.bw?k:null;} +// Like a day, the desk is a generator: a routing trial is a step the day answers (in play, the route worker does). +const slAutoDay=d=>dayGo(slAutoRun(d),(g,v)=>g.next(v)); +function* slAutoRun(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floor(d/7); + // A new week: last week's tally becomes the report, and the one notice of the week. + if(!A.wk||A.wk.w!==w){if(slWkAny(A.wk)&&A.wk.w${esc(tr('sales.desk'))} ${esc(slWeekLine(A.rep,true))}`,A.rep.rev>0?'good':'',[],{a:'tab',v:'deals'});}A.wk={w,p,n:0,rev:0,x:0,y:0};} + const W=A.wk,used=new Map();W.p=p;let tries=0,dirty=false; + const tried=UI.slTried&&UI.slTried.s===S?UI.slTried.m:(UI.slTried={s:S,m:new Map()}).m; + const won=o=>{if(S.offers.includes(o))return false;W.n++;W.rev+=Math.round(bizMo(o));dirty=true;return true;}; + for(const o of S.offers.slice()){ + // What this offer needs, muted: nothing, or a routing trial (b), which the day answers between the two quiet steps. + let b;const todo=opsQuiet(()=>{if(!S.offers.includes(o))return;const T=BIZ_T[o.type];if(!T||!(o.exp>d))return;const v=T.event?(o.fee||0):bizMo(o); + if(A.min&&vb0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}return;} + if(!A.on||!ip4Fits(o))return; + if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cashd)))return;ACT.accept({id:o.id});won(o);return;} + // Each trial is a full routing pass: at most SL_TRIALS a day, and an offer that did not fit waits a week. + if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)return;tries++;b=offerTrialOf(o);return true;}); + if(!todo)continue; + // o: the offer itself, for a trial the page has to run again on the game as it is by then (dayAgain()). + const got=b?yield {trial:b,hx:offerHealthy(b),o}:null; + // Signed or declined by hand while the trial routed: it is not the desk's. + if(!S.offers.includes(o))continue; + opsQuiet(()=>{OFFER_TRIED={o,b:got};try{ACT.accept({id:o.id,auto:true});}finally{OFFER_TRIED=null;}if(!won(o))tried.set(o.id,d);});} + if(dirty)yield;} diff --git a/src/game/60-features/39-sales-renewals.js b/src/game/60-features/39-sales-renewals.js new file mode 100644 index 0000000..cb26161 --- /dev/null +++ b/src/game/60-features/39-sales-renewals.js @@ -0,0 +1,38 @@ +/* ---------- The sales desk answers renewal haggles ---------- + A customer near the end of its term may ask for a discount (#178, 75-customer-lifecycle.js). With S.slAuto.ren on, + whoever runs sales answers it SL_REN_WAIT days after it opens, so the player can still answer first. Each in their way: + - the engineer talks technology, not price: nerdy customers get an afternoon with the network diagrams and renew at + the market price, now and then halfway; everyone else gets the discount they asked for. Nobody leaves. + - the shark gives nothing away: most renew at the old price, often with a fresh promise, and he bills a month of what + he saved you. Some walk, nerdy ones most of all. + - the CEO settles it on the golf course: a deeper discount than asked for a contract twice as long, a quick yes, or + a fight that ends with the customer gone. + Each answer is a hash of the contract (clR), so no random numbers are drawn. */ +const SL_REN_WAIT=3; +const slRenOn=()=>!!(S&&S.slAuto&&S.slAuto.ren&&slP()); +// The day the desk answers this haggle: a few days after it opened (30 days before the term ends), today at the earliest. +const slRenAt=b=>b.hag.until-30+SL_REN_WAIT; +// A step of the day (dayPost()): its yield is the routing after a price changed. slRenDay() is the same all at once. +function slRenDay(d){runNow(slRenRun(d));} +function* slRenRun(d){if(!slRenOn())return;const p=slP();let any=false; + for(const b of S.biz.slice())if(b.hag&&d>=slRenAt(b)&&d({name:esc(slCap()),cust:esc(b.name),...x}),bill=rate=>fmt$(clBill(b,rate)); + const keep=(rate,how,key,x,s)=>{clRenew(b,rate);clNote('ren');toast(tr(key,v({price:bill(b.rate),...x})),s===undefined?'good':s,[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);return how;}; + const gone=(how,key)=>{clGone(b,'cheap');toast(tr(key,v({})),'bad');sfx('err');return how;}; + if(p==='eng'){if(!nerd)return keep(ask,'cave',N_('sales.ren_eng_cave')); + return r<0.7?keep(Math.max(ask,Math.min(was,clFair(b))),'tech',N_('sales.ren_eng_tech')):keep(mid,'mid',N_('sales.ren_mid'));} + if(p==='shark'){const walk=nerd?0.4:0.12;if(rslRenOn()&&b.hag.until>S.day?`
${tr('sales.ren_when',{name:esc(slCap()),date:dateStr(Math.max(S.day+1,slRenAt(b)))})}
`:''; diff --git a/src/game/60-features/40-tutorial.js b/src/game/60-features/40-tutorial.js new file mode 100644 index 0000000..a61a0e1 --- /dev/null +++ b/src/game/60-features/40-tutorial.js @@ -0,0 +1,20 @@ +/* ---------- guided first game ---------- */ +const TUT=[ + {t:tr('tutorial.your_router_is_live_press_launch'),sel:'[data-act="launchBB"]',ok:()=>S.pops[S.home]&&S.pops[S.home].bb}, + {t:tr('tutorial.your_customers_want_the_whole'),sel:'[data-act="tab"][data-args*=\'"up"\'],[data-act="buyTransit"]',ok:()=>S.transit.length>0,skip:()=>!NETS.some(n=>sellsAt(n,S.home))}, + {t:tr('tutorial.transit_costs_money_per_gigabit'),sel:'[data-act="tab"][data-args*=\'"peer"\'],[data-act="buyIx"],[data-act="rs"]',ok:()=>Object.keys(S.rs).length>0,skip:()=>!ixName(S.home)}, + {t:tr('tutorial.start_the_clock_with_1_and'),sel:'#sp1',ok:()=>netAge()>=5}, + {t:tr('tutorial.grow_drag_from_your_pink_router'),sel:null,ok:()=>S.links.length>0}, + {t:tr('tutorial.businesses_pop_up_as_bubbles_on'),sel:'[data-act="leftTab"][data-args*=\'"deals"\']',ok:()=>S.biz.length>0}, +]; +function tutorialStart(){let done=false;try{done=!!localStorage.getItem('sot-tut');}catch(e){}if(done||window.__TUBES_TEST__&&!window.__TUBES_TUT__)return;S.tut=0;renderCoach();} +// The coach: the steps done move S.tut on (tutAdvance, state only: a server runs it after every day and action), then +// the box shows the step it is at (coachDom, the screen only). +function renderCoach(){if(!$('coach'))return;tutAdvance();coachDom();} +function tutAdvance(){if(!S||S.tut===undefined||S.tut===null||S.lost)return; + while(S.tut=TUT.length){S.tut=null;try{localStorage.setItem('sot-tut','1');}catch(e){}toast(tr('tutorial.you_know_the_basics_the_goals'),'goal');}} +function coachDom(){const el=$('coach');if(!el)return;document.querySelectorAll('.coach-glow').forEach(x=>x.classList.remove('coach-glow')); + if(!S||S.tut===undefined||S.tut===null||S.lost){el.hidden=true;return;} + const st=TUT[S.tut];el.innerHTML=`
${tr('tutorial.step_n_of_total',{n:S.tut+1,total:TUT.length})}${esc(st.t)}
${btn(tr('common.skip_tutorial'),'tutSkip',{},'ghost sm')}`;el.hidden=false; + if(st.sel){const t=document.querySelector(st.sel);if(t)t.classList.add('coach-glow');}} diff --git a/src/game/60-features/45-teleports.js b/src/game/60-features/45-teleports.js new file mode 100644 index 0000000..6fae59b --- /dev/null +++ b/src/game/60-features/45-teleports.js @@ -0,0 +1,126 @@ +/* ---------- Teleports and rented satellite capacity (#83) ---------- + The rules, the money and save repair. Catalog and physics: 10-catalog/75-satellites.js; actions: 90-actions/87-teleports.js; + panels: 93-ui/72-teleport-panels.js. A circuit is a link (kind 'sat'): routing, standby, metrics and the map treat it like + any other, with the radio path as its km and its orbit's latency. */ +// A POP's teleport (S.pops[c].tele): 0 none, 1 dishes for GEO birds, 2 with tracking antennas for the MEO ring too. +const teleOf=c=>{const p=S&&S.pops[c];return p&&(p.tele===1||p.tele===2)?p.tele:0;}; +const teleCities=()=>Object.keys(S.pops).filter(teleOf); +// The birds that see city c, whatever your level. +const teleSees=c=>Object.keys(SATS).filter(id=>satSees(id,c)); +// Why no teleport can go up at city c (nothing on sale sees it at your level, or no POP); '' when it can. +function teleWhy(c){if(!isCity(c)||!S.pops[c])return tr('satellites.no_pop_in_city',{city:isCity(c)?CITY[c].name:'?'}); + if(lvl()lvl()>=SAT_ORB[SATS[id].orb].lv)){const O=SAT_ORB[SATS[ids[0]].orb];return tr('satellites.orbit_unlocks_at_level',{orb:O.n,lv:O.lv});} + return '';} +// Why the teleport at c cannot add MEO tracking antennas; '' when it can. +function trkWhy(c){const O=SAT_ORB.meo;if(lvl()SATS[id].orb==='meo'))return tr('satellites.meo_ring_misses_city',{city:CITY[c].name,lat:O.lat}); + return '';} +// The birds that see both ends of a circuit, by orbit (GEO, MEO, LEO: SAT_ORB's order), then the cheapest. +const SAT_ORD=Object.keys(SAT_ORB); +function satBirds(a,b){return Object.keys(SATS).filter(id=>satPairOk(id,a,b)).sort((x,y)=>SAT_ORD.indexOf(SATS[x].orb)-SAT_ORD.indexOf(SATS[y].orb)||SAT_PROV[SATS[x].p].pg-SAT_PROV[SATS[y].p].pg);} +// Why a circuit from teleport a to b over bird id (g Gbps, when given) cannot be ordered; '' when it can. +function satWhy(a,b,id,g){const B=own(SATS,id)?SATS[id]:null;if(!B||!isCity(a)||!isCity(b)||a===b)return tr('satellites.no_such_circuit');const O=SAT_ORB[B.orb]; + if(lvl()C.id!==a&&satRemote(C.id)&&(S.pops[C.id]||cityOn(C.id))&&satBirds(a,C.id).length).map(C=>C.id) + .sort((x,y)=>(!S.pops[x])-(!S.pops[y])||kmBetween(a,x)-kmBetween(a,y));} +// Your teleports that can reach city b. +const satFrom=b=>satRemote(b)?teleCities().filter(a=>a!==b&&satBirds(a,b).length):[]; +// A new link between a and b (a wave, fiber, a fabric circuit, a cable): the circuits already there go on standby beside +// it, as one ordered next to a link does, and the player hears about it. Without this the pair's load is shared with orbit. +function satBeside(a,b){const ls=pairLinks(a,b).filter(l=>l.kind==='sat'&&!l.standby);for(const l of ls)l.standby=true; + if(ls.length)toast(trn('satellites.n_circuits_go_on_standby',ls.length,{a:CITY[a].name,b:CITY[b].name}));return ls.length;} +/* A wired link that is built and lit: a wave, a lit fiber, a cable, a fabric circuit. What is built counts, never today's + cuts. A fiber or cable with no optics of its own yet carries nothing (an express only passes through a city's ROADM, + and is a link of its own where it ends). */ +const wiredLink=l=>l.kind!=='sat'&&!(l.ready>S.day)&&(l.kind!=='df'||(l.ch||[]).length>0); +/* An island or remote town that only satellites join to the rest of your network: its fastest commissioned circuit, or + its fastest one being pointed when none is up yet (null when a wired link or a pie dish reaches it too). A selective + peer judges what you built, not this week's repair (50-peering-policy.js), and a circuit still being pointed does not + change its verdict while another is up. */ +function satOnly(c){if(!satRemote(c)||!S.pops[c]||S.pie&&(S.pie.dishes||[]).some(x=>x.city===c))return null;let best=null,up=null; + for(const l of S.links){if(l.a!==c&&l.b!==c)continue; + if(l.kind!=='sat'){if(wiredLink(l))return null;continue;}if(!best||satLat(l)S.day)&&(!up||satLat(l)t.city===c))return true; + for(const l of S.links)if((l.a===c||l.b===c)&&wiredLink(l))return true;return false;} +// A Starblink gateway at the teleport in c (S.pops[c].leo). +const leoGw=c=>own(S.pops,c)&&S.pops[c].leo===1&&teleOf(c)>0; +// Your own constellation carries traffic (Pie in the Sky, at least 40% coverage, safe mode or not): Starblink sells a +// rival nothing new. Circuits already rented keep running. +const leoRival=()=>!!(S&&S.pie)&&Object.keys(CRUSTS).some(id=>pieCarry(id)>0); +// Why no LEO gateway can go up at c; '' when it can. +function leoGwWhy(c){const O=SAT_ORB.leo;if(!isCity(c)||!own(S.pops,c))return tr('satellites.no_pop_in_city',{city:isCity(c)?CITY[c].name:'?'}); + if(lvl()O.lat)return tr('satellites.leo_shell_misses_city',{prov:SAT_PROV.sbk.n,city:CITY[c].name,lat:O.lat}); + if(!satWired(c))return tr('satellites.leo_needs_fiber',{city:CITY[c].name}); + if(leoRival())return tr('satellites.leo_no_rivals',{prov:SAT_PROV.sbk.n}); + return '';} +// Why LEO circuit l cannot get bigger; '' when it can (shrinking always works). +function leoGrowWhy(l){const a=l.a;if(!leoGw(a))return tr('satellites.needs_leo_gateway',{city:CITY[a].name}); + if(!satWired(a))return tr('satellites.leo_needs_fiber',{city:CITY[a].name}); + if(leoRival())return tr('satellites.leo_no_rivals',{prov:SAT_PROV.sbk.n});return '';} +// A LEO circuit, and one a solar storm holds in safe mode (S.ev.sky: the day it passes). +const leoLink=l=>l.kind==='sat'&&own(SATS,l.bird)&&SATS[l.bird].orb==='leo'; +const leoStorm=()=>S.ev.sky>S.day; +const leoDown=l=>leoStorm()&&leoLink(l); +// A storm can only find circuits in the sky: a commissioned LEO circuit, an island zone's too (failureRun, and Pie's own storms). +const leoLive=()=>S.links.some(l=>leoLink(l)&&!(l.ready>S.day))||wispLeoLive(); +// A solar storm: Starblink puts its satellites in safe mode for 1 or 2 days (days: how many, when the caller knows). +function leoStormGo(days){S.ev.sky=S.day+(days||1+Math.floor(Math.random()*2)); + addInc({type:'leostorm',ref:'sbk',until:S.ev.sky,msg:tr('satellites.leo_storm_msg',{prov:SAT_PROV.sbk.n}),cost:0});} +/* WISP hook: whether the gateway at city c may carry LEO to the point lat, lon (a zone, not a city id) today. It reads S + and changes nothing: a gateway on your fiber, your level, no flying constellation of yours, both ends under the shell + and at most SAT_ORB.leo.km apart. Pair it with leoKmLL/leoMsLL (10-catalog/75-satellites.js), satMo(LEO_BIRD,g) for + the rent, SAT_ORB.leo.loss for what users notice, and leoStorm() for the storm. */ +function leoReachLL(c,lat,lon){const O=SAT_ORB.leo;if(!leoGw(c)||lvl()O.lat||!(Math.abs(lat)<=O.lat))return false;return leoArcLL(c,lat,lon)*Math.PI/180*SAT_RE<=O.km;} +// What the teleports and their circuits cost a month (R.cost.sat), the island zones' circuits too. +function satMoAll(){let m=0;for(const c in S.pops){const t=teleOf(c);if(t)m+=TPORT_MO+(t>1?TRK_MO:0)+(S.pops[c].leo===1?LEO_GW_MO:0);}for(const l of S.links)if(l.kind==='sat')m+=l.mo||0;return m+wispSatMoAll();} +/* compute(): what users notice on the edges a satellite circuit is on. sv: the losses of the orbits there; sx: the edge's + latency is the satellite's (no cable carries ahead of it), so it is no haul to transit on the ground. Returns how many + edges there were, for compute() to know a satellite is in the picture at all. */ +function satEdges(SE){for(const e of SE){let ta=false,ts=false,act=false;const v=e.sv; + for(const l of e.links){const sb=!!l.standby;if(!sb)act=true;if(l.kind==='sat'){const x=SAT_ORB[SATS[l.bird].orb].loss;if(!v.includes(x))v.push(x);}else if(sb)ts=true;else ta=true;} + e.sx=act?!ta:!ts;} + return SE.length;} +// A flow of ok Gbps from city index ci crossed these edges: keep it, and what each orbit would cost it beyond the tl its +// haul to transit already does (users count the worse of the two, not both). +function satNote(se,ci,ok,tl){for(let k=0;ktl)a[1+j]+=ok*(v[j]-tl);}} +/* After routing: each orbit's share of the edge's traffic, split as compute() splits it (active links by capacity, standby + ones the overflow). A satellite on standby beside a cable that has room carries nothing and costs nobody anything; one + that takes the overflow, or shares the load, costs the users of that share. LATP gets the lost service and SATU the + Gbps that rode a satellite, by city index. */ +function satAfter(SE,LATP,SATU){for(const e of SE){const ld=e.ld||0;if(!e.sa||ld<=1e-9)continue; + const v=e.sv,sh=new Float64Array(v.length),ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;let only=true,all=0; + for(const l of e.links){if(l.kind!=='sat'){only=false;continue;}const c=capOf(l);sh[v.indexOf(SAT_ORB[SATS[l.bird].orb].loss)]+=(l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0))/ld;} + if(only&&v.length===1)sh[0]=1;for(let j=0;jr&&r.satU&&r.citySrv&&r.citySrv[c]>0?Math.min(1,(r.satU[c]||0)/r.citySrv[c]):0; +// Saves: a teleport is 1 or 2, a LEO gateway 1 on a teleport; a circuit needs a known bird that sees both POPs, a teleport +// able to work it (MEO: tracking antennas; LEO: the gateway), a size it sells. The storm's day stays a key once it is one. +function satSanitize(s){ + for(const c of Object.keys(s.pops)){const p=s.pops[c];if(p.tele!==undefined&&p.tele!==1&&p.tele!==2)delete p.tele;if(p.leo!==undefined&&(p.leo!==1||!p.tele))delete p.leo;} + if(s.ev&&s.ev.sky!==undefined)s.ev.sky=int(s.ev.sky,0,s.day+LEO_STORM_MAX,0); + s.links=s.links.filter(l=>{if(l.kind!=='sat')return true;const B=typeof l.bird==='string'&&own(SATS,l.bird)?SATS[l.bird]:null,p=s.pops[l.a]; + if(!B||!p||!p.tele||B.orb==='meo'&&p.tele<2||B.orb==='leo'&&p.leo!==1||!s.pops[l.b]||!satPairOk(l.bird,l.a,l.b))return false; + const G=SAT_ORB[B.orb].g;if(!G.includes(l.g))l.g=G.reduce((x,v)=>v<=num(l.g,0)?v:x,G[0]); + l.km=satKm(l.bird,l.a,l.b);l.sub=true;l.ready=num(l.ready,0);l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of ['tier','cable','trench','mult','border','premium','vt','prov','own','sys','ch'])delete l[k];return true;});} diff --git a/src/game/60-features/46-wisp-zones.js b/src/game/60-features/46-wisp-zones.js new file mode 100644 index 0000000..a701b0c --- /dev/null +++ b/src/game/60-features/46-wisp-zones.js @@ -0,0 +1,112 @@ +/* ---------- Island Wi-Fi (#83): the outer islands, served from a POP in the city they look to ---------- + A zone (WISP, 10-catalog/76-wisp-zones.js) is a pool of island homes hanging off your POP in its city: no node and no + link on the map. Its backhaul lands in that city: satellite capacity from the teleport there (GEO, then MEO with + tracking antennas, then Starblink LEO from a gateway there) or a spur cable laid from it. What reaches the islands + caps how many sign up (SAT_ORB[orb].wisp; all of them over a cable). Their Gbps join the city's demand (compute()), so + they ride its routers, links and transit, and they are IPv6-only homes in your NAT64 pool from day one. A spur can be + cut (failure 'wspur', a weeks-long repair): a satellite circuit kept beside it carries the islands meanwhile. + State: S.pops[c].wisp[z]={day, d: Gbps of homes signed up, sat?, nxt?: a move being commissioned, sp?: the spur}; + a cut is only ever an incident. Actions: 90-actions/87-wisp-zones.js; panels: 93-ui/73-wisp-panels.js. */ +// Normal and sandbox games from the level teleports come at; never puzzles, the Architect or scenarios (weekly too). +const wispOn=()=>!!S&&!pzOn()&&!S.ar&&!S.scn&&(S.mode==='normal'||S.mode==='sandbox')&&lvl()>=SAT_ORB.geo.lv; +// The zones of city c, and zone z's state (null without it). +const WISP_AT=(()=>{const m={};for(const z of Object.keys(WISP))(m[WISP[z].c]||(m[WISP[z].c]=[])).push(z);return m;})(); +const wispAt=c=>own(WISP_AT,c)?WISP_AT[c]:[]; +function wispZ(z){if(!own(WISP,z))return null;const c=WISP[z].c,W=own(S.pops,c)&&S.pops[c].wisp;return W&&own(W,z)?W[z]:null;} +// Every zone you run: [z, its state]. +function wispAll(){const o=[];for(const c in S.pops){const W=S.pops[c].wisp;if(W)for(const z in W)o.push([z,W[z]]);}return o;} +const wispPool=z=>WISP[z].P*eraMul(); +const wispRate=z=>EYE_RATE*arpuOf(WISP[z].c)*WISP_ARPU; +const wispStart=z=>wispPool(z)*WISP_START; +const wispOrb=o=>SATS[o.bird].orb; +// Lit (cut or not); and a lit spur a cut holds down, until that day (0: none). +const wispLit=Z=>!!Z.sp&&!(Z.sp.ready>S.day); +function wispCut(z){let u=0;for(const i of S.inc)if(i.type==='wspur'&&i.z===z&&i.until>S.day)u=Math.max(u,i.until);return u;} +// How many islanders may sign up over what reaches them (a cut lasts weeks; they wait for it), and how many that is. +const wispTake=Z=>wispLit(Z)?1:Z.sat&&!(Z.sat.ready>S.day)?SAT_ORB[wispOrb(Z.sat)].wisp:0; +const wispK=(z,Z)=>wispPool(z)*wispTake(Z); +// What carries the islands today: the spur, unless it is cut; else the circuit, unless a solar storm holds LEO in safe mode. +function wispLink(z,Z){if(wispLit(Z)&&!wispCut(z))return {g:WISP_SPUR_G,sp:true};const o=Z.sat; + return o&&!(o.ready>S.day)&&!(leoStorm()&&wispOrb(o)==='leo')?o:null;} +// Prices: a contended share of a beam, the island kit with the first order, its upkeep, the spur at today's prices. +const wispSatMo=(bird,g)=>Math.round(satMo(bird,g)*WISP_SHARE/10)*10; +const wispKit=z=>WISP_KIT+WISP_KIT_G*WISP[z].P; +const wispUpMo=z=>WISP_MO+WISP_MO_G*WISP[z].P; +const wispSpurCost=z=>Math.round((WISP_SPUR+WISP_SPUR_KM*WISP[z].km)*hwMul('build')/1000)*1000; +const wispSpurMo=z=>Math.round(WISP_SPUR_MO+WISP_SPUR_MO_KM*WISP[z].km); +const wispSpurDays=z=>leadDays(Math.round(WISP_SPUR_D0+WISP_SPUR_DKM*WISP[z].km)); +// The birds that see both the city and the zone, by orbit (GEO, MEO, LEO), then the cheapest (as satBirds). +function wispBirds(z){const W=WISP[z],C=CITY[W.c];return Object.keys(SATS).filter(id=>satPairAt(id,C,W)).sort((x,y)=>SAT_ORD.indexOf(SATS[x].orb)-SAT_ORD.indexOf(SATS[y].orb)||SAT_PROV[SATS[x].p].pg-SAT_PROV[SATS[y].p].pg);} +// One way over bird id from the city to the zone, in ms (LEO: Starblink's own bent pipe, leoMsLL). +function wispMs(z,id){const W=WISP[z];return SATS[id].orb==='leo'?leoMsLL(W.c,W.lat,W.lon):satKmAt(id,CITY[W.c],W)/SAT_C+SAT_ORB[SATS[id].orb].proc;} +/* Why zone z cannot take a circuit on bird id (g Gbps, when given); '' when it can. Its capacity comes down at the teleport + in the zone's own city: tracking antennas for MEO, a Starblink gateway on your fiber for LEO (and none once your own + constellation carries traffic, leoReachLL: said first, with what the islands have left, as a zone takes no pie dish). + One circuit and one move at a time. */ +function wispSatWhy(z,id,g){if(!own(WISP,z))return tr('satellites.no_such_circuit');const W=WISP[z],c=W.c,C=CITY[c].name; + if(lvl()wispAt(c).filter(z=>{const Z=wispZ(z);return !!Z&&[Z.sat,Z.nxt].some(o=>o&&(!orb||wispOrb(o)===orb));}); +// The lit spurs no cut holds down: what a failure can find. +const wispSpurs=()=>wispAll().filter(([z,Z])=>wispLit(Z)&&!wispCut(z)).map(([z])=>z); +// A commissioned LEO circuit for a zone: a solar storm can find it too (leoLive). +const wispLeoLive=()=>!!S&&wispOn()&&wispAll().some(([,Z])=>!!Z.sat&&!(Z.sat.ready>S.day)&&wispOrb(Z.sat)==='leo'); +/* compute(): each zone's homes (Gbps, with the day's viral factor) and what reaches them, added to its city's demand. + null when you run none. by: Gbps carried, by city; L: [{z, c, zd: wanted, car: carried}]. */ +function wispIn(viral){let L=null;const by={}; + for(const [z,Z] of wispAll()){const c=WISP[z].c,k=wispLink(z,Z),zd=Z.d*viral,car=k?Math.min(zd,k.g):0;(L||(L=[])).push({z,c,zd,car});if(car>0)by[c]=(by[c]||0)+car;} + return L?{by,L}:null;} +/* computeMoney(): what the islanders pay for what reached them, served as well as their city (sfOf), and the towers and + lit spurs' upkeep. R.wisp[z]: d wanted, car carried, sf served, k the take-up cap today. Circuit rent is the + satellite row (satMoAll). */ +function wispMoney(R2,C,V){const L=R2.wispL;if(!L)return;let v=0,up=0; + for(const x of L){const Z=wispZ(x.z),sf=x.zd>0?sfOf(R2,x.c)*x.car/x.zd:0;R2.wisp[x.z]={d:x.zd,car:x.car,sf,k:wispK(x.z,Z)};v+=x.zd*sf*wispRate(x.z); + up+=wispUpMo(x.z)+(wispLit(Z)?wispSpurMo(x.z):0);} + V.wisp=v;if(up>0)C.wisp=up;} +// The rent of the zones' circuits, from the order on (satMoAll). +const wispSatMoAll=()=>wispAll().reduce((a,[,Z])=>a+(Z.sat?Z.sat.mo||0:0)+(Z.nxt?Z.nxt.mo||0:0),0); +/* The day's take-up, after broadband's (10-day-tick.js), on the last routing: served well, more islanders sign up toward + the cap; served badly, they leave down to the floor; above a cap that dropped, they drift down to it. */ +function wispGrow(){if(!wispOn())return;for(const [z,Z] of wispAll()){const r=R&&R.wisp&&R.wisp[z],sf=r?r.sf:0,K=wispK(z,Z),fl=wispStart(z); + if(sf<0.9)Z.d=Math.max(fl,Z.d*(1-(0.9-sf)*0.04));else if(Z.dK)Z.d-=(Z.d-K)*0.01;}} +// The day's news: a move done, the first islanders online, a spur lit. +function wispDay(d){if(!wispOn())return;for(const [z,Z] of wispAll()){const zone=esc(WISP[z].n),go=[{l:tr('common.open'),act:'wispOpen',args:{z}}]; + const mv=!!Z.nxt&&!(Z.nxt.ready>d);if(mv){Z.sat=Z.nxt;delete Z.nxt;toast(tr('wisp.moved',{zone,bird:esc(SATS[Z.sat.bird].n)}),'good',go);} + else if(Z.sat&&Z.sat.ready===d&&!(Z.sp&&Z.sp.ready{const B=o&&typeof o==='object'&&typeof o.bird==='string'&&own(SATS,o.bird)?SATS[o.bird]:null; + if(!B||!p.tele||B.orb==='meo'&&p.tele<2||B.orb==='leo'&&p.leo!==1||!satPairAt(o.bird,CITY[c],W))return false; + const G=SAT_ORB[B.orb].g;if(!G.includes(o.g))o.g=G.reduce((x,v)=>v<=num(o.g,0)?v:x,G[0]); + o.mo=Math.max(0,Math.round(num(o.mo,0)));o.day=int(o.day,0,s.day,s.day);o.ready=int(o.ready,0,1e7,o.day);return true;}; + for(const k of ['sat','nxt'])if(Z[k]!==undefined&&!ok(Z[k]))delete Z[k]; + if(Z.nxt&&!Z.sat){Z.sat=Z.nxt;delete Z.nxt;} + if(Z.sp!==undefined){const o=Z.sp;if(!W.km||!o||typeof o!=='object')delete Z.sp;else{o.day=int(o.day,0,s.day,s.day);o.ready=int(o.ready,o.day,o.day+3650,o.day);}}} + if(!Object.keys(p.wisp).length)delete p.wisp;} + // A cut holds down a spur that is there, at the zone's own city. + s.inc=s.inc.filter(i=>i.type!=='wspur'||typeof i.z==='string'&&own(WISP,i.z)&&i.ref===WISP[i.z].c&&!!(s.pops[i.ref]&&s.pops[i.ref].wisp&&own(s.pops[i.ref].wisp,i.z)&&s.pops[i.ref].wisp[i.z].sp));} +// An incident for a zone that is gone (closed, or its POP decommissioned): purgeInc() drops it. +const wispIncOk=i=>typeof i.z==='string'&&own(WISP,i.z)&&!!wispZ(i.z)&&!!wispZ(i.z).sp; diff --git a/src/game/60-features/50-traceroute.js b/src/game/60-features/50-traceroute.js new file mode 100644 index 0000000..a190234 --- /dev/null +++ b/src/game/60-features/50-traceroute.js @@ -0,0 +1,86 @@ +/* ---------- traceroute and looking glass ---------- */ +const slug=t=>String(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x'; +// The three ways a customer's circuit can be routed (RT in 90-sites-and-service.js), applied to the trace: follow the metrics, +// lowest latency, or the quietest links (one path; a scenic circuit may share the load between two). +const TR_MODES=['normal','fast','scenic']; +const trUtil=l=>{const c=capOf(l);return c>0?Math.max(0,((R.load&&R.load[l.id])||0)/c):0;}; +// bh: a cut-off POP whose backhaul through orbit (R.pie.bh, as compute() routed it) the trace may take: only to or from that POP. +function trPaths(src,mode,bh){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={}; + // Every link between two cities costs what the pair costs, as in compute(); the trace shows an active link over one on standby. + const pw={};for(const l of live){const k=edgeKey(l);pw[k]=Math.min(pw[k]??Infinity,pairW(k,l.km));} + for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const k=edgeKey(l),w=(mode==='fast'?linkLat(l)+0.05:mode==='scenic'?pw[k]*(1+10*trUtil(l)):pw[k])+(l.standby?1e-6:0);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);} + const B=trBh(bh);if(B){const l={id:'pie:bh:'+B.city,a:B.city,b:B.land,bh:B};(adj[l.a]=adj[l.a]||[]).push([l.b,l,PIE_BH_W]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,PIE_BH_W]);} + const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};} +function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[]; + for(const x of S.caches)if(x.net===net&&popUp(x.city)&&!siteDown(x.city,'a'))out.push({k:'c',rank:0,city:x.city,pref:'normal',lab:tr('common.name_cache',{name:NET[net].cache.name}),used:R.useCache[x.id]||0,cap:cacheG(x)}); + // A peer's customer cone (#85): one AS hop more, so tried after direct peering and before transit, as in compute(). + for(const p of S.pni)if(CONE_S[p.net].has(net)&&pniOn(p)&&popUp(p.city)&&liveN(p.city,p.site,p.n))out.push({k:'p',rank:p.net===net?2:CONE_RANK,via:p.net===net?null:p.net,city:p.city,pref:p.pref||'normal',lab:tr('common.pni_with_net',{net:NET[p.net].name}),used:R.usePni[p.id]||0,cap:liveCap(pniG(p),p.city,p.site,p.n)}); + for(const c in S.ixp){const ses=ixSessions(c),via=ses.has(net)?null:ANC[net].find(u=>ses.has(u))||null;if((ses.has(net)||via)&&(popUp(ixCity(c))||remoteCities().includes(ixCity(c)))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:via?CONE_RANK:2,via,city:ixCity(c),id:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:tr('common.ix_peering',{ix:ixName(c)}),used:R.useIx[c]||0,cap:ixCap(c)});} + for(const t of S.transit)if(popUp(t.city)&&!(t.down>day)&&liveN(t.city,t.site,t.n)&&net!==leak&&!((ev.depeer>day||scnRule('spat'))&&t.net==='cog'&&net==='ggl'))out.push({k:'t',rank:3,city:t.city,pref:t.pref||'normal',carry:!!t.carry,lab:tr('traceroute.name_transit',{name:NET[t.net].name}),tnet:t.net,used:R.useT[t.id]||0,cap:liveCap(PORT[t.tier].g,t.city,t.site,t.n)}); + return out;} +// coneChain(peer,net): [peer, …, net], the shortest walk down customer links (the network's up lists, read backwards). +function coneChain(top,id){const prev={[id]:null},q=[id];while(q.length){const x=q.shift();if(x===top)break;for(const u of NET[x].up||[])if(NET[u]&&!(u in prev)){prev[u]=x;q.push(u);}} + if(!(top in prev))return [top,id];const out=[];for(let x=top;x!==null;x=prev[x])out.push(x);return out;} +// The backhaul of cut-off POP c, if it has one today. +const trBh=c=>c&&R&&R.pie&&R.pie.bh?R.pie.bh.find(b=>b.city===c&&b.cap>0)||null:null; +function traceroute(src,to,mode){mode=TR_MODES.includes(mode)?mode:'normal';const bh=trBh(src)?src:to.city&&trBh(to.city)?to.city:null,P=trPaths(src,mode,bh),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1; + const hop=(host,addr,extra,note)=>{rtt+=extra;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);}; + hop(`lo0.cr1.${src}.${me}`,ip(hstr(src),1),0,tr('traceroute.city_your_router',{city:CITY[src].name})); + // Through orbit: up at one dish, across space with lasers, down at the other, each hop's round trip as compute() priced it. + const walk=path=>{for(const h of path){const l=h.l;if(l.bh){const b=l.bh,cr=CRUSTS[b.cr],e={bh:{city:b.city,land:b.land,cr:b.cr,las:b.las,km:b.km}}; + for(const x of pieBhHops(e,h.from===b.city)){const ms=x.ms*2+0.05;if(x.k==='up')hop(`dish.${x.city}.${me}`,ip(hstr(x.city),5),ms,tr('traceroute.sky_up',{city:CITY[x.city].name,crust:tr(cr.n)})); + else if(x.k==='las')hop(`laser.${b.cr}.${me}`,`10.255.${hstr(b.cr)%250}.${(x.km|0)%250}`,ms,tr('traceroute.sky_laser',{km:Math.round(x.km).toLocaleString()})); + else hop(`dish.${x.city}.${me}`,ip(hstr(x.city),6),ms,tr('traceroute.sky_down',{city:CITY[x.city].name}));}continue;} + const lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.kind==='xp'?tr('express.trace_hop',{via:xpVia(l)}):l.kind==='sat'?tr('satellites.via_bird',{bird:satName(l)}):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}}; + if(to.city){const path=P.path(to.city);lines.unshift(`traceroute to ${to.city}.${me} (${CITY[to.city].name}), 30 hops max`);if(!path){lines.push(' 2 * * * ← '+tr('traceroute.no_working_path_between_these_pops'));return {text:lines.join('\n'),why:tr('traceroute.no_path_every_route_between_these')};}walk(path);const bw=trBhWhy(bh,path);return {text:lines.join('\n'),why:bw+(S.te&&S.te.on?trn('traceroute.internal_path_over_n_link_chosen',path.length):trn('traceroute.internal_path_over_n_link_chosen_8620',path.length))};} + const N=NET[to.net],ex=trExits(to.net).filter(e=>P.dist[e.city]!==undefined); + lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`); + if(!ex.length){lines.push(' 2 * * *\n 3 * * * ← '+tr('traceroute.n_network_unreachable'));return {text:lines.join('\n'),why:tr('traceroute.nothing_on_your_network_reaches_net',{net:N.name,city:CITY[src].name}),asPath:null};} + // As in compute(): a carrier's own port (or its customers' carrier) goes before other transit, at this POP or anywhere when it + // carries, except from a POP with a Prefer-marked transit port, where Prefer keeps the say. + const hiHere=S.transit.some(t=>t.city===src&&t.pref==='high'&&popUp(t.city)&&!(t.down>S.day)&&liveN(t.city,t.site,t.n)),dtier=e=>hiHere||e.k!=='t'||e.pref==='low'?0:directTier(e.tnet,N.id); + const rk=e=>{const r=e.pref==='low'?4:e.rank,t=dtier(e);return t&&(e.carry||e.city===src)?Math.min(r,DIRECT_RANK[t][e.carry?0:1]):r;}; + ex.sort((a,b)=>rk(a)-rk(b)||(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||P.dist[a.city]+(a.k==='ix'?PNI_TIE:0)-P.dist[b.city]-(b.k==='ix'?PNI_TIE:0)); + const e=ex.find(x=>x.usedkmBetween(e.city,c)S.day?35:20}):''; + return {text:lines.join('\n'),why:`${trBhWhy(bh,ep)}${tr('traceroute.exit_exit_in_city',{exit:e.lab,city:CITY[e.city].name})} ${tr('traceroute.rule_and_closer_exits_win_ties',{rule:order[0].toUpperCase()+order.slice(1)})}${e.pref!=='normal'?tr('traceroute.this_one_is_set_to_mode',{mode:e.pref==='high'?tr('common.prefer'):tr('common.backup_only')}):''}.${direct}${e.used>=e.cap*0.999?' '+tr('traceroute.it_is_full_so_some_traffic'):''}${cn}`,asPath};} +// A note when the trace rode a cut-off POP's backhaul: why, and what orbit adds. +function trBhWhy(c,path){const b=trBh(c);return b&&path&&path.some(h=>h.l.bh)?tr('traceroute.bh_why',{city:CITY[c].name,dish:CITY[b.land].name,ms:pieMs(2*b.ms)})+' ':'';} +// A circuit riding orbit (R.pie.flows, kind 'c'): its hops as compute() routed them, fiber legs, up, across space and down. +const trSkyList=()=>R&&R.pie&&R.pie.flows?R.pie.flows.filter(f=>f.k==='c'&&f.hops&&f.hops.some(h=>h.k==='las')):[]; +function trSky(id){const f=trSkyList().find(x=>x.id===id),b=f&&S.biz.find(x=>x.id===id);if(!f||!b)return null;const me=slug(S.name)+'.net',lines=[],ip=(a,c)=>`100.64.${a%250}.${c%250}`;let rtt=0.3,n=1; + const hop=(host,addr,ms,note)=>{rtt+=ms;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);}; + lines.push(`traceroute to ${f.b}.${me} (${CITY[f.b].name}) for ${b.name}, 30 hops max`); + hop(`lo0.cr1.${f.a}.${me}`,ip(hstr(f.a),1),0,tr('traceroute.city_your_router',{city:CITY[f.a].name})); + // Round trip, as for the fiber hops: twice the one-way latency. + for(const h of f.hops){const ms=h.ms*2+0.05,cr=h.cr&&CRUSTS[h.cr]?CRUSTS[h.cr]:null; + if(h.k==='f')hop(`ae1.cr1.${h.city}.${me}`,ip(hstr(h.city),2),ms,CITY[h.city].name); + else if(h.k==='up')hop(`dish.${h.city}.${me}`,ip(hstr(h.city),5),ms,tr('traceroute.sky_up',{city:CITY[h.city].name,crust:cr?tr(cr.n):''})); + else if(h.k==='las')hop(`laser.${h.cr||'sky'}.${me}`,`10.255.${hstr(h.cr||'x')%250}.${(h.km|0)%250}`,ms,tr('traceroute.sky_laser',{km:Math.round(h.km).toLocaleString()})); + else hop(`dish.${h.city}.${me}`,ip(hstr(h.city),6),ms,tr('traceroute.sky_down',{city:CITY[h.city].name}));} + const fm=pieFiberMs(f); + return {text:lines.join('\n'),why:isFinite(fm)?tr('traceroute.sky_why',{o:pieMs(f.ms||0),f:pieMs(fm)}):tr('traceroute.sky_why_nofiber',{o:pieMs(f.ms||0)}),asPath:null};} +function traceModal(src,to,mode){const pops=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));src=src&&S.pops[src]?src:UI.trFrom&&S.pops[UI.trFrom]?UI.trFrom:S.home&&S.pops[S.home]?S.home:pops[0]; + const nets=NETS.slice().sort((a,b)=>b.share-a.share),t=to||UI.trTo||'net:ggl';UI.trFrom=src;UI.trTo=t;mode=TR_MODES.includes(mode)?mode:UI.trMode||'normal';UI.trMode=mode; + const sky=trSkyList(),r=(t.startsWith('sky:')&&trSky(t.slice(4)))||(t.startsWith('net:')||t.startsWith('sky:')?traceroute(src,{net:t.startsWith('net:')?t.slice(4):'ggl'},mode):traceroute(src,{city:t.slice(5)},mode)); + openModal(`
${tr('common.looking_glass')}

${tr('common.traceroute')}

+
+ ${btn(tr('common.run'),'traceRun',{},'pink sm')}
+
${tr('common.route_4a2e')}${TR_MODES.map(m=>btn(RT[m],'traceMode',{m},mode===m?'pink sm':'ghost sm')).join('')}
+ ${mode!=='normal'?`

${tr('traceroute.your_traffic_follows_the_metrics_this',{mode:RT[mode]})}

`:''}
${esc(r.text)}
${r.asPath?`

${tr('traceroute.as_path_path',{path:r.asPath.map(a=>'AS'+a).join(' → ')})}

`:''}

${esc(r.why)}

+
${btn(tr('common.copy'),'traceCopy',{},'ghost sm')}
`);UI.trText=r.text;} + diff --git a/src/game/60-features/60-share-card.js b/src/game/60-features/60-share-card.js new file mode 100644 index 0000000..1b86351 --- /dev/null +++ b/src/game/60-features/60-share-card.js @@ -0,0 +1,31 @@ +/* ---------- share card ---------- */ +// Straight link segments in map coordinates for flat maps. A link across the date line leaves one edge +// and comes back in at the other, so it becomes two segments, one per edge (#42). +function linkSegs(){const out=[];for(const l of S.links){const A=CITY[l.a],B=CITY[l.b];if(!A||!B)continue;const d=Math.abs(B.x-A.x)>W/2?(B.xi?g.lineTo(mx+q[0]*sx,my+q[1]*sy):g.moveTo(mx+q[0]*sx,my+q[1]*sy));g.closePath();g.fill();g.stroke();} + g.strokeStyle='#FF4F9A';g.lineWidth=2.5;for(const [x1,y1,x2,y2] of linkSegs()){g.beginPath();g.moveTo(mx+x1*sx,my+y1*sy);g.lineTo(mx+x2*sx,my+y2*sy);g.stroke();} + for(const c in S.pops){const C=CITY[c];g.fillStyle='#FF4F9A';g.strokeStyle='#1E2640';g.lineWidth=2;g.beginPath();g.arc(mx+C.x*sx,my+C.y*sy,5,0,7);g.fill();g.stroke();} + g.restore();g.strokeStyle='#1E2640';g.lineWidth=5;g.strokeRect(mx,my,mw,mh); + // header + g.fillStyle='#1E2640';g.font='900 54px "Baloo 2", sans-serif';g.textBaseline='top';g.fillText(S.name,40,28); + g.font='800 26px Nunito, sans-serif';g.fillText(`AS${S.asn} · ${tierLabel()} · ${dateStr(S.day)}${ruleTag()?' · '+ruleTag():''}`,42,92); + // stats + const got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined),rk={l:0,e:1,r:2,c:3},lv=b=>bvar(S.achP&&S.achP[b.id]).lv,top=got.slice().sort((a,b)=>rk[a.r]-rk[b.r]||lv(b)-lv(a)).slice(0,8); + const rows=[[tr('common.peak_traffic'),fmtG(S.stats.peak||0)],[tr('common.peered'),pct(R.peerShare||0)],[tr('common.pops'),tr('share_card.n_in_r_regions',{n:Object.keys(S.pops).length,r:regionsCount()})],[tr('common.links'),String(S.links.length)],[tr('common.customers'),String(S.biz.length)],[tr('common.incidents_survived'),String(S.stats.survived||0)],[tr('common.shark_bites'),String(S.stats.sharks||0)],[tr('common.badges'),`${got.length}/${BADGES.length}`]]; + if(S.solWon)rows.unshift(['⚡ '+tr('specialist.speed_of_light'),dateStr(S.solWon)]); + if(S.scn)rows.unshift([scnName(),S.scn.done?(S.scn.id==='weekly'?tr('share_card.score_v',{v:fmtG(S.scn.score||S.stats.peak||0)}):tr('features.done_in_d_days',{d:S.scn.done})):S.scn.failed?tr('share_card.not_this_time'):tr('common.in_progress')]); + let y=150;for(const [k,v] of rows.slice(0,9)){g.fillStyle='#fff';g.strokeStyle='#1E2640';g.lineWidth=3;g.beginPath();g.roundRect?g.roundRect(770,y,390,42,12):g.rect(770,y,390,42);g.fill();g.stroke();g.fillStyle='#5A6280';g.font='800 18px Nunito, sans-serif';g.fillText(k,786,y+11);g.fillStyle='#1E2640';g.font='900 22px Nunito, sans-serif';const tw=g.measureText(v).width;g.fillText(v,1146-tw,y+9);y+=48;} + // Badge variants show as a ring: frosted for Change Freeze, fiery for BGP at 3 a.m. + top.forEach((b,i)=>{const v=S.achP&&S.achP[b.id];if(v&&v!=='oncall'&&own(BVAR,v)){g.strokeStyle=BVAR[v].col;g.lineWidth=4;g.beginPath();g.arc(60+i*48,537,22,0,7);g.stroke();}}); + g.font='34px sans-serif';top.forEach((b,i)=>g.fillText(b.i,40+i*48,520)); + {const n=v=>got.filter(b=>(S.achP&&S.achP[b.id]||'oncall')===v).length,f=n('freeze'),h=n('bgp');if(f||h){g.fillStyle='#1E2640';g.font='800 18px Nunito, sans-serif';g.fillText([h?`🔥 ${h}`:'',f?`🧊 ${f}`:''].filter(Boolean).join(' '),40+Math.max(1,top.length)*48+8,526);}} + g.fillStyle='#1E2640';g.font='900 30px "Baloo 2", sans-serif';g.fillText('seriesoftub.es',40,572);g.font='700 20px Nunito, sans-serif';g.fillText(tr('share_card.build_the_internet_one_tube_at'),300,580); + return cv;} +function shareModal(){const cv=shareCanvas();if(!cv){toast(tr('share_card.your_browser_cannot_draw_the_card'),'bad');return;}let url='';try{url=cv.toDataURL('image/png');}catch(e){} + UI.shareCv=cv;openModal(`
${tr('common.share')}

${tr('share_card.your_network_card')}

${url?`${tr('share_card.stats_card_for_name',{name:esc(S.name)})}`:''}
${navigator.share?btn(tr('common.share_2cd9'),'shareGo',{},'pink'):''}${btn(tr('common.download_png'),'shareDl',{},navigator.share?'':'pink')}

${tr('share_card.post_it_wherever_your_peering')}

`);track('share_open');} +function shareFile(cb){const cv=UI.shareCv;if(!cv||!cv.toBlob){cb(null);return;}cv.toBlob(b=>cb(b?new File([b],`series-of-tubes-${slug(S.name)}.png`,{type:'image/png'}):null),'image/png');} diff --git a/src/game/60-features/62-device-transfer.js b/src/game/60-features/62-device-transfer.js new file mode 100644 index 0000000..bef22d7 --- /dev/null +++ b/src/game/60-features/62-device-transfer.js @@ -0,0 +1,41 @@ +/* ---------- moving a network to another device (#263) ---------- + No server, no account. The save file goes through the device's own share sheet (AirDrop, Quick Share, a chat with + yourself, email), whatever its size, and opens on the other device with "Import a save". For copy and paste + (a synced clipboard, a note to self) the network also fits in a link: gzipped, in the fragment (#sot1..0.1.), + which browsers never send to any server. Opening the link, or pasting it, imports the network like a save file. */ +const XFER_RE=/sot1\.([a-z0-9]{3,8})\.0\.1\.([A-Za-z0-9_-]+)/; +// Taken out of the address bar before anything else can read it (the stats counter only loads after this script): +// a network in a link belongs to the player, and a reload must not import it again. +const XFER_HASH=(()=>{try{const h=location.hash||'';if(!h.startsWith('#sot1.'))return '';history.replaceState(null,'',location.pathname+location.search);return h.slice(1);}catch(e){return '';}})(); +const b64u=u=>b64(u).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,''); +const unb64u=t=>unb64(t.replace(/-/g,'+').replace(/_/g,'/')+'==='.slice((t.length+3)%4)); +const xferBase=()=>/^https?:$/.test(location.protocol)?location.origin+location.pathname:'https://seriesoftub.es/'; +// A network's save text: the one playing now (saved first), or any other straight from storage. +function xferText(id){if(id===UI.slot&&S&&!pzOn()){save(true);return Promise.resolve(JSON.stringify(packSave(S)));} + const raw=slotRaw(id);if(raw==null)return Promise.reject(new Error('no save'));return raw.startsWith(GZ)?gunzip(raw):Promise.resolve(raw);} +/* Everything is ready before the sheet opens: browsers only open a share sheet straight from a tap, not after waiting + for compression. Chromium shares only some file types, and not .json (Safari does): there the same file is a .txt, + which "Import a save" takes too. */ +async function xferPack(id){const e=slotIdx().find(x=>x.id===id),t=await xferText(id),name=e&&e.name||S&&S.name; + const w=`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},"exported":"${new Date().toISOString()}","S":${t}}`; + let file=null;try{const fn=saveFileName(name),ok=f=>!!navigator.canShare&&navigator.canShare({files:[f]}); + file=new File([w],fn,{type:'application/json'});if(!ok(file)){file=new File([w],fn.replace(/\.json$/,'.txt'),{type:'text/plain'});if(!ok(file))file=null;}}catch(err){file=null;} + // A network of a multiplayer session (self-hosted builds): the session's own link instead of a copy (mpXfer()). + const ms=mpXfer(e);if(ms)return {id,name,file,link:ms.link,mp:ms.code}; + let link=null;if(gzOk()){const k=Math.floor(Math.random()*36**5).toString(36).padStart(5,'0'); + link=`${xferBase()}#sot1.${k}.0.1.${b64u(await gzPipe(new TextEncoder().encode(w),new CompressionStream('gzip')))}`;} + return {id,name,file,link};} +// A link (or just its fragment, or text with one in it). A session's #mp= link (mpXfer(), self-hosted builds) is opened +// as a link is: mpBoot() reads it at boot, so the page saves and loads again with it in the address bar. +function xferTake(h){const m=XFER_RE.exec(String(h||'')),mp=MP_API&&/#mp=[0-9A-Za-z-]{6,8}\.[a-z0-9]{8}\.[0-9a-f]{64}(?![0-9a-f])/.exec(String(h||'')); + if(!m&&mp){try{history.replaceState(null,'',location.pathname+location.search+mp[0]);}catch(e){return false;}if(S)save(true);location.reload();return true;} + if(!m){toast(tr('transfer.that_is_not_a_transfer_link'),'bad');sfx('err');return false;} + xferOpen(m[2]);return true;} +function xferOpen(d){if(!gzOk()){toast(tr('transfer.this_browser_cannot_open_transfer_links'),'bad');return;} + let u=null;try{u=unb64u(d);}catch(e){} + const bad=()=>{toast(tr('transfer.that_link_is_incomplete_or_damaged'),'bad');sfx('err');};if(!u){bad();return;} + gzPipe(u,new DecompressionStream('gzip')).then(b=>{const r=parseSave(new TextDecoder().decode(b)); + if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;}importAsk(r);track('xfer_in');},bad);} +addEventListener('hashchange',()=>{const h=location.hash||'';if(!h.startsWith('#sot1.'))return;try{history.replaceState(null,'',location.pathname+location.search);}catch(e){}xferTake(h.slice(1));}); +// After boot: a page opened from a transfer link imports it. +function xferBoot(){if(XFER_HASH)xferTake(XFER_HASH);} diff --git a/src/game/60-features/70-scenario-progress.js b/src/game/60-features/70-scenario-progress.js new file mode 100644 index 0000000..4436e58 --- /dev/null +++ b/src/game/60-features/70-scenario-progress.js @@ -0,0 +1,13 @@ +function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)return; + if(sc.id==='weekly'&&sc.wk){wsTick(d);return;} + if(sc.id==='weekly'){if(d>=sc.days){sc.done=d;const score=Math.round(S.stats.peak||0);sc.score=score;let best=null;try{const wk=JSON.parse(localStorage.getItem('sot-weekly')||'{}');best=wk[sc.key];if(!best||score>best){wk[sc.key]=score;localStorage.setItem('sot-weekly',JSON.stringify(wk));}}catch(e){} + const h=scnHof();h.weekly=h.weekly||{d:new Date().toISOString().slice(0,10)};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){} + openModal(`
${tr('features.weekly_challenge_key',{key:esc(sc.key)})}

${tr('scenario_progress.your_score_score',{score:fmtG(score)})}

${best&&best>score?tr('scenario_progress.peak_traffic_served_in_one_year',{best:fmtG(best)}):best?tr('scenario_progress.peak_traffic_served_in_one_year_c7e5'):tr('scenario_progress.peak_traffic_served_in_one_year_a67b')}

${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);track('weekly_done');}return;} + const def=SCN.find(x=>x.id===sc.id);if(!def)return;let ok=false;try{ok=def.ok();}catch(e){} + if(ok){sc.done=d;const h=scnHof();if(!h[sc.id]||h[sc.id].days>d)h[sc.id]={d:new Date().toISOString().slice(0,10),days:d};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){}track('scenario_'+sc.id); + openModal(`
${tr('common.scenario_complete')}

${tr('scenario_progress.name_done_in_d_days',{name:esc(def.n),d})}

${esc(def.goal)}. ${d

${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}${btn(tr('common.more_scenarios'),'scenarios',{},'ghost')}
`);sfx('coin');} + else if(d>=def.days){sc.failed=d;openModal(`
${tr('common.scenario_over')}

${tr('common.time_s_up')}

${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(def.goal),d:def.days})}

${btn(tr('common.try_again'),'startScn',{id:def.id},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);}} +function scenarioModal(){wsEnsure();const h=scnHof(); + openModal(`
${tr('common.scenarios')}

${tr('scenario_progress.pick_a_challenge')}

+ ${wsRow()} + ${SCN.map(x=>`
${esc(x.n)} ${h[x.id]?`${tr('features.done_in_d_days',{d:h[x.id].days})}`:''}
${esc(x.d)}
${tr('scenario_progress.goal_goal_time_d_days_start',{goal:esc(x.goal),d:x.days,city:esc(CITY[x.city].name)})}
${btn(tr('common.play'),'startScn',{id:x.id},'')}
`).join('')}`);} diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js new file mode 100644 index 0000000..452abf4 --- /dev/null +++ b/src/game/60-features/80-new-game.js @@ -0,0 +1,10 @@ +// Every field a reload gives a game is here from the start (sanitize() would add the rest), so a new game is what a +// reload makes of it: a server checks every action against that (tests/canonical-state.test.js). +function newGame(name,home){ + S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,day0:0,cash:START_CASH, + ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, + done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},vol:0,cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,popTiers:ptNew(),won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',cm:cmNew(),chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null, + lvl:1,hist:[],ach:{},ixn:{},ixPref:{},ixSite:{},confReg:{},cl:{odd:-1e9,mo:[]},sales:{p:null,hired:0,vp:null,golf:null,say:null},baronWon:0}; + for(const o of OPS)S.ops.p[o.k]={}; +} + diff --git a/src/game/60-features/81-late-joiners.js b/src/game/60-features/81-late-joiners.js new file mode 100644 index 0000000..ccb4497 --- /dev/null +++ b/src/game/60-features/81-late-joiners.js @@ -0,0 +1,27 @@ +/* ---------- Late joiners (server sessions, docs/plans/server-run.md "What Q1 changes") ---------- + A network that joins a session after its market started moving starts on the session's date (S.day0), with its + first-days rules counted from there (netAge()), a top-up as large as the rise in hardware prices, and its first year + of home broadband income matched: what its homes pay after any wholesale cut, outside investors' share (they funded + the business, not a subsidy). Only S.day0 is stored; being late, the year and the top-up follow from it. The market + and the calendar stay on the session's date: one market for everyone (gameplay rule F11). */ +// Until day 180 the shared market has not moved (HW_FREE, MK_FREE, IP4_FREE): a joiner then gets nothing extra. +const LATE_FROM=180,LATE_DAYS=365; +const lateIs=()=>!!S&&(S.day0|0)>LATE_FROM; +const lateOn=()=>lateIs()&&S.day<=S.day0+LATE_DAYS; +const lateLeft=()=>lateIs()?Math.max(0,S.day0+LATE_DAYS-S.day):0; +// The top-up buys what START_CASH bought on day 0 (hardware only: customer prices are what the match makes up for). +const lateCash=d=>d>LATE_FROM&&rule('market')?Math.round(START_CASH*(hwTrend(d)-1)/1000)*1000:0; +// beginState's last step: the network begins on day D, its schedules and its first block stamped with that day (a block +// stamped 0 could be sold on the first day at the session's price). +function lateStart(D){S.day=S.day0=D;S.nextFail+=D;S.nextEvent+=D;S.pops[S.home].day=D;for(const b of S.ip4.b)b.d=D;S.cash+=lateCash(D);} +// computeMoney: the match, once more what homes pay after the Australian wholesale cut or levy. +function lateMoney(V,C){if(!lateOn())return;const v=V.eyeballs-(C.wholesale||0)-(C.levy||0);if(v>0)V.late=v;} +function lateHello(){const n=S.day0,g=lateCash(n),t=hwTrend(n)-1; + toast(g>0?tr('late.hello',{n,p:pct(t),cash:fmt$(g)}):tr('late.hello_flat',{n}),'goal',[{l:tr('common.bank'),act:'bank',args:{}}]);} +function lateDay(d){if(lateIs()&&d===S.day0+LATE_DAYS+1)toast(tr('late.over'),'');} +function lateCard(){const n=lateLeft();if(!n)return ''; + return `
🎟️ ${tr('late.title')}
${trn('late.card',n,{price:fmt$((R&&R.rev&&R.rev.late)||0)})}
`;} +function lateBank(){if(!lateLeft())return '';const g=lateCash(S.day0),kv=(l,v)=>`
${l}${v}
`; + return `

🎟️ ${tr('late.title')}

${g>0?kv(tr('late.top_up'),fmt$(g)):''}` + +kv(tr('late.match'),tr('late.until',{date:dateStr(S.day0+LATE_DAYS)}))+kv(tr('late.this_month'),tr('common.price_mo',{price:fmt$((R&&R.rev&&R.rev.late)||0)})) + +`

${tr('late.bank_note')}

`;} diff --git a/src/game/60-features/85-pitcairn.js b/src/game/60-features/85-pitcairn.js new file mode 100644 index 0000000..ea026a9 --- /dev/null +++ b/src/game/60-features/85-pitcairn.js @@ -0,0 +1,13 @@ +/* Pitcairn (#124): no cable lands there yet, but you may land your own, and the UK pays a monthly grant while the + islanders are online through you: a POP with broadband, up and nearly fully served. The money is for a cable: with more + than GRANT_SAT of their traffic on a rented satellite circuit (#83) it never comes, however well MEO serves them. */ +const GRANT_MO=300000,GRANT_SAT=0.1; +const grantOn=r=>!!(S&&S.pops.pcn&&S.pops.pcn.bb&&!(S.pops.pcn.down>S.day)&&sfOf(r,'pcn')>=0.9&&satShare(r,'pcn')<=GRANT_SAT); +/* Satellite tier: Pitcairn online through your pies (its POP on backhaul, or home terminals there) is good enough for the + UK at a lower bar, orbit's latency forgiven (sfOf() counts it, so the fiber grant never comes), for less money. */ +const GRANT_SKY_MO=120000,GRANT_SKY_Q=0.9; +function grantSky(r){if(!S||!S.pie||!r||!r.pie||grantOn(r))return false;const p=S.pops.pcn; + if(p&&p.bb&&!(p.down>S.day)&&r.pie.bh.some(b=>b.city==='pcn'&&b.g>0)){const d=r.cityDem.pcn||0;if(d>1e-6&&(r.citySrv.pcn||0)/d>=GRANT_SKY_Q)return true;} + return S.biz.some(b=>b.city==='pcn'&&b.type==='pizza'&&(r.pie.sf[b.id]||0)>=GRANT_SKY_Q);} +function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R),sky=!on&&grantSky(R),sat=!on&&!sky&&satShare(R,'pcn')>GRANT_SAT; + return `${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):sky?tr('pitcairn.uk_sky_grant_mo',{mo:fmt$(GRANT_SKY_MO),full:fmt$(GRANT_MO)}):sat?tr('pitcairn.uk_grant_needs_a_cable',{mo:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}`;} diff --git a/src/game/60-features/89-multiplayer.js b/src/game/60-features/89-multiplayer.js new file mode 100644 index 0000000..0d7f487 --- /dev/null +++ b/src/game/60-features/89-multiplayer.js @@ -0,0 +1,188 @@ +/* ================= MULTIPLAYER (docs/MULTIPLAYER.md) ================= + Only in a self-hosted copy built with MP_API (scripts/mp-server.js on the same origin); with MP_API empty nothing here + runs. Players share a session by a six-character code: each builds their own network in the same world (one seed, + one rules preset), each network's save is also kept on the server (so it can move to another device), and a small + public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing + when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq, sim?}; the secret token is never in + S (saves get exported and shared): it lives in this browser's storage, sot-mp::. */ +const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i; +// Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive +// request (the page is going away) carries at most 64 KiB, so only a small save goes with it (MP_KEEP bytes of request, +// with room to spare), else the card alone. +const MP_GAP=15000,MP_POLL=5000,MP_KEEP=63000,MP_GZ=32768,MP_FEED=['join','leave','t2','t1','t1first','chat']; +/* cur: the push on its way ({cut, ac}); staleSeq: the server's number when it said it has a newer save; sig: what the + last push that landed looked like (mpSig); force: the player chose to keep this save; now: push at the next save. */ +const MP={roster:null,day:-1,last:-1e9,busy:false,cur:null,stale:false,staleSeq:0,gone:false,leaving:false,wait:0,fails:0,told:false,poll:null,sig:'',force:false,now:false}; +const mpIs=()=>!!(MP_API&&S&&S.mp&&!pzOn()); +const mpShow=c=>c.slice(0,3)+'-'+c.slice(3); +// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code, or null. I, L and O read as 1, 1 and 0 (Crockford's base32). +function mpNorm(s){if(typeof s!=='string'||s.length>20)return null;const c=s.toUpperCase().replace(/[\s-]/g,'').replace(/[IL]/g,'1').replace(/O/g,'0');return MP_CODE.test(c)?c:null;} +const mpPath=(m,p)=>'/sessions/'+m.code+(p||''); +const mpTokK=(c,p)=>'sot-mp:'+c+':'+p; +function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;const t=lsGet(mpTokK(m.code,m.pid));return typeof t==='string'&&MP_TOK.test(t)?t:null;} +function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}} +// The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses. +const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64); +// sim:1, a network the session server runs (its days happen there, this page shows them). Only a page built with the +// server's client (src/game/98-server-play/, MP builds) says yes here; everywhere else this one stays. +function srvOn(){return false;} +function mpSanitize(s){const m=s.mp; + if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;} + s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall', + color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0),...(m.sim===1?{sim:1}:{})};} +// What the server said when a session started or someone joined: checked before it becomes S.mp. +function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null; + return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};} +/* One call to the session server. Same origin, never cached; a call that takes over 15 s gives up. Rejects with + {status, j} on an HTTP error, so callers can tell "no such session" from "server away". */ +function mpReq(method,p,body,o={}){ + if(!MP_API||typeof fetch!=='function')return Promise.reject(Object.assign(new Error('off'),{status:0})); + const h={};if(body!==undefined)h['content-type']='application/json'; + // o.tok: a token not stored yet (a #mp= link's, until the server takes it). + if(o.auth){const t=o.tok||mpTok(o.auth);if(!t)return Promise.reject(Object.assign(new Error('no token'),{status:401}));h.authorization='Bearer '+o.auth.pid+'.'+t;} + const ac=o.keep?null:o.ac||(typeof AbortController==='function'?new AbortController():null),tm=ac?setTimeout(()=>ac.abort(),15000):0; + let f;try{f=fetch(MP_API+p,{method,headers:h,body:body===undefined?undefined:typeof body==='string'?body:JSON.stringify(body),cache:'no-store',credentials:'same-origin',...(o.keep?{keepalive:true}:{}),...(ac?{signal:ac.signal}:{})});} + catch(e){clearTimeout(tm);return Promise.reject(Object.assign(e,{status:0}));} + return Promise.resolve(f).then(r=>Promise.resolve(r.json?r.json():null).catch(()=>null).then(j=>{clearTimeout(tm);if(!r.ok)throw Object.assign(new Error(j&&j.error||'HTTP '+r.status),{status:r.status,j});return j;}), + e=>{clearTimeout(tm);throw Object.assign(e||new Error('failed'),{status:e&&e.status||0});});} +/* The public card: what the leaderboard shows (and what peering between players will need later). */ +function mpCard(){let t1=false,tl='Tier 3';try{t1=isTier1();tl=tierLabel();}catch(e){} + const tier=tl==='Tier 1'?'t1':tl==='Tier 2'?'t2':'t3',pairs=new Map(); + for(const l of S.links){if(l.ready>S.day)continue;const k=l.ab[1]-a[1]).slice(0,300).map(([k,g])=>{const [a,b]=k.split('|');return [a,b,Math.round(g)];}); + const served=R.served||0; + return {day:S.day,name:S.name,asn:S.asn,tier,t1,lvl:S.lvl||1,pops:Object.keys(S.pops).slice(0,500),links,ix:Object.keys(S.ixp).slice(0,500),transit:[...new Set(S.transit.map(t=>t.net))].slice(0,64), + ppol:ppol(),reach:Math.round((R.reach||0)*1e4)/1e4,peak:Math.round((S.stats.peak||0)*10)/10,served:Math.round(served*10)/10,cust:S.biz.length,rev:Math.round(R.revMo||0), + cashB:S.cash<0?-1:Math.min(20,Math.floor(Math.log10(Math.max(1,S.cash)))),score:(t1?2e9:tier==='t2'?1e9:0)+Math.round(served)};} +/* Other players' data, as it comes back: the same whitelist the server keeps, and every id checked against our own + catalogs. Names and chat stay text: everything that shows them escapes them. */ +function mpCardOk(c){if(!c||typeof c!=='object'||Array.isArray(c))return null; + const n=(v,lo,hi)=>{v=+v;return Number.isFinite(v)?Math.min(hi,Math.max(lo,v)):0;},L=(v,ok,max)=>Array.isArray(v)?[...new Set(v.filter(ok))].slice(0,max):[]; + return {day:Math.round(n(c.day,0,1e7)),tier:['t1','t2','t3'].includes(c.tier)?c.tier:'t3',t1:c.t1===true,lvl:Math.round(n(c.lvl,0,99)),pops:L(c.pops,isCity,500), + links:(Array.isArray(c.links)?c.links:[]).filter(l=>Array.isArray(l)&&isCity(l[0])&&isCity(l[1])&&l[0]!==l[1]).slice(0,300).map(l=>[l[0],l[1],n(l[2],0,1e7)]), + ix:L(c.ix,isIx,500),transit:L(c.transit,isNet,64),ppol:PPOL.includes(c.ppol)?c.ppol:'open',reach:n(c.reach,0,1),peak:n(c.peak,0,1e9),served:n(c.served,0,1e9), + cust:Math.round(n(c.cust,0,1e7)),rev:n(c.rev,-1e13,1e13),cashB:Math.round(n(c.cashB,-1,20)),score:n(c.score,0,1e15)};} +function mpRosterOk(j){if(!j||typeof j!=='object'||Array.isArray(j)||!Array.isArray(j.players))return null; + const txt=(v,max)=>typeof v==='string'?v.slice(0,max):''; + const players=j.players.filter(p=>p&&typeof p==='object'&&MP_PID.test(p.pid)).slice(0,12).map(p=>({pid:p.pid,name:txt(p.name,32),asn:int(p.asn,0,4294967294,0), + color:typeof p.color==='string'&&MP_COL.test(p.color)?p.color:'#888888',card:mpCardOk(p.card),seen:num(p.seen,0),joined:num(p.joined,0)})); + const feed=(Array.isArray(j.feed)?j.feed:[]).filter(f=>f&&typeof f==='object'&&MP_FEED.includes(f.k)).slice(-100).map(f=>({k:f.k,pid:MP_PID.test(f.pid)?f.pid:'',name:txt(f.name,32),at:num(f.at,0),text:f.k==='chat'?txt(f.text,200):''})); + return {code:MP_CODE.test(j.code)?j.code:'',title:txt(j.title,40),preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',players,feed};} +// Tier 1 first, then Tier 2, then whoever serves the most traffic; players who never pushed a card last. +const mpTierN=c=>c?(c.t1?3:c.tier==='t2'?2:1):0; +function mpRank(ps){return ps.slice().sort((a,b)=>mpTierN(b.card)-mpTierN(a.card)||(b.card?b.card.served:0)-(a.card?a.card.served:0)||(b.card?b.card.peak:0)-(a.card?a.card.peak:0)||a.joined-b.joined);} +/* ---------- staying in step with the server ---------- */ +function mpOk(roster){MP.fails=0;MP.wait=0;if(MP.told)MP.told=false;const r=mpRosterOk(roster);if(r)MP.roster=r;if(MP_API)mpHud();mpPanelUpdate();} +/* The server is away: back off (30 s, 1, 2, 4 min, at most 5), say so once, and keep playing. Too many pushes at once + (429: another one still on its way, or too often; 503 busy: too many uploads on the server right now) is not "away": + wait a little, quietly. The session panel's own refresh (poll) runs every few seconds while it is open: it may say + the server is away, but never stretches the wait. */ +function mpFail(e,poll){const st=e&&e.status; + if((st===401||st===404)&&S&&S.mp){MP.gone=true;toast(tr('mp.not_in_session'),'bad',[{l:tr('mp.session'),act:'mpOpen',args:{}}]);return;} + if(st===429||st===503&&e.j&&e.j.busy===true){MP.wait=performance.now()+MP_GAP*2;return;} + if(!poll||!MP.fails){MP.fails++;MP.wait=performance.now()+Math.min(300000,MP_GAP*2**MP.fails);} + if(!MP.told){MP.told=true;toast(tr('mp.server_away'),'bad');}} +const mpHid=()=>MP.leaving||document.visibilityState==='hidden'; +// What a save looks like, in a few characters (FNV-1a and the length): a page hidden on the same game day pushes only +// when something changed since the last push. +function mpSig(t){let h=0x811c9dc5;for(let i=0;i>>0).toString(36)+'.'+t.length;} +// The request's size in bytes (UTF-8), which is what the keepalive limit counts. +function mpBytes(t){let n=t.length;for(let i=0;i127)n+=c>2047&&(c<0xd800||c>0xdfff)?2:1;}return n;} +/* Does this save go to the server too? 1: yes; 2: if it changed since the last push (the page is being hidden, or the + player asked, on the same game day); 0: no. A push goes on a new game day at most every MP_GAP; at once when the page + is hidden or closed, when the player chose to keep this save (MP.force) or asked for it (MP.now). Never mid-day or in + a puzzle: save() returns before then. */ +function mpDue(){if(!mpIs()||MP.stale||MP.gone||S.lost)return 0; + const hid=mpHid(),now=performance.now(); + // One push at a time, except when the page goes away: that one cuts the one on its way short (mpPush). + if(MP.busy&&!hid)return 0; + const ask=MP.now;MP.now=false; + if(MP.force&&(hid||now>=MP.wait))return 1; + if(S.day===MP.day)return hid||ask?2:0; + return hid||ask||(now-MP.last>=MP_GAP&&now>=MP.wait)?1:0;} +/* save()'s text for a network in a session, and its push when one is due. The number the server will keep it under is + picked before the text is made, so the save here and the one on the server carry the same: reopening this device + then knows the server has nothing newer. A push that fails leaves this one ahead, which the server accepts. */ +function mpSave(st){let d=mpDue();if(d===1)S.mp.seq=(S.mp.seq||0)+1;let txt=JSON.stringify(packSave(st)); + if(d===2){if(mpSig(txt)===MP.sig)d=0;else{S.mp.seq=(S.mp.seq||0)+1;txt=JSON.stringify(packSave(st));}} + if(d)mpPush(txt);return txt;} +/* Sends that save (it carries S.mp.seq), gzipped when big, with the card. When the page is being hidden or closed it + goes at once, as a keepalive request: the save when the request fits in one, else the card alone. */ +function mpPush(txt){if(!mpIs()||MP.stale||MP.gone||S.lost)return; + const m=S.mp,day=S.day,seq=m.seq||0,hid=mpHid(),force=MP.force,me={cut:false,ac:null};let card;try{card=mpCard();}catch(e){card=undefined;} + // A push still on its way while the page goes away with a newer save: that one is cut short, this one goes. + if(MP.cur){MP.cur.cut=true;try{if(MP.cur.ac)MP.cur.ac.abort();}catch(e){}} + MP.cur=me;MP.busy=true;MP.last=performance.now(); + const sig=mpSig(txt),body=data=>({seq,at:Date.now(),data,card,...(force?{force:true}:{})}); + // Only a save that went counts as this day's push; a card alone does not. + const done=j=>{if(me.cut)return;if(j&&j.seq!==undefined&&S&&S.mp===m){m.seq=Math.max(m.seq||0,int(j.seq,0,1e15,seq));MP.day=day;MP.sig=sig;if(force)MP.force=false;}mpOk(j&&(j.roster||j));}; + const bad=e=>{if(me.cut)return;if(e&&e.status===409&&S&&S.mp===m){MP.stale=true;MP.staleSeq=int(e.j&&e.j.seq,0,1e15,seq);mpStaleTell();}else mpFail(e);}; + const fin=()=>{if(MP.cur===me){MP.cur=null;MP.busy=false;}}; + const send=(p,b,keep)=>{if(me.cut)return;if(!keep&&typeof AbortController==='function')me.ac=new AbortController(); + mpReq('PUT',mpPath(m,p),b,{auth:m,keep,ac:me.ac}).then(done,bad).finally(fin);}; + if(hid){const b=txt.lengthsend('/save',body(data),false); + if(txt.length>=MP_GZ&&gzOk())gzip(txt).then(go,()=>go(txt));else go(txt);} +// The page is going away (pagehide comes before save()'s own handler, which then pushes as a keepalive request). +if(MP_API){addEventListener('pagehide',()=>{MP.leaving=true;});addEventListener('pageshow',()=>{MP.leaving=false;});} +function mpStaleTell(){toast(tr('mp.moved_on_elsewhere'),'bad',[{l:tr('mp.load_newer'),act:'mpNewer',args:{}},{l:tr('mp.keep_mine'),act:'mpKeep',args:{}}]);} +// Pushes this network's save now if it changed since the last push (before a link to another device is handed out). +function mpSyncNow(){if(!mpIs())return;MP.now=true;save(true);} +// The server's save text as a game state: unzipped, parsed, and only if it is this very network. +function mpUnpack(data){if(typeof data!=='string')return Promise.reject(new Error('no save')); + return (data.startsWith(GZ)?gunzip(data):Promise.resolve(data)).then(t=>JSON.parse(t));} +function mpSaveOk(s,m){if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links)||s.lost)return false; + if(!Object.keys(s.pops).every(isCity))return false;return !!(s.mp&&s.mp.code===m.code&&s.mp.pid===m.pid);} +/* Opening a network of a session: if another device played on and pushed a newer save, that one is loaded instead. + Nothing is pushed until the answer is in. */ +function mpResume(){if(!mpIs())return;const m=S.mp;mpReset({day:S.day,last:performance.now(),busy:true});mpHud(); + // A push of the page going away meanwhile is its own: only an answer to this question frees the next one. + const free=()=>{if(!MP.cur)MP.busy=false;}; + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{free();if(S&&S.mp===m&&j&&int(j.seq,0,1e15,0)>(m.seq||0))mpAdopt(j,m);else mpRefresh();}, + e=>{free();if(e&&e.status===404&&S&&S.mp===m)mpRefresh();else mpFail(e);});} +// A network of a session opened or started: nothing from another one carries over (a push still on its way is forgotten). +function mpReset(o){if(MP.cur)MP.cur.cut=true;Object.assign(MP,{roster:null,cur:null,busy:false,stale:false,staleSeq:0,gone:false,fails:0,wait:0,told:false,sig:'',force:false,now:false},o);} +function mpAdopt(j,m,n=0){if(!S||S.mp!==m)return; + // A day still routing in the worker finishes first. + if(RW.job){if(n<50)setTimeout(()=>mpAdopt(j,m,n+1),100);return;} + mpUnpack(j.data).then(s=>{if(!S||S.mp!==m||!mpSaveOk(s,m))throw new Error('not this network');delete s.sv;const nx=migrate(s);nx.mp.seq=int(j.seq,0,1e15,0); + S=nx;compute();UI.sel=null;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);Object.assign(MP,{stale:false,staleSeq:0,force:false,day:S.day,last:performance.now()}); + renderAll();save(true);toast(tr('mp.loaded_newer',{name:esc(S.name),date:dateStr(S.day)}),'good');mpRefresh();}) + .catch(e=>{console.error('[tubes] loading the session save failed',e);toast(tr('mp.save_unreadable'),'bad');});} +function mpRefresh(poll){if(!mpIs()||MP.gone)return Promise.resolve();const m=S.mp;return mpReq('GET',mpPath(m),undefined,{auth:m}).then(mpOk,e=>mpFail(e,poll));} +/* ---------- a link to the same network on another device ---------- + /#mp=..: the fragment never reaches a server. At boot (before the slots are picked) the save + is fetched into a new slot, or the one this browser already has for that network is opened (one open in another tab + too: slotBoot then offers to take it over), and the fragment is cleared. The link's token is stored only once the + server took it: a wrong or old link never replaces nor deletes the one this browser already has. */ +const mpLink=m=>{const t=mpTok(m);return t?location.origin+location.pathname+'#mp='+m.code+'.'+m.pid+'.'+t:'';}; +// "Send to another device" (#263) for a network of a session (e: its slot entry): the link it sends is this one, so the +// network carries on in the session as the same player; a save file stays a copy that plays on alone elsewhere (no +// token goes with it). Without the token here, no link at all. null for any other network, and in every other build. +function mpXfer(e){if(!MP_API||!e||typeof e.mp!=='string')return null;const m={code:e.mp.slice(0,6),pid:e.mp.slice(7)}; + return MP_CODE.test(m.code)&&MP_PID.test(m.pid)?{code:m.code,link:mpLink(m)||null}:null;} +function mpBoot(go){const hash=String(location.hash||''),h=MP_API?/^#mp=([0-9A-Za-z-]{6,8})\.([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(hash):null; + if(!h){go();return;} + try{history.replaceState(null,'',location.pathname+location.search);}catch(e){} + const code=mpNorm(h[1]),m={code,pid:h[2]},tok=h[3],fin=b=>{UI.mpBoot=b;go();}; + if(!code){fin({bad:1});return;} + const had=mpTok(m),keep=()=>{if(had!==tok)mpTokSet(code,m.pid,tok);}; + // The server is away (or busy): the link may be fine, so it stays in the address bar for a reload to try again. + const no=e=>{console.error('[tubes] moving the network here failed',e);const st=e&&e.status,away=st===0||st===429||st>=500; + if(away)try{history.replaceState(null,'',location.pathname+location.search+hash);}catch(x){}fin(away?{away:1}:{bad:1});}; + const ex=slotIdx(true).find(e=>e.mp===code+'.'+m.pid&&!e.broken); + if(ex){const open=()=>{ssSet(SLOT_SS,ex.id);fin({code});}; + // Opening it fetches the server's save when that one is newer. A link with another token is asked about first. + if(had===tok)open();else mpReq('GET',mpPath(m),undefined,{auth:m,tok}).then(()=>{keep();open();},no);return;} + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m,tok}).then(j=>mpUnpack(j&&j.data).then(s=>{if(!mpSaveOk(s,m))throw new Error('not this network'); + delete s.sv;s.mp.seq=int(j.seq,0,1e15,0);const txt=JSON.stringify(s);return (txt.length>=GZ_MIN&&gzOk()?gzip(txt):Promise.resolve(txt)).then(data=>{ + const id=slotRid();localStorage.setItem(SLOT_K+id,data);keep(); + slotIdxPut(slotIdx(true).filter(x=>x.id!==id).concat([slotClean({id,...slotMeta(s,null),seq:1,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})]));ssSet(SLOT_SS,id);});})) + .then(()=>fin({code}),no);} +// Said once the game is on screen (or the title is). +function mpBootTell(){const b=UI.mpBoot;if(!b)return;UI.mpBoot=null; + if(b.bad)toast(tr('mp.link_bad'),'bad');else if(b.away)toast(tr('mp.err_offline'),'bad'); + else if(S&&S.mp&&S.mp.code===b.code)toast(tr('mp.welcome_device',{name:esc(S.name),code:mpShow(b.code)}),'goal');} diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js new file mode 100644 index 0000000..ae0ba88 --- /dev/null +++ b/src/game/60-features/90-automation.js @@ -0,0 +1,37 @@ +/* The sales engine of #185: would this offer work if signed now? The sales desk runs it once a day (39-sales-auto.js). + It trials the new demand on a copy of the game, so a failed trial leaves the live game untouched. */ +// Every field a reloaded save gives a customer (sanitize, unpackBiz), so live S is what a reload makes of it. +function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined,warned:false,warn60:false,pm:100};} +// OFFER_TRIED: the answer of a trial the intern's sales order already ran for this offer (the customer, or null). +let OFFER_TRIED=null; +function autoOffer(o){if(OFFER_TRIED&&OFFER_TRIED.o===o)return OFFER_TRIED.b;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;} +// The checks on the live game, and the customer the offer would be: null when there is nothing to trial. +function offerTrialOf(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null; + const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; + if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null; + if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id; + if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;} + return b;} +const offerFuture=()=>S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day); +// Who is happy today (indices in S.biz), the one thing the trial reads from the live result: null when future events +// make the trial route without the offer first and judge on that. +const offerHealthy=b=>{if(offerFuture())return null;const h=[];S.biz.forEach((x,i)=>{if(!bizWhy(x).length)h.push(i);});return h;}; +/* The trial: the game routed with the customer added, on a copy, S and R put back after. It reads nothing else of the + live result than hx (offerHealthy()), so the route worker can run it on the game it is sent (28-route-worker.js). */ +function offerTrial(b,hx){const T=BIZ_T[b.type],start=b.start; + const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day); + // Trial the added demand before signing; failed trials leave the live game untouched. + try{S={...S,biz:S.biz}; + // shortcut: future events reserve capacity together; use per-date trials if separate bookings must share capacity. + if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x); + /* Signed if the offer works and nobody who works without it breaks. compute() reads the last result only for + scenic circuits, so without them the pass with the offer can go first: when the offer fails, or nobody is + unhappy with it, the pass without it cannot change the answer and is skipped. */ + const fut=S.biz,all=fut.concat(b); + if(!all.some(x=>x.route==='scenic')){if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=all;compute();if(bizWhy(b).length)return null; + const bad=fut.filter(x=>bizWhy(x).length);if(!bad.length)return b;S.biz=fut;compute();return bad.every(x=>bizWhy(x).length)?b:null;} + compute();} + const healthy=hx&&!future?hx.map(i=>S.biz[i]):S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); + return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null; + }finally{S=state;R=result;UI.hotMap=hot;b.start=start;if(T.cap)delete b.live;}} diff --git a/src/game/60-features/90-puzzles-data.js b/src/game/60-features/90-puzzles-data.js new file mode 100644 index 0000000..b9c611e --- /dev/null +++ b/src/game/60-features/90-puzzles-data.js @@ -0,0 +1,42 @@ +/* Puzzles: one entry per line, in play order. A puzzle is data: + id, pack, n (name), j (one-line joke), src (the content origins: eyeballs pull from the nearest), dem (the traffic: + {t:'eye',a,g} eyeballs in city a want g Gbps; {t:'l2',a,b,g,ms} a circuit of g Gbps between a and b, under ms + milliseconds one way; be:1 marks a flow best effort, which may drop when something is cut), via (suggested stepping + stones), budget (setup + a year of monthly, 0 = no budget star to chase: it is given), and at most a twist: + noSub (no subsea cables), ring (one ring through every POP), avoid (cities you may not build in). + Each pack teaches one idea; the budgets sit a little above the cheapest 3-star build found (tests/puzzles.test.js). */ +const PZ_PACKS=[ + {id:'hello',n:tr('puzzles.fat_pipes'),d:tr('puzzles.capacity_first_every_link_has_a'),need:0}, + {id:'rodeo',n:tr('puzzles.router_rodeo'),d:tr('puzzles.routers_have_ports_and_a_limit'),need:10}, + {id:'cops',n:tr('puzzles.traffic_cops'),d:tr('puzzles.your_routers_pick_the_path'),need:18}, + {id:'n1',n:tr('puzzles.n_1_club'),d:tr('puzzles.survive_any_single_cut_with_the'),need:26}, + {id:'final',n:tr('puzzles.grand_tour'),d:tr('puzzles.everything_at_once_across_oceans'),need:36}, +]; +const PZ=[ + {id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),src:['nyc'],dem:[{t:'eye',a:'lon',g:8}],budget:0}, + {id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),src:['ams'],dem:[{t:'eye',a:'lon',g:30},{t:'eye',a:'fra',g:60}],budget:0}, + {id:'bigboat',pack:'hello',n:tr('puzzles.a_bigger_boat'),j:tr('puzzles.paris_wants_150g_one_100g_wave'),src:['fra'],dem:[{t:'eye',a:'par',g:150}],budget:175000}, + {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),src:['nyc'],dem:[{t:'eye',a:'chi',g:40},{t:'eye',a:'dal',g:30},{t:'eye',a:'sjc',g:60}],budget:715000}, + {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),src:['syd'],dem:[{t:'eye',a:'mel',g:50},{t:'eye',a:'bne',g:30},{t:'eye',a:'adl',g:20}],budget:585000}, + {id:'edgelord',pack:'rodeo',n:tr('puzzles.edge_lord'),j:tr('puzzles.london_wants_half_a_terabit_your'),src:['ams'],dem:[{t:'eye',a:'lon',g:500}],budget:240000}, + {id:'hubcap',pack:'rodeo',n:tr('puzzles.hub_cap'),j:tr('puzzles.all_of_europe_s_cat_videos'),src:['lon'],dem:[{t:'eye',a:'ams',g:150},{t:'eye',a:'par',g:150},{t:'eye',a:'fra',g:120}],budget:455000}, + {id:'ports',pack:'rodeo',n:tr('puzzles.port_authority'),j:tr('puzzles.six_cities_a_few_gigs_each'),src:['zrh'],dem:[{t:'eye',a:'mil',g:12},{t:'eye',a:'muc',g:12},{t:'eye',a:'fra',g:12},{t:'eye',a:'par',g:12},{t:'eye',a:'vie',g:12},{t:'eye',a:'prg',g:12}],budget:470000}, + {id:'flash',pack:'cops',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),src:['nyc'],dem:[{t:'l2',a:'nyc',b:'lon',g:10,ms:26},{t:'eye',a:'lon',g:80,be:1}],budget:660000}, + {id:'baltic',pack:'cops',n:tr('puzzles.baltic_shortcut'),j:tr('puzzles.the_road_to_tallinn_is_short'),src:['fra'],dem:[{t:'eye',a:'tll',g:60},{t:'l2',a:'fra',b:'tll',g:10,ms:8.8}],via:['hel'],budget:285000}, + {id:'fjord',pack:'cops',n:tr('puzzles.fjord_focus'),j:tr('puzzles.the_oil_rigs_want_their_numbers'),src:['par'],dem:[{t:'eye',a:'svg',g:30},{t:'l2',a:'par',b:'svg',g:10,ms:7.2}],via:['lon'],budget:265000}, + {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),src:['nyc'],dem:[{t:'eye',a:'lon',g:60},{t:'eye',a:'dub',g:40}],budget:840000}, + {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),src:['lis'],dem:[{t:'eye',a:'mad',g:40},{t:'eye',a:'par',g:60},{t:'eye',a:'mil',g:30}],via:['bcn','mrs'],noSub:true,budget:450000}, + {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),src:['ams'],dem:[{t:'eye',a:'ber',g:50},{t:'eye',a:'muc',g:50},{t:'eye',a:'zrh',g:40}],via:['ham','dus'],avoid:['fra'],budget:390000}, + {id:'fire',pack:'n1',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),src:['tok'],dem:[{t:'eye',a:'hkg',g:20},{t:'eye',a:'sin',g:20},{t:'eye',a:'syd',g:10}],ring:true,budget:4070000}, + {id:'suez',pack:'final',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),src:['fra'],dem:[{t:'l2',a:'fra',b:'sin',g:10,ms:68},{t:'eye',a:'sin',g:30,be:1}],via:['mrs','bom'],budget:1790000}, + {id:'kiwi',pack:'final',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),src:['sea'],dem:[{t:'eye',a:'akl',g:20},{t:'eye',a:'syd',g:40}],via:['hnl','suv','lax'],budget:4200000}, + {id:'samba',pack:'final',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),src:['mia'],dem:[{t:'l2',a:'sao',b:'mia',g:10,ms:45},{t:'eye',a:'sao',g:40},{t:'eye',a:'rio',g:20,be:1}],via:['for'],budget:2655000}, +]; +// Weekly puzzle pools: each is one landmass and one region, so every pair has an overland route. +const PZ_WEEK_POOLS=[ + ['fra','ams','par','mad','mil','ber','waw','vie','sto','cph','prg','zrh','bcn','mrs','muc','bud'], + ['nyc','chi','dal','sea','sjc','lax','mia','ash','atn','den','bos','hou','phx','tor','mtl'], + ['sao','rio','bsb','bhz','cwb','poa','ssa','rec','for','cpq'], + ['syd','mel','bne','adl','cbr','per'], + ['bom','del','maa','blr','hyd'], +]; diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js new file mode 100644 index 0000000..793fce2 --- /dev/null +++ b/src/game/60-features/92-puzzles.js @@ -0,0 +1,169 @@ +/* ================= PUZZLES (#190) ================= + Small, calm builds that carry real traffic: every puzzle has demand (eyeballs pulling from a content origin, circuits + between two cities with a latency cap), and the game's own compute() routes it: metrics, standby, LAGs, router + capacity and ports all behave as in the main game. A puzzle runs as its own S (S.mode='puzzle'): no clock, no bills, + no incidents, links up at once. The demand is ordinary game state, so compute() needs no puzzle cases: an origin is a + transit port (t.pz, which takes no router port), a circuit is an L2VPN customer, eyeballs are broadband with a fixed + demand. That S is never saved. Only progress (stars and best spend per puzzle, weekly results and the weekly streak) + is kept, under its own key, so the main save is never touched. */ +const PZ_KEY='sot-puzzles',PZ_YEAR=12,PZ_SET=2; +const pzOn=()=>!!(S&&S.mode==='puzzle'&&S.pz); +const pzDef=id=>PZ.find(p=>p.id===id)||null; +// goal: a city the traffic starts or ends in; via: a suggested stepping stone; avoid: off limits; off: any other city +// (the whole world is open, it just is not part of the plan). +const pzKind=c=>!pzOn()?null:S.ar?arKind(c):S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':pzCityOk(c)&&(S.pops[c]||pzNear(c))?'off':null; +// The puzzle's area: its cities' box plus a margin. Stepping stones outside it are off the map (a far capital is no use). +function pzArea(){const P=S.pz,k=P.id+'|'+(P.key||'')+'|'+P.cities.join();if(UI.pzArea&&UI.pzArea.k===k)return UI.pzArea; + const cs=[...new Set([...P.cities,...P.via,...P.avoid])].map(c=>CITY[c]).filter(Boolean),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity; + for(const C of cs){const x=x0+wrapDx(x0,C.x);a=Math.min(a,x);b=Math.max(b,x);c=Math.min(c,C.y);d=Math.max(d,C.y);} + const m=20+0.15*Math.max(b-a,d-c);return UI.pzArea={k,x0,a:a-m,b:b+m,c:c-m,d:d+m};} +const pzNear=c=>{const A=pzArea(),C=CITY[c],x=A.x0+wrapDx(A.x0,C.x);return x>=A.a&&x<=A.b&&C.y>=A.c&&C.y<=A.d;}; +// Not drawn at all: Architect's cities outside the run, a puzzle's cities outside its area. +const pzHide=c=>pzOn()&&!pzKind(c); +// A stepping stone with no part to play yet is a quiet dot with no name, until it is picked, used or zoomed in on +// (twice the zoom the puzzle opened at: a phone and a desktop open at very different zooms). +const pzQuiet=c=>pzKind(c)==='off'&&!S.pops[c]&&cam.z<2*(UI.pzZ0||1)&&!(UI.sel&&UI.sel.id===c)&&UI.hover!==c&&!(UI.snap&&UI.snap.id===c)&&!(UI.drag&&UI.drag.from===c)&&!(UI.pending&&(UI.pending.a===c||UI.pending.b===c)); +const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key',{key:d.key})):d.n; +const pzStarStr=n=>'⭐'.repeat(n)+'⬜'.repeat(3-n); +// Every city a puzzle's traffic touches, origins first. +const pzCities=d=>[...new Set([...(d.src||[]),...d.dem.flatMap(f=>f.t==='l2'?[f.a,f.b]:[f.a])])]; +// ---------- progress (localStorage, never trusted) ---------- +// `set` is the puzzle set the stars belong to: the set with traffic (2) started again, and the stars won before hang +// framed on the wall (`old`), with a note shown once (`noted`). Weekly results and the streak carry on. +function pzClean(j){const o={set:PZ_SET,s:{},wk:{},streak:{last:null,n:0,best:0},old:null,noted:1};if(!j||typeof j!=='object')return o; + const rec=r=>{if(!r||typeof r!=='object')return null;const o={st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)},rv=int(r.rv,1,999,1);if(rv>1)o.rv=rv;return o;}; + const cur=j.set===PZ_SET; + if(j.s&&typeof j.s==='object'){if(cur){for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;}} + else{let n=0;for(const k of Object.keys(j.s).slice(0,200)){const r=rec(j.s[k]);if(r&&/^[a-z0-9]{1,20}$/.test(k))n+=r.st;}if(n){o.old=n;o.noted=0;}}} + if(cur){o.old=j.old==null?null:int(j.old,0,9999,0)||null;o.noted=j.noted?1:0;if(o.old==null)o.noted=1;} + if(j.wk&&typeof j.wk==='object')for(const k of Object.keys(j.wk)){const r=rec(j.wk[k]);if(/^\d{4}-W\d{2}$/.test(k)&&r)o.wk[k]=r;} + const st=j.streak;if(st&&typeof st==='object'){o.streak.last=typeof st.last==='string'&&/^\d{4}-W\d{2}$/.test(st.last)?st.last:null;o.streak.n=int(st.n,0,9999,0);o.streak.best=int(st.best,0,9999,0);} + return o;} +// A weekly's stars belong to the revision they were earned on: a week regenerated for new prices starts again. +const pzWkRec=(p,d)=>{const r=p.wk[d.key];return r&&(r.rv||1)===(d.rev||1)?r:null;}; +function pzLoad(){try{return pzClean(JSON.parse(localStorage.getItem(PZ_KEY)||'{}'));}catch(e){return pzClean(null);}} +function pzStore(p){try{localStorage.setItem(PZ_KEY,JSON.stringify(p));}catch(e){}} +const pzStarsTotal=p=>PZ.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0); +const pzPackOpen=(k,p)=>{const P=PZ_PACKS.find(x=>x.id===k);return !!P&&pzStarsTotal(p||pzLoad())>=P.need;}; +// ---------- prices: the real game's waves and routers, on day 0, for a year ---------- +const pzMood=(a,b,sub)=>{const k=waveMarket(a,b,sub);return k.m/k.ero;}; +// Overland (when the two cities share a landmass) and every cable between them, each with its price factor and latency. +function pzRoutes(a,b){const out=[],sub=isSub(a,b); + if(!sub){const km=kmBetween(a,b);out.push({via:'land',cab:null,km,sub:false,f:landMult(a,b)*pzMood(a,b,false),ms:km*1.3/200});} + for(const c of cablesFor(a,b))if(!out.some(r=>r.via===c.cid))out.push({via:c.cid,cab:c.cid,km:c.km,sub:true,f:CAB[c.cid].price*pzMood(a,b,true),ms:c.km*(CAB[c.cid].lat||1)/200}); + return out;} +const pzMo=(r,tier,div)=>Math.round(waveMo(r.km,r.sub,tier)*r.f*(div?DIVERSE:1)); +const pzLinkCost=(r,tier,div)=>pzMo(r,tier,div)*PZ_YEAR;// leased waves have no setup fee: a year of rent +const pzPopCost=c=>popCost(c)+PZ_YEAR*popMo(c);// thin markets cost more every month too (#94) +// 10G to 800G: an 800G wave needs an 800G router at both ends, as in the main game. +const PZ_TIERS=[0,1,2,3]; +// Router models on offer: the main game's catalogue up to its level-3 gear, cheapest class first. +const PZ_RG=RG.map((r,i)=>i).filter(i=>RG[i].lvl<=3&&!RG[i].noPz).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cost-RG[b].cost); +// A POP's routers for a year: the chassis (the first Rusty Router is free), each extra one as the main game prices it +// (#157 cages included), and their rent. +function pzRtCost(g,rt){let s=Math.round(RG[g].cost*hwMul('rt'));for(let k=1;k{const p=S.pops[c];return p?pzRtCost(p.rgen||0,p.routers||1):0;}; +function pzSpend(){let s=0;for(const c in S.pops)s+=pzPopCost(c)+pzRouterCost(c);for(const l of S.links)s+=l.mo*PZ_YEAR;return s;} +// What one backhoe or one anchor takes out: waves in the same trench, or every wave on the same cable (a cable fails +// as a whole, as in the main game's diversity checks). +const pzUnit=l=>l.cable?'cab:'+l.cable:String(l.trench||l.id); +// ---------- the traffic ---------- +// Origins are transit ports the size of a content farm; circuits are L2VPN customers; eyeballs come with their POP. +const PZ_NET='lvl',PZ_ORIG=5; +const pzFlowId=i=>'pzf'+i; +const pzFlowName=f=>f.t==='l2'?tr('puzzles.flow_circuit_a_b',{a:CITY[f.a].name,b:CITY[f.b].name}):tr('puzzles.flow_eyeballs_in_city',{city:CITY[f.a].name}); +function pzDemand(){const P=S.pz;S.transit=P.src.map((c,i)=>({id:'pzo'+i,city:c,net:PZ_NET,tier:PZ_ORIG,n:1,pz:1,pref:'normal',hist:[]})); + S.biz=P.dem.map((f,i)=>f.t==='l2'?{id:pzFlowId(i),type:'l2vpn',name:pzFlowName(f),city:f.a,city2:f.b,bw:f.g,rate:0,route:'normal',reqs:[],day:0}:null).filter(Boolean);} +const pzEye=c=>{const f=pzOn()&&S.pz.dem.find(x=>x.t==='eye'&&x.a===c);return f?f.g:0;}; +const pzNewPop=c=>{const g=pzEye(c);return {day:0,bb:g?{d:g}:null,boost:0,down:0,routers:1,gen:false,br:S.ar?S.ar.bi:0};}; +// What each flow gets from the last compute(): Gbps delivered, and a circuit's latency. +// Eyeball traffic to networks behind the Great Firewall loses a fifth at the border, as in the main game; that is not +// the player's doing, so a puzzle counts what crosses the border as delivered (pzGfw: the share that arrives). +let PZ_GFW=null;const pzGfw=()=>PZ_GFW||(PZ_GFW=1-0.2*NETS.filter(n=>n.cn).reduce((a,n)=>a+(NSH[n.id]||0),0)); +function pzGot(){return S.pz.dem.map((f,i)=>f.t==='l2'?{g:R.l2[pzFlowId(i)]||0,ms:isFinite(R.l2lat[pzFlowId(i)])?R.l2lat[pzFlowId(i)]:null}:{g:S.pops[f.a]?(R.citySrv[f.a]||0)/pzGfw():0,ms:null});} +const pzFull=(f,x)=>x.g>=f.g*0.999-1e-6; +const pzFast=(f,x)=>!f.ms||(x.ms!=null&&x.ms<=f.ms+1e-9); +// ---------- checks ---------- +function pzRingOk(ls){const nb={};for(const l of ls){(nb[l.a]=nb[l.a]||new Set()).add(l.b);(nb[l.b]=nb[l.b]||new Set()).add(l.a);} + const ns=Object.keys(nb);if(ns.length<3||!S.pz.cities.every(c=>nb[c])||!Object.keys(S.pops).every(c=>nb[c])||!ns.every(c=>nb[c].size===2))return false; + let prev=null,cur=ns[0],n=0;do{const nx=[...nb[cur]].find(x=>x!==prev);prev=cur;cur=nx;n++;}while(cur!==ns[0]&&n<=ns.length);return cur===ns[0]&&n===ns.length;} +// The same build always gets the same answer, so pzEval() keeps the last one (it routes once, then once per cut). +const pzSig=()=>JSON.stringify([S.pops,S.links,S.pairMet||null,S.biz.map(b=>b.route),S.pz.budget]); +/* ⭐ every flow delivered in full (circuits within their latency cap), and the twists; ⭐⭐ the year's spend within + budget; ⭐⭐⭐ N-1 under load: whichever single trench or cable is cut, every priority flow still gets all of its traffic + (best-effort flows may drop). The cut is routed by compute() like the real thing. */ +function pzEval(){const sig=pzSig(),c0=UI.pzEv;if(c0&&(c0.sig===sig||UI.pzMk))return c0.e;// mid-scene the monkey's cuts are not the build + const P=S.pz,hot=UI.hotMap;compute();const R0=R,got=pzGot(),spend=pzSpend(),peak={},pk=()=>{for(const c in R.nodeLoad)peak[c]=Math.max(peak[c]||0,R.nodeLoad[c]);};pk(); + const flows=P.dem.map((f,i)=>({f,i,g:got[i].g,ms:got[i].ms,full:pzFull(f,got[i]),fast:pzFast(f,got[i])})); + const tw=[];if(P.noSub)tw.push({k:'sub',ok:!S.links.some(l=>l.sub)}); + if(P.ring)tw.push({k:'ring',ok:pzRingOk(S.links)}); + if(P.avoid.length)tw.push({k:'avoid',ok:P.avoid.every(c=>!S.pops[c])}); + const del=flows.every(x=>x.full&&x.fast),goal=del&&tw.every(t=>t.ok),units=[...new Set(S.links.map(pzUnit))],cuts=[]; + if(goal)try{for(const u of units){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1; + try{compute();pk();const g=pzGot(),lost=[];P.dem.forEach((f,i)=>{if(!f.be&&!pzFull(f,g[i]))lost.push({i,g:Math.max(0,f.g-g[i].g)});});if(lost.length)cuts.push({u,lost,g:lost.reduce((a,x)=>a+x.g,0)});} + finally{for(const l of ls)l.cut=0;}}} + finally{R=R0;UI.hotMap=hot;} + cuts.sort((a,b)=>b.g-a.g); + const n1=goal&&units.length>0&&!cuts.length,cheap=!P.budget||spend<=P.budget; + const e={flows,del,tw,goal,spend,cheap,n1,weak:cuts.map(x=>x.u),worst:cuts[0]||null,peak,stars:goal?1+(cheap?1:0)+(n1?1:0):0}; + UI.pzEv={sig,e};return e;} +// ---------- the seeded weekly puzzle: the same for everyone, and the stand-in when the published one (93-puzzles-weekly.js) is not there ---------- +function pzWeekly(dt){const key=pzWeekKey(dt||new Date());let r=hstr('puzzle|'+key)||1;const nx=()=>{r=(Math.imul(r,1103515245)+12345)>>>0;return r/4294967296;}; + const pool=PZ_WEEK_POOLS[Math.floor(nx()*PZ_WEEK_POOLS.length)].slice(),n=4+Math.floor(nx()*2),cities=[]; + while(cities.lengthkmBetween(u,a)-kmBetween(u,b));ring.push(left.shift());} + let cost=cities.reduce((a,c)=>a+pzPopCost(c),0);const used=new Set(),via=[]; + for(let i=0;i!x.cab||!used.has(x.cab)).sort((x,y)=>pzLinkCost(x,0,false)-pzLinkCost(y,0,false))[0]; + if(r.cab)used.add(r.cab);via.push(r.via);cost+=pzLinkCost(r,0,false);} + const g=Math.floor(9/(n-1)),dem=cities.slice(1).map(c=>({t:'eye',a:c,g})); + return {id:'weekly',key,cities,src:[cities[0]],dem,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring,refVia:via};} +function pzStreak(p,key){const st=p.streak;if(st.last===key)return;st.n=st.last&&st.last===pzPrevKey(key)?st.n+1:1;st.last=key;st.best=Math.max(st.best,st.n);} +function pzShareText(e){const P=S.pz;return tr('puzzles.share_line',{what:P.id==='weekly'?P.key:pzName(pzDef(P.id)),stars:pzStarStr(e.stars),spend:fmt$(e.spend)});} +// ---------- entering and leaving ---------- +// Toasts from one world never carry over into the other (their buttons act on the S they came from). +const pzToastsClear=()=>{$('toasts').textContent='';}; +// The running game gets its usual save first and is kept in memory, set aside: save() keeps writing it to its slot +// (leaving the page mid-puzzle), and leaving the puzzle picks it up again. +function pzFlush(){save(true);UI.pzKeep=S;} +function pzBegin(def){if(!def)return;pzMkStop();mkStop(); + const go=()=>{const cs=pzCities(def);newGame(pzName(def),cs[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null; + S.pz={id:def.id,key:def.key||null,cities:cs,src:(def.src||[]).slice(),dem:def.dem.map(f=>({t:f.t,a:f.a,b:f.t==='l2'?f.b:null,g:f.g,ms:f.ms||0,be:!!f.be})), + via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null,rev:def.rev||1}; + pzDemand(); + UI.pzHist=[];UI.pzTop=0;UI.pzEv=null;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null; + $('dash').hidden=true;$('bankBox').hidden=true;closeModal();pzToastsClear();document.body.classList.add('pz'); + compute();pzCam();renderAll();track('puzzle_'+def.id); + toast(`${esc(pzName(def))}
${tr('puzzles.carry_list',{list:S.pz.dem.map(f=>`${esc(pzFlowName(f))} ${fmtG(f.g)}`).join(', ')})}`,'goal');}; + if(pzOn()){go();return;} + const live=!!(S&&UI.started&&!S.lost);UI.pzFrom=live?'game':'title'; + if(live)pzFlush();go();} +function pzLeave(){pzMkStop();if(S&&S.ar)arStop(true);mkStop();const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; + if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null; + if(sv){try{S=migrate(sv);compute();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} + // It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told. + if(UI.slot&&(sv||UI.loadBad)){slotBroke(UI.slot);return;}} + renderAll();showTitle();} +// The camera frames the puzzle's cities beside the puzzle card: left on wide screens, right on phones on their side, a bottom sheet on phones. +function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity; + for(const C of cs){const x=x0+wrapDx(x0,C.x);a=Math.min(a,x);b=Math.max(b,x);c=Math.min(c,C.y);d=Math.max(d,C.y);} + const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:S.ar&&CW>760&&CH>500?410:330,pb=ph&&!side?(S.ar?Math.min(230,CH*0.4):Math.min(230,CH*0.3)):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); + cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);UI.pzZ0=cam.z;cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();} +// ---------- building ---------- +function pzSnap(){pzMkStop();if(S.ar)arStop();const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route),k:S.ar?S.ar.sunk:0}));if(h.length>60)h.shift();} +function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI.sel.id))||(UI.sel.type==='city'&&!pzKind(UI.sel.id))))UI.sel=null; + if(S.ar)arRouters();compute();renderAll();pzCheck();} +// Stars count the moment they are earned. +// Every solved state is recorded, so a cheaper build at the same stars counts too. +// A new star below three is a cheer and a nudge, and play goes on; the results card opens at three stars, or when the +// player says they are done (the card's Finish button). +function pzCheck(){if(arOn())return null;const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;const show=()=>{if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}};if(pzMkCan())pzMonkey(show);else show();return e;} +// The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend. +function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null}; + if(e.stars1)r.rv=P.rev;else delete r.rv;bag[k]=r;if(P.id==='weekly')pzStreak(p,P.key);pzStore(p);} +// The next puzzle in the list whose pack is open. +function pzNextDef(){const p=pzLoad(),i=PZ.findIndex(x=>x.id===S.pz.id);for(let j=i+1;j.json (scripts/weekly-puzzle.js): a static file next to + the page, fetched only when the player opens Puzzles. It is checked field by field; when it is missing, offline or + wrong, the seeded weekly in 92-puzzles.js stands in, so the weekly puzzle never breaks. */ +// Europe/Berlin is UTC+1, and UTC+2 from the last Sunday of March to the last Sunday of October, 01:00 UTC both times. +const pzLastSun=(y,m)=>{const d=new Date(Date.UTC(y,m+1,0));return Date.UTC(y,m,d.getUTCDate()-d.getUTCDay(),1);}; +const pzBerlinOff=t=>{const y=new Date(t).getUTCFullYear();return t>=pzLastSun(y,2)&&tsun+(6-pzBerlinOff(sun+4*3600e3))*3600e3; +function pzIso(t){const d=new Date(t);d.setUTCHours(0,0,0,0);d.setUTCDate(d.getUTCDate()+4-(d.getUTCDay()||7));const y=d.getUTCFullYear();return `${y}-W${String(Math.ceil(((d-Date.UTC(y,0,1))/864e5+1)/7)).padStart(2,'0')}`;} +// The key of the puzzle week holding this moment. +function pzWeekKey(dt){const t=+dt,d=new Date(t);let sun=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate())-d.getUTCDay()*864e5; + if(t{const t=pzWeekStart(key);return t==null?null:pzWeekKey(t+n*7*864e5+3*3600e3);}; +const pzPrevKey=key=>pzKeyAdd(key,-1); +// ---------- themes and their text: labels, so the file names a label and the player reads their language ---------- +// A file may only use these labels (N_: kept whole in the shipped page, since the file names them in full). +const PZ_WK_THEMES={ + detour:{i:'🚧',t:N_('puzzles_weekly.detour'),names:[N_('puzzles_weekly.name_anywhere_but_hub'),N_('puzzles_weekly.name_who_needs_hub')],jokes:[N_('puzzles_weekly.joke_hub_is_having_a_very'),N_('puzzles_weekly.joke_the_obvious_path_goes_through')]}, + islands:{i:'🏝️',t:N_('puzzles_weekly.island_hopping'),names:[N_('puzzles_weekly.name_hop_skip_and_a_cable'),N_('puzzles_weekly.name_sun_sea_and_subsea')],jokes:[N_('puzzles_weekly.joke_every_hop_is_a_cable'),N_('puzzles_weekly.joke_the_cheapest_way_between_two')]}, + ocean:{i:'🌊',t:N_('puzzles_weekly.ocean_crossing'),names:[N_('puzzles_weekly.name_sea_you_in_b'),N_('puzzles_weekly.name_across_the_big_blue')],jokes:[N_('puzzles_weekly.joke_the_ocean_is_big_and'),N_('puzzles_weekly.joke_somewhere_between_a_and_b')]}, + ring:{i:'💍',t:N_('puzzles_weekly.ring'),names:[N_('puzzles_weekly.name_one_ring_to_rule_reg'),N_('puzzles_weekly.name_ring_around_reg')],jokes:[N_('puzzles_weekly.joke_one_ring_through_every_pop'),N_('puzzles_weekly.joke_a_ring_survives_one_cut')]}, + sprint:{i:'⚡',t:N_('puzzles_weekly.latency_sprint'),names:[N_('puzzles_weekly.name_race_to_b'),N_('puzzles_weekly.name_ms_ms_or_bust')],jokes:[N_('puzzles_weekly.joke_a_to_b_under_ms'),N_('puzzles_weekly.joke_the_speed_of_light_is')]}, + tour:{i:'🗺️',t:N_('puzzles_weekly.region_tour'),names:[N_('puzzles_weekly.name_tour_de_reg'),N_('puzzles_weekly.name_are_we_there_yet_a')],jokes:[N_('puzzles_weekly.joke_n_cities_one_landmass_and'),N_('puzzles_weekly.joke_a_road_trip_for_photons')]}, +}; +// What each {placeholder} in those labels holds: c a city id, r a region code, n a whole number. +const PZ_WK_P={a:'c',b:'c',hub:'c',reg:'r',ms:'n',n:'n'}; +const pzCityOk=c=>isCity(c)&&!CITY[c].off&&!CITY[c].cn; +const pzTxt=o=>{const v={};for(const k in o.p){const x=o.p[k],t=PZ_WK_P[k];v[k]=t==='c'?CITY[x].name:t==='r'?WAVE_NAME[x]:x;}return tr(o.l,v);}; +// ---------- the file: never trusted. Only known fields, known cities, known labels and sane numbers get through ---------- +const pzObj=o=>!!o&&typeof o==='object'&&!Array.isArray(o); +function pzWkTxt(o,list){if(!pzObj(o)||typeof o.l!=='string'||!list.includes(o.l))return null;const p=o.p==null?{}:o.p;if(!pzObj(p))return null; + const need=[...new Set([...String(EN[o.l]).matchAll(/\{(\w+)\}/g)].map(m=>m[1]))],out={}; + if(Object.keys(p).length!==need.length)return null; + for(const k of need){const t=PZ_WK_P[k],v=own(p,k)?p[k]:undefined; + if(t==='c'&&pzCityOk(v))out[k]=v;else if(t==='r'&&typeof v==='string'&&own(WAVE_NAME,v))out[k]=v;else if(t==='n'&&Number.isInteger(v)&&v>0&&v<1000)out[k]=v;else return null;} + return {l:o.l,p:out};} +// rev: the file's revision, from 2 when a release's new prices made the week regenerate (scripts/weekly-puzzle.js). +const PZ_WK_FIELDS=['v','key','theme','cities','src','dem','via','avoid','budget','twist','name','joke','ref','rev']; +// Schema 2 (puzzles with traffic): `src` the content origins, `dem` the flows ({t:'eye',a,g} eyeballs in a; {t:'l2',a,b,g,ms} +// a circuit, ms its latency cap; be:true best effort), `cities` exactly the cities they touch. Older files are refused. +const PZ_WK_V=2; +function pzWkDem(a){if(!Array.isArray(a)||a.length<1||a.length>6)return null;const out=[],eye=new Set(); + for(const f of a){if(!pzObj(f)||Object.keys(f).some(k=>!['t','a','b','g','ms','be'].includes(k))||!pzCityOk(f.a)||!Number.isInteger(f.g)||f.g<1||f.g>2000)return null; + if(own(f,'be')&&f.be!==true)return null; + if(f.t==='eye'){if(own(f,'b')||own(f,'ms')||eye.has(f.a))return null;eye.add(f.a);out.push({t:'eye',a:f.a,g:f.g,be:!!f.be});} + else if(f.t==='l2'){if(!pzCityOk(f.b)||f.b===f.a||(own(f,'ms')&&!(typeof f.ms==='number'&&isFinite(f.ms)&&f.ms>=1&&f.ms<=500)))return null;out.push({t:'l2',a:f.a,b:f.b,g:f.g,ms:f.ms||0,be:!!f.be});} + else return null;} + return out;} +function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==PZ_WK_V||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null; + const T=PZ_WK_THEMES[j.theme],ids=(a,lo,hi)=>Array.isArray(a)&&a.length>=lo&&a.length<=hi&&a.every(pzCityOk)&&new Set(a).size===a.length?a.slice():null; + const cities=ids(j.cities,2,6),src=ids(j.src==null?[]:j.src,0,3),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2),dem=pzWkDem(j.dem);if(!cities||!src||!via||!avoid||!dem)return null; + // Eyeballs need somewhere to pull from; an origin is not also a city of eyeballs. + if(dem.some(f=>f.t==='eye')&&!src.length||dem.some(f=>f.t==='eye'&&src.includes(f.a)))return null; + const d0={src,dem},cs=pzCities(d0);if(cs.length!==cities.length||!cs.every(c=>cities.includes(c)))return null; + const all=[...cities,...via,...avoid];if(new Set(all).size!==all.length)return null; + if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>2e7)return null; + const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['ring','noSub'].includes(k)))return null; + if(j.rev!==undefined&&!(Number.isInteger(j.rev)&&j.rev>=2&&j.rev<=999))return null; + const d={id:'weekly',key,theme:j.theme,cities,src,dem,via,avoid,budget:j.budget,noSub:false,ring:false,rev:j.rev||1}; + if(own(tw,'ring')){if(tw.ring!==true)return null;d.ring=true;} + if(own(tw,'noSub')){if(tw.noSub!==true)return null;d.noSub=true;} + d.wn=pzWkTxt(j.name,T.names);d.wj=pzWkTxt(j.joke,T.jokes);if(!d.wn||!d.wj)return null; + return d;} +// ---------- fetching it: when Puzzles opens, never on page load ---------- +function pzWkEnsure(){const key=pzWeekKey(new Date()),w=UI.pzWk; + if(w&&w.key===key&&(w.st!=='fb'||Date.now()-w.at<5*60e3))return; + const st=UI.pzWk={key,st:w&&w.key===key&&w.def?'ok':'load',def:w&&w.key===key?w.def:null,at:Date.now()}; + let done=false;const fin=def=>{if(done)return;done=true;clearTimeout(to);if(UI.pzWk!==st)return;if(def){st.def=def;st.st='ok';}else if(!st.def)st.st='fb';st.at=Date.now();pzWkRefresh();}; + const ac=window.AbortController?new AbortController():null,to=setTimeout(()=>{if(ac)ac.abort();fin(null);},5000); + if(!window.fetch||location.protocol==='file:'){fin(null);return;} + // Relative and same origin; each week has its own file name, so caches never serve last week's. + try{fetch(`puzzles/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>pzWkValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +// This week's puzzle: the published one when it came, else the seeded one. +function pzWkDef(){const key=pzWeekKey(new Date()),w=UI.pzWk;return w&&w.key===key&&w.def?w.def:pzWeekly();} +const pzWkLoading=()=>{const w=UI.pzWk;return !!w&&w.st==='load'&&w.key===pzWeekKey(new Date());}; +function pzWkRefresh(){const el=$('pzWk');if(el)el.outerHTML=pzWkRow();} +// "Next weekly puzzle in 2 d 14 h". +function pzWkNext(now){const key=pzWeekKey(now),t=pzWeekStart(pzKeyAdd(key,1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60); + return d?tr('puzzles.next_weekly_in_d_h',{d,h}):tr('puzzles.next_weekly_in_h_m',{h,m:m%60});} +// The Puzzles door says so when this week's puzzle has not been played yet. +function pzWkNew(){try{const k=pzWeekKey(new Date()),w=UI.pzWk;return !pzWkRec(pzLoad(),w&&w.key===k&&w.def?w.def:{key:k});}catch(e){return false;}} diff --git a/src/game/60-features/94-scenarios-weekly.js b/src/game/60-features/94-scenarios-weekly.js new file mode 100644 index 0000000..fa8c053 --- /dev/null +++ b/src/game/60-features/94-scenarios-weekly.js @@ -0,0 +1,125 @@ +/* ================= THE PUBLISHED WEEKLY SCENARIO ================= + The twin of the weekly puzzle: the same weeks (Sunday 06:00 Berlin, pzWeekKey), one themed scenario per week, + published by a GitHub workflow as scenarios/weekly/.json (scripts/weekly-scenario.js) and fetched only when the + Scenarios list opens. The file is data only: a theme, a start, rules from the scenario vocabulary, and a goal TYPE + with its parameters; every goal type is implemented once here, with its progress card. Missing, offline or wrong, + the in-browser weekly() stands in. Like every scenario it runs On-call plus its own rules (M4). */ +// What a {placeholder} holds: c a city, r a region, n a whole number, k a cable id. +const WS_P={a:'c',b:'c',city:'c',reg:'r',n:'n',g:'n',day:'n',ms:'n',cab:'k'}; +const WS_THEMES={ + budget:{i:'🪙',names:[N_('wkscn.name_shoestring_backbone'),N_('wkscn.name_ramen_profitable')],descs:[N_('wkscn.desc_city_on_a_shoestring'),N_('wkscn.desc_start_in_city_with_pocket')]}, + cable:{i:'✂️',names:[N_('wkscn.name_suez_you_later'),N_('wkscn.name_cut_and_run')],descs:[N_('wkscn.desc_cab_is_cut_for_the'),N_('wkscn.desc_a_ship_dragged_its_anchor')]}, + event:{i:'🎉',names:[N_('wkscn.name_party_like_its_1999'),N_('wkscn.name_stream_team')],descs:[N_('wkscn.desc_a_g_event_comes_to'),N_('wkscn.desc_the_whole_city_is_watching')]}, + flood:{i:'🌊',names:[N_('wkscn.name_flood_week'),N_('wkscn.name_packet_monsoon')],descs:[N_('wkscn.desc_city_hosts_the_internets_favourite'),N_('wkscn.desc_booters_picked_city_for_their')]}, + island:{i:'🏝️',names:[N_('wkscn.name_island_hopper'),N_('wkscn.name_sea_you_soon')],descs:[N_('wkscn.desc_start_on_city_and_string'),N_('wkscn.desc_city_is_surrounded_by_water')]}, + latency:{i:'⚡',names:[N_('wkscn.name_ludicrous_speed'),N_('wkscn.name_light_speed_please')],descs:[N_('wkscn.desc_a_trading_firm_needs_a'),N_('wkscn.desc_every_millisecond_between_a_and')]}, + region:{i:'🗺️',names:[N_('wkscn.name_continental_breakfast'),N_('wkscn.name_planting_flags')],descs:[N_('wkscn.desc_city_is_just_the_start'),N_('wkscn.desc_every_exchange_in_reg_wants')]}, + spat:{i:'🙊',names:[N_('wkscn.name_not_on_speaking_terms'),N_('wkscn.name_peering_pressure')],descs:[N_('wkscn.desc_cogentle_and_goggle_stopped_talking'),N_('wkscn.desc_two_giants_de_peered_over')]}, +}; +const wsRun=()=>S.scn.run|0; +const wsIxN=reg=>Object.keys(S.ixp).filter(c=>isIx(c)&&CITY[ixCity(c)]&&CITY[ixCity(c)].reg===reg).length; +const wsCs=p=>p.cs.map(c=>CITY[c].name).join(', '); +// The goal types. p: each parameter's kind and range ([kind,lo,hi]); ok(p) won; m(p) a number the generator calibrates +// against (and the progress bar reads); daily: the goal counts days in a row; prog(p) the card's rows. +const WS_GOALS={ + served:{p:{g:['n',5,50000]},l:N_('wkscn.goal_serve_g'),ok:p=>R.served>=p.g,m:()=>R.served,prog:p=>[pSrv(p.g)]}, + reach:{p:{r:['n',50,99],g:['n',1,50000]},l:N_('wkscn.goal_reach_r_and_serve_g'),ok:p=>R.reach>=p.r/100&&R.served>=p.g,m:()=>R.served,prog:p=>[{l:tr('common.reach'),v:R.reach,max:p.r/100,txt:`${pct(R.reach)} / ${p.r}%`},pSrv(p.g)]}, + path:{p:{a:['c'],b:['c'],g:['n',10,12800],n:['n',1,120]},daily:p=>fastPath(p.a,p.b,p.g),l:N_('wkscn.goal_g_on_every_hop_from'),ok:p=>wsRun()>=p.n,m:()=>wsRun(), + prog:p=>[pChk(tr('wkscn.p_path_g_a_b',{g:fmtG(p.g),a:CITY[p.a].name,b:CITY[p.b].name}),fastPath(p.a,p.b,p.g)),{l:tr('wkscn.p_days_in_a_row'),v:wsRun(),max:p.n,txt:`${wsRun()} / ${p.n}`}]}, + ix:{p:{reg:['r'],n:['n',2,60]},l:N_('wkscn.goal_ports_on_n_exchanges_in'),ok:p=>wsIxN(p.reg)>=p.n,m:p=>wsIxN(p.reg),prog:p=>{const n=wsIxN(p.reg);return [{l:tr('wkscn.p_exchange_ports_in_reg',{reg:WAVE_NAME[p.reg]}),v:n,max:p.n,txt:`${n} / ${p.n}`}];}}, + pops:{p:{cs:['cs',1,8]},l:N_('wkscn.goal_a_connected_pop_in_list'),ok:p=>p.cs.every(c=>pathExists(S.scn.home,c)),m:p=>p.cs.filter(c=>pathExists(S.scn.home,c)).length,prog:p=>p.cs.map(c=>pChk(tr('progress.city_on_your_network',{city:CITY[c].name}),pathExists(S.scn.home,c)))}, + event:{p:{city:['c'],g:['n',10,6400],day:['n',20,360],dur:['n',1,10]},l:N_('wkscn.goal_deliver_the_event_in_city'),ok:()=>(S.stats.evFull||0)>=1,m:()=>S.stats.evFull||0, + setup:p=>S.biz.push({id:uid(),scripted:true,city:p.city,city2:null,reqs:[],name:tr('wkscn.event_name_city',{city:CITY[p.city].name}),type:'event',bw:p.g,rate:0,mood:100,since:0,start:p.day,dur:p.dur,fee:p.g*p.dur*70}), + prog:p=>[pChk(tr('wkscn.p_event_delivered_in_full'),(S.stats.evFull||0)>=1),{l:tr('common.traffic_served'),v:0,max:0,txt:tr('wkscn.p_g_on_day_d',{g:fmtG(p.g),d:p.day})}]}, + floods:{p:{n:['n',1,60],big:['n',0,20]},l:N_('wkscn.goal_hold_n_floods_big_of'),ok:p=>(S.stats.ddosOk||0)>=p.n&&(S.stats.ddosOkBig||0)>=p.big,m:()=>S.stats.ddosOk||0, + prog:p=>[{l:tr('common.floods_held'),v:S.stats.ddosOk||0,max:p.n,txt:`${S.stats.ddosOk||0} / ${p.n}`},...(p.big?[{l:tr('progress.terabit_floods_held'),v:S.stats.ddosOkBig||0,max:p.big,txt:`${S.stats.ddosOkBig||0} / ${p.big}`}]:[])]}, + lat:{p:{a:['c'],b:['c'],ms:['n',1,400],n:['n',1,120]},daily:p=>bestLat(p.a,p.b)<=p.ms,l:N_('wkscn.goal_a_to_b_under_ms'),ok:p=>wsRun()>=p.n,m:()=>wsRun(), + prog:p=>{const v=bestLat(p.a,p.b);return [pChk(tr('wkscn.p_a_b_now',{a:CITY[p.a].name,b:CITY[p.b].name,ms:isFinite(v)?v.toFixed(1)+' ms':tr('common.no_path')}),v<=p.ms),{l:tr('wkscn.p_days_in_a_row'),v:wsRun(),max:p.n,txt:`${wsRun()} / ${p.n}`}];}}, +}; +// Filled-in text: a label from the file and its typed parameters, in the player's language. +const wsVal=(k,x)=>{const t=WS_P[k];return t==='c'?CITY[x].name:t==='r'?WAVE_NAME[x]:t==='k'?CAB[x].name:k==='g'?fmtG(x):x;}; +const wsTxt=o=>{const v={};for(const k in o.p)v[k]=wsVal(k,o.p[k]);return tr(o.l,v);}; +function wsGoalTxt(j){const G=j.goal,p=G.p,v={};for(const k in p)v[k]=k==='cs'?wsCs(p):WS_P[k]?wsVal(k,p[k]):p[k];return tr(G.t==='floods'&&!p.big?N_('wkscn.goal_hold_n_floods'):WS_GOALS[G.t].l,v);} +// ---------- the file: never trusted ---------- +const WS_FIELDS=['v','key','theme','city','cash','days','lvl','rules','mods','goal','name','desc','seed','par','ref','rev']; +const WS_V=1,WS_RULES=['anchors','banCities','banPairs','ddos','spat']; +const wsPairOk=s=>typeof s==='string'&&CABLE_PAIRS.some(c=>s===`${c.cid}:${c.a}-${c.b}`); +function wsLab(o,list){if(!pzObj(o)||typeof o.l!=='string'||!list.includes(o.l))return null;const p=o.p==null?{}:o.p;if(!pzObj(p))return null; + const need=[...new Set([...String(EN[o.l]).matchAll(/\{(\w+)\}/g)].map(m=>m[1]))],out={};if(Object.keys(p).length!==need.length)return null; + for(const k of need){const t=WS_P[k],v=own(p,k)?p[k]:undefined; + if(t==='c'&&pzCityOk(v)||t==='r'&&typeof v==='string'&&own(WAVE_NAME,v)||t==='k'&&typeof v==='string'&&own(CAB,v)||t==='n'&&Number.isInteger(v)&&v>0&&v<1e6)out[k]=v;else return null;} + return {l:o.l,p:out};} +function wsGoal(o){if(!pzObj(o)||typeof o.t!=='string'||!own(WS_GOALS,o.t)||!pzObj(o.p))return null;const G=WS_GOALS[o.t],out={}; + if(Object.keys(o.p).length!==Object.keys(G.p).length)return null; + for(const k in G.p){const [t,lo,hi]=G.p[k],v=o.p[k]; + if(t==='c'){if(!pzCityOk(v))return null;}else if(t==='r'){if(typeof v!=='string'||!own(WAVE_NAME,v))return null;} + else if(t==='cs'){if(!Array.isArray(v)||v.lengthhi||!v.every(pzCityOk)||new Set(v).size!==v.length)return null;} + else if(!Number.isInteger(v)||vhi)return null; + out[k]=Array.isArray(v)?v.slice():v;} + if(out.a&&out.a===out.b)return null;return {t:o.t,p:out};} +// A checked copy of the file, or null. The copy is what a game stores and reloads (sanitize() checks it again). +function wsValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!WS_FIELDS.includes(k))||j.v!==WS_V||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(WS_THEMES,j.theme))return null; + const T=WS_THEMES[j.theme],I=(v,lo,hi)=>Number.isInteger(v)&&v>=lo&&v<=hi; + if(!pzCityOk(j.city)||!I(j.cash,50000,2e7)||!I(j.days,60,400)||!I(j.lvl,1,4)||!I(j.seed,1,2**31-1)||!I(j.par,1,j.days))return null; + if(j.rev!==undefined&&!I(j.rev,2,999))return null;if(j.ref!==undefined&&!pzObj(j.ref))return null; + const r=j.rules==null?{}:j.rules;if(!pzObj(r)||Object.keys(r).some(k=>!WS_RULES.includes(k)))return null;const rules={}; + for(const k in r){const v=r[k]; + if(k==='spat'||k==='ddos'){if(v!==true)return null;rules[k]=true;} + else if(k==='anchors'){if(!I(v,1,5))return null;rules[k]=v;} + else if(k==='banCities'){if(!Array.isArray(v)||v.length>6||!v.every(isCity)||v.includes(j.city))return null;rules[k]=v.slice();} + else{if(!Array.isArray(v)||v.length<1||v.length>40||!v.every(wsPairOk))return null;rules[k]=v.slice();}} + const mods=j.mods==null?[]:j.mods;if(!Array.isArray(mods)||mods.length>2||new Set(mods).size!==mods.length||!mods.every(m=>WEEK_MODS.some(x=>x.id===m)))return null; + const goal=wsGoal(j.goal);if(!goal)return null; + // A city the goal needs is never one the rules ban. + if(rules.banCities&&Object.values(goal.p).flat().some(c=>rules.banCities.includes(c)))return null; + if(goal.t==='event'&&goal.p.day+goal.p.dur>=j.days||goal.t==='floods'&&!rules.ddos)return null; + const name=wsLab(j.name,T.names),desc=wsLab(j.desc,T.descs);if(!name||!desc)return null; + const o={v:WS_V,key,theme:j.theme,city:j.city,cash:j.cash,days:j.days,lvl:j.lvl,rules,mods:mods.slice(),goal,name,desc,seed:j.seed,par:j.par};if(j.rev)o.rev=j.rev;return o;} +// ---------- fetching it: when the Scenarios list opens, never on page load ---------- +function wsEnsure(){const key=pzWeekKey(new Date()),w=UI.wsWk; + if(w&&w.key===key&&(w.st!=='fb'||Date.now()-w.at<5*60e3))return; + const st=UI.wsWk={key,st:w&&w.key===key&&w.def?'ok':'load',def:w&&w.key===key?w.def:null,at:Date.now()}; + let done=false;const fin=def=>{if(done)return;done=true;clearTimeout(to);if(UI.wsWk!==st)return;if(def){st.def=def;st.st='ok';}else if(!st.def)st.st='fb';st.at=Date.now();wsRefresh();}; + const ac=window.AbortController?new AbortController():null,to=setTimeout(()=>{if(ac)ac.abort();fin(null);},5000); + if(!window.fetch||location.protocol==='file:'){fin(null);return;} + try{fetch(`scenarios/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>wsValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +const wsDef=()=>{const key=pzWeekKey(new Date()),w=UI.wsWk;return w&&w.key===key&&w.def?w.def:null;}; +const wsLoading=()=>{const w=UI.wsWk;return !!w&&w.st==='load'&&w.key===pzWeekKey(new Date());}; +function wsRefresh(){const el=$('wsRow');if(el)el.outerHTML=wsRow();} +// ---------- the player's record: started weeks (for the badge), wins and the streak ---------- +function wsLoad(){let j=null;try{j=JSON.parse(localStorage.getItem('sot-wkscn')||'null');}catch(e){}const o={go:{},w:{},streak:{last:null,n:0,best:0}};if(!pzObj(j))return o; + const K=/^\d{4}-W\d{2}$/;if(pzObj(j.go))for(const k in j.go)if(K.test(k))o.go[k]=1; + if(pzObj(j.w))for(const k in j.w){const x=j.w[k];if(K.test(k)&&pzObj(x)&&Number.isInteger(x.d)&&x.d>0)o.w[k]={d:x.d,rv:Number.isInteger(x.rv)?x.rv:1};} + const s=j.streak;if(pzObj(s)){o.streak.last=typeof s.last==='string'&&K.test(s.last)?s.last:null;for(const k of ['n','best'])o.streak[k]=Number.isInteger(s[k])&&s[k]>=0?s[k]:0;}return o;} +const wsStore=o=>{try{localStorage.setItem('sot-wkscn',JSON.stringify(o));}catch(e){}}; +// A win counts for its revision: when a week is regenerated (rev), last week's result for it no longer shows. +const wsWin=(o,d)=>{const x=d&&o.w[d.key];return x&&x.rv===(d.rev||1)?x:null;}; +function wsNew(){try{return !wsLoad().go[pzWeekKey(new Date())];}catch(e){return false;}} +const wsStreak=(o,key)=>{const s=o.streak;return s.last===key||s.last===pzPrevKey(key)?s.n:0;}; +// ---------- playing it ---------- +function wsBegin(j,nm){const d=wsValid(j,j&&j.key);if(!d)return false;const G=WS_GOALS[d.goal.t]; + const o=wsLoad();o.go[d.key]=1;wsStore(o); + beginGame(nm||UI.nm||(S&&S.name)||randomNetworkName(),d.city,{seed:d.seed,scn:{id:'weekly',key:d.key,n:wsTxt(d.name),days:d.days,cash:d.cash,rules:JSON.parse(JSON.stringify(d.rules)), + mods:d.mods.map(m=>WEEK_MODS.find(x=>x.id===m)),goal:wsGoalTxt(d),setup:()=>{S.scn.wk=d;S.scn.home=d.city;S.scn.run=0;S.lvl=Math.max(S.lvl||1,d.lvl);if(G.setup)G.setup(d.goal.p);}}}); + return true;} +const wsOk=()=>{const sc=S&&S.scn;if(!sc||!sc.wk)return false;const G=sc.wk.goal;try{return !!WS_GOALS[G.t].ok(G.p);}catch(e){return false;}}; +const wsMeasure=()=>{const G=S.scn.wk.goal;try{return +WS_GOALS[G.t].m(G.p)||0;}catch(e){return 0;}}; +function wsShareText(){const sc=S.scn,d=sc.wk;return tr('wkscn.share_line',{key:sc.key,name:wsTxt(d.name),d:sc.done,par:d.par});} +// Called by scnTick once a day for a published weekly scenario. +function wsTick(d){const sc=S.scn,w=sc.wk,G=WS_GOALS[w.goal.t]; + if(G.daily){let on=false;try{on=!!G.daily(w.goal.p);}catch(e){}sc.run=on?(sc.run|0)+1:0;} + if(wsOk()){sc.done=d;const o=wsLoad(),x=wsWin(o,w);if(!x||x.d>d)o.w[w.key]={d,rv:w.rev||1};const s=o.streak;if(s.last!==w.key){s.n=s.last===pzPrevKey(w.key)?s.n+1:1;s.last=w.key;s.best=Math.max(s.best,s.n);}wsStore(o);track('wkscn_won'); + openModal(`
${T_WS(w)} ${tr('wkscn.weekly_scenario_key',{key:esc(w.key)})}

${tr('wkscn.won_on_day_d',{d})}

${esc(wsGoalTxt(w))}. ${d<=w.par?tr('wkscn.under_par_par',{par:w.par}):tr('wkscn.par_was_day_par',{par:w.par})}

${esc(wsShareText())}

${btn(tr('wkscn.copy_my_result'),'wsShare',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);sfx('coin');} + else if(d>=sc.days){sc.failed=d;openModal(`
${tr('common.scenario_over')}

${tr('common.time_s_up')}

${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(wsGoalTxt(w)),d:sc.days})}

${btn(tr('common.try_again'),'startWeekly',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);}} +const T_WS=w=>(WS_THEMES[w.theme]||{}).i||'📅'; +// The top row of the Scenarios list. +function wsRow(){const d=wsDef(),o=wsLoad(),key=pzWeekKey(new Date()),st=wsStreak(o,key),badge=o.go[key]?'':` ${tr('puzzles.new_this_sunday')}`,cd=`
⏳ ${wsNext(Date.now())}
`; + if(!d){const wk=weekly();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){} + return `
📅 ${tr('wkscn.weekly_scenario_key',{key:esc(wk.key)})}${badge}
${wsLoading()?tr('wkscn.loading_this_week_s_scenario'):tr('features.weekly_challenge_key',{key:esc(wk.key)})}
${tr('scenario_progress.start_in_city_mods_one_year',{city:esc(CITY[wk.city].name),mods:wk.mods.map(m=>esc(m.n)).join(' · ')})}${best?' '+tr('scenario_progress.your_best_best',{best:fmtG(best)}):''}
${cd}
${btn(tr('common.play'),'startWeekly',{},'pink',wsLoading())}
`;} + const x=wsWin(o,d),mods=d.mods.map(m=>esc(WEEK_MODS.find(y=>y.id===m).n)); + return `
📅 ${tr('wkscn.weekly_scenario_key',{key:esc(d.key)})}${badge}
+
${T_WS(d)} ${esc(wsTxt(d.name))} ${x?`${tr('wkscn.won_day_d_par_par',{d:x.d,par:d.par})}`:''}
${esc(wsTxt(d.desc))}
+
🎯 ${esc(wsGoalTxt(d))}
${tr('wkscn.start_in_city_d_days_cash',{city:esc(CITY[d.city].name),d:d.days,cash:fmt$(d.cash)})}${mods.length?' · '+mods.join(' · '):''} · ${tr('wkscn.par_day_par',{par:d.par})}
+
${tr('wkscn.same_scenario_for_everyone_this_week')}${st?' · 🔥 '+trn('puzzles.n_week_streak',st):''}
${cd}
${btn(tr('common.play'),'startWeekly',{},x?'ghost':'pink')}
`;} +function wsNext(now){const key=pzWeekKey(now),t=pzWeekStart(pzKeyAdd(key,1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60); + return d?tr('wkscn.next_weekly_in_d_h',{d,h}):tr('wkscn.next_weekly_in_h_m',{h,m:m%60});} diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js new file mode 100644 index 0000000..f30b77e --- /dev/null +++ b/src/game/60-features/95-standing-orders.js @@ -0,0 +1,408 @@ +/* ---------- Standing orders (#98) ---------- + A NOC intern runs the player's standing orders once per game day. Every job goes through the same action a click + would (ACT.*, pniPlace, the #185/#192 planners), so it costs exactly what the click costs, with toasts and redraws + muted and one recompute at the end. Without an intern nothing here runs and no random numbers are drawn. */ +const INTERN_MO=6000,OPS_LOG=12,OPS_CAPS=[10000,50000,250000,1e6,5e6,0],OPS_CAPS_MO=[1000,2500,5000,10000,25000,0],OPS_FLOORS=[0,50000,250000,1e6,5e6]; +// Every intern runs every order, the same way and at the same price; each is better at one part of the job (g: what). +// Annie peers: the IX order every day, the PNI order twice a week. Kevin does maintenance: two line systems a night, +// and never a fat finger. Tracy plans ahead: the capacity orders act as if traffic were OPS_AHEAD higher already. +const INTERNS={ + annie:{i:'📡',n:N_('ops.anycast_annie'),s:N_('ops.annie'),d:N_('ops.annie_d'),g:N_('ops.good_annie')}, + kevin:{i:'🌙',n:N_('ops.kevin_from_the_night_shift'),s:N_('ops.kevin'),d:N_('ops.kevin_d'),g:N_('ops.good_kevin')}, + tracy:{i:'🧭',n:N_('ops.tracy_route'),s:N_('ops.tracy'),d:N_('ops.tracy_d'),g:N_('ops.good_tracy')}, +}; +const OPS_AHEAD=1.1,opsIs=id=>!!S&&!!S.ops&&S.ops.intern===id,opsAhead=()=>opsIs('tracy')?OPS_AHEAD:1; +// Deals are not the intern's: the sales desk signs them (39-sales-auto.js). +// The orders, in the order the panel shows them. pop: can be switched off per POP. cap: default monthly budget, of setup +// fees, or (mo) of the running costs the order adds, for caches, which are free to rack but cost rent every month. +const OPS=[ + {k:'transit',i:'📈',pop:1,cap:50000,t:N_('ops.o_transit'),d:N_('ops.o_transit_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'},prov:{d:'cheap',ok:v=>v==='cheap'||v==='have'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}}, + {k:'ports',i:'🔌',pop:1,cap:50000,t:N_('ops.o_ports'),d:N_('ops.o_ports_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'}}}, + // The model to standardize on is the build standard's, set in its sheet (96-pop-standard.js): none of its own here. + {k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_std_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}}}, + // The build standard (96-pop-standard.js): its targets are set in their own sheet, so here it has only the budget. + {k:'std',i:'📐',pop:1,cap:250000,t:N_('ops.o_std'),d:N_('ops.o_std_wave_d'),p:{}}, + {k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}}, + {k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}}, + {k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>v?tr('common.on'):tr('common.off')}}}, + {k:'repair',i:'🔧',cap:50000,t:N_('ops.o_repair'),d:N_('ops.o_repair_d'),p:{}}, + {k:'optics',i:'🌈',cap:250000,t:N_('ops.o_optics'),d:N_('ops.o_optics_d'),p:{at:{d:70,v:[50,60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},pick:{d:'cheap',v:['cheap','big'],l:N_('ops.p_pick'),f:v=>tr({cheap:N_('ops.pick_cheap'),big:N_('ops.pick_big')}[v])}, + // New fiber pulls traffic onto itself the day it is lit (#316): the player may want to light it by hand, when the + // ports behind it are ready. Off: fiber without a channel stays dark; lit fiber still gets more optics when hot. + fresh:{d:true,v:[true,false],l:N_('ops.p_fresh'),f:v=>v?tr('common.on'):tr('common.off')}}}, + // Line systems up to a bigger one, and optics swapped for bigger ones, on fiber that is full and runs hot, or every fiber up to + // the build standard's line system. A line system swap is a day without that fiber: only where the traffic gets around it. + {k:'optup',i:'🔭',cap:250000,t:N_('ops.o_optup'),d:N_('ops.o_optup_wave_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'}, + swap:{d:true,v:[true,false],l:N_('ops.p_swap'),f:v=>v?tr('common.on'):tr('common.off')}}}, + {k:'decom',i:'🧹',t:N_('ops.o_decom'),d:N_('ops.o_decom_d'),p:{keep:{d:true,v:[true,false],l:N_('ops.p_keep'),f:v=>v?tr('common.on'):tr('common.off')}}}, +]; +const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k); +const OPS_TPL=['bb','transit','ix','kit']; +// What the shift log can say. One line per day: "{name} did this, that and the other." +const OPS_SAY={std:N_('ops.l_std'),transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),optup:N_('ops.l_optup'),optswap:N_('ops.l_optswap'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')}; +// Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. +const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; +const OPS_FF_RATE={oncall:1/150,bgp:1/60}; +function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),addMo:{},mon:0,skip:{},log:[],wk:null,rep:null,floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} +const opsO=()=>S.ops||(S.ops=opsNew()); +const opsHired=()=>!!(S&&S.ops&&S.ops.intern&&own(INTERNS,S.ops.intern)); +const opsCanHire=()=>lvl()>=2; +const opsName=(long)=>{const I=INTERNS[S.ops.intern];return I?tr(long?I.n:I.s):'';}; +function opsP(k,p){const P=OPSK[k].p[p],v=S.ops.p[k]&&S.ops.p[k][p];return v!==undefined&&(P.ok?P.ok(v):P.v.includes(v))?v:P.d;} +// Every value a setting can take, in the order its list shows them, providers that sell where you have POPs as well. +// The current value is always on the list, so the list can show it. +function opsOpts(k,p){const cur=opsP(k,p),L=p==='prov'?['cheap','have',...NETS.filter(n=>n.price&&Object.keys(S.pops).some(c=>sellsAt(n,c))).map(n=>n.id)]:OPSK[k].p[p].v.slice(); + if(!L.includes(cur))L.push(cur);return L;} +const opsCaps=k=>OPSK[k].mo?OPS_CAPS_MO:OPS_CAPS; +function opsCap(k){const c=S.ops.cap[k];return opsCaps(k).includes(c)?c:OPSK[k].cap||0;} +const opsHere=(k,c)=>!(S.ops.skip[c]||[]).includes(k); +const opsPops=k=>Object.keys(S.pops).filter(c=>opsHere(k,c)); +// Saves are untrusted: rebuild ops from known orders, params, cities and log shapes. Runs after the POPs are repaired, +// so exceptions only survive for POPs that still exist. Old saves get no intern, and the #185 auto-repair toggle becomes +// the repair order. A sales order the intern was running moves to the sales desk (slAutoFrom); #185's auto-accept never +// ran without an intern, so it goes. +function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s.ops)?s.ops:{},n=opsNew(),ob=x=>x&&typeof x==='object'&&!Array.isArray(x)?x:{}; + n.intern=typeof o.intern==='string'&&own(INTERNS,o.intern)?o.intern:null;n.hired=int(o.hired,0,1e7,0);n.mon=int(o.mon,0,1e6,0); + n.floor=OPS_FLOORS.includes(o.floor)?o.floor:n.floor; + const on=ob(o.on),p=ob(o.p),cap=ob(o.cap),sp=ob(o.spent); + // The routers order's model and the optical order's line system moved to the build standard (bstdAdopt()), each only + // from an order that ran: one paused, or with nobody hired, did nothing, and a standard's model costs every new POP. + const ran=k=>!!n.intern&&on[k]===true; + bstdAdopt(s,ran('routers')?ob(p.routers).model:undefined,ran('optup')?ob(p.optup).sys:undefined); + for(const d of OPS){const k=d.k;n.on[k]=on[k]===true;const q=ob(p[k]),r={}; + for(const pk of Object.keys(d.p)){const P=d.p[pk];if(own(q,pk)&&(P.ok?P.ok(q[pk]):P.v.includes(q[pk])))r[pk]=q[pk];}n.p[k]=r; + if(d.cap&&opsCaps(k).includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0)); + {const v=num(ob(o.addMo)[k],0);if(v)n.addMo[k]=Math.max(-1e9,Math.min(1e9,v));}} + {const t=ob(o.tpl);for(const k of OPS_TPL)if(typeof t[k]==='boolean')n.tpl[k]=t[k];} + {const sk=ob(o.skip);for(const c of Object.keys(sk))if(isCity(c)&&own(s.pops,c)&&Array.isArray(sk[c])){const ks=[...new Set(sk[c].filter(k=>OPS_POP.includes(k)))];if(ks.length)n.skip[c]=ks;}} + if(Array.isArray(o.log))n.log=o.log.map(opsLogOk).filter(Boolean).slice(0,OPS_LOG); + n.wk=opsWkOk(o.wk);n.rep=opsWkOk(o.rep); + slAutoFrom(s,on.sales===true&&!!n.intern,ob(p.sales));if(s.autoRepair===true)n.on.repair=true;delete s.autoSales;delete s.autoRepair; + s.ops=n;} +// A log entry: {d, i: intern, r: [[kind, n, [where…]]], f: fat-finger index, c: its city, up: paid up front, mo: running costs added}. +const opsWhereOk=w=>typeof w==='string'&&w.length<=48&&/^[a-z0-9~|]+( [+\w.×→⇧]+)?$/i.test(w)&&w.split(' ')[0].split('|').every(x=>isIx(x)||own(OPSK,x)||isNet(x)); +function opsLogOk(e){if(!e||typeof e!=='object'||!own(INTERNS,e.i))return null;const r0=Array.isArray(e.r)?e.r:[],r=r0.filter(x=>Array.isArray(x)&&own(OPS_SAY,x[0])&&Array.isArray(x[2])).map(x=>[x[0],int(x[1],1,1e6,1),x[2].filter(opsWhereOk).slice(0,3)]).slice(0,16); + const f=Number.isInteger(e.f)&&OPS_FF[e.f]?e.f:undefined,up=int(e.up,0,1e12,0),mo=int(e.mo,-1e9,1e9,0); + // A day that only signed or declined deals (the retired sales order) has nothing left to say. + if(r0.length&&!r.length&&f===undefined&&!up&&!mo)return null; + return {d:int(e.d,0,1e7,0),i:e.i,r,...(f!==undefined&&isCity(e.c)?{f,c:e.c}:{}),...(up?{up}:{}),...(mo?{mo}:{})};} +// A week's tally, for the shift report and the one NOC notice a week: {w: week, i: intern, n: {kind: count}, wh: {kind: [where…]}, up, mo, ff}. +function opsWkOk(x){if(!x||typeof x!=='object'||Array.isArray(x)||!own(INTERNS,x.i))return null;const n={},wh={},xn=x.n&&typeof x.n==='object'?x.n:{},xw=x.wh&&typeof x.wh==='object'?x.wh:{}; + for(const k of Object.keys(OPS_SAY)){if(own(xn,k)){const v=int(xn[k],0,1e6,0);if(v)n[k]=v;}if(own(xw,k)&&Array.isArray(xw[k])){const w=xw[k].filter(opsWhereOk).slice(0,3);if(w.length)wh[k]=w;}} + // A tally of only the retired sales order says nothing any more. + const ff=int(x.ff,0,7,0);if(Object.keys(xn).length&&!Object.keys(n).length&&!ff)return null; + return {w:int(x.w,0,1e6,0),i:x.i,n,wh,up:int(x.up,0,1e12,0),mo:int(x.mo,-1e9,1e9,0),ff};} +const opsWkNew=w=>({w,i:S.ops.intern,n:{},wh:{},up:0,mo:0,ff:0}); +const opsWkAny=x=>!!x&&(Object.keys(x.n).length>0||x.ff>0); +// "Kevin's week: topped up transit 2 times (Frankfurt +1×100G), rushed a repair. Week total: …" +function opsWeekLine(x){const I=INTERNS[x.i],name=I?tr(I.s):'',ks=Object.keys(x.n).sort((a,b)=>(a==='broke')-(b==='broke')); + const parts=ks.map(k=>trn(OPS_SAY[k],x.n[k],{where:(x.wh[k]||[]).map(w=>opsWhere(w,k)).join(', ')})); + if(x.ff)parts.push(trn('ops.w_oops',x.ff)); + return tr('ops.w_line',{name,list:parts.join(', ')})+(x.up||x.mo?' '+tr('ops.w_money',{cost:fmt$(x.up),mo:opsMo$(x.mo)}):'');} +// The intern's mood, from what the week has been like. No dice: the same day always reads the same. +function opsMood(){const O=S.ops,x=O.wk&&O.wk.w===Math.floor(S.day/7)?O.wk:null,n=x?x.n:{},jobs=Object.keys(n).filter(k=>k!=='broke').reduce((a,k)=>a+n[k],0); + const k=S.day-O.hired<7?'new':x&&x.ff?'oops':n.snag?'snag':S.inc.some(i=>i.until>S.day&&i.type!=='ddos')?'outage':n.broke?'broke':jobs>=5?'busy':S.day%2?'quiet':O.intern; + return tr({new:N_('ops.mood_new'),oops:N_('ops.mood_oops'),snag:N_('ops.mood_snag'),outage:N_('ops.mood_outage'),broke:N_('ops.mood_broke'),busy:N_('ops.mood_busy'),quiet:N_('ops.mood_quiet'), + annie:N_('ops.mood_annie'),kevin:N_('ops.mood_kevin'),tracy:N_('ops.mood_tracy')}[k],{name:opsName()});} +// "fra +1×100G", "fra|ams", "ams~3", "transit" (an order, for the budget line) or "ggl" (a network). +// Peering is always at an exchange, and a city's first exchange has the city's id ("lon" is LYNX): name the exchange (#228). +function opsWhere(w,k){if(k==='peer'&&isIx(w)&&ixName(w))return ixName(w);const [a,x]=w.split(' '),nm=a.split('|').map(p=>own(OPSK,p)?tr(OPSK[p].t):isCity(p)?CITY[p].name:isNet(p)?NET[p].name:ixName(p)).join('–');return x?nm+' '+(isNet(x)?NET[x].name:x):nm;} +function opsLine(e){const I=INTERNS[e.i],name=I?tr(I.s):'',parts=e.r.map(([k,n,w])=>trn(OPS_SAY[k],n,{where:w.map(x=>opsWhere(x,k)).join(', ')})); + return (parts.length?tr('ops.l_line',{name,list:parts.join(', ')}):tr('ops.l_quiet',{name}))+opsPaid(e);} +const opsMo$=v=>(v>0?'+':'')+fmt$(v); +const opsPaid=e=>e.up||e.mo?' '+tr('ops.l_paid',{cost:fmt$(e.up||0),mo:opsMo$(e.mo||0)}):''; +// What the network costs every month before traffic: what a job adds to the bill (ports, routers, rent, links, cache boxes). +// PNIs count from the day they are ordered, at the size they are going to be. +function opsMoNow(){let m=cachesMo(); + for(const c in S.pops){const p=S.pops[c],rt=p.routers||1;m+=(rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[p.rgen||0].mo+(p.gen?GEN_MO:0)+(p.site2?SITE2_MO:0);} + for(const l of S.links)m+=(l.mo||0)+(l.kind==='df'?(l.spares?Math.round(150+(l.ch||[]).length*80):0)+(l.regen|0)*REGEN_MO:0); + for(const t of S.transit)m+=transitMo(t,0); + for(const p of S.pni){const q=p.up||p,N=NET[p.net];m+=(q.g1?Math.round(PORT[0].pni/2):PORT[q.tier].pni)*(q.n||1)+(N.pol==='paid'&&!paidFree(N)?N.paidFee:0);} + for(const c in S.ixp)if(!S.myIx[c])m+=ixPortMo(c,S.ixp[c])*((S.ixn||{})[c]||1); + return m;} +const opsFFLine=e=>tr('ops.ff_line',{name:tr(INTERNS[e.i].s),what:tr(OPS_FF[e.f],{city:CITY[e.c].name})}); +// Mute what a click would show (toasts, sounds, floaters, the full redraw) and keep the player's selection. +function opsQuiet(fn){const a=after,t=toast,s=sfx,f=floater,sel=UI.sel,cf=UI.confirm,tab=UI.tab;after=()=>{};toast=()=>{};sfx=()=>{};floater=()=>{}; + try{return fn();}finally{after=a;toast=t;sfx=s;floater=f;UI.confirm=cf;UI.tab=tab;UI.sel=sel&&(sel.type!=='link'||S.links.some(l=>l.id===sel.id))&&(sel.type!=='city'||isCity(sel.id))?sel:null;}} +// One shift's bookkeeping: what got done, and whether a job had to wait for next month's budget. +// dirty: a job changed the network, so R (loads, routing) is out of date until the next compute(). +// up/mo: what this shift paid up front and added to the monthly bill. +// dk: the night's fibers taken dark (n) and routings to test one (t), shared by the orders that do it (opsDarkRoom()). +// fib: the fibers and waves an order worked on this shift, by order: one owner per fiber a shift. +// ow: money already promised that has not left yet, what the IPv6-only swaps under way still owe (ip6Owed()), whoever +// started them: every order keeps it above the cash floor, so the swaps pay their routers without going under it. +// The order that starts a swap counts it again (bstdShift()). +function opsShift(){const r=new Map(),broke=new Set(); + return {r,broke,dirty:false,up:0,mo:0,dk:{n:0,t:0},fib:new Map(),ow:ip6Owed(),did(k,w){this.dirty=true;const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, + // A job that costs nothing up front still has to pass the cash floor if it adds to the monthly bill. + // quiet: only asking, so a no is not logged as the budget running out. + can(k,cost,mo=0,quiet){const O=S.ops,cap=opsCap(k);if(cost<=0&&!(mo>0))return true; + if(S.cash-Math.max(0,cost)-this.owcap)){if(!quiet)broke.add(k);return false;}return true;}, + book(k,d,dm){const O=S.ops;if(d>0){this.up+=d;if(OPSK[k].cap)O.spent[k]=(O.spent[k]||0)+d;}if(dm){this.mo+=dm;O.addMo[k]=(O.addMo[k]||0)+dm;}}, + // Run a click and book what it really cost; false when the action refused (no ports, no cash, a quote changed). + pay(k,fn){const c0=S.cash,m0=opsMoNow(),x=fn();this.book(k,c0-S.cash,opsMoNow()-m0);return x===undefined?c0-S.cash>0:x;}};} +// Never buy from a provider that breaks a promise: a customer's "no Cogentle" or "two upstreams", a bank's covenant, +// or Cogentle while it is not speaking to Goggle (the Spat scenario, a de-peering). Only met → failed counts. +const OPS_TREQ=['nocog','twoup']; +function opsTransitOk(n,c){if(n.id==='cog'&&(scnRule('spat')||S.ev.depeer>S.day))return false; + const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>OPS_TREQ.includes(k))),ls=(S.loans||[]).filter(l=>(l.covs||[]).includes('nocog'));if(!bz.length&&!ls.length)return true; + const chk=()=>bz.map(b=>b.reqs.every(k=>!OPS_TREQ.includes(k)||REQS[k].ok(b))).concat(ls.map(l=>COVS.nocog.ok(l))); + const was=chk(),all=S.transit;S.transit=all.concat({net:n.id,city:c});try{const now=chk();return was.every((v,i)=>!v||now[i]);}finally{S.transit=all;}} +const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)&&opsTransitOk(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0]; +// 'cheap' and 'have' (Already connected) name no network: quote the cheapest seller (#249). +const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;return n&&sellsAt(n,c)&&opsTransitOk(n,c)?n:cheapestTransit(c);}; +// The orders. Each takes the shift and does its jobs through the player's own actions. Most are generators: a yield +// after a job is only a place where a long shift may let a frame through (opsRun()), nothing changes there. +const OPS_RUN={ + // Bring POPs, ports and fiber up to the build standard: the busiest first, a few jobs a shift (96-pop-standard.js). + *std(X){yield* bstdShift(X);}, + *repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id}))){X.did('repair');yield;}}, + // Ports in use are counted for every POP at once, after the model swaps: a router added or swapped here changes no other POP's count. + *routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),G=bstd().g,fix=G!=='keep',cs=opsPops('routers'), + load=(c,u)=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),u/Math.max(1,portsMax(c))); + // The build standard's model: swap every POP still on a smaller one to the model the standard gives it (bstdModel(): + // the best unlocked one no bigger, never a step down, never one that does not fit or cannot run the core), the + // busiest first, while the budget lasts, and only with a second router or no traffic there. Not a POP marked as a kind + // (ptKind): its kind's standard picks its model. + if(fix){const pu=portsAt(cs);for(const c of cs.slice().sort((a,b)=>load(b,pu.get(b))-load(a,pu.get(a)))){const p=S.pops[c]; + if(p.rupDay===S.day||!((p.routers||1)>1||popIdle(c))||ptKind(c))continue;const m=bstdModel(G,c);if(m<0)continue; + const cost=swapCost(c,m);if(!X.can('routers',cost))continue; + if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}} + const pu=portsAt(cs); + for(const c of cs){const p=S.pops[c];if(p.rupDay===S.day)continue; + const ld=load(c,pu.get(c));if(ld=0&&rgOpen(nx)&&!modelFits(c,nx)&&(rt>1||popIdle(c)),add=rt=4||!add);if(!doSwap&&(how==='swap'||!add))continue; + const cost=doSwap?swapCost(c,nx):routerCost(g,rt);if(!X.can('routers',cost))continue; + if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));yield;}}, + *transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x'); + for(const c of opsPops('transit')){let ts=S.transit.filter(t=>t.city===c);if(!ts.length)continue; + // Thirty days of 95th-percentile-ish history per port; their peaks summed is a safe (high) estimate of the POP's peak. + const peak=ts.reduce((a,t)=>a+(t.hist||[]).reduce((m,v)=>Math.max(m,v),0),0)*opsAhead();if(!(peak>0))continue; + // "Already connected" (#227): only the providers you buy from here, the smallest first, never a new contract. + const have=opsP('transit','prov')==='have',n=have?null:opsProv(c);if(!have&&!n)continue; + const grow=t=>{const k=t.n||1,up=t.tier+1; + if(k<4&&portOk(c,t.tier))return {cost:PORT[t.tier].setup,go:()=>ACT.lagT({id:t.id,d:1}),w:'+1×'+PORT[t.tier].n}; + if(PORT[up]&&portShown(up)&&portOk(c,up))return {cost:PORT[up].setup*k,go:()=>ACT.buyTransit({city:c,net:t.net,tier:up}),w:PORT[t.tier].n+'→'+PORT[up].n}; + if(kACT.lagT({id:t.id,d:1}),w:'+1×'+PORT[t.tier].n};return null;}; + for(let step=0;step<4;step++){const cap=ts.reduce((a,t)=>a+lagCap(PORT[t.tier].g,t.n),0);if(cap>=N*peak)break; + let job=null; + if(have){for(const t of ts.slice().sort((a,b)=>lagCap(PORT[a.tier].g,a.n)-lagCap(PORT[b.tier].g,b.n)||transitPerG(NET[a.net],c,!!a.premium)-transitPerG(NET[b.net],c,!!b.premium))){job=grow(t);if(job)break;}} + else{const t=ts.find(x=>x.net===n.id); + if(t)job=grow(t); + else{const need=N*peak-cap,ok=PORT.map((P,i)=>i).filter(i=>portShown(i)&&portOk(c,i)),i=ok.find(i=>PORT[i].g>=need)??ok.at(-1); + if(i!==undefined)job={cost:PORT[i].setup,go:()=>ACT.buyTransit({city:c,net:n.id,tier:i}),w:'+'+PORT[i].n};}} + if(!job||!X.can('transit',job.cost)||!X.pay('transit',job.go))break; + X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);yield;}}}, + // PNIs and IX ports keep Headroom times today's traffic, hottest first. One port at a POP with several routers gets a + // second in a LAG, so it is not the only way out; anything else moves up to the smallest port size that fits. A PNI + // augment lands weeks later, so that port waits for it. A flood fills ports for a day or two: not worth buying for. + *ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[], + // Router ports that pending PNI augments will take when they land are spoken for. + // Both, by city, are worked out once between two jobs (a job may change them; KV is dropped after each), in the order + // the PNIs come, as the sum over them was: the same numbers. + KV={rv:null,pu:new Map()}, + resv=c=>{if(!KV.rv){KV.rv=new Map();for(const p of S.pni)if(p.up)KV.rv.set(p.city,(KV.rv.get(p.city)||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)));}return KV.rv.get(c)||0;}, + used=c=>{let u=KV.pu.get(c);if(u===undefined)KV.pu.set(c,u=portsUsed(c));return u;},room=c=>portsMax(c)-used(c)+1e-9-resv(c); + // Each port: cap() now, use today, lag() and ups() the jobs it could have as {cost, cap after, w for the log, go}, sig() to see a job took. + for(const p of S.pni){const c=p.city,use=(R.usePni[p.id]||0)*opsAhead(),cap=()=>lagCap(pniG(p),p.n),n=()=>p.n||1;if(!pniOn(p)||p.up||!(use>0)||cap()>=N*use||!opsHere('ports',c))continue; + L.push({city:c,at:c,use,u:use/cap(),cap,n,rt:(S.pops[c]||{}).routers||1,busy:()=>!!p.up,sig:()=>[p.tier,n(),!!p.g1,!!p.up].join(), + lag:()=>n()ACT.lagP({id:p.id,d:1})}:null, + ups:()=>{const out=[];for(let t=p.g1?0:p.tier+1;tACT.pni({city:c,net:p.net,tier:t})});}return out;}});} + // Nominal capacity, not ixCap(): a LACP fault or one building down halves a LAG for a day or two, not worth a bigger port. + for(const x in S.ixp){const c=ixCity(x),use=(R.useIx[x]||0)*opsAhead(),n=()=>(S.ixn||{})[x]||1,cap=()=>lagCap(PORT[S.ixp[x]].g,n())*(isRemote(x)?REMOTE_CAP:1),pop=S.pops[c];if(S.myIx[x]||!(use>0)||!(cap()>0)||cap()>=N*use||!opsHere('ports',c))continue; + const g=()=>PORT[S.ixp[x]].g; + L.push({city:c,at:x,use,u:use/cap(),cap,n,rt:pop?pop.routers||1:1,busy:()=>false,sig:()=>S.ixp[x]+','+n(), + lag:()=>pop&&n()ACT.lagIx({city:x,d:1})}:null, + // A remote port (no POP there) stops at 100G; at a POP the router has to take the bigger port. + ups:()=>{const out=[],t0=S.ixp[x];for(let t=t0+1;troom(c):t>1)continue; + out.push({cost:ixPortMo(x,t)*n(),cap:cap()*lagCap(PORT[t].g,n())/lagCap(g(),n()),w:PORT[t0].n+'→'+PORT[t].n,go:()=>ACT.buyIx({city:x,tier:t})});}return out;}});} + for(const o of L.sort((a,b)=>b.u-a.u))for(let step=0;step<3&&!o.busy()&&o.cap()1,ups=wantLag&&lag?null:o.ups(),fit=ups&&(ups.find(u=>u.cap>=N*o.use)||ups.at(-1)),job=wantLag?lag||fit:fit||lag,was=o.sig(); + if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;})){KV.rv=null;KV.pu.clear();break;} + KV.rv=null;KV.pu.clear();X.did('ports',o.at+' '+job.w);yield;}}, + *optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',fresh=opsP('optics','fresh'),gpd=(o,l)=>optG(o,l)/optCost(o); + for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day||(!fresh&&!(l.ch||[]).length))continue; + let cap=dfCap(l);const load=((R.load&&R.load[l.id])||0)*opsAhead(); + // New fiber gets its first channel; lit fiber gets more while it runs hot. A fiber that only carries expresses is + // not new: it was left bare so the city in the middle needs no router ports. + for(let step=0;step<8&&(cap<=0?!(l.ch||[]).length&&!xpSlots(l):load>=cap*at);step++){if(chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l)<=0)break; + const cnt={};for(const k of l.ch||[])cnt[k]=(cnt[k]||0)+1; + // More of what is already lit, or else the most Gbps per dollar that reaches. Told to go big (#262), the intern + // picks the most Gbps per channel it can afford for a new kind of optic, but never swaps what is already lit. + const fit=Object.keys(OPT).filter(o=>!chWhy(l,o)),cheap=fit.slice().sort((a,b)=>gpd(b,l)-gpd(a,l)), + // A build standard that wants the fastest optics gets those first, so the two orders never undo each other. + fast=bstdFast()&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)), + o=fast||fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||(big&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||gpd(b,l)-gpd(a,l)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)))||cheap[0];if(!o)break; + const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break; + X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break; + cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);yield;}}}, + *optup(X){const at=opsP('optup','at')/100,sys=bstd().sys,goal=sys==='keep'?'next':sys,swap=opsP('optup','swap'); + const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)*opsAhead()>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l)); + // A fiber the build standard's order worked on this shift is that order's until tomorrow. + const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)&&(X.fib.get(l.id)||'optup')==='optup').sort((a,b)=>u(b)-u(a)); + for(const l of ls){ + // The line system: one step at a time up to the build standard's, or the next one where the fiber is full and hot. + const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]S.day)&&X.can('optup',cost)){const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT); + if(ok){const s0=l.sys,top=goal==='next'?to:goal; + for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;} + // The fiber is dark until tomorrow: its optics wait. + if(l.sys!==s0){X.dk.n++;X.fib.set(l.id,'optup');X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);yield;continue;}}}} + // Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and + // the old optics go on the shelf as spares. + if(!swap)continue; + for(let step=0;step<8&&full(l)&&hot(l);step++){const cnt={};for(const k of l.ch||[])cnt[k]=(cnt[k]||0)+1; + const lit=Object.keys(cnt).sort((a,b)=>optG(a,l)-optG(b,l)),o1=lit[0];if(!o1)break; + const ports=(o,c)=>S.pops[c]?chPorts(o,c):0,room=(o2,c)=>!S.pops[c]||portsUsed(c)+ports(o2,c)-ports(o1,c)<=portsMax(c)+1e-9; + // Asked with one small channel already out: a full fiber refuses any optic. + const ch0=l.ch,i1=ch0.indexOf(o1);l.ch=ch0.filter((k,i)=>i!==i1);let o2; + try{o2=Object.keys(OPT).filter(o=>optG(o,l)>optG(o1,l)&&!chWhy(l,o)&&room(o,l.a)&&room(o,l.b)).sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b))[0];}finally{l.ch=ch0;}if(!o2)break; + const n2=(cnt[o2]||0)+1,cost=opticCountCost(l,o2,n2);if(!X.can('optup',cost))break; + const was=dfCap(l); + X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2}); + if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;}); + if(!(dfCap(l)>was))break;X.fib.set(l.id,'optup');X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}}, + // The boxes sorted by POP once: the boxes racked at one POP change no other POP's plan. + *caches(X){const g=opsP('caches','g'),by=new Map();for(const x of S.caches){const a=by.get(x.city);if(a)a.push(x);else by.set(x.city,[x]);} + for(const c of opsPops('caches')){const add=cachePlan(c,by.get(c)||[]);if(!add||!add.length)continue; + const want=add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9; + for(const x of want){if(cachePortsAdd(c,[x])>free())continue;if(!X.can('caches',0,cacheMo(x)))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site,...(x.g?{g:x.g}:{})});X.book('caches',0,cacheMo(x));X.did('caches',c);} + yield;}}, + // Weekly, like a person going through PeeringDB on a Monday: route servers, then every willing member (#192). + ix(X){if(S.day%7&&!opsIs('annie'))return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');} + for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}}, + // Weekly too: every willing network above the threshold, at its own minimum size and lead time (#181). + *pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return; + // The batch a few networks at a time; if the player acted in between (an action routes), it is made again in one go. + const g0=RW.gen,it=pniBatchRun(null,opsP('pni','tier'));let b;for(;;){const s=it.next();if(s.done){b=s.value;break;}yield;} + if(RW.gen!==g0)b=pniBatch(null,opsP('pni','tier'));if(!b)return;yield;const g=opsP('pni','g'),paid=opsP('pni','paid'); + // The traffic a PNI there would take over: what your users at that POP send to the network today over transit, an + // exchange or a PNI elsewhere, the same figure the PNI list shows. Not the city's whole demand: a network's own + // cache boxes in that POP already serve most of it (#244). + // pniVal()'s want, without the rest pniVal() prices (the transit it saves, the port): all the order asks (pniWant()). + const lv=new Map(),loc=q=>{let v=lv.get(q);if(v===undefined)lv.set(q,v=pniWant(q.city,q.net));return v;}; + // Each order quoted again just before it is placed: the player may have ordered the same PNI by hand while the shift + // let a frame through or waited for a routing, and the batch's quote would order it a second time. + for(const q0 of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){ + const q=pniRequote(q0);if(!q)continue;if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);yield;}}, + // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). + // Loads must include what this shift already did (a customer just signed, a repair): opsRun() routes first if a + // job changed the network and anything could go (opsDecomWaits()). A wave another order worked on today stays. + // (Left out of what the pick hands back, not out of the pick: it may still be the spare the pick keeps.) + *decom(X){for(const ls of opsPairs().values())for(const l of opsDecomPick(ls).filter(l=>!X.fib.has(l.id))){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}}, +}; +// Line system swaps per shift, and how many fibers a shift may test for one with a routing: each test routes the whole +// network once, so a shift costs at most one routing more, and only on a night with a fiber to try. The build standard's +// order and this one share them (X.dk). A fiber that failed the test is not tested again for a week +// (not saved: after a reload it is simply tested again). +const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,roadm:1,cl:2},SYS_TAG={roadm:'ROADM',cl:'C+L'}; +// Room tonight for one more fiber going dark. Kevin does maintenance: twice the swaps, and twice the tests. +const opsDarkRoom=X=>{const k=opsIs('kevin')?2:1;return X.dk.n{const L=(R&&R.load)||{};return !(L[l.id]>1e-6)&&!xpOver(l.id).some(x=>L[x.id]>1e-6);}; +// What a day dark comes to, said without routing: false (a customer's wave rides its line system, or it carries traffic +// with no other way between its cities), true (nothing rides it, so nothing is lost), null (a routing decides: +// opsDarkTrial()). Leased pairs and IRUs are glass: a line-system swap never touches them. ws: as dfWaveCust() takes it. +function opsDarkPre(l,ws){if(dfWaveCust(l,ws))return false;return opsUnused(l)?true:opsAround(l)?null:false;} +const OPS_ROUTE={route:true}; +// X.dk.t counts the tests that route. +function* opsDark(l,X){let k=opsDarkPre(l);if(k===false)return false;if(X.dirty){yield OPS_ROUTE;X.dirty=false;k=opsDarkPre(l);} + if(k!==null)return k;X.dk.t++;return !!(yield {dark:l.id,s0:R.served,L0:R.l2||{}});} +// The test itself, on the game it is given: R is put back after. The fiber's line system is down for the day (eqDown), +// and every express riding it with it (xpDown()): their traffic has to get around too. +function opsDarkTrial(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const R0=R,e0=l.eqDown,s0=y.s0,L0=y.L0; + try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);} + finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}} +// The waves decom hands back on one city pair (ls: every link between them): the smaller ones the rest carry with 25% to +// spare, smallest first, less the spare it keeps. cf: each link's capacity (the build standard asks with the sizes its +// wave upgrades will give, so it never upgrades one that goes back). +function opsDecomPick(ls,cf=capOf){if(!ls||ls.length<2)return [];const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||cf(l)>cf(a)?l:a,null),out=[];if(!big)return out; + let cap=live.reduce((a,l)=>a+cf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0); + const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&cf(l)b.link===l.id)).sort((a,b)=>cf(b)-cf(a)); + // The spare is there for when the big link's trench is cut, so it has to live in another trench. + if(opsP('decom','keep')&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);} + for(const l of small.reverse()){if(cap-cf(l)x.id===y.dark);if(!l)return false;const k=opsDarkPre(l); + return k!==null?k:opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});} +// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it (and gone) first. +function opsDecomSafe(l,gone=[]){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; + const was=bz.filter(promiseCheck()),all=S.links;S.links=all.filter(x=>x!==l&&!gone.includes(x));try{return was.every(promiseCheck());}finally{S.links=all;}} +/* Those promises, asked for many customers on one network: each search is made once and shared (a diversity graph, the + land islands, one latency search per city a customer starts from). Same answers as diversePaths(), terrestrialPath() + and bestLat() asked one by one. */ +function promiseCheck(){let dg=null,ti=null,lg=null;const dv=new Map(),ld=new Map(); + const div=(a,b)=>{const k=a+'>'+b;let r=dv.get(k);if(r===undefined)dv.set(k,r=divOn(dg||(dg=divGraph()),a,b));return r;}; + const land=(a,b)=>{if(a===b)return true;ti=ti||terrIslands();const A=ti.get(a);return A!==undefined&&A===ti.get(b);}; + const lat=(a,b)=>{lg=lg||latGraph();if(!ld.has(a))ld.set(a,latRun(lg,a));return latAt(lg,ld.get(a),a,b);}; + return b=>(b.reqs||[]).every(k=>k==='diverse'?div(b.city,b.city2):k==='sharks'?land(b.city,b.city2):k==='lat'?lat(b.city,b.city2)<=b.latMax:true);} +// The links between each pair of cities, VXCs and satellite circuits left out. +function opsPairs(){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'&&l.kind!=='sat'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}return by;} +const opsDecomWaits=()=>[...opsPairs().values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave')); +const OPS_ORDER=['repair','std','routers','transit','ports','optup','optics','caches','ix','pni','decom']; +// The shift: once per game day from dayTick, after outages and events have had their turn. +// One shift. Like a day (dayRun()), it is a generator: each yield is a compute() it needs, answered by the route worker +// in play, so the shift never routes on the page. opsDay() runs it in one go. +function opsDay(d){dayGo(opsRun(d),(g,v)=>g.next(v));} +function* opsRun(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} + // A new week: last week's tally becomes the shift report, and the one NOC notice of the week. + const w=Math.floor(d/7);if(!O.wk||O.wk.w!==w){if(opsWkAny(O.wk)&&O.wk.w${esc(tr('ops.shift_report',{name:opsName()}))} ${esc(opsWeekLine(O.rep))}`,'',[],{a:'ops'});}O.wk=opsWkNew(w);} + const X=opsShift(); + // One order that trips over something (an odd save, a bug) is paused and noted; payday, goals and the save still happen. + // Each order is a step of the day: a long shift lets the map draw between two (DAY_REST). The interface the orders + // click through (selection, tab, confirmation) goes on from where the last order left it, as in one go; the player's + // own is back in between. + let ui=null; + // One step of an order, muted (opsQuiet()): a plain order all at once, a generator up to its next yield. A bare yield + // is a rest; OPS_ROUTE or a {dark} test is a routing the day answers (v, passed back in). + const step=(k,st,v)=>opsQuiet(()=>{if(ui){UI.sel=ui.sel;UI.confirm=ui.cf;UI.tab=ui.tab;}st.ask=undefined; + try{if(!st.it){const r=OPS_RUN[k](X);if(r&&typeof r.next==='function')st.it=r;else st.done=true;}if(!st.done){const s=st.it.next(v);if(s.done)st.done=true;else st.ask=s.value;}} + catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);st.done=true;} + ui={sel:UI.sel,cf:UI.confirm,tab:UI.tab};}); + const order=function*(k){const st={it:null,done:false};let v;for(;;){step(k,st,v);v=undefined;if(st.done)return; + if(st.ask===OPS_ROUTE)yield;else if(st.ask&&st.ask.dark)v=yield st.ask;else yield DAY_REST;}}; + // Every order but the last, decommissioning, which reads today's loads: routed first when a job changed them. + for(const k of OPS_ORDER.slice(0,-1))if(O.on[k]){yield* order(k);yield DAY_REST;} + if(O.on.decom&&X.dirty&&opsDecomWaits()){yield;X.dirty=false;} + ui=null;if(O.on.decom)yield* order('decom'); + // At most three places a kind, as the shift log keeps them (opsLogOk()): the count still says how many budgets ran out. + const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke].slice(0,3)]); + // Very rarely, and never under Change Freeze, the intern fat-fingers something harmless. + // Kevin rolls the same dice (so a seeded game plays the same whoever is hired) and catches it before pressing Enter. + const ff=OPS_FF_RATE[rulePreset()];if(ff&&Object.keys(S.pops).length&&Math.random()t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;else X.dirty=true;} + e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);}} + if(X.up)e.up=Math.round(X.up);if(Math.round(X.mo))e.mo=Math.round(X.mo); + // Stopping at a budget changes nothing a route depends on: no recompute for that. + if(X.dirty)yield; + if(e.r.length||e.f!==undefined){O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);} + // The day's detail stays in the Ops sheet; the NOC gets one notice a week (above). + // A job with no place (a rushed repair, a route server) adds no empty list to the tally: a reload keeps none (opsWkOk()). + const W=O.wk;for(const [k,n,ws] of e.r){W.n[k]=(W.n[k]||0)+n;if(!ws.length)continue;const a=W.wh[k]||(W.wh[k]=[]);for(const x of ws)if(a.length<3&&!a.includes(x))a.push(x);} + W.up+=e.up||0;W.mo+=e.mo||0;if(e.f!==undefined)W.ff=Math.min(7,W.ff+1);} +// New POP from the template: price the whole bundle first, then click through it in one go. +function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))return null;const T=S.ops.tpl,parts=[];let cost=popCost(c),net=null,ix=null,kit=null; + if(T.bb){cost+=bbCost(c);parts.push(tr('ops.tpl_bb'));} + if(T.transit&&!scnRule('noTransit')){net=opsProv(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}} + // Priced as if the POP were already there (an IX port is dearer from afar). DE-KICKS wants a sales call first, so not those. + // The standard routers go in first (#261), so they are in the price and the kit is priced for them. + // The standard's building and generator too, so the kit only prices what the standard leaves out: nothing twice. + const sq=popStdQuote();if(sq){cost+=sq.cost;parts.push(sq.site2||sq.gen?tr('ops.tpl_bstd'):tr('ops.tpl_std'));} + S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:sq?sq.rt:1,gen:!!(sq&&sq.gen),rgen:sq?sq.g:0,...(sq&&sq.site2?{site2:true}:{})}; + try{if(T.ix&&CITY[c].ix&&!isDk(c)&&S.ixp[c]===undefined){ix=c;cost+=ixPortMo(c,0);parts.push(tr('ops.tpl_ix'));} + if(T.kit){kit=utilityKit(c);if(kit&&kit.cost){cost+=kit.cost;parts.push(tr('ops.tpl_kit'));}}}finally{delete S.pops[c];} + return {cost,net:net&&net.id,ix,kit:!!(kit&&kit.cost),parts};} diff --git a/src/game/60-features/96-architect.js b/src/game/60-features/96-architect.js new file mode 100644 index 0000000..ed69701 --- /dev/null +++ b/src/game/60-features/96-architect.js @@ -0,0 +1,164 @@ +/* ================= ARCHITECT RUNS (prototype) ================= + One network, built brief by brief. A brief adds sites, makes some of them gold (a gold site must stay connected to HQ + whichever single trench or cable is cut), sets a latency cap, or closes a city. The build carries over: what earlier + briefs built is paid for, so removing it gives nothing back. ▶ lets the chaos monkey loose: it cuts every trench and cable one + at a time, and the brief is done when every gold site survives. Runs on the puzzle machinery (S.mode 'puzzle' with + S.ar), so there is no clock, no bills, no incidents, and the main save is never touched. + Capacity: every site pulls its traffic from HQ, and the review also checks that the detour has room: after any single + cut, everything still connected gets all of its traffic. Tubes come in three sizes; routers follow by themselves (the + cheapest model that takes the tubes), and traffic finds the detour by itself (Auto-TE): models, ports and metrics are + someone else's job. */ +const AR_KEY='sot-architect',AR_TIER=1,AR_TIERS=[0,1,2],AR_RUN=550,AR_HOLD=650; // ms: the monkey's run to a tube, then how long the cut shows +// A brief: add (new sites), gold (sites that must survive any single cut), ring (sites that must sit on one ring), drop +// (close a city: no POP allowed there any more), dem {city: Gbps} (what a site pulls from HQ, 10G unless set; a later +// brief can raise it), lat [a,b,ms] (the fastest path between two sites under ms), tubes (the +// plan: how many new tubes this brief should take; going over is allowed and costs a star), t (the brief). +// budget: one round number for the whole run, a little above the best plan found (tests/architect.test.js), and below +// the obvious one. Money never blocks a brief. ⭐ every brief done, ⭐ never over a brief's tubes, ⭐ within budget. +const AR_RUNS=[ + {id:'euro',n:tr('architect.euro_run'),j:tr('architect.euro_run_joke'),hq:'ams',via:[],budget:410000,briefs:[ + {add:['fra'],dem:{fra:40},tubes:1,t:tr('architect.euro_1')}, + {add:['par','lon'],dem:{par:50,lon:60},tubes:2,t:tr('architect.euro_2b')}, + {gold:['fra','par'],tubes:1,t:tr('architect.euro_3b')}, + {add:['zrh'],dem:{zrh:40},gold:['zrh'],tubes:2,t:tr('architect.euro_5')}, + {ring:['ams','par','lon'],dem:{par:100},tubes:2,t:tr('architect.euro_ring_grow')}, + {drop:['fra'],add:['dus'],dem:{dus:60},gold:['dus'],tubes:2,t:tr('architect.euro_6')}, + ]}, + {id:'usa',n:tr('architect.coast_to_coast'),j:tr('architect.coast_to_coast_joke'),hq:'ash',via:[],budget:610000,briefs:[ + {add:['nyc'],t:tr('architect.usa_1')}, + {add:['chi'],t:tr('architect.usa_2')}, + {gold:['nyc'],t:tr('architect.usa_3')}, + {lat:['nyc','chi',8],t:tr('architect.usa_4')}, + {add:['dal','sjc'],t:tr('architect.usa_5')}, + {gold:['sjc'],t:tr('architect.usa_6')}, + ]}, + {id:'pacific',n:tr('architect.pacific_rim'),j:tr('architect.pacific_rim_joke'),hq:'tok',via:[],budget:2350000,briefs:[ + {add:['hkg'],t:tr('architect.pac_1')}, + {add:['sin'],t:tr('architect.pac_2')}, + {gold:['hkg'],t:tr('architect.pac_3')}, + {gold:['sin'],t:tr('architect.pac_4')}, + {add:['syd'],t:tr('architect.pac_5')}, + ]}, +]; +const arOn=()=>pzOn()&&!!S.ar; +const arRunDef=id=>AR_RUNS.find(r=>r.id===id)||arWkRun(id); +const arRun=()=>arRunDef(S.ar.id); +const arBrief=()=>arRun().briefs[S.ar.bi]; +const arLast=()=>S.ar.bi>=arRun().briefs.length-1; +// ---------- progress: best stars, spend and briefs cleared per run, under its own key ---------- +function arLoad(){let j=null;try{j=JSON.parse(localStorage.getItem(AR_KEY)||'{}');}catch(e){}const o={runs:{}}; + if(j&&j.runs&&typeof j.runs==='object')for(const k of Object.keys(j.runs)){const r=j.runs[k];if((!arRunDef(k)&&!AR_WK_ID.test(k))||!r||typeof r!=='object')continue; + o.runs[k]={st:int(r.st,0,3,0),br:int(r.br,0,99,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)};if(AR_WK_ID.test(k))o.runs[k].rv=int(r.rv,1,999,1);} + return o;} +function arStore(p){try{localStorage.setItem(AR_KEY,JSON.stringify(p));}catch(e){}} +function arRecord(st,br,sp){const p=arLoad(),run=arRun(),old=p.runs[S.ar.id],r=old&&(!run.wk||(old.rv||1)===run.rev)?old:{st:0,br:0,sp:null};if(run.wk)r.rv=run.rev; + if(st>r.st||(st===r.st&&st>0&&(r.sp==null||sppzPopCost(c)+pzRouterCost(c); +const arLinkCost=l=>l.mo*PZ_YEAR; +const arSpend=()=>pzSpend()+S.ar.sunk; +// Removing what an earlier brief built gives nothing back. +const arAge=l=>l.ub==null?(l.br|0):l.ub; +function arSink(pops,links){const A=S.ar;for(const c of pops)if(S.pops[c]&&(S.pops[c].br|0)pzUnit(l)===u),r=arReach(S.ar.hq,nb);return S.pz.cities.filter(c=>S.pops[c]&&!r.has(c));} +// The fastest path between two sites, by the links' own latency. +function arLat(a,b){if(!S.pops[a]||!S.pops[b])return null;const d={[a]:0},done=new Set(); + for(;;){let u=null;for(const k in d)if(!done.has(k)&&(u===null||d[k]nb[c]&&nb[c].size>=2))return false;const st=cs[0],on=new Set([st]);let ok=false,n=0; + const dfs=(u,d)=>{for(const v of nb[u]){if(ok||++n>50000)return;if(v===st&&d>=3&&cs.every(c=>on.has(c))){ok=true;return;}if(on.has(v))continue;on.add(v);dfs(v,d+1);on.delete(v);}}; + dfs(st,1);return ok;} +// Tubes laid in this brief, against its plan. +const arTubes=()=>{const b=arBrief(),u=S.links.filter(l=>(l.br|0)===S.ar.bi).length;return {u,max:b.tubes==null?null:b.tubes,over:b.tubes==null?0:Math.max(0,u-b.tubes)};}; +// ---------- the brief's checklist ---------- +function arEval(){const A=S.ar,P=S.pz,nb=arAdj(),r=arReach(A.hq,nb); + const got=S.links.some(l=>l.cut)&&UI.arBaseGot?UI.arBaseGot:arGot(); + const sites=P.cities.map(c=>({c,pop:!!S.pops[c],ok:!!S.pops[c]&&r.has(c),gold:A.gold.includes(c),hq:c===A.hq,dem:c===A.hq?0:arDem(c),got:c===A.hq?0:got[c]||0}));for(const s of sites)s.full=s.hq||s.got>=s.dem*0.999-1e-6; + const conn=sites.every(s=>s.ok),lat=A.lat?{a:A.lat[0],b:A.lat[1],cap:A.lat[2],ms:arLat(A.lat[0],A.lat[1])}:null;if(lat)lat.ok=lat.ms!=null&&lat.ms<=lat.cap+1e-9; + const moveOut=P.avoid.filter(c=>S.pops[c]),spend=arSpend(),budget=arRun().budget,cheap=spend<=budget+1e-6,miss=sites.filter(s=>!s.ok).map(s=>CITY[s.c].name),rings=A.rings.map(cs=>({cs,ok:arRingOk(cs)})),tubes=arTubes(); + const why=!conn?tr('architect.not_connected_yet_list',{list:miss.join(', ')}):lat&&!lat.ok?tr('architect.too_slow_for_the_cap'):rings.some(r=>!r.ok)?tr('architect.not_a_ring_yet'):sites.some(s=>!s.full)?tr('architect.too_thin_list',{list:sites.filter(s=>!s.full).map(s=>`${CITY[s.c].name} ${arG(s.got)}/${arG(s.dem)}`).join(', ')}):moveOut.length?tr('architect.move_out_of_city',{city:moveOut.map(c=>CITY[c].name).join(', ')}):''; + return {sites,conn,lat,rings,tubes,moveOut,spend,budget,cheap,ready:!why,why,passed:A.passed===pzSig()};} +// ---------- the shape: the game names what you drew ---------- +const AR_SHAPES={braces:['🦺',N_('architect.shape_braces')],tube:['🧪',N_('architect.shape_tube')],line:['➖',N_('architect.shape_line')],star:['✳️',N_('architect.shape_star')],tree:['🌳',N_('architect.shape_tree')],ring:['💍',N_('architect.shape_ring')],lolli:['🍭',N_('architect.shape_lolli')],ladder:['🪜',N_('architect.shape_ladder')],mesh:['🕸️',N_('architect.shape_mesh')],full:['🧶',N_('architect.shape_full')],islands:['🏝️',N_('architect.shape_islands')],spaghetti:['🍝',N_('architect.shape_spaghetti')]}; +function arShape(){const ns=Object.keys(S.pops),n=ns.length;if(n<2||!S.links.length)return null;const nb=arAdj(),m=new Set(S.links.map(edgeKey)).size,deg=c=>nb[c].size,maxd=Math.max(...ns.map(deg)); + const dbl=[...new Set(S.links.map(edgeKey))].filter(e=>new Set(S.links.filter(l=>edgeKey(l)===e).map(pzUnit)).size>1).length; + let k;if(arReach(ns[0],nb).size=4?'star':maxd<=2?'line':'tree'; + else if(ns.every(c=>deg(c)===2))k='ring';else if(n>=4&&m===n*(n-1)/2)k='full'; + else{const core={};for(const c of ns)core[c]=new Set(nb[c]);let cut=true;while(cut){cut=false;for(const c in core)if(core[c].size<=1){for(const v of core[c])core[v]&&core[v].delete(c);delete core[c];cut=true;}} + const cs=Object.keys(core),cm=cs.reduce((a,c)=>a+core[c].size,0)/2,d2=cs.filter(c=>core[c].size===2).length; + k=cs.lengthcore[c].size===2)?'lolli':cs.length===n&&n>=6&&n%2===0&&cm===3*n/2-2&&d2===4&&cs.every(c=>core[c].size<=3)?'ladder':m>=n*1.8?'spaghetti':'mesh';} + return {k,i:AR_SHAPES[k][0],n:tr(AR_SHAPES[k][1])};} +// What later briefs do to a city, for the map: [{n: brief number, i: icon}], earliest first. +// ---------- starting, briefs and the end ---------- +const arDem=c=>S.ar.dem[c]||10; +// Short Gbps for chips and tags: 40G, 1.2T. +const arG=g=>g>=1000?+(g/1000).toFixed(1)+'T':Math.round(g)+'G'; +function arDemand(){const P=S.pz,A=S.ar;P.src=[A.hq];P.dem=P.cities.filter(c=>c!==A.hq).map(c=>({t:'eye',a:c,b:null,g:arDem(c),ms:0,be:false}));pzDemand(); + for(const c in S.pops)S.pops[c].bb=P.cities.includes(c)&&c!==A.hq?{d:arDem(c)}:null;} +// What each site gets right now, from the last compute(). +function arGot(){const g=pzGot(),o={};S.pz.dem.forEach((f,i)=>{o[f.a]=g[i].g;});return o;} +// Connected sites that do not get all of their traffic. +function arShort(dark){const got=arGot();return S.pz.cities.filter(c=>c!==S.ar.hq&&S.pops[c]&&!(dark||[]).includes(c)&&(got[c]||0)PZ_RG.slice().sort((a,b)=>pzRtCost(a,1)-pzRtCost(b,1)); +function arRouters(){for(const c in S.pops){const p=S.pops[c];p.routers=1;p.rgen=AR_RG().find(g=>!modelFits(c,g))??(p.rgen||0);}} +// The yearly router cost a tube of this size would add at a city (0 when its router already takes it). +function arRouterDelta(c,tier){const p=S.pops[c],cur=p?pzRtCost(p.rgen||0,1):0,need=Math.max(tier,...S.links.filter(l=>l.a===c||l.b===c).map(l=>l.tier)),g=AR_RG().find(i=>RG[i].maxLT>=need);return g==null?0:Math.max(0,pzRtCost(g,1)-cur);} +const arSnapStr=()=>JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},k:S.ar.sunk}); +function arBegin(run){if(!run)return;mkStop();const b0=run.briefs[0]; + pzBegin({id:'ar_'+run.id,n:run.n,src:[run.hq],dem:b0.add.map(c=>({t:'eye',a:c,g:1})),via:run.via,budget:0}); + pzToastsClear();S.pz.n=run.n;S.te={on:true,day:0};S.ar={id:run.id,hq:run.hq,bi:-1,sunk:0,over:0,dem:{},rings:[],gold:[],lat:null,passed:null,start:null};UI.arAll=false;arStop(true); + S.pops[run.hq]=pzNewPop(run.hq);arApply(0);} +function arApply(i){const A=S.ar,P=S.pz,b=arRun().briefs[i];A.bi=i; + for(const c of b.drop||[]){P.cities=P.cities.filter(x=>x!==c);A.gold=A.gold.filter(x=>x!==c);if(!P.avoid.includes(c))P.avoid.push(c);if(A.lat&&A.lat.includes(c))A.lat=null;A.rings=A.rings.filter(r=>!r.includes(c));} + for(const c of b.add||[])if(!P.cities.includes(c))P.cities.push(c); + for(const c of b.gold||[])if(!A.gold.includes(c))A.gold.push(c); + if(b.ring)A.rings.push(b.ring.slice());Object.assign(A.dem,b.dem||{}); + if(b.lat)A.lat=b.lat.slice();A.passed=null; + // Later briefs stay a surprise: their cities do not show until they come (Show all cities shows everything). + P.via=(arRun().via||[]).filter(c=>!P.cities.includes(c)&&!P.avoid.includes(c)); + arDemand();A.start=arSnapStr();UI.pzHist=[];UI.sel=null;UI.arFail=null; + compute();pzCam();renderAll(); + toast(`${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}
${esc(b.t)}`,'goal');sfx('click');} +function arNext(){if(!arOn())return;const e=arEval();if(!e.passed)return;mkStop();if(arLast()){arResults(true);return;}S.ar.over+=e.tubes.over;arApply(S.ar.bi+1);} +function arReset(){const o=JSON.parse(S.ar.start);S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};S.ar.sunk=o.k||0;arDemand();UI.sel=null;} +// Tubes over plan in the run so far, this brief included. +const arOver=()=>S.ar.over+arTubes().over; +function arStars(sp){return 1+(arOver()?0:1)+(sp<=arRun().budget+1e-6?1:0);} +function arShareText(st,sp){const sh=arShape();return tr('architect.share_line',{what:arRun().n,stars:pzStarStr(st),spend:fmt$(sp),shape:sh?sh.i+' '+sh.n:''});} +// ---------- ▶ the chaos monkey review ---------- +// Every trench and cable is cut in turn, routed by compute() so the traffic visibly moves; a gold site losing HQ stops +// the review with the cut still on the map, until the next edit. +function arStop(quiet){mkStop();const sh=UI.arShow;if(sh&&sh.t)clearTimeout(sh.t);UI.arShow=null;if(!S||!S.links)return;let any=false;for(const l of S.links)if(l.cut){l.cut=0;any=true;} + if(UI.arFail){UI.arFail=null;any=true;}if(any&&!quiet)compute();} +function arShowStart(){if(!arOn()||UI.arShow)return;const e=arEval();if(!e.ready){toast(esc(e.why),'bad');sfx('err');return;} + arStop(true);UI.sel=null;closeModal();UI.arBaseGot=arGot();UI.arShow={units:[...new Set(S.links.map(pzUnit))],i:-1,t:0,dark:[],short:[]};mkStart(S.ar.hq);arStep();} +// One cut, routed: who goes dark, which gold sites with it, and who is still connected but short of room. +function arCut(u){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1;compute();const dark=arDark(u);return {ls,dark,gold:dark.filter(c=>S.ar.gold.includes(c)),short:arShort(dark)};} +// The monkey sets off: the tube it last snipped is whole again, the next one stays whole until it gets there. +function arStep(now){const sh=UI.arShow;if(!sh||!arOn())return;for(const l of S.links)l.cut=0;sh.i++;sh.hit=false; + if(sh.i>=sh.units.length){UI.arShow=null;compute();S.ar.passed=pzSig();renderAll();sfx('star');haptic(15); + mkEnd(true);toast(`✅ ${tr('architect.review_passed')}
${arLast()?tr('architect.last_brief_done'):tr('architect.next_brief_waiting')}`,'good');if(arLast())setTimeout(()=>{if(arOn()&&S.ar.passed===pzSig())arResults(true);},900);return;} + const u=sh.units[sh.i];compute();renderAll();mkRun(S.links.find(l=>pzUnit(l)===u),AR_RUN/MK_RUN); + if(now)arHit();else sh.t=setTimeout(arHit,AR_RUN);} +// It has arrived and snips: who goes dark, and does a mission-critical site go with it? +function arHit(){const sh=UI.arShow;if(!sh||!arOn())return;sh.hit=true; + const u=sh.units[sh.i],{ls,dark,gold,short}=arCut(u),l0=ls[0];sh.dark=dark;sh.short=short;sh.u=u; + floater((CITY[l0.a].x+CITY[l0.a].x+wrapDx(CITY[l0.a].x,CITY[l0.b].x))/2,(CITY[l0.a].y+CITY[l0.b].y)/2-26,l0.sub?tr('architect.anchor'):tr('architect.backhoe'),'#FF8A3D'); + for(const c of dark)floater(CITY[c].x,CITY[c].y-34,gold.includes(c)?'💥 '+CITY[c].name:tr('architect.city_goes_dark',{city:CITY[c].name}),gold.includes(c)?'#FF4D5E':'#9AA3BE'); + for(const c of short)floater(CITY[c].x,CITY[c].y-34,tr('architect.city_short_g',{city:CITY[c].name,g:arG(arDem(c)-(arGot()[c]||0))}),'#FF4D5E'); + const bad=gold.length||short.length;if(UI.mk)UI.mk.bad=!!bad;sfx(bad?'err':'click'); + if(bad){UI.arShow=null;UI.arFail={u,gold,dark,short};renderAll();haptic(30);return;} + renderAll();sh.t=setTimeout(arStep,dark.length?AR_HOLD*1.7:AR_HOLD);} +// Skip the show: check every cut at once, and stop at the first that breaks a gold site. +function arShowSkip(){const sh=UI.arShow;if(!sh)return;clearTimeout(sh.t);for(const l of S.links)l.cut=0; + for(let i=sh.hit?sh.i+1:sh.i;i['keep',...RG.map((r,i)=>i).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cap-RG[b].cap||a-b)],ok:v=>v==='keep'||(Number.isInteger(v)&&!!RG[v])}, + {k:'rt',grp:'pop',l:N_('common.routers'),d:1,v:()=>[1,2,3,4,6,8,12,16],ok:v=>Number.isInteger(v)&&v>=1&&v<=RMAX}, + {k:'site2',grp:'pop',l:N_('bstd.l_site2'),d:false,v:()=>[false,true]}, + {k:'gen',grp:'pop',l:N_('common.backup_generator'),d:false,v:()=>[false,true]}, + {k:'v6',grp:'pop',l:N_('bstd.l_v6'),d:false,v:()=>[false,true],on:()=>ip4On()}, + {k:'lag',grp:'port',l:N_('bstd.l_lag'),d:1,v:()=>[1,2,4]}, + {k:'split',grp:'port',l:N_('bstd.l_split'),d:false,v:()=>[false,true]}, + {k:'ix',grp:'port',l:N_('bstd.l_ix'),d:false,v:()=>[false,true]}, + {k:'pni',grp:'port',l:N_('bstd.l_pni'),d:0,v:()=>[0,2,3]}, + {k:'sys',grp:'fiber',l:N_('common.line_system'),d:'keep',v:()=>['keep','roadm','cl']}, + {k:'opt',grp:'fiber',l:N_('common.optics'),d:'keep',v:()=>['keep','fast']}, + {k:'wv',grp:'fiber',l:N_('common.waves'),d:'keep',v:()=>['keep',...LT.map((x,i)=>i).filter(i=>i>0&&waveShown(i))],ok:v=>v==='keep'||(Number.isInteger(v)&&v>0&&!!LT[v])}, +]; +const BSTDK=Object.fromEntries(BSTD.map(x=>[x.k,x])),BSTD_MAX=16,BSTD_SYS={lite:0,roadm:1,cl:2}; +const bstdOk=(x,v)=>x.ok?x.ok(v):x.v().includes(v),bstdOn=x=>!x.on||x.on(); +// The whole standard, every target filled in. d: a saved one (untrusted: anything odd reads as "keep"). +function bstd(d=S&&S.popStd){const o={},ob=d&&typeof d==='object'&&!Array.isArray(d)?d:{}; + for(const x of BSTD){const v=ob[x.k];o[x.k]=x.k==='rt'?(own(ob,'rt')?int(v,1,RMAX,1):1):own(ob,x.k)&&bstdOk(x,v)?v:x.d;}return o;} +// Back to the saved form: the model and router count, and any other target that is not "keep". Nothing set: null. +function bstdPut(o){const d={};for(const x of BSTD)if(x.k==='rt'||o[x.k]!==x.d)d[x.k]=o[x.k];return Object.keys(d).length>1||d.rt>1?d:null;} +function popStdSanitize(s){s.popStd=s.popStd&&typeof s.popStd==='object'&&!Array.isArray(s.popStd)?bstdPut(bstd(s.popStd)):null;} +// Saves from when the intern's orders had their own router model (routers) and line system (optup): the standard takes +// them where it has none of its own; one that names its own keeps it. 'next' was no choice at all: nothing moves. +// opsSanitize() passes only what an order that was running used (undefined otherwise): the rest is dropped. +function bstdAdopt(s,g,sys){const D=bstd(s.popStd);let n=0; + if(D.g==='keep'&&Number.isInteger(g)&&bstdOk(BSTDK.g,g)){D.g=g;n++;} + if(D.sys==='keep'&&sys!=='keep'&&bstdOk(BSTDK.sys,sys)){D.sys=sys;n++;} + if(n)s.popStd=bstdPut(D);} +// A bank that forbids generators (Stormy Weather's covenant): the standard never installs one while that loan runs. +const bstdNoGen=()=>(S.loans||[]).some(l=>(l.covs||[]).includes('nogen')); +// The model a POP should get: the standard's if you can buy it, else the best main-line model that is unlocked and no +// bigger. Never a step down, never one that does not fit, and never one that would drop a POP out of the backbone core. +// c: an existing POP, or null for a new, empty one. -1: nothing to do. A vendor's demo unit (at its markup) only ever +// goes into a new POP, as before: swapping every POP onto one is the player's call, not the intern's. A new POP takes the +// model as chosen, even one smaller than the basic router (the Mikrowtik CCR has more ports): nothing is replaced there. +function bstdModel(g,c){if(g==='keep'||!RG[g])return -1;const p=c&&S.pops[c],cur=p?p.rgen||0:0,core=!!p&&coreRun()>0&&inCore(c); + const ok=i=>i>=0&&RG[i].cap<=RG[g].cap&&(!p||(RG[i].cap>RG[cur].cap&&!modelFits(c,i)&&(!core||rgCore(i,coreRun())))); + if((p?rgOpen(g):techOk('rg',g,RG[g].lvl))&&ok(g))return g;let b=-1; + for(let k=0;k<=4;k++){const i=mainRG(k);if(i!==g&&rgOpen(i)&&ok(i)&&(b<0||RG[i].cap>RG[b].cap))b=i;}return b;} +// What the standard adds to a fresh POP, priced the way popStdApply pays for it, so it can be on the button (#261). +function popStdQuote(){if(!S||!S.popStd||pzOn())return null;const D=bstd(),m=bstdModel(D.g,null),g=m>0?m:0,rt=D.rt; + let cost=g?swapCostOf(g,0,1):0;for(let n=1;n0?m:0].cap0&&m!==(p.rgen||0)){if(S.cash>=swapCost(city,m)){spend(swapCost(city,m));p.rgen=m;}else miss=true;} + while((p.routers||1)=SITE2_COST){spend(SITE2_COST);p.site2=true;p.site2Day=S.day;}else miss=true;} + if(D.gen&&!p.gen&&!bstdNoGen()){if(S.cash>=GEN_COST){spend(GEN_COST);p.gen=true;}else miss=true;} + if(c0===S.cash&&!miss)return; + toast(miss?tr('pop_std.not_all_of_the_standard',{city:CITY[city].name}):tr('pop_std.city_gets_the_standard_cost',{city:CITY[city].name,n:p.routers||1,model:esc(RG[p.rgen||0].n),cost:fmt$(c0-S.cash)}),miss?'bad':'good');} +// The line in a POP's router section: the standard, a button to edit it, and one to make this POP's build the standard. +function popStdHtml(c){const p=S.pops[c];if(!p||pzOn())return '';const D=bstd(),on=!!S.popStd,mine=bstd(bstdPut({...D,g:p.rgen||0,rt:p.routers||1,site2:!!p.site2,gen:!!p.gen})), + same=on&&BSTD.every(x=>D[x.k]===mine[x.k]); + return `
${tr('bstd.title')}${on?esc(bstdLine(D)):tr('pop_std.none')}
${btn(tr('bstd.edit'),'bstdOpen',{},'sm')}${same?'':btn(tr('pop_std.make_this_the_standard'),'popStdSet',{city:c},'ghost sm')}${on?btn(tr('pop_std.clear'),'popStdClear',{},'ghost sm'):''}
`;} +// "2 × Absolute Unit 3.2T, second building, generator": the POP part, what a new POP gets. +function bstdPopParts(D){const a=[];if(D.g!=='keep'||D.rt>1)a.push(`${D.rt} × ${D.g==='keep'?tr('bstd.any_model'):RG[D.g].n}`);if(D.site2)a.push(tr('bstd.second_building'));if(D.gen)a.push(tr('bstd.generator'));return a;} +// The POP part first, then how many other targets (IPv6-only broadband is not part of a new POP: it has no homes yet). +function bstdLine(D){const a=bstdPopParts(D),n=['v6','lag','split','ix','pni','sys','opt','wv'].filter(k=>D[k]!==BSTDK[k].d&&bstdOn(BSTDK[k])).length;if(n)a.push(trn('bstd.n_more_targets',n));return a.join(', ')||tr('pop_std.none');} + +/* What the standard still asks for, as jobs in the order they get done: POPs busiest first, then ports hottest first, + then fiber and waves hottest first. Pure: it reads S and R and changes nothing. Each job is priced with the game's + own helpers on a running copy of the few numbers earlier jobs change (routers, spares), so the sum is what the clicks + cost. Jobs that build on each other form a chain (ch: a POP's routers, a port, a fiber): when one cannot be done, the + rest of that chain waits. A job that needs another chain's work first (optics only the new router model takes, a split + that needs the second building) names that job in dep and waits for it too. Whether a fiber may go dark is settled + here, not on the way, so the plan is what the button does and its sum is the quote. + intern: only where the intern may work (per-POP exceptions). J.held: fibers whose line system has to wait; J.wv: those + of them that wait because a customer's wave rides the line system (dfWaveCust()), which no traffic test changes. */ +function bstdPlan(intern){const J=[];J.held=[];J.wv=[];if(!S||!S.popStd||pzOn())return J;const D=bstd(),here=c=>!intern||opsHere('std',c); + const load=c=>Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c))); + const cs=Object.keys(S.pops).filter(here),ld={};for(const c of cs)ld[c]=load(c);cs.sort((a,b)=>ld[b]-ld[a]||(aS.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0); + const room=c=>rmn[c]??(rmn[c]=(V[c]?portsMax(c,V[c].g,V[c].rt)-portsUsed(c,V[c].g):portsMax(c)-portsUsed(c))-resv(c)+1e-9); + const take=(c,n,dry)=>{if(n<=0)return true;if(room(c){const j={grp,k,ch,w,cost,mo,go,...x};J.push(j);return j;}; + for(const c of cs){const p=S.pops[c],ch='p:'+c;let g=p.rgen||0,rt=p.routers||1,sw=null,s2=null; + // A router job checks the POP still has what the plan counted on: the intern's shift rests between jobs, and the player + // may click meanwhile (the button, a router by hand). So does a PNI job: one ordered meanwhile is not upgraded. + const add=()=>{const g0=g,r0=rt;job('pop','rt',ch,c+' +1',routerCost(g0,r0),routerMo(g0)+cageMo(r0+1)-cageMo(r0),()=>{const n=S.pops[c].routers||1;if(n!==r0)return false;ACT.addRouter({city:c});return (S.pops[c].routers||1)>n;},{c});rt++;}; + // A POP marked as a kind (POP standards, 96-pop-tiers.js) keeps its kind's routers: no model or router jobs for it. + const kd=ptKind(c),m=kd||p.rupDay===S.day?-1:bstdModel(D.g,c); + if(m>=0){ + // One router carrying traffic: a second goes in first, so the swap rolls through with no maintenance window. + if(rt===1&&!popIdle(c))add(); + const old=g,r=rt;sw=job('pop','g',ch,c+' ⇧'+RG[m].pn,swapCostOf(m,old,r),r*(RG[m].mo-RG[old].mo),()=>{if((S.pops[c].rgen||0)!==old)return false;ACT.upRouter({city:c,g:m});return (S.pops[c].rgen||0)===m;},{c});g=m;} + while(!kd&&rt{ACT.addSite({city:c});return !!S.pops[c].site2;},{c}); + if(D.gen&&!p.gen&&!bstdNoGen())job('pop','gen','e:'+c,c,GEN_COST,GEN_MO,()=>{if(bstdNoGen())return false;ACT.addGen({city:c});return !!S.pops[c].gen;},{c}); + V[c]={g,rt,site2:!!p.site2||D.site2,sw,s2};} + // Broadband IPv6-only: every city still on dual stack starts its home-router swap (ACT.ip6Go()), the most dual-stack + // homes first: those are the most behind CGNAT, and free the most addresses. Its price is the whole swap, paid as the + // routers go in (ip6Day()): later, so the shift and the button keep what it still owes, as for every swap running, above + // the floor for every job after it. + // mo: what it does to the month's IPv4 bill, counted one city after another on a copy, so the sum is all of them done. + if(D.v6&&ip4On()){const v6=cs.filter(ip6Todo).sort((a,b)=>ip6Homes(S.pops[b])-ip6Homes(S.pops[a])||(ab.box+b.box64+b.refund,s={ip4:S.ip4,biz:S.biz,pops:{...S.pops}};let b0=v6.length?m(ip4Bill(eye,s)):0; + for(const c of v6){const p=S.pops[c];s.pops[c]={...p,bb:{...p.bb,v6:1}};const b1=m(ip4Bill(eye,s)),mo=b1-b0;b0=b1; + job('pop','v6','6:'+c,c+' IPv6',ip6Cost(c),mo,()=>{if(!ip6Todo(c))return false;ACT.ip6Go({city:c});return !!S.pops[c].bb.v6e;},{c,later:true,price:()=>ip6Cost(c)});}} + // Ports: LAG members up to the standard, then the members split over both buildings. + if(D.lag>1||D.split){const P=[]; + for(const t of S.transit)if(S.pops[t.city]&&here(t.city))P.push({k:'t',c:t.city,id:t.id,o:t,n:t.n||1,tier:t.tier,u:(R.useT[t.id]||0)/lagCap(PORT[t.tier].g,t.n)}); + for(const x of S.pni)if(S.pops[x.city]&&here(x.city)&&pniOn(x)&&!x.up)P.push({k:'p',c:x.city,id:x.id,o:x,n:x.n||1,tier:x.tier,u:(R.usePni[x.id]||0)/lagCap(pniG(x),x.n)}); + for(const x in S.ixp){const c=ixCity(x);if(!S.myIx[x]&&S.pops[c]&&here(c))P.push({k:'ix',c,id:x,n:(S.ixn||{})[x]||1,tier:S.ixp[x],u:(R.useIx[x]||0)/Math.max(1e-9,lagCap(PORT[S.ixp[x]].g,(S.ixn||{})[x]))});} + P.sort((a,b)=>b.u-a.u||(a.id!isDk(x)&&!S.myIx[x]&&!!ixName(x)&&S.ixp[x]===undefined);if(!x||!take(c,PORT_SLOT(0)))continue; + const ch='i:'+x,pm=ixPortMo(x,0);job('port','ix',ch,x+' +'+PORT[0].n,pm,pm,()=>{ACT.buyIx({city:x,tier:0});return S.ixp[x]!==undefined;},{c}); + bstdPort({k:'ix',c,id:x,n:1,tier:0,fresh:true},D,V[c],take,job);} + // PNIs spread out: every network you have a PNI with gets one in at least that many cities, where one is worth it. + if(D.pni){const by={};for(const p of S.pni)(by[p.net]||(by[p.net]=new Set())).add(p.city); + for(const net of Object.keys(by).sort()){let k=D.pni-by[net].size;if(k<=0||!isNet(net))continue; + const opts=NET[net].pops.filter(c=>S.pops[c]&&here(c)&&!by[net].has(c)).map(c=>({c,v:pniVal(net,c)})).filter(o=>o.v.worth).sort((a,b)=>b.v.want-a.v.want||(a.c=pniMin(net)&&!q;t--){const x=pniQuote(c,net,t,resv(c));if(x&&!x.why)q=x;} + if(!q||!take(c,q.slots))continue;const tier=q.tier;k--; + job('port','pni','n:'+net+'@'+c,c+' '+net,q.cost,pniMo({net,tier,n:1},0),()=>{const x=pniQuote(c,net,tier,resv(c));if(!x||x.why||x.ex||!spend(x.cost))return false;pniPlace(x);return true;},{c});}}} + // Fiber and waves, hottest first. A POP excepted from the order keeps its links as they are too. + if(D.sys!=='keep'||D.opt!=='keep'||D.wv!=='keep'){const sp={...(S.spares||{})},dk=new Map(),wv=new Map();let wc=null; + const ls=S.links.filter(l=>(l.kind==='df'||l.kind==='wave')&&here(l.a)&&here(l.b)&&S.pops[l.a]&&S.pops[l.b]).map(l=>({l,u:(R.load[l.id]||0)/Math.max(1e-9,capOf(l))})).sort((a,b)=>b.u-a.u||(a.l.idl.tier;t--){if(subWaveWhy(t,l.km,l.sub)||soldOut(l.a,l.b,t,l.cable)||!waveOk(l.a,l.b,t))continue;wv.set(l,t);break;} + if(wv.size&&opsHired()&&S.ops.on.decom){const by=new Map(),cf=x=>wv.has(x)?capOf(x)*LT[wv.get(x)].g/LT[x.tier].g:capOf(x); + for(const x of S.links)if(x.kind!=='vxc'&&x.kind!=='sat'){const k=edgeKey(x);(by.get(k)||by.set(k,[]).get(k)).push(x);} + for(const k of new Set([...wv.keys()].map(edgeKey)))for(const x of opsDecomPick(by.get(k),cf))wv.delete(x);}} + for(const {l} of ls){const ch='l:'+l.id; + if(l.kind==='wave'){const t=wv.get(l);if(t){const nm=Math.round(waveMo(l.km,l.sub,t)*(l.mult||1));job('fiber','wv',ch,l.a+'|'+l.b,nm,nm-(l.mo||0),()=>{ACT.upLink({id:l.id,tier:t});return l.tier===t;},{l});}continue;} + if(l.eqDown>S.day)continue; + let sys=l.sys;const lit=l.ready<=S.day,nx=D.sys!=='keep'&&BSTD_SYS[sys]S.day)&&opsDarkPre(l,ws)!==false:bstdDarkOk(l,undefined,ws)))J.held.push(l); + else if(lit&&(intern?pairLinks(l.a,l.b).some(x=>x!==l&&dk.get(x.id)):!bstdDarkOk(l,dk,ws))){J.held.push(l);continue;} + else{const busy=lit&&(intern?!opsUnused(l):bstdBusy(l)); + while(BSTD_SYS[sys]{if(l.sys!==s0)return false;ACT.upSys({id:l.id});return l.sys===to;},{l,dark:lit,busy});sys=to;} + if(lit)dk.set(l.id,busy);}} + // Optics for the line system the fiber will have. + if(D.opt==='fast'&&lit&&(l.ch||[]).length)J.push(...bstdOptJobs(l,sys,sp,V,take,ch));}} + return J;} +// One port's LAG members up to the standard, then split over both buildings. A PNI's new member is an augment that +// lands later; it remembers to split when it does. o.fresh: a port the plan is buying (the IX job before it). +function bstdPort(o,D,v,take,job){const {k,c,id}=o,ch=(o.fresh?'i:':'x:'+k+':')+id;let n=o.n; + const site2=v?v.site2:!!(S.pops[c]&&S.pops[c].site2),split=D.split&&site2, + // A second building still to buy is a job of its own: the split waits for it, or it would be tried every shift. + sx={c,...(v&&v.s2&&!S.pops[c].site2?{dep:[v.s2]}:{})}; + if(k==='p'){const x=o.o; + if(n{if((x.n||1)!==n0||x.up)return false;ACT.lagP({id,d:1});return !!x.up||(x.n||1)>n0;},{c});n++;} + if(split&&n>=2&&x.site!=='ab')job('port','split',ch,c,0,0,()=>{if(!S.pops[c].site2)return false;if(x.up){if(x.up.n<2)return false;x.up.site='ab';return true;} + if((x.n||1)<2)return false;ACT.siteSet({k:'p',id,s:'ab'});return x.site==='ab';},sx); + return;} + const t=k==='t'?o.o:null,tier=o.tier,each=k==='t'?PORT[tier].setup:ixPortMo(id,tier); + while(n{if((t.n||1)!==n0)return false;ACT.lagT({id,d:1});return (t.n||1)>n0;} + :()=>{const m=(S.ixn||{})[id]||1;if(m!==n0)return false;ACT.lagIx({city:id,d:1});return ((S.ixn||{})[id]||1)>m;},{c});n++;} + const cur=k==='t'?t.site:(S.ixSite||{})[id]; + if(split&&n>=2&&cur!=='ab')job('port','split',ch,k==='t'?c:id,0,0,()=>{if(!S.pops[c].site2)return false; + if(k==='t'){if((t.n||1)<2)return false;ACT.siteSet({k:'t',id,s:'ab'});return t.site==='ab';} + if(((S.ixn||{})[id]||1)<2)return false;ACT.siteSet({k:'ix',id,s:'ab'});return (S.ixSite||{})[id]==='ab';},sx);} +// Can it see the fastest optic that reaches, ignoring the free-slot check (a swap frees its own slot first)? rg: each +// end's router model once the plan's swaps are in, so the optics a new model takes are part of the plan. +const bstdOptFits=(l,o,sys,rg)=>{const O=OPT[o];return techOk('opt',o,O.lvl)&&(O.sys!=='roadm'||isRdm(sys))&&!!optMode(o,l)&&[l.a,l.b].every(c=>!S.pops[c]||RG[rg(c)].cls>=O.rg);}; +const bstdCnt=(l,o)=>(l.ch||[]).filter(k=>k===o).length; +// Swap a fiber's slower optics for the fastest that reaches on it, one job per kind, slowest first: the old ones go on +// the spares shelf (setChCount), the new ones come from the shelf first. sp: spares as earlier jobs leave them. +function bstdOptJobs(l,sys,sp,V,take,ch){const rg=c=>V[c]?V[c].g:(S.pops[c].rgen||0),fits=Object.keys(OPT).filter(o=>bstdOptFits(l,o,sys,rg));if(!fits.length)return []; + const best=fits.sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b))[0],bg=optG(best,l),g=c=>V[c]?V[c].g:undefined,out=[]; + // Optics only the new router model takes wait for its swap: until it is in, nothing is pulled. + const low=c=>!!S.pops[c]&&RG[S.pops[c].rgen||0].clsV[c]&&V[c].sw).filter(Boolean); + for(const o0 of [...new Set(l.ch||[])].filter(o=>OPT[o]&&optG(o,l)optG(a,l)-optG(b,l)||(aMath.max(0,chPorts(best,c,g(c))-chPorts(o0,c,g(c)));let k=bstdCnt(l,o0); + while(k>0&&!(take(l.a,per(l.a)*k,true)&&take(l.b,per(l.b)*k,true)))k--;if(!k)continue;take(l.a,per(l.a)*k);take(l.b,per(l.b)*k); + const r=REGEN_CH*(l.regen|0),c=optCost(best),s=Math.max(0,Math.min(k,sp[best]|0)),cost=s*Math.round(c*r)+(k-s)*Math.round(c*(1+r)); + sp[best]=(sp[best]|0)-s;sp[o0]=(sp[o0]|0)+k; + // price: what it costs when it runs. The plan's price counts on the shelf as the jobs before it leave it; one of those + // refused (budget, cash) leaves the shelf emptier, and the budget and the floor must see the real bill. + out.push({grp:'fiber',k:'opt',ch,w:l.a+'|'+l.b,cost,mo:0,l,...(dep.length?{dep}:{}),price:()=>opticCountCost(l,best,bstdCnt(l,best)+k), + go:()=>{const n0=bstdCnt(l,o0),h0=bstdCnt(l,best);if(n0((R.load&&R.load[l.id])||0)>Math.max(1,capOf(l)*0.1); +// Express lightpaths (#58) ride the fiber's glass: its own load says nothing about them, and its parallel links do not +// carry them, so an express with any traffic at all keeps the fiber lit (the line system waits, as for a busy fiber). +// The intern's routing test needs no such rule: an express goes dark with its fiber there (opsDarkTrial()). +const bstdXpBusy=l=>xpSlots(l)>0&&xpOver(l.id).some(x=>((R.load&&R.load[x.id])||0)>1e-6); +function bstdDarkOk(l,ex,ws){if(dfWaveCust(l,ws)||bstdXpBusy(l))return false;const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true; + return P.filter(x=>!linkDown(x)&&!x.standby&&!(ex&&ex.has(x.id))).reduce((a,x)=>a+Math.max(0,capOf(x)-((R.load&&R.load[x.id])||0)),0)>=((R.load&&R.load[l.id])||0);} +/* Do the plan's jobs in order. can(j): may it be paid for (budget, floor, cash); pay(j): run it, true if it took. + dark(j, ex): may the first job that darkens a fiber go ahead (ex: fibers gone dark so far, as bstdDarkOk() takes them), + a generator, so a test can route (yields included); done1(j, first): after each job done (first: it took a fiber dark). + max: at most that many jobs tried, done or failed, so a shift's work stays bounded whatever goes wrong. A bare yield + after each job is a place to let a frame through. Returns what was done. */ +function* bstdRun(J,can,pay,dark,done1,max=1e9){const stop=new Set(),done=new Set(),dk=new Map();let n=0; + for(const j of J){if(n>=max)break;if(stop.has(j.ch))continue;if(j.dep&&!j.dep.every(d=>done.has(d))){stop.add(j.ch);continue;} + // The money first: no fiber is tested for a job the budget cannot pay, and asked again after a test that routed. + const first=!!j.dark&&!dk.has(j.l.id); + if(!can(j)||first&&(!(yield* dark(j,dk))||!can(j))){stop.add(j.ch);continue;}n++; + if(!pay(j)){stop.add(j.ch);continue;} + if(j.dark)dk.set(j.l.id,!!j.busy);done.add(j);if(done1)done1(j,first);yield;} + return [...done];} +// The button: the whole plan at once, on the page, every fiber judged as the plan judged it. +function bstdDo(J,can,pay){const g=bstdRun(J,can,pay,function*(j,ex){return bstdDarkOk(j.l,ex);});for(;;){const s=g.next();if(s.done)return s.value;}} +// What a job costs as it runs (an optics swap is priced again then: see bstdOptJobs). +const bstdPrice=j=>j.price?j.price():j.cost; +// The sheet's summary and the MCP quote: how much is below the standard, and what bringing it all up costs. The plan is +// what the button does, so its sum is the bill. held: the fibers whose line system waits ("fra|ams"); they are below it. +// Of them, wait: the ones that wait for their traffic, wv: the ones that wait for a customer's wave to leave. +function bstdQuote(intern){const J=bstdPlan(intern),P=new Set(),Q=new Set(),L=new Set(J.held.map(l=>l.id));let cost=0,mo=0; + for(const j of J){cost+=j.cost;mo+=j.mo;if(j.grp==='pop')P.add(j.c);else if(j.grp==='port')Q.add(j.ch);else L.add(j.l.id);} + const w=l=>l.a+'|'+l.b; + return {cost:Math.round(cost),mo:Math.round(mo),pops:P.size,ports:Q.size,links:L.size,n:J.length,held:J.held.map(w),wait:J.held.filter(l=>!J.wv.includes(l)).map(w),wv:J.wv.map(w)};} +// The optics order lights the standard's fastest optics while this order keeps to a standard that wants them. +const bstdFast=()=>!!(S.popStd&&opsHired()&&S.ops.on.std&&bstd().opt==='fast'); +/* The intern's shift: the same plan, every job through the budget and the cash floor at what it costs then, a few at a + time. A fiber goes dark only on the optical order's test (opsDark(): a routing without it, in play in the route + worker), within the night's dark swaps that order shares (opsDarkRoom()), and a fiber that fails waits a week. One + owner per fiber: a fiber or wave the optical order worked on this shift is left alone, and what this order works on + is its own until tomorrow (X.fib: that order and decom leave it alone). The plan is made once a shift, and the shift + rests between jobs: a POP decommissioned or a link given up meanwhile is not worked on (the links last: a walk of them, + only for a job the budget lets through). */ +// An IPv6-only swap (j.later) pays nothing today: the whole swap counts against the month's budget when it starts, and +// from then on it is owed (X.ow): every later job of every order keeps it above the cash floor, as for the swaps already +// under way. Not in what the shift paid up front. +function* bstdShift(X){const mine=j=>(!j.c||!!S.pops[j.c])&&(!j.l||(X.fib.get(j.l.id)||'std')==='std'); + yield* bstdRun(bstdPlan(true),j=>mine(j)&&X.can('std',bstdPrice(j),j.mo)&&(!j.l||S.links.includes(j.l)), + j=>{const k=j.later?bstdPrice(j):0;if(!X.pay('std',()=>j.go()))return false;if(k){S.ops.spent.std=(S.ops.spent.std||0)+k;X.ow=ip6Owed();}X.did('std',j.w);return true;}, + function*(j){const l=j.l;if(OPTUP_NO.get(l.id)>S.day||!opsDarkRoom(X))return false;const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);return ok;}, + (j,first)=>{if(j.l)X.fib.set(j.l.id,'std');if(first)X.dk.n++;},BSTD_MAX);} diff --git a/src/game/60-features/96-pop-tiers.js b/src/game/60-features/96-pop-tiers.js new file mode 100644 index 0000000..eb0ea8b --- /dev/null +++ b/src/game/60-features/96-pop-tiers.js @@ -0,0 +1,55 @@ +/* ---------- POP standards: micro, medium, regional hub (#315) ---------- + Real networks build a few kinds of POP, not one: a small edge site, a medium one, a regional hub. The player saves a + POP's routers as one of three standards and marks POPs as that kind; a POP is brought up to its standard with one + button, and every POP of a kind with one more once the standard grows (a new model unlocked, more routers). Which POP + is which stays the player's choice, so growth stays selective. Never a step down: a POP with a bigger model keeps it. + The build standard (96-pop-standard.js) is the design for every POP; a POP marked as a kind keeps its kind's routers + instead (ptKind), so the two never pull one POP's routers two ways. From customer level 2, like the intern. */ +const POP_TIERS=['micro','medium','hub']; +const POP_TIER_L={micro:N_('pop_tiers.micro'),medium:N_('pop_tiers.medium'),hub:N_('pop_tiers.hub')}; +const ptNew=()=>({def:{micro:null,medium:null,hub:null},at:{}}); +const ptOn=()=>!!S&&opsCanHire()&&!pzOn(); +const ptO=()=>S.popTiers||(S.popTiers=ptNew()); +// The kind a POP is marked as, when that kind has a standard: its routers (model and count) are then that standard's, +// and the build standard's router row and the intern's model swaps leave them alone. null for every other POP. +function ptKind(c){const T=S&&S.popTiers,k=T&&own(T.at,c)?T.at[c]:null;return k&&T.def[k]?k:null;} +// Whether the build standard sets routers at all (a model, or more than one): then a POP's panel says who owns its routers. +const bstdRouters=()=>{if(!S.popStd)return false;const D=bstd();return D.g!=='keep'||D.rt>1;}; +// Saves are untrusted: known kinds, router models that exist, POPs that still exist. +function ptSanitize(s){const o=s.popTiers&&typeof s.popTiers==='object'&&!Array.isArray(s.popTiers)?s.popTiers:{},n=ptNew(),d=o.def&&typeof o.def==='object'?o.def:{},at=o.at&&typeof o.at==='object'&&!Array.isArray(o.at)?o.at:{}; + for(const k of POP_TIERS){const x=d[k];if(x&&typeof x==='object'&&Number.isInteger(x.g)&&RG[x.g])n.def[k]={g:x.g,rt:int(x.rt,1,RMAX,1)};} + for(const c of Object.keys(at))if(isCity(c)&&own(s.pops,c)&&POP_TIERS.includes(at[c]))n.at[c]=at[c]; + s.popTiers=n;} +// The clicks that bring a POP up to a standard, in order, priced as each click prices it: a second router first where a +// lone router carries traffic (so the swap is a rolling upgrade, not a maintenance window), the bigger model, the rest of +// the routers. null when the POP already meets it. why: what stops it today. +function ptPlan(c,k){const p=own(S.pops,c)&&S.pops[c],d=S.popTiers&&S.popTiers.def[k];if(!p||!d)return null; + const g0=p.rgen||0,rt0=p.routers||1,up=d.g!==g0&&RG[d.g].cap>RG[g0].cap,steps=[];let rt=rt0,cost=0; + if(up&&rt===1&&d.rt>=2&&!popIdle(c)){cost+=routerCost(g0,1);steps.push('add');rt=2;} + if(up){cost+=Math.max(0,Math.round(RG[d.g].cost*rt*hwMul('rt')*techMul(RG[d.g].lvl))-tradeIn(g0,rt));steps.push('swap');} + const g=up?d.g:g0;while(rt(n-1)*ROUTER_MO+cageMo(n),why=up?(!techOk('rg',d.g,RG[d.g].lvl)?tr('pop_tiers.model_locked',{model:esc(RG[d.g].n),lv:RG[d.g].lvl}):modelFits(c,d.g)||(p.rupDay===S.day?tr('pop_tiers.swapped_today'):'')):''; + return {steps,cost,g:d.g,mo:mo(rt)+rt*RG[g].mo-mo(rt0)-rt0*RG[g0].mo,why};} +// Run the plan through the Infra tab's own actions, quietly. True when every click went through. +function ptRun(c,q){let ok=true;opsQuiet(()=>{for(const s of q.steps){const p=S.pops[c],rt=p.routers||1,g=p.rgen||0; + if(s==='add')ACT.addRouter({city:c});else ACT.upRouter({city:c,g:q.g});if((p.routers||1)===rt&&(p.rgen||0)===g){ok=false;break;}}});return ok;} +// The POPs of one kind, the busiest first, with their plans. +function ptAll(k){const at=S.popTiers?S.popTiers.at:{},cs=Object.keys(at).filter(c=>at[c]===k&&own(S.pops,c)).sort((a,b)=>(R.nodeLoad[b]||0)-(R.nodeLoad[a]||0)||a.localeCompare(b)); + const todo=[],stuck=[];for(const c of cs){const q=ptPlan(c,k);if(!q)continue;(q.why?stuck:todo).push({c,q});} + return {cs,todo,stuck,cost:todo.reduce((a,x)=>a+x.q.cost,0)};} +const ptName=k=>tr(POP_TIER_L[k]),ptDesc=d=>d?`${d.rt} × ${esc(RG[d.g].n)}`:tr('pop_tiers.not_set'); +// In a POP's router section: the three standards, what this POP is, and one button each. +function popTierHtml(c){if(!ptOn()||!S.pops[c])return '';const T=ptO(),p=S.pops[c],mine=T.at[c]; + return `
${tr('pop_tiers.title')}${mine?tr('pop_tiers.this_pop_is',{kind:ptName(mine)}):tr('pop_tiers.no_kind')}
+ ${POP_TIERS.map(k=>{const d=T.def[k],q=d?ptPlan(c,k):null,same=d&&d.g===(p.rgen||0)&&d.rt===(p.routers||1); + const main=!d?'':q?btn(tr('pop_tiers.apply_cost',{cost:fmt$(q.cost)}),'ptApply',{city:c,k,cost:q.cost},mine===k?'pink sm':'sm',!!q.why||S.cash✓ ${tr('pop_tiers.meets_it')}`; + return `
${ptName(k)} ${ptDesc(d)}
${q&&q.why?`
${esc(q.why)}
`:''} +
${main}${same?'':btn(tr('pop_tiers.save_here'),'ptSave',{city:c,k},'ghost sm')}
`;}).join('')} +

${tr('pop_tiers.note')}${bstdRouters()?' '+tr('bstd.kinds_note'):''}

`;} +// In Utilities: every kind with its POPs, and one button that brings them all up to their standard. +function popTierAllHtml(city){if(!ptOn())return '';const T=ptO();if(!POP_TIERS.some(k=>T.def[k]))return ''; + return `

${tr('pop_tiers.title')}

${tr('pop_tiers.bulk_note')}

+ ${POP_TIERS.filter(k=>T.def[k]).map(k=>{const A=ptAll(k);return `
${ptName(k)} ${ptDesc(T.def[k])}
+
${trn('pop_tiers.n_pops',A.cs.length)}${A.todo.length?' · '+trn('pop_tiers.n_below',A.todo.length):''}${A.stuck.length?' · '+trn('pop_tiers.n_stuck',A.stuck.length):''}
+ ${A.todo.length?`
${btn(trn('pop_tiers.bring_up_n',A.todo.length,{cost:fmt$(A.cost)}),'ptAll',{k,cost:A.cost,city},'pink sm',S.cash`:''}
`;}).join('')}
`;} diff --git a/src/game/60-features/97-puzzle-monkey.js b/src/game/60-features/97-puzzle-monkey.js new file mode 100644 index 0000000..ff43a69 --- /dev/null +++ b/src/game/60-features/97-puzzle-monkey.js @@ -0,0 +1,23 @@ +/* ---------- the chaos monkey in puzzles: the N-1 star, acted out ---------- + The third star already asks whether the build survives any single cut (pzEval tries every trench and cable). When a + new star lands, and on request, the monkey plays that check on the map: it runs to each trench or cable, snips it, + and the cities that lose traffic say so. Only while the map is really being drawn: the stars never wait on it. */ +const PZ_RUN=450,PZ_HOLD=550; // ms: the run to a tube, then how long its cut shows +const pzMkCan=()=>animOn()&&!UI.mapHid&&performance.now()-(UI.drawnAt||-1e9)<2000; +function pzMonkey(then){pzMkStop();const units=[...new Set(S.links.map(pzUnit))];if(!units.length){if(then)then();return;} + const c=S.pz.src[0]||S.pz.cities[0];UI.pzMk={units,i:-1,t:0,then,bad:0};if(CITY[c])mkStart(c);sfx('alert');pzMkStep();} +// Off to the next one: the tube it last snipped is whole again, the next one stays whole until it gets there. +function pzMkStep(){const m=UI.pzMk;if(!m||!pzOn())return;for(const l of S.links)l.cut=0;m.i++;if(m.i>=m.units.length){pzMkDone();return;} + const u=m.units[m.i];compute();renderAll();mkRun(S.links.find(l=>pzUnit(l)===u),PZ_RUN/MK_RUN);m.t=setTimeout(pzMkHit,PZ_RUN);} +function pzMkHit(){const m=UI.pzMk;if(!m||!pzOn())return;const ls=S.links.filter(l=>pzUnit(l)===m.units[m.i]),l0=ls[0];for(const l of ls)l.cut=1;compute(); + const g=pzGot(),lost=[];S.pz.dem.forEach((f,i)=>{if(!f.be&&!pzFull(f,g[i]))lost.push({c:f.t==='l2'?f.b:f.a,g:Math.max(0,f.g-g[i].g)});}); + floater((CITY[l0.a].x+CITY[l0.a].x+wrapDx(CITY[l0.a].x,CITY[l0.b].x))/2,(CITY[l0.a].y+CITY[l0.b].y)/2-26,tr('puzzles.monkey_snip'),'#FF8A3D'); + for(const x of lost)floater(CITY[x.c].x,CITY[x.c].y-34,tr('puzzles.city_loses_g',{city:CITY[x.c].name,g:fmtG(x.g)}),'#FF4D5E'); + if(UI.mk)UI.mk.bad=lost.length>0;if(lost.length)m.bad++;sfx(lost.length?'err':'click');renderAll();m.t=setTimeout(pzMkStep,lost.length?PZ_HOLD*2:PZ_HOLD);} +// The end: a cheer if nothing broke, a tantrum if something did, then whatever was waiting (the stars). +function pzMkDone(bad){const m=UI.pzMk;if(!m)return;clearTimeout(m.t);UI.pzMk=null;for(const l of S.links)l.cut=0;compute(); + mkEnd(!(bad!=null?bad:m.bad),true);renderAll();if(m.then)m.then();} +// Skip: straight to the end; the verdict is already known. +function pzMkSkip(){if(UI.pzMk)pzMkDone(pzEval().n1?0:1);} +// Gone without a word: the build changed under it, or the puzzle closed. +function pzMkStop(){const m=UI.pzMk;if(!m)return;clearTimeout(m.t);UI.pzMk=null;for(const l of S.links)l.cut=0;mkStop();} diff --git a/src/game/60-features/98-architect-weekly.js b/src/game/60-features/98-architect-weekly.js new file mode 100644 index 0000000..d7a00d0 --- /dev/null +++ b/src/game/60-features/98-architect-weekly.js @@ -0,0 +1,63 @@ +/* ---------- the published weekly Architect run ---------- + Every Sunday scripts/weekly-architect.js publishes architect/weekly/.json next to the page: an HQ, a budget and + the briefs, as data. Fetched only when Puzzles opens, checked field by field, and played like the handmade runs + (AR_RUNS) under the id 'wk-'. A brief's text is written here from what it asks for, in the player's language, so + the file can never say one thing and want another. When the file is missing, offline or wrong there is simply no + weekly run that week. */ +const AR_WK_V=1,AR_WK_FIELDS=['v','key','hq','budget','name','joke','briefs','ref','rev'],AR_WK_BRIEF=['add','gold','ring','drop','dem','lat','tubes']; +// The labels a file may name (N_: kept whole in the shipped page); their only placeholder is {hq}, a city. +const AR_WK_NAMES=[N_('architect_weekly.name_all_roads_lead_to_hq'),N_('architect_weekly.name_the_hq_job'),N_('architect_weekly.name_hq_and_friends')]; +const AR_WK_JOKES=[N_('architect_weekly.joke_hq_signed_the_lease'),N_('architect_weekly.joke_one_network_a_handful')]; +const arWkId=key=>'wk-'+key,AR_WK_ID=/^wk-\d{4}-W\d{2}$/; +function arWkTxt(o,list){if(!pzObj(o)||!list.includes(o.l))return null;const p=o.p==null?{}:o.p;if(!pzObj(p))return null; + const need=[...new Set([...String(EN[o.l]).matchAll(/\{(\w+)\}/g)].map(m=>m[1]))]; + if(Object.keys(p).length!==need.length||!need.every(k=>k==='hq'&&pzCityOk(p[k])))return null;return {l:o.l,p:Object.assign({},p)};} +const arWkSay1=o=>tr(o.l,o.p.hq?{hq:CITY[o.p.hq].name}:{}); +// What a brief says, built from what it wants. +function arWkSay(b){const n=c=>CITY[c].name,t=[]; + if(b.drop)t.push(tr('architect_weekly.t_drop',{a:n(b.drop[0])})); + const ag=b.add&&b.gold&&b.add.length===1&&b.gold.length===1&&b.add[0]===b.gold[0]; + if(ag)t.push(tr('architect_weekly.t_add_gold',{a:n(b.add[0])})); + else if(b.add)t.push(b.add.length>1?tr('architect_weekly.t_add_two',{a:n(b.add[0]),b:n(b.add[1])}):tr('architect_weekly.t_add_one',{a:n(b.add[0])})); + if(b.gold&&!ag)t.push(b.gold.length>1?tr('architect_weekly.t_gold_two',{a:n(b.gold[0]),b:n(b.gold[1])}):tr('architect_weekly.t_gold_one',{a:n(b.gold[0])})); + for(const c of Object.keys(b.dem||{}))if(!(b.add||[]).includes(c))t.push(tr('architect_weekly.t_grow',{a:n(c),g:arG(b.dem[c])})); + if(b.ring)t.push(tr('architect_weekly.t_ring',{list:b.ring.map(n).join(', ')})); + if(b.lat)t.push(tr('architect_weekly.t_lat',{a:n(b.lat[0]),b:n(b.lat[1]),ms:+b.lat[2].toFixed(1)})); + return t.join(' ');} +// The briefs, in order: a site exists from the brief that adds it until one drops it; every brief asks for something. +function arWkBriefs(a,hq){if(!Array.isArray(a)||a.length<3||a.length>7)return null;const sites=new Set([hq]),gone=new Set(),out=[]; + const ids=(x,lo,hi)=>x==null?[]:Array.isArray(x)&&x.length>=lo&&x.length<=hi&&x.every(pzCityOk)&&new Set(x).size===x.length?x.slice():null; + for(const b of a){if(!pzObj(b)||Object.keys(b).some(k=>!AR_WK_BRIEF.includes(k)))return null; + const drop=ids(b.drop,1,1),add=ids(b.add,1,2),gold=ids(b.gold,1,2),ring=b.ring==null?[]:ids(b.ring,3,4);if(!drop||!add||!gold||!ring)return null; + for(const c of drop){if(c===hq||!sites.has(c))return null;sites.delete(c);gone.add(c);} + for(const c of add){if(sites.has(c)||gone.has(c))return null;sites.add(c);} + if(![...gold,...ring].every(c=>sites.has(c))||gold.includes(hq))return null; + const dem={};if(b.dem!=null){if(!pzObj(b.dem))return null;for(const c of Object.keys(b.dem)){const g=b.dem[c];if(!sites.has(c)||c===hq||!Number.isInteger(g)||g<10||g>400)return null;dem[c]=g;}} + let lat=null;if(b.lat!=null){const l=b.lat;if(!Array.isArray(l)||l.length!==3||!sites.has(l[0])||!sites.has(l[1])||l[0]===l[1]||typeof l[2]!=='number'||!isFinite(l[2])||l[2]<1||l[2]>300)return null;lat=l.slice();} + if(!Number.isInteger(b.tubes)||b.tubes<0||b.tubes>9)return null; + if(!add.length&&!gold.length&&!ring.length&&!lat&&!Object.keys(dem).length)return null; + const o={tubes:b.tubes};if(add.length)o.add=add;if(gold.length)o.gold=gold;if(ring.length)o.ring=ring;if(drop.length)o.drop=drop;if(Object.keys(dem).length)o.dem=dem;if(lat)o.lat=lat; + o.t=arWkSay(o);out.push(o);} + return out[0].add?out:null;} +// The file, never trusted: a run definition like AR_RUNS's, or null. +function arWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!AR_WK_FIELDS.includes(k))||j.v!==AR_WK_V||j.key!==key||pzWeekStart(key)==null||!pzCityOk(j.hq))return null; + if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>2e7)return null; + if(j.rev!==undefined&&!(Number.isInteger(j.rev)&&j.rev>=2&&j.rev<=999))return null;if(j.ref!==undefined&&!pzObj(j.ref))return null; + const name=arWkTxt(j.name,AR_WK_NAMES),joke=arWkTxt(j.joke,AR_WK_JOKES),briefs=arWkBriefs(j.briefs,j.hq);if(!name||!joke||!briefs)return null; + return {id:arWkId(key),key,wk:true,n:arWkSay1(name),j:arWkSay1(joke),hq:j.hq,via:[],budget:j.budget,briefs,rev:j.rev||1};} +// The run behind an id, when it is this week's. +function arWkRun(id){const w=UI.arWk;return w&&w.def&&w.def.id===id?w.def:null;} +// ---------- fetching it: when Puzzles opens, never on page load ---------- +function arWkEnsure(){const key=pzWeekKey(new Date()),w=UI.arWk;if(w&&w.key===key&&(w.def||Date.now()-w.at<5*60e3))return; + const st=UI.arWk={key,def:null,at:Date.now()};let done=false; + const fin=def=>{if(done)return;done=true;clearTimeout(to);if(UI.arWk!==st)return;st.def=def;st.at=Date.now();const el=$('arWk');if(el)el.outerHTML=arWkRow();}; + const ac=window.AbortController?new AbortController():null,to=setTimeout(()=>{if(ac)ac.abort();fin(null);},5000); + if(!window.fetch||location.protocol==='file:'){fin(null);return;} + try{fetch(`architect/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>arWkValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +// Its row in the Puzzles menu, above the handmade runs; nothing while there is none. +function arWkRow(){const w=UI.arWk,r=w&&w.key===pzWeekKey(new Date())?w.def:null;if(!r)return '
'; + const x=arLoad().runs[r.id],ok=x&&(x.rv||1)===r.rev?x:null; + return `
🗓️ ${tr('architect_weekly.weekly_run')} · ${arWkNext(new Date())}
${esc(r.n)} ${pzStarStr(ok?ok.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)} · ${tr('puzzles.budget_x',{x:fmt$(r.budget)})}${ok&&ok.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(ok.sp)}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},ok&&ok.st>=3?'ghost':'pink')}
`;} +// "New run in 2 d 14 h": when next week's run comes out. +function arWkNext(now){const t=pzWeekStart(pzKeyAdd(pzWeekKey(now),1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60); + return d?tr('architect_weekly.next_run_in_d_h',{d,h}):tr('architect_weekly.next_run_in_h_m',{h,m:m%60});} diff --git a/src/game/60-features/99-pie-in-the-sky.js b/src/game/60-features/99-pie-in-the-sky.js new file mode 100644 index 0000000..4dfe8ec --- /dev/null +++ b/src/game/60-features/99-pie-in-the-sky.js @@ -0,0 +1,150 @@ +/* ---------- Pie in the Sky: your own satellite constellation (docs/plans/pie-in-the-sky.md) ---------- + Unlocks once, on becoming Tier 1 in a save started on this version (S.pieV>=1), or from day 0 with open gates. + Pies are counted in cohorts per crust, never one object per satellite. Saves without S.pie pay nothing: + pieDay() returns at once, compute() adds one falsy check. + + Hooks for the parts that come later (routing, incidents and spats, the globe): + - pieDishes() -> [{id,city,cc,ant,g}]: dishes that work today (POP there, not down, landing rights held) + - pieHubs() -> ['short',…]: crusts that carry traffic (over 40%, all of it from 60%: pieCarry) and up (not in safe mode, not down) + - pieLicOk(cc) -> true when landing rights in that country are held and in force + - pieCov(id), pieBaked(id), pieCarry(id), pieCap(id), pieUp(id), pieLive(id), pieLiveLas(id) (10-catalog/70-pie.js and below) + - PIE_ON.day / .launch / .fail: arrays of f(d) / f(L,ok) / f(L), called by pieDay() and pieFly() + - S.pie.spat[id] with PIE_SPATS[id]={fix(o,s),day?(o,d),end?(o)}: a spat's state, repaired by pieSanitize(), ticked and + dropped when o.until<=d by pieSpatDay(d) + - S.pie.crusts[id].down: day a crust is out until (a solar storm); S.pie.dishes[i].down likewise (a backhoe) + - pieGlobeData() -> {crusts:[{id,alt,inc,n,las}],dishes:[{city,lat,lon,up,u}],pads:[{city,lat,lon,next}], + launches:[{id,rk,cr,n,day,pad}],flows:[{id,k:'c'|'t'|'b',g,pts:[city,city],alt?}],hi} + - pieFounder(k,{n,c}) -> a Founder post (k from FOUNDER_POSTS); pieCharge(v) bills a cost (book kept) + - book.earned: revenue from orbit, for the customers that come with routing. */ +function pieBlank(day){const crusts={};for(const id in CRUSTS)crusts[id]={cohorts:[],queued:0}; + return {born:day,co:null,fac:false,stock:0,rd:{reuse:false,heavy:false,heavyTests:0},pads:[],crusts,dishes:[],lic:{},q:[], + founder:{posts:[],promises:0,broken:0,due:[],jit:0,next:0,kid:0,bill:0,nerv:0,hype:0,leak:0,mars:0},book:{spent:0,earned:0,wouldHave:0},spat:{},safe:false,gov:pieGovBlank()};} +function pieInit(){if(!S.pie)S.pie=pieBlank(S.day);return S.pie;} +// The unlock: only on the Tier 1 transition of a save of this version, and only in a normal game. +function pieUnlock(){if(S.pie||!(S.pieV>=1)||S.mode!=='normal'||S.scn)return;pieInit();track('pie_unlock'); + toast(`🥧 ${tr('pie.unlocked_title')}
${tr('pie.unlocked_body')}`,'goal',[{l:tr('pie.open_pie_control'),act:'pieOpen',args:{}}]);} +// Sandbox: there from day 0, created on the first action. +const pieGet=()=>pieOn()?S.pie||pieInit():null; +const pieSand=()=>S.mode==='sandbox'; +const pieCoName=()=>{const n=S.pie&&S.pie.co&&S.pie.co.name;return !n?tr(PIE_NAMES[0]):PIE_NAMES.includes(n)?tr(n):n;}; +// What it costs: sandbox pays nothing real but keeps count of what it would have paid. +function pieSpend(v){const P=S.pie;if(pieSand()){P.book.wouldHave+=v;sfx('build');return true;}if(!spend(v))return false;P.book.spent+=v;return true;} +function pieCharge(v){const P=S.pie;if(!P||!(v>0))return;if(pieSand())P.book.wouldHave+=v;else{S.cash-=v;P.book.spent+=v;}} +function pieMo(){const P=S.pie;if(!P||!P.co)return 0;return PIE_CO_MO+(P.fac?PIE_FAC_MO:0)+P.pads.length*PIE_PAD_MO+P.dishes.length*PIE_DISH_MO;} +const pieLiveLas=id=>{const c=S.pie&&S.pie.crusts[id];let n=0;if(pieLasCut(id))return 0;if(c)for(const k of c.cohorts)if(k.las)n+=pieAlive(k,CRUSTS[id].life);return Math.round(n);}; +const pieLicOk=cc=>{const l=S.pie&&S.pie.lic[cc];return !!l&&l.state==='ok'&&l.until>S.day;}; +function pieDishes(){const P=S&&S.pie;if(!P)return [];const o=[];for(const x of P.dishes){if(!S.pops[x.city]||x.down>S.day)continue;const cc=CITY[x.city].cc;if(pieLicOk(cc))o.push({id:x.id,city:x.city,cc,ant:x.ant,g:x.ant*PIE_ANT_G*pieDishMul(x)});}return o;} +function pieHubs(){return S&&S.pie?Object.keys(CRUSTS).filter(pieUp):[];} +const PIE_LOG=[]; +function pieGlobeData(){const P=S&&S.pie;if(!P)return {crusts:[],dishes:[],pads:[],launches:[]};const ll=c=>({city:c,lat:CITY[c].lat,lon:CITY[c].lon}),Q=R&&R.pie,ld=Q&&Q.load||{}; + // Traffic from the last compute: sky circuits dish to dish (k 'c'), terminals from their city to their dish (k 't'), and a + // cut-off POP's backhaul up from its dish and down at the landing dish (k 'b'). + const flows=[];if(Q&&Q.flows)for(const f of Q.flows){if(!(f.g>0))continue;if(f.k==='c'&&f.via.length>1)flows.push({id:f.id,k:'c',g:f.g,pts:[f.via[0],f.via[f.via.length-1]],alt:f.cr?CRUSTS[f.cr].alt:550}); + else if(f.k==='t'&&f.dish)flows.push({id:f.id,k:'t',g:f.g,pts:[f.city,f.dish]}); + else if(f.k==='b')flows.push({id:f.id,k:'b',g:f.g,pts:[f.city,f.dish],alt:CRUSTS[f.cr].alt});} + return {crusts:Object.keys(CRUSTS).map(id=>({id,alt:CRUSTS[id].alt,inc:CRUSTS[id].inc,n:pieLive(id),las:pieLiveLas(id)})), + dishes:P.dishes.map(x=>({...ll(x.city),up:!(x.down>S.day),u:ld[x.city]})),pads:P.pads.map(p=>({...ll(p.city),next:p.next})),launches:P.q.map(L=>({id:L.id,rk:L.rk,cr:L.cr,n:L.n,day:L.day,pad:L.pad})),flown:PIE_LOG.filter(x=>x.day<=S.day&&S.day-x.day<=60&&P.pads.some(p=>p.city===x.pad)).map(x=>({pad:x.pad,ok:x.ok,rk:x.rk})), + flows:flows.sort((a,b)=>b.g-a.g),hi:UI.pieHi||null};} +// Spats (geopolitics) register in PIE_SPATS and keep their state in S.pie.spat; this ticks and ends them. +function pieSpatDay(d){const sp=S.pie.spat;for(const k of Object.keys(sp)){const o=sp[k],D=PIE_SPATS[k];if(!D||o.until<=d){delete sp[k];if(D&&D.end)D.end(o);continue;}if(D.day)D.day(o,d);}} +const pieYear=d=>1+Math.floor(d/360); +function pieFounder(k,v={}){const F=S.pie.founder,p={d:S.day,k};if(v.n!==undefined)p.n=v.n;if(v.c)p.c=v.c;F.posts.unshift(p);if(F.posts.length>PIE_POSTS)F.posts.length=PIE_POSTS;} +// Every promise slips by a year: made today, due in a year, broken then. +function piePromise(k=N_('pie.fp_promise')){const F=S.pie.founder;F.promises++;const due=S.day+360;F.due.push(due);if(F.due.length>8)F.due.shift();pieFounder(k,{n:pieYear(due)});return due;} +function pieFpText(p){const C=own(CRUSTS,p.c||'')?tr(CRUSTS[p.c].n):'',n=p.n||0,K=pieKid();return tr(p.k,{co:pieCoName(),n,crust:C,kid:K?K.n:'',nick:K?K.k:''});} +// Pads that can reach a crust: an orbit's inclination is at least the pad's latitude. +const piePadOk=(c,cr)=>CRUSTS[cr].polar||Math.abs(CITY[c].lat)<=CRUSTS[cr].inc; +const pieRkOk=rk=>{const R0=ROCKETS[rk];return !R0.rd||!!S.pie.rd[R0.rd];}; +const pieTests=()=>S.pie.rd.heavyTests+S.pie.q.filter(L=>L.test).length; +// A quote for a launch: why not, or what it costs, when and from where. The panel and the action both use it. +function pieQuote(rk,cr,o={}){const P=S.pie;if(!P||!own(ROCKETS,rk)||!own(CRUSTS,cr))return {why:tr('pie.why_pick')};const R0=ROCKETS[rk],C=CRUSTS[cr]; + if(!pieCanBuild())return {why:tr('pie.why_not_t1')}; + if(!P.co)return {why:tr('pie.why_no_company')};if(!P.fac)return {why:tr('pie.why_no_factory')}; + if(!pieRkOk(rk))return {why:tr('pie.why_no_rd',{rd:tr(PIE_RD[R0.rd].n)})}; + const pads=P.pads.filter(p=>piePadOk(p.city,cr));if(!P.pads.length)return {why:tr('pie.why_no_pad')};if(!pads.length)return {why:tr('pie.why_pad_lat',{inc:C.inc})}; + if(P.q.length>=PIE_Q_MAX)return {why:tr('pie.why_queue_full')}; + const test=rk==='heavy'&&pieTests()C.full*PIE_SPARE)return {why:tr('pie.why_full')}; + const t0=S.day+leadDays(PIE_PREP),pad=pads.slice().sort((a,b)=>Math.max(t0,a.next)-Math.max(t0,b.next)||Math.abs(CITY[a.city].lat)-Math.abs(CITY[b.city].lat))[0]; + const rocket=piePrice(R0.cost)*(1-pieEq(pad.city))*pieCrMul(cr),boost=rk==='again'&&!pad.boosters.length?piePrice(PIE_BOOST):0,pies=n*piePrice(PIE_PIE+(o.las?PIE_LAS:0)); + const ins=o.ins&&!test?Math.round((rocket+pies)*PIE_INS*pieInsMul()):0; + return {ok:true,test,n,pad:pad.city,day:Math.max(t0,pad.next),cost:Math.round(rocket+boost+pies+ins),insured:Math.round(rocket+pies),ins:!!ins};} +// The cheapest a crust can be filled from nothing (one-off costs only): rule O7. +function pieFullCost(cr){const C=CRUSTS[cr],base=PIE_CO+PIE_FAC+PIE_PAD,pies=C.full*PIE_PIE; + return base+pies+Math.min(...Object.keys(ROCKETS).map(rk=>{const R0=ROCKETS[rk],n=Math.ceil(C.full/R0.pies);return (R0.rd?PIE_RD[R0.rd].cost:0)+(n+(rk==='heavy'?PIE_HEAVY_TESTS:0))*R0.cost;}));} +/* The Launch tab's forecast: how long until crust cr is full at today's pace, or null (no factory, no pad that reaches it, + no rocket). The rocket is the one last queued for it, else the one that lifts most a day. Each pad flies one every + leadDays(gap) (pieLaunch sets pad.next), so the pads lift pies/gap a day each; the factory adds PIE_FAC_MONTH a month, + and pies on the shelf and in the queue let the pads outrun it until they are gone. Wear and failures are left out: + it says "about". pad: true when the pads, not the factory, set the pace (another pad would help). */ +function piePace(cr){const P=S.pie;if(!P||!P.fac||!own(CRUSTS,cr))return null;const need=Math.max(0,CRUSTS[cr].full-pieLive(cr)),pads=P.pads.filter(p=>piePadOk(p.city,cr)).length;if(!pads)return null; + const use=rk=>pieRkOk(rk)&&!(rk==='heavy'&&pieTests()ROCKETS[rk].pies/leadDays(ROCKETS[rk].gap); + const L=P.q.filter(x=>x.cr===cr&&!x.test).sort((a,b)=>b.day-a.day)[0],rk=L&&use(L.rk)?L.rk:Object.keys(ROCKETS).filter(use).sort((a,b)=>rate(b)-rate(a))[0];if(!rk)return null; + const rp=pads*rate(rk),rf=PIE_FAC_MONTH/30,st=P.stock+P.crusts[cr].queued;let days; + if(rp<=rf)days=need/rp;else{const t=st/(rp-rf);days=need<=rp*t?need/rp:t+(need-rp*t)/rf;} + return {days:Math.ceil(days),rk,mo:Math.round(Math.min(rp,rf)*30),pad:rp<=rf};} +// Where another pad would help crust cr most: the coastal POP nearest the equator that has none and reaches it. +function piePadTip(cr){const P=S.pie;return Object.keys(S.pops).filter(c=>!P.pads.some(p=>p.city===c)&&piePadOk(c,cr)).sort((a,b)=>Math.abs(CITY[a].lat)-Math.abs(CITY[b].lat)).find(pieCoast)||null;} +function pieCohort(cr,n,las){const c=S.pie.crusts[cr],m=Math.floor(S.day/30),k=c.cohorts.find(x=>x.las===las&&Math.floor(x.day/30)===m);if(k)k.n+=n;else c.cohorts.push({n,day:S.day,las}); + if(c.cohorts.length>PIE_COHORTS)c.cohorts.splice(0,c.cohorts.length-PIE_COHORTS);} +// A launch: every one costs a party; a test always ends in a fireball; the rest fail by the rocket's odds and the chaos rule, +// never in the first 90 days after the unlock. +function pieFly(L){const P=S.pie,R0=ROCKETS[L.rk],C=P.crusts[L.cr],pad=P.pads.find(p=>p.city===L.pad);C.queued=Math.max(0,C.queued-L.n); + pieCharge(PIE_PARTY);S.stats.pieLaunch=(S.stats.pieLaunch||0)+1; + const quiet=S.day-P.bornx.flights-y.flights)[0];} + let ok; + if(L.test){ok=false;P.rd.heavyTests=Math.min(PIE_HEAVY_TESTS,P.rd.heavyTests+1);pieFounder(N_('pie.fp_test'),{n:P.rd.heavyTests}); + toast(tr('pie.t_test',{n:P.rd.heavyTests,left:PIE_HEAVY_TESTS-P.rd.heavyTests}),'bad');} + else{ok=!(cm>0&&Math.random()6)PIE_LOG.shift(); + if(b&&pad){if(ok&&!(cm>0&&Math.random()<(R0.land||0)*cm)){b.flights++;if(b.flights>=PIE_BOOST_MAX)pad.boosters=pad.boosters.filter(x=>x!==b);} + else if(!L.test){pad.boosters=pad.boosters.filter(x=>x!==b);if(ok){pieFounder(N_('pie.fp_booster'));toast(tr('pie.t_booster'),'bad');}}} + for(const f of PIE_ON.launch)f(L,ok);} +function pieRefund(v){const P=S.pie;if(pieSand())P.book.wouldHave=Math.max(0,P.book.wouldHave-v);else{S.cash+=v;P.book.spent=Math.max(0,P.book.spent-v);}} +function pieDay(d){const P=S.pie;if(!P)return; + if(P.fac)P.stock=Math.min(PIE_STOCK_MAX,P.stock+PIE_FAC_MONTH/30); + if(P.q.length){const due=P.q.filter(L=>L.day<=d);if(due.length){P.q=P.q.filter(L=>L.day>d);for(const L of due)pieFly(L);}} + for(const id in CRUSTS){const c=P.crusts[id],life=CRUSTS[id].life;if(c.cohorts.length&&d-c.cohorts[0].day>=life)c.cohorts=c.cohorts.filter(k=>d-k.dayx&&typeof x==='object'&&!Array.isArray(x); + if(!ob(p)||(s.pieV<1&&s.mode!=='sandbox')||s.scn||s.mode==='puzzle'){s.pie=null;return;} + const o=pieBlank(int(p.born,0,s.day,s.day)),day=s.day,n=(v,hi)=>int(v,0,hi,0),m=(v,hi)=>clamp(num(v,0),0,hi); + if(ob(p.co)){const nm=p.co.name;o.co={name:typeof nm==='string'&&nm.trim()?(PIE_NAMES.includes(nm)?nm:nm.replace(/\s+/g,' ').trim().slice(0,40)):PIE_NAMES[0]};} + o.fac=!!p.fac&&!!o.co;o.stock=o.fac?m(p.stock,PIE_STOCK_MAX):0;o.safe=!!p.safe;o.t1=!!p.t1; + if(ob(p.rd)){o.rd.reuse=!!p.rd.reuse;o.rd.heavy=!!p.rd.heavy;o.rd.heavyTests=o.rd.heavy?n(p.rd.heavyTests,PIE_HEAVY_TESTS):0;} + const seen=new Set(); + o.pads=(Array.isArray(p.pads)?p.pads:[]).filter(x=>ob(x)&&isCity(x.city)&&s.pops[x.city]&&pieCoast(x.city)&&!seen.has(x.city)&&seen.add(x.city)).slice(0,PIE_PAD_MAX) + .map(x=>({city:x.city,next:int(x.next,0,day+3650,day),boosters:(Array.isArray(x.boosters)?x.boosters:[]).filter(ob).slice(0,PIE_BOOSTERS).map(b=>({id:sid0(b.id),flights:n(b.flights,PIE_BOOST_MAX-1)}))})); + if(ob(p.crusts))for(const id in CRUSTS){const c=p.crusts[id];if(!ob(c))continue;const C=CRUSTS[id]; + o.crusts[id].cohorts=(Array.isArray(c.cohorts)?c.cohorts:[]).filter(k=>ob(k)&&num(k.n,0)>=1).map(k=>({n:n(k.n,C.full*2),day:int(k.day,0,day,day),las:!!k.las})).filter(k=>day-k.dayday)o.crusts[id].down=int(c.down,day,day+365,day);if(c.bk)o.crusts[id].bk=1;if(c.open!==undefined)o.crusts[id].open=int(c.open,0,day,day);} + const ds=new Set(); + o.dishes=(Array.isArray(p.dishes)?p.dishes:[]).filter(x=>ob(x)&&isCity(x.city)&&s.pops[x.city]&&!ds.has(x.city)&&ds.add(x.city)).slice(0,PIE_DISH_MAX) + .map(x=>({id:sid0(x.id),city:x.city,ant:int(x.ant,1,PIE_ANT_MAX,1),down:int(x.down,0,day+365,0)})); + const ccs=new Set(CITIES.map(c=>c.cc)); + if(ob(p.lic))for(const cc of Object.keys(p.lic)){const l=p.lic[cc];if(!ccs.has(cc)||!ob(l))continue;o.lic[cc]={state:PIE_LIC_STATES.includes(l.state)?l.state:'ok',until:int(l.until,0,day+PIE_LIC_DAYS*10,0)};} + o.q=(Array.isArray(p.q)?p.q:[]).filter(L=>ob(L)&&own(ROCKETS,L.rk)&&own(CRUSTS,L.cr)&&o.pads.some(x=>x.city===L.pad)&&(!ROCKETS[L.rk].rd||o.rd[ROCKETS[L.rk].rd])).slice(0,PIE_Q_MAX) + .map(L=>{const t=L.rk==='heavy'&&!!L.test;return {id:sid0(L.id),rk:L.rk,cr:L.cr,pad:L.pad,n:t?0:n(L.n,ROCKETS[L.rk].pies),day:int(L.day,0,day+3650,day),cost:m(L.cost,1e10),ins:!!L.ins,las:!!L.las,test:t};}); + for(const L of o.q)o.crusts[L.cr].queued+=L.n; + if(ob(p.founder)){const F=p.founder;o.founder.promises=n(F.promises,1e6);o.founder.broken=n(F.broken,o.founder.promises); + o.founder.posts=(Array.isArray(F.posts)?F.posts:[]).filter(x=>ob(x)&&FOUNDER_POSTS.includes(x.k)).slice(0,PIE_POSTS).map(x=>{const q={d:int(x.d,0,day,day),k:x.k};if(x.n!==undefined)q.n=n(x.n,1e7);if(own(CRUSTS,x.c||''))q.c=x.c;return q;}); + o.founder.due=(Array.isArray(F.due)?F.due:[]).map(v=>int(v,0,day+720,day)).sort((a,b)=>a-b).slice(-8);pieAnticFix(o.founder,F,day);} + if(ob(p.book))for(const k of ['spent','earned','wouldHave'])o.book[k]=m(p.book[k],1e15); + if(ob(p.spat))for(const k of Object.keys(p.spat)){const D=PIE_SPATS[k];if(!D||!ob(p.spat[k]))continue;const v=D.fix?D.fix(p.spat[k],s):null;if(v)o.spat[k]=v;} + o.gov=pieGovFix(p.gov,s); + s.pie=o;} +const sid0=v=>typeof v==='string'&&v&&v.length<=40?v:uid(); diff --git a/src/game/60-features/99-pie-jitters.js b/src/game/60-features/99-pie-jitters.js new file mode 100644 index 0000000..79d6a4e --- /dev/null +++ b/src/game/60-features/99-pie-jitters.js @@ -0,0 +1,68 @@ +/* ---------- Pie in the Sky: the Founder's antics and the market's jitters (docs/plans/pie-in-the-sky.md) ---------- + Every 60 to 120 days while a rocket company exists, the Founder does something daft: a post, a gasp (a toast) and a + real effect that wears off. Each antic also bumps the market's jitters (S.pie.founder.jit, 0..1), which fade to nothing + over PIE_JIT_DAYS and meanwhile make orbit customers call less and keep the happiest a little less happy (at most + PIE_JIT_CAP under 100, never low enough to cancel over it): Ooooh, Uuuuuh, then it normalises. + Rule O5: the harm needs pieChaos() (chaos on, the 90 quiet days over); without it he still posts and nothing else + happens. Dice are rolled only with a company (pieAnticDay returns first), so every other game plays as before. + State in S.pie.founder (pieBlank, pieSanitize): jit; next, the day of the next antic (0: not planned yet); kid, 1 + an + index of PIE_KIDS (once a game, then a running gag); bill, the day orbit billing is back; nerv, hype, leak: the days + those last until; mars, the due day (in due) of the Mars promise, whose slip costs a few orbit customers. */ +const PIE_ANTIC_FIRST=90,PIE_ANTIC_GAP=60,PIE_ANTIC_SPAN=61,PIE_JIT_DAYS=30,PIE_JIT_OFFER=0.3,PIE_JIT_CAP=25, + PIE_KID_DAYS=3,PIE_SPREE_DAYS=14,PIE_NERV=0.6,PIE_SPREE_MOOD=4,PIE_LEAK_DAYS=30,PIE_LEAK_INS=1.75,PIE_HYPE_DAYS=14,PIE_HYPE=1.5,PIE_MARS_CHURN=0.02; +// The kid's name (code, not words: never translated) and what the feed calls him afterwards. +const PIE_KIDS=[{n:"Orbit'); DROP TABLE invoices;--",k:'Orby Tables'},{n:"Perigee'); DELETE FROM billing;--",k:'Perry Tables'},{n:"Max Q'); TRUNCATE customers;--",k:'Maxie Tables'}]; +FOUNDER_POSTS.push(N_('pie.fp_backup'),N_('pie.fp_kid'),N_('pie.fp_leak'),N_('pie.fp_leak_kid'),N_('pie.fp_mars'),N_('pie.fp_mars_kid'),N_('pie.fp_mars_slip'),N_('pie.fp_reg'),N_('pie.fp_spree'),N_('pie.fp_spree_kid')); +const pieKid=()=>{const F=S&&S.pie&&S.pie.founder;return F&&F.kid?PIE_KIDS[F.kid-1]:null;}; +const pieBump=(F,v)=>{F.jit=Math.min(1,+(F.jit+v).toFixed(4));}; +const pieOrbitBiz=()=>S.biz.filter(b=>BIZ_T[b.type].orbit); +// Read by pieMoney() (no orbit income while billing is down), pieQuote() (insurance) and the orbit sales desk (offers). +function pieBillOff(){const P=S&&S.pie;return !!P&&P.founder.bill>S.day&&pieChaos();} +function pieInsMul(){const P=S&&S.pie;return P&&P.founder.leak>S.day&&pieChaos()?PIE_LEAK_INS:1;} +function pieOfferMul(){const P=S.pie;if(!P||!pieChaos())return 1;const F=P.founder;let m=1-PIE_JIT_OFFER*F.jit;if(F.nerv>S.day)m*=PIE_NERV;if(F.hype>S.day)m*=PIE_HYPE;return m;} +// The antics: w their weight, ok(F) whether he can, go(F,harm,d) posts and, with harm, does it and returns the toast's text; +// j: how much it rattles the market. +const PIE_ANTICS={ + kid:{w:1.5,j:0.7,ok:F=>!F.kid,go:(F,h,d)=>{F.kid=1+Math.floor(Math.random()*PIE_KIDS.length);pieFounder(N_('pie.fp_kid'));if(!h)return ''; + const n=rint(PIE_KID_DAYS,3);F.bill=d+n+1;return tr('pie_ant.kid',{kid:esc(pieKid().n),n});}}, + spree:{w:3,j:0.6,ok:()=>true,go:(F,h,d)=>{const n=rint(40,50);pieFounder(F.kid?N_('pie.fp_spree_kid'):N_('pie.fp_spree'),{n});if(!h)return ''; + F.nerv=d+PIE_SPREE_DAYS;pieMood(b=>!!BIZ_T[b.type].orbit,-PIE_SPREE_MOOD);return tr('pie_ant.spree',{n,d:PIE_SPREE_DAYS});}}, + reg:{w:1,j:0.4,ok:()=>true,go:(F,h)=>{pieFounder(N_('pie.fp_reg'));if(!h)return '';const P=S.pie; + // A country where you have a dish or landing rights, through the spats' own machinery (pieSpatStart). + if(Object.keys(P.spat).lengthtrue,go:(F,h,d)=>{pieFounder(F.kid?N_('pie.fp_leak_kid'):N_('pie.fp_leak'));if(!h)return ''; + F.leak=d+PIE_LEAK_DAYS;return tr('pie_ant.leak',{p:pct(PIE_INS*PIE_LEAK_INS),n:PIE_LEAK_DAYS});}}, + mars:{w:2,j:0.3,ok:F=>!F.mars,go:(F,h,d)=>{F.mars=piePromise(F.kid?N_('pie.fp_mars_kid'):N_('pie.fp_mars'));if(!h)return ''; + F.hype=d+PIE_HYPE_DAYS;return tr('pie_ant.mars',{n:PIE_HYPE_DAYS});}}, +}; +const PIE_ANTIC_KEYS=Object.keys(PIE_ANTICS); +// One antic (k forces which, for tests); true when he did something. +function pieAntic(k){const P=S.pie;if(!P||!P.co)return false;const F=P.founder,d=S.day,h=pieChaos(); + if(!k){const o=PIE_ANTIC_KEYS.filter(x=>PIE_ANTICS[x].ok(F));let r=Math.random()*o.reduce((a,x)=>a+PIE_ANTICS[x].w,0);k=o[o.length-1];for(const x of o){r-=PIE_ANTICS[x].w;if(r<=0){k=x;break;}}} + const A=PIE_ANTICS[k];if(!A||!A.ok(F))return false;S.stats.pieAnt=(S.stats.pieAnt||0)+1; + const b=A.go(F,h,d);if(!h)return true; + pieBump(F,A.j);toast(`😱 ${tr('pie_ant.gasp')}
${b}`,'bad');sfx('alert');return true;} +// The Mars promise slipped (pieDay, when its due day comes): the unhappiest few orbit customers had enough. +function pieMarsSlip(d){const F=S.pie.founder;F.mars=0;pieFounder(N_('pie.fp_mars_slip'),{n:pieYear(d+360)});if(!pieChaos())return;pieBump(F,PIE_ANTICS.mars.j); + const bs=pieOrbitBiz().sort((a,b)=>a.mood-b.mood),n=Math.round(bs.length*PIE_MARS_CHURN); + if(n){const go=new Set(bs.slice(0,n));S.biz=S.biz.filter(b=>!go.has(b));S.stats.pieChurn=(S.stats.pieChurn||0)+n;} + toast(`😱 ${tr('pie_ant.gasp')}
${n?trn('pie_ant.mars_slip',n):tr('pie_ant.mars_slip_none')}`,'bad');} +function pieAnticDay(d){const P=S.pie,F=P.founder;if(!P.co)return; + if(F.bill&&d>=F.bill-1){F.bill=0;pieFounder(N_('pie.fp_backup'));if(pieChaos())toast(tr('pie_ant.backup'),'good');} + if(F.mars&&!F.due.includes(F.mars))F.mars=0; + if(F.jit>0){if(pieChaos()){const top=100-PIE_JIT_CAP*F.jit;for(const b of S.biz)if(BIZ_T[b.type].orbit&&b.mood>top)b.mood=top;}const j=+(F.jit-1/PIE_JIT_DAYS).toFixed(4);F.jit=j<0.005?0:j;} + if(!F.next)F.next=d+PIE_ANTIC_FIRST;else if(d>=F.next){F.next=d+rint(PIE_ANTIC_GAP,PIE_ANTIC_SPAN);pieAntic();}} +PIE_ON.day.push(pieAnticDay); +// sanitize: the antics' part of S.pie.founder (o: the repaired founder, F: the saved one). +function pieAnticFix(o,F,day){const n=(v,hi)=>int(v,0,hi,0);o.jit=clamp(num(F.jit,0),0,1);o.next=n(F.next,day+PIE_ANTIC_FIRST+PIE_ANTIC_GAP+PIE_ANTIC_SPAN);o.kid=n(F.kid,PIE_KIDS.length); + o.bill=n(F.bill,day+PIE_KID_DAYS+3);if(o.bill<=day)o.bill=0;o.nerv=n(F.nerv,day+PIE_SPREE_DAYS);o.hype=n(F.hype,day+PIE_HYPE_DAYS);o.leak=n(F.leak,day+PIE_LEAK_DAYS); + o.mars=n(F.mars,day+720);if(!o.due.includes(o.mars))o.mars=0;} +// The Company tab, next to the feed: how jumpy the market is and how long until it calms down. +function pieJitHtml(F){const j=F.jit||0,K=pieKid();let h=''; + if(!(j>0))h=`

${tr('pie_ant.jit_calm')}

`; + else{const l=j>=0.6?tr('pie_ant.jit_high'):j>=0.3?tr('pie_ant.jit_mid'):tr('pie_ant.jit_low'); + h=`

${trn('pie_ant.jit_line',Math.ceil(j*PIE_JIT_DAYS),{lvl:l})}

`;} + if(pieBillOff())h+=`

${tr('pie_ant.bill_paused',{d:dateStr(F.bill),kid:esc(K?K.n:'')})}

`; + return h;} diff --git a/src/game/60-features/99-pie-orbit-customers.js b/src/game/60-features/99-pie-orbit-customers.js new file mode 100644 index 0000000..5012f29 --- /dev/null +++ b/src/game/60-features/99-pie-orbit-customers.js @@ -0,0 +1,36 @@ +/* ---------- Pie in the Sky: customers in orbit (docs/plans/pie-in-the-sky.md) ---------- + Terminal customers (BIZ_T[].orbit: pizza homes and boats, flywifi airlines, boat cruise ships, marsorb the Mars mission + over your pies) are offered only once the network can serve them (rule F3's spirit): a baked crust over the city and a + pie dish that can land it (pieServe(), from the last compute). The market is the shell, not your ambition: what all + your crusts can sell (PIE_SELL of their capacity, the rest flies over ocean and empty land) caps what is signed and + on offer, so orbit income cannot outgrow the sky (like F5). Remote towns (no POP of yours, few people) are the first + to call: Pitcairn, the Arctic, the outer islands. */ +const PIE_SELL=0.4,PIE_REMOTE=0.6,PIE_OFFER_RATE=1/3,PIE_OFFERS=2; +// Orbit customers know the sky has bad weeks: without service they lose at most PIE_PATIENCE happiness a day (the day tick), +// so they grumble, then fume, and cancel only after about a month of nothing, not in three days like a fiber customer. +const PIE_PATIENCE=4; +// Gbps the sky can sell: what each crust carries (pieCap(): a half-baked one, a share of it). +function pieMarket(){if(!S.pie)return 0;let g=0;for(const id of pieHubs())g+=pieCap(id)*PIE_SELL;return g;} +// Gbps signed and on offer, of one kind (t) or of all. +const pieSold=t=>{let g=0;for(const b of S.biz)if(BIZ_T[b.type].orbit&&(!t||b.type===t))g+=b.bw;for(const o of S.offers)if(BIZ_T[o.type].orbit&&(!t||o.type===t))g+=o.bw;return g;}; +const pieRoom=t=>{const m=pieMarket(),sh=BIZ_T[t].share;return Math.min(m-pieSold(),sh?m*sh-pieSold(t):Infinity);}; +// Which kinds can be offered today: only with a crust up, a dish working, and market left. +function pieOfferTypes(){if(!pieOn()||!R||!R.pie||!R.pie.hubs.length||!pieDishes().length||pieSold()>=pieMarket())return []; + const t=['pizza','pizza','pizza','boat','boat'];if(R.pie.hubs.some(pieLased))t.push('flywifi','flywifi','flywifi'); + // The Mars mission's orbital option exists only in saves of this version (S.pieV), at the top level. + if(S.pieV>=1&&lvl()>=13)t.push('marsorb');return t.filter(x=>pieRoom(x)>=BIZ_T[x].opts[0]);} +// Cities a terminal could sit in: cruise ships call at the coast, airlines at big airports, homes anywhere. +function pieCands(t){if(t==='boat')return CITIES.filter(c=>c.beach||pieCoast(c.id));if(t==='flywifi')return CITIES.filter(c=>c.P>=250);return CITIES;} +// The size fits the market left and the room on the dish it would land on (offers on the table count as taken). +// Whoever runs sales has a say (99-pie-sales.js): the room they will sell, the size they ask for, how they dress it up. +function pieSpawn(t){const T=BIZ_T[t],min=T.opts[0],ok=pieCands(t).filter(c=>{if(c.cn)return false;const L=pieServe(c.id,t);return !!L&&pieSlRoom(L)>=min;});if(!ok.length)return; + const far=ok.filter(c=>!S.pops[c.id]&&c.P<=60),city=(far.length&&Math.random()a+(BIZ_T[o.type].orbit?o.bw:0),0)),opts=T.opts.filter(g=>g<=left),bw=opts.length?pieSlSize(opts):0;if(!bw)return; + const list=T.names.filter(n=>!S.usedNames.includes(n)),name=list.length?pick(list):pick(T.names);useName(name); + const o={id:uid(),city,city2:null,name,type:t,bw,rate:T.rate,reqs:[],exp:S.day+40};pieSlShape(o);S.offers.push(o);} +// Grand opening: the first PIE_OPEN_DAYS after a crust starts carrying traffic (crust.open, the day it first did), the phone +// rings every day and up to PIE_OPEN_OFFERS wait, so regular customers sign while the patchy-sky income fades (99-pie-patchy.js). +const PIE_OPEN_DAYS=30,PIE_OPEN_OFFERS=4; +function pieOpening(){const P=S.pie;let on=false;for(const id of pieHubs()){const c=P.crusts[id];if(!c)continue;if(c.open===undefined&&pieCap(id)>0)c.open=S.day;if(c.open!==undefined&&S.day-c.open{const op=pieOpening();if(S.offers.filter(o=>BIZ_T[o.type].orbit).length>=(op?PIE_OPEN_OFFERS:PIE_OFFERS))return;const t=pieOfferTypes();if(t.length&&(op||Math.random()S.day)continue;const f=piePatchyShare(id);if(!(f>0)||!ds.some(d=>pieCovers(id,d.city)))continue; + const v=Math.round(PIE_PATCHY_MO*CRUSTS[id].g/CRUSTS.short.g*f);o.cr[id]=v;o.mo+=v;} + return o;} +// How many of the names to show for mo $/mo: one per few $M, at least one. +const piePatchyN=mo=>clamp(Math.ceil(mo/4e6),1,PIE_PATCHY_NAMES.length); diff --git a/src/game/60-features/99-pie-sales.js b/src/game/60-features/99-pie-sales.js new file mode 100644 index 0000000..f7b3973 --- /dev/null +++ b/src/game/60-features/99-pie-sales.js @@ -0,0 +1,36 @@ +/* ---------- Pie in the Sky: the sales desk sells orbit too (38-sales-desk.js, 99-pie-orbit-customers.js) ---------- + Orbit offers go through whoever runs sales, as ground offers do: they carry o.by (so the shark's commission, the + renewal haggles and each one's mark at renewal apply), plus what each of them does with a sky to sell: + - the engineer only offers a deal where the dish it lands on has room to spare (PIE_ENG_ROOM times the deal) and its + POP is well served (PIE_ENG_SF), and their orbit customers renew like the nerds do (salesLeaveMul); + - the shark calls airlines and cruise lines first, asks for the biggest size that fits at a quarter more, and promises + half of them a full sky (REQS.skyfull) before the crust is there: those customers grumble until it is, but never + cancel over the promise alone (they stop at PIE_GRUMBLE happiness); + - the CEO plays some of his golf with the Founder (one game in two while a rocket company exists): the biggest orbit + deal that fits, the Mars mission first, at 30% off and with a promise nobody checked. A jumpy market costs him: + his orbit prices drop by PIE_CEO_JIT times the jitters, and from PIE_CEO_SKIP the Founder does not show up. + Rolls are hashes of the deal (slR), never Math.random: without a salesperson orbit offers are drawn exactly as before. */ +const PIE_ENG_ROOM=1.5,PIE_ENG_SF=0.98,PIE_SHARK=1.25,PIE_SHARK_OVER=0.5,PIE_PROMISE=0.9,PIE_GRUMBLE=40,PIE_GOLF_SKY=0.5,PIE_CEO_JIT=0.4,PIE_CEO_SKIP=0.6; +// What the salesperson can sell on a landing (pieServe()'s answer): the engineer keeps headroom on healthy dishes only. +function pieSlRoom(L){if(slP()!=='eng')return L.left;const d=pieDishes()[L.k];return d&&!R.pie.isl.includes(d.city)&&sfOf(R,d.city)>=PIE_ENG_SF?L.left/PIE_ENG_ROOM:0;} +// Which kinds get a call: the shark rings airlines and cruise lines first. +function pieSlTypes(t){if(slP()!=='shark')return t;const big=t.filter(x=>x==='flywifi'||x==='boat'||x==='marsorb');return big.length?big:t;} +// The size: the shark asks for the biggest that fits, everyone else as the customer asks (pick, as before). +const pieSlSize=opts=>slP()==='shark'?opts[opts.length-1]:pick(opts); +// A new orbit offer, dressed by whoever is at the desk. +function pieSlShape(o){const p=slP();if(!p)return;o.by=p; + if(p==='shark'){o.rate=Math.round(o.rate*PIE_SHARK);if(!REQS.skyfull.ok()&&slR('skyover|'+slKey(o))0)o.rate=Math.round(o.rate*(1-PIE_CEO_JIT*j));}} +const pieJit=()=>(S.pie&&S.pie.founder&&S.pie.founder.jit)||0; +// The CEO's golf with the Founder (salesGolf, on a golf day): true when this game was in orbit, deal or no deal. +function pieGolf(d){if(!pieOn()||!S.pie||!S.pie.co||slR('golfsky|'+d)>=PIE_GOLF_SKY)return false; + const ts=pieOfferTypes();if(!ts.length)return false; + if(pieJit()>=PIE_CEO_SKIP){toast(tr('sales.ceo_golf_skip'),'');return true;} + for(const t of ['marsorb','boat','flywifi','pizza']){if(!ts.includes(t))continue;const T=BIZ_T[t]; + const cs=pieCands(t).filter(c=>!c.cn).map(c=>[c,pieServe(c.id,t)]).filter(([,L])=>L&&L.left>=T.opts[0]).sort((a,b)=>b[0].P-a[0].P||(a[0].idg<=Math.min(pieRoom(t),L.left)).pop();if(!bw)continue; + const list=T.names.filter(n=>!S.usedNames.includes(n)),name=list.length?list[Math.floor(slR('golfskyn|'+d)*list.length)]:T.names[0];useName(name); + const off=1-0.7*(1-PIE_CEO_JIT*pieJit()),o={id:uid(),city:c.id,city2:null,name,type:t,bw,rate:Math.round(T.rate*(1-off)),reqs:REQS.skyfull.ok()?[]:['skyfull'],exp:d+40}; + const b=offerCustomer(o);b.by='ceo';S.biz.push(clSign(b)); + toast(tr('sales.ceo_golf_sky',{name:esc(name),city:esc(c.name),bw:fmtG(bw),price:fmt$(bw*o.rate),p:pct(off)})+(o.reqs.length?' '+tr('sales.ceo_promised',{req:esc(REQS.skyfull.l())}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');return true;} + return false;} diff --git a/src/game/60-features/99-pie-subsidies.js b/src/game/60-features/99-pie-subsidies.js new file mode 100644 index 0000000..21949af --- /dev/null +++ b/src/game/60-features/99-pie-subsidies.js @@ -0,0 +1,120 @@ +/* ---------- Pie in the Sky: government money (docs/plans/pie-in-the-sky.md) ---------- + Two state programmes for a rocket company, kept in S.pie.gov (pieBlank(), repaired by pieGovFix()): + - The Rural Digital Pie Fund: reverse auctions for support of a remote town that only orbit reaches (a cut-off POP on + backhaul, or a town of your terminal customers with no POP of yours). The lowest ask wins; a rival bids too. A win + pays a monthly subsidy (V.gov in compute()) for PIE_RDF_TERM days, while the town's service, averaged over each + month, stays at PIE_RDF_NEED from the deadline on. A month below it is a warning; two in a row revoke the award, and + PIE_RDF_CLAW of the last year's support goes back. + - The Ex-Im Pie Bank: a cheap state loan sized to the constellation (a BANKS entry, so it bills and shows like any + loan), with space covenants: launch n pies by a day, keep a pie dish in the lending country. A breach is a loan + breach (the bank's penalty), plus tighter terms (PIE_EXIM_PEN on the rate, the launch target rescheduled) and, with + chaos on (rule O5), a geopolitical spat in the lending country. + Pitcairn's satellite tier of the UK grant is in 85-pitcairn.js. Subsidies count in the orbit's books (book.earned). */ +const PIE_RDF_MO=5e6,PIE_RDF_P=30,PIE_RDF_TERM=1800,PIE_RDF_DUE=90,PIE_RDF_NEED=0.7,PIE_RDF_CLAW=0.5,PIE_RDF_MAX=6, + PIE_RDF_DAYS=20,PIE_RDF_RATE=1/45,PIE_RDF_FAR=60,PIE_RDF_BIDS=[0.9,0.7,0.5],PIE_RDF_RIV=0.4, + PIE_EXIM_SHARE=0.5,PIE_EXIM_MIN=250e6,PIE_EXIM_CAPF=0.2,PIE_EXIM_APR=0.015,PIE_EXIM_TERM=60,PIE_EXIM_BY=360,PIE_EXIM_PEN=0.03, + PIE_EXIM_RESCHED=180,PIE_EXIM_EVERY=90; +// Rival bidders: the old satellite crowd and the local co-op. +const PIE_RIVALS=[N_('pie_gov.rival_viasad'),N_('pie_gov.rival_hugsnet'),N_('pie_gov.rival_coop')]; +const pieGovBlank=()=>({auc:[],aw:[],ex:null,told:0}); +// A town's service today, from the last compute: a POP's share of its demand served (orbit's latency is accepted: the +// fund pays for coverage), or the share its terminal customers get. +function pieRdfSrv(c){if(!R||!R.pie)return 0;if(S.pops[c]){const d=R.cityDem[c]||0;return d>1e-6?clamp((R.citySrv[c]||0)/d,0,1):0;} + let w=0,g=0;for(const b of S.biz)if(b.city===c&&BIZ_T[b.type].orbit){w+=b.bw;g+=b.bw*Math.min(1,R.pie.sf[b.id]||0);}return w>0?g/w:0;} +// Towns the fund will auction: cut-off POPs with home broadband on backhaul, and small towns with no POP of yours where +// your terminals are, that are not up for auction or awarded already. +function pieRdfCands(){if(!R||!R.pie||!R.pie.hubs.length)return [];const G=S.pie.gov,busy=new Set([...G.auc,...G.aw].map(x=>x.city)),o=new Set(); + for(const b of R.pie.bh)if(b.land&&S.pops[b.city]&&S.pops[b.city].bb)o.add(b.city); + for(const b of S.biz)if(BIZ_T[b.type].orbit&&!S.pops[b.city]&&CITY[b.city].P<=PIE_RDF_FAR)o.add(b.city); + return [...o].filter(c=>!busy.has(c)&&!CITY[c].cn).sort();} +// The reserve grows with the town, up to a small one's worth: the fund is for the last mile, not for cities. +const pieRdfAsk=c=>Math.round(PIE_RDF_MO*(1+Math.min(CITY[c].P,PIE_RDF_FAR)/PIE_RDF_P)/1e5)*1e5; +function pieRdfOpen(c){const G=S.pie.gov,a={id:uid(),city:c,ask:pieRdfAsk(c),close:S.day+PIE_RDF_DAYS,riv:+(PIE_RDF_RIV+(1-PIE_RDF_RIV)*Math.random()).toFixed(3),rv:Math.floor(Math.random()*PIE_RIVALS.length)%PIE_RIVALS.length,bid:0}; + G.auc.push(a);toast(`🏛️ ${tr('pie_gov.t_auction_title')}
${tr('pie_gov.t_auction',{city:esc(CITY[c].name),mo:fmt$(a.ask),y:PIE_RDF_TERM/360,d:dateStr(a.close)})}`,'goal',[{l:tr('pie_gov.bid'),act:'pieGovOpen',args:{}}]);} +// Bids close: the lower ask wins. Silent when you did not bid. +function pieRdfClose(a){const G=S.pie.gov,c=esc(CITY[a.city].name);if(!a.bid)return; + if(a.bid<=a.riv&&G.aw.lengthx!==w); + if(!pieSand())S.cash-=claw;P.book.earned=Math.max(0,P.book.earned-claw);S.stats.pieRdfLost=(S.stats.pieRdfLost||0)+1; + toast(tr('pie_gov.t_revoked',{city:esc(CITY[w.city].name),p:pct(avg),need:pct(PIE_RDF_NEED),amt:fmt$(claw)}),'bad',[{l:tr('pie_gov.open'),act:'pieGovOpen',args:{}}]);sfx('err');} +// What the fund pays this month: every award in force (compute()). +function pieGovMo(){const G=S.pie&&S.pie.gov;if(!G)return 0;let v=0;for(const w of G.aw)v+=w.mo;return v;} +/* ---- The Ex-Im Pie Bank ---- */ +// What a pie in orbit is worth to a lender: the pie, its laser and its seat on the cheapest rocket. +const pieEximUnit=()=>piePrice(PIE_PIE+PIE_LAS)+piePrice(ROCKETS.falcon.cost)/ROCKETS.falcon.pies; +// The most it lends: a share of the cheapest full Shortcrust (rule O7 counts it). +const pieEximCap=()=>Math.round(pieFullCost('short')*PIE_EXIM_CAPF/50e6)*50e6; +// Sized to the constellation: half the value of the pies flying and booked, between PIE_EXIM_MIN and the cap. +function pieEximAmt(){const P=S.pie;let n=pieLiveAll();for(const id in CRUSTS)n+=P.crusts[id].queued;return clamp(Math.round(n*pieEximUnit()*PIE_EXIM_SHARE/50e6)*50e6,PIE_EXIM_MIN,pieEximCap());} +const pieEximLoan=()=>(S.loans||[]).find(l=>l.bank==='exim')||null; +// The covenants (COVS.pielaunch / COVS.piedish, 10-banks.js). +function pieEximLaunchOk(l){const q=l&&l.pie;return !q||S.day=q.n;} +function pieEximDishOk(l){const q=l&&l.pie;return !q||!!S.pie&&S.pie.dishes.some(x=>S.pops[x.city]&&CITY[x.city].cc===q.cc);} +// A fresh offer every PIE_EXIM_EVERY days, from a country you have a POP in, while you have a factory and no Ex-Im loan. +function pieEximOffer(d){const P=S.pie,G=P.gov;if(!P.fac||pieEximLoan()||!pieCanBuild()){if(G.ex&&pieEximLoan())G.ex=null;return;}if(G.ex&&G.ex.exp>d)return; + const ccs=piePopCc();if(!ccs.length)return;const amt=pieEximAmt(); + G.ex={cc:pick(ccs),amt,apr:+(PIE_EXIM_APR+0.01*Math.random()).toFixed(3),term:PIE_EXIM_TERM,n:Math.ceil(amt/pieEximUnit()/20)*20,exp:d+PIE_EXIM_EVERY}; + if(!G.told){G.told=1;toast(`🏦 ${tr('pie_gov.t_exim_title')}
${tr('pie_gov.t_exim',{amt:fmt$(amt),a:esc(pieLicCountry(G.ex.cc))})}`,'goal',[{l:tr('pie_gov.open'),act:'pieGovOpen',args:{}}]);}} +// Taking it: a loan like any other, plus its space covenants. +function pieEximTake(){const P=S.pie,o=P.gov.ex;if(!o||pieEximLoan())return false;const pay=Math.round(annuity(o.amt,o.apr,o.term)); + S.cash+=o.amt;S.stats.loans=(S.stats.loans||0)+1; + S.loans.push({id:uid(),bank:'exim',start:S.day,amount:o.amt,got:o.amt,bal:o.amt,apr:o.apr,apr0:o.apr,pay,left:o.term,term:o.term,share:0,covs:['pielaunch','piedish'],base:{sub:S.links.filter(seaLink).length}, + pie:{cc:o.cc,n:o.n,by:S.day+PIE_EXIM_BY,flown:0,br:0}}); + P.gov.ex=null;track('loan_taken');return true;} +// A breach (loanTick(), after the bank's own penalty): tighter terms, the launch target rescheduled, and a spat. +function pieEximBreach(l,broken){const q=l.pie;if(!q)return;q.br=(q.br||0)+1;l.apr=+(l.apr+PIE_EXIM_PEN).toFixed(3);l.pay=Math.round(annuity(l.bal,l.apr,Math.max(1,l.left))); + if(broken.includes('pielaunch'))q.by=S.day+PIE_EXIM_RESCHED; + let sp='';if(S.pie&&pieChaos()){const ids=broken.includes('piedish')?['home','lic']:['lic','home'];for(const id of ids)if(!S.pie.spat[id]&&pieSpatStart(id,q.cc)){sp=id;break;}} + toast(tr('pie_gov.t_breach',{a:esc(pieLicCountry(q.cc)),apr:(l.apr*100).toFixed(1)})+(sp?' '+tr('pie_gov.t_breach_spat'):''),'bad');} +/* ---- The day ---- */ +function pieGovDay(d){const P=S.pie;if(!P.co)return;const G=P.gov; + if(G.auc.length)for(const a of G.auc.slice())if(d>=a.close){G.auc=G.auc.filter(x=>x!==a);pieRdfClose(a);} + for(const w of G.aw.slice()){if(w.start===d)continue;if(d>=w.end){G.aw=G.aw.filter(x=>x!==w);toast(tr('pie_gov.t_done',{city:esc(CITY[w.city].name),amt:fmt$(w.paid)}),'good');continue;} + w.paid+=w.mo/30;w.s+=pieRdfSrv(w.city);w.n++; + if(w.n>=30){const avg=w.s/w.n;w.s=0;w.n=0;if(d=PIE_RDF_NEED){w.k=0;continue;} + if(w.k){pieRdfRevoke(w,avg);continue;}w.k=1;toast(tr('pie_gov.t_warn',{city:esc(CITY[w.city].name),p:pct(avg),need:pct(PIE_RDF_NEED)}),'bad',[{l:tr('pie_gov.open'),act:'pieGovOpen',args:{}}]);}} + if(!G.auc.length&&G.aw.length0)P.book.earned+=v/30;}} +PIE_ON.day.push(pieGovDay); +// Pies launched count towards the Ex-Im target. +PIE_ON.launch.push((L,ok)=>{const l=ok&&!L.test&&pieEximLoan();if(l&&l.pie)l.pie.flown+=L.n;}); +/* ---- The save gate ---- */ +function pieGovFix(g,s){const o=pieGovBlank(),day=s.day,ob=x=>x&&typeof x==='object'&&!Array.isArray(x);if(!ob(g))return o; + const ccs=new Set(CITIES.map(c=>c.cc)),seen=new Set(),one=x=>isCity(x.city)&&!seen.has(x.city)&&seen.add(x.city),mx=PIE_RDF_MO*20; + o.auc=(Array.isArray(g.auc)?g.auc:[]).filter(a=>ob(a)&&one(a)).slice(0,1).map(a=>({id:sid0(a.id),city:a.city,ask:clamp(num(a.ask,0),0,mx),close:int(a.close,0,day+PIE_RDF_DAYS,day), + riv:clamp(num(a.riv,1),PIE_RDF_RIV,1),rv:int(a.rv,0,PIE_RIVALS.length-1,0),bid:PIE_RDF_BIDS.includes(a.bid)?a.bid:0})); + o.aw=(Array.isArray(g.aw)?g.aw:[]).filter(w=>ob(w)&&one(w)).slice(0,PIE_RDF_MAX).map(w=>{const st=int(w.start,0,day,day); + return {id:sid0(w.id),city:w.city,mo:clamp(num(w.mo,0),0,mx),start:st,due:int(w.due,st,st+PIE_RDF_DUE,st+PIE_RDF_DUE),end:int(w.end,st,st+PIE_RDF_TERM,st+PIE_RDF_TERM), + s:clamp(num(w.s,0),0,30),n:int(w.n,0,29,0),k:w.k?1:0,paid:clamp(num(w.paid,0),0,mx*PIE_RDF_TERM/30)};}).map(w=>(w.s=Math.min(w.s,w.n),w)); + if(ob(g.ex)&&ccs.has(g.ex.cc)){const x=g.ex;o.ex={cc:x.cc,amt:clamp(num(x.amt,PIE_EXIM_MIN),0,pieEximCap()),apr:clamp(num(x.apr,PIE_EXIM_APR),0,0.2),term:PIE_EXIM_TERM,n:int(x.n,0,1e5,0),exp:int(x.exp,0,day+PIE_EXIM_EVERY,day)};} + o.told=g.told?1:0;return o;} +// Ex-Im loans live in S.loans (sanitized there); their covenants' numbers are repaired here, or reset when unreadable. +function pieEximFix(s){const ccs=new Set(CITIES.map(c=>c.cc)),home=isCity(s.home)?CITY[s.home].cc:CITIES[0].cc; + for(const l of s.loans||[]){if(l.bank!=='exim')continue;const q=l.pie&&typeof l.pie==='object'?l.pie:{}; + l.pie={cc:ccs.has(q.cc)?q.cc:home,n:int(q.n,0,1e5,0),by:int(q.by,0,s.day+PIE_EXIM_BY,0),flown:int(q.flown,0,1e6,0),br:int(q.br,0,1e4,0)};l.covs=['pielaunch','piedish'];}} +/* ---- The bank's Government money section (it was Pie Control's Gov tab) ---- */ +// Shown once there is a rocket company, or anything of the fund's or the Ex-Im bank's to show. +function pieGovShow(){const P=S&&S.pie;return !!(P&&pieOn()&&(P.co||P.gov.auc.length||P.gov.aw.length||P.gov.ex||pieEximLoan()));} +function pieGovBank(){return pieGovShow()?`

🏛️ ${tr('pie_gov.section')}

${tr('pie_gov.section_note')}

${pieGovHtml()}
`:'';} +function pieGovHtml(){const P=S.pie,G=P.gov,can=pieCanBuild();let h=`
🏛️ ${tr('pie_gov.rdf')}

${tr('pie_gov.rdf_note',{y:PIE_RDF_TERM/360,p:pct(PIE_RDF_NEED),c:pct(PIE_RDF_CLAW)})}

`; + for(const a of G.auc)h+=`
${esc(CITY[a.city].name)} · ${tr('pie_gov.up_to',{mo:fmt$(a.ask)})}${tr('pie_gov.closes',{d:dateStr(a.close)})}
+
${PIE_RDF_BIDS.map(f=>btn(tr('pie_gov.ask',{mo:fmt$(Math.round(a.ask*f))}),'pieBid',{id:a.id,f},a.bid===f?'pink sm':'ghost sm',!can)).join('')}
`; + if(!G.auc.length)h+=`

${tr('pie_gov.no_auction')}

`; + for(const w of G.aw){const s=pieRdfSrv(w.city),ok=s>=PIE_RDF_NEED; + h+=`
${esc(CITY[w.city].name)} · ${tr('common.price_mo',{price:fmt$(w.mo)})}${tr('pie_gov.served',{p:pct(s)})}
+
${S.day'+tr('pie_gov.warned')+'':''}
`;} + h+=`
🇵🇳 ${tr('pie_gov.pitcairn')}

${tr('pie_gov.pitcairn_note',{mo:fmt$(GRANT_MO),sky:fmt$(GRANT_SKY_MO)})}

${grantFact('pcn')}
`; + const l=pieEximLoan(),o=G.ex;h+=`
🏦 ${tr('pie_gov.exim')}
`; + if(l){const q=l.pie;h+=`
${tr('common.still_owed')}${fmt$(l.bal)}
${loanLine(l)}
+
${pieEximLaunchOk(l)?'✓':'✗'} ${esc(covLabel('pielaunch',l))}
+
${pieEximDishOk(l)?'✓':'✗'} ${esc(covLabel('piedish',l))}
`;} + else if(o){const pay=Math.round(annuity(o.amt,o.apr,o.term));h+=`

${tr('pie_gov.exim_offer',{amt:fmt$(o.amt),apr:(o.apr*100).toFixed(1),n:o.term,pay:fmt$(pay)})}

+
• ${tr('pie_gov.cov_launch',{n:o.n,d:dateStr(S.day+PIE_EXIM_BY)})}
• ${tr('pie_gov.cov_dish',{a:esc(pieLicCountry(o.cc))})}
+

${tr('pie_gov.exim_breach',{apr:(PIE_EXIM_PEN*100).toFixed(0)})}

${btn(tr('bank.take_the_money'),'pieExim',{},'pink sm',!can)}
`;} + else h+=`

${tr('pie_gov.exim_none')}

`; + return h+'
';} diff --git a/src/game/70-rules/10-helpers.js b/src/game/70-rules/10-helpers.js new file mode 100644 index 0000000..a7bda34 --- /dev/null +++ b/src/game/70-rules/10-helpers.js @@ -0,0 +1,46 @@ +/* ================= HELPERS ================= */ +const fmt$=v=>{const a=Math.abs(v),s=v<0?'-':'';if(a>=999.95e6)return s+'$'+(a/1e9).toFixed(a>=9.995e9?1:2)+'B';if(a>=1e6)return s+'$'+(a/1e6).toFixed(a>=1e7?1:2)+'M';if(a>=1e3)return s+'$'+(a/1e3).toFixed(a>=1e5?0:1)+'k';return s+'$'+Math.round(a);}; +const fmtG=g=>g>=999950?(g/1e6).toFixed(g>=9.995e6?1:2)+' Pbps':g>=1000?(g/1000).toFixed(g>=10000?1:2)+' Tbps':(g>=100?g.toFixed(0):g.toFixed(1))+' Gbps'; +const pct=x=>Math.round(x*100)+'%'; +// Reach never rounds up to 100%: Tier 1 needs more than 99.9%, and 99.6% must not look like a full house (#73). +const reachPct=x=>x>0.999?'100%':x>=0.99?(Math.floor(x*1000)/10).toFixed(1)+'%':pct(x); +const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)); +const pick=a=>a[Math.floor(Math.random()*a.length)]; +// Names already given to customers, each once: only whether a name is in the list counts. Once every name had been +// used, the same names were added again every day (half a million entries, half of a late-game save). +const useName=n=>{if(!S.usedNames.includes(n))S.usedNames.push(n);}; +const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +/* A real calendar (#257): months of 28 to 31 days and Gregorian leap years, counted from Y1 (Y4 is a leap year, + Y100 is not). Day 0 is 1 January Y1. Monthly prices are per calendar month. */ +const leapY=y=>y%4===0&&(y%100!==0||y%400===0),MDAYS=[31,28,31,30,31,30,31,31,30,31,30,31],monDays=(y,m)=>m===1&&leapY(y)?29:MDAYS[m]; +const yearStart=y=>{const n=y-1;return n*365+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400);}; +function cal(d){d=Math.max(0,Math.floor(d)||0);let y=1+Math.floor(d/365.2425);while(y>1&&yearStart(y)>d)y--;while(yearStart(y+1)<=d)y++; + let r=d-yearStart(y),m=0;while(r>=monDays(y,m)){r-=monDays(y,m);m++;}return {y,m,d:r+1};} +const dayOf=(y,m,dd)=>{let n=yearStart(y);for(let i=0;i{const c=cal(d);return (c.y-1)*12+c.m;},monLen=d=>{const c=cal(d);return monDays(c.y,c.m);}; +// A monthly date that started on day s: the same day of the month, or the month's last day when it is shorter. +const monthiversary=(s,d)=>{if(d<=s)return false;const a=cal(s),b=cal(d);return b.d===Math.min(a.d,monDays(b.y,b.m));}; +function dateStr(d){const c=cal(d);return tr('helpers.y_y_mon_d',{y:c.y,mon:MONTHS[c.m],d:c.d});} +// The network's age in days: S.day is the calendar (a server session's, shared), S.day0 the day this network began. +const netAge=()=>S?S.day-(S.day0|0):0; +function wrapDx(a,b){let dx=b-a;if(dx>W/2)dx-=W;if(dx<-W/2)dx+=W;return dx;} +function kmBetween(a,b){const A=CITY[a],B=CITY[b];return Math.max(20,Math.round(hav(A.lon,A.lat,B.lon,B.lat)));} +// Cities on a land bridge belong to two landmasses: Cairo reaches Asia overland across the Sinai, the way +// Istanbul does across the Bosporus (#47). Overland between continents still costs the intercontinental price. +const lands=C=>C.land2?[C.land,C.land2]:[C.land]; +// On one landmass, so fiber can go overland: the same landmass, or two cities of one country on the land a no-road +// landmass is really part of (Pevek and Moscow, Juneau and Seattle, Nuuk and Sisimiut). +const LAND_ON=Object.fromEntries(LANDS_LL.filter(l=>l.on).map(l=>[l.id,l.on])),landOf=x=>LAND_ON[x]||x; +// South Korea's only land border is the DMZ: everything out of the country goes by sea. +const SEALED=['KR']; +const overland=(A,B)=>{if(A.cc!==B.cc&&(SEALED.includes(A.cc)||SEALED.includes(B.cc)))return false;const P=lands(A),Q=lands(B);return P.some(x=>Q.includes(x))||A.cc===B.cc&&P.some(x=>Q.some(y=>landOf(x)===landOf(y)));}; +const isSub=(a,b)=>!overland(CITY[a],CITY[b]); +const popUp=c=>S.pops[c]&&!(S.pops[c].down>S.day); +const regionsCount=()=>new Set(Object.keys(S.pops).map(c=>CITY[c].reg)).size; +const ixCity=x=>String(x).split('~')[0]; +function ixIdsIn(c){const o=ixStatic(c);if(S&&S.myIx&&S.myIx[c]&&!o.includes(c))o.unshift(c);return o;} +const hasIxAt=c=>ixIdsIn(c).some(x=>S.ixp[x]!==undefined); +function ixName(c){if(XIXM[c])return XIXM[c].name;return S.myIx[c]?S.myIx[c].name:CITY[c].ix;} +// IX.brrr Campinas already says where it is, so messages skip "in Campinas" (#134) +const ixNamesCity=c=>String(ixName(c)||'').toLowerCase().includes(CITY[ixCity(c)].name.toLowerCase()); diff --git a/src/game/70-rules/20-exchanges.js b/src/game/70-rules/20-exchanges.js new file mode 100644 index 0000000..6b7f569 --- /dev/null +++ b/src/game/70-rules/20-exchanges.js @@ -0,0 +1,51 @@ +/* Australian exchanges follow PeeringDB (every Australian exchange's member list, Oct 2026): networks that sit on + every IX elsewhere list the Australian cities they really peer in as auIx, and the big incumbents peer only privately. */ +/* Transit in Australia is sold only by carriers with an Australian site and at least ten Australian networks buying + from them (RIPEstat, Oct 2026): Telstraya, Hocus Pocus, Speedyloop, SingTell, Drizzle Electric, Cogentle, + Not That Telecom and Level Tree (whose real-world network lists no sites in PeeringDB at all, but sells in Sydney). Others can sit in + an Australian city, like the Pacific carriers backhauling to Sydney (or Glowball Sakura Lager), but reach Australian + customers only from overseas. */ +const AU_SELLERS=['tsy','voc','spl','sgt','drz','cog','ntt','lvl'],sellsAt=(n,c)=>!!n.price&&(n.pops.includes(c)||!!n.premOnly&&n.premOnly.includes(c))&&(!CITY[c].au||AU_SELLERS.includes(n.id))&&!noTransitIn(c); +// A scenario city where nobody sells transit (Anchors Away: Tallinn's internet is across the water). +const noTransitIn=c=>{const x=S&&S.scn&&S.scn.rules&&S.scn.rules.noTransitIn;return Array.isArray(x)&&x.includes(c);}; +/* China Telecomet's premium crossing into China (CN-Too) is sold where its border routes start: Hong Kong, and Moscow + (#195), where it rides the land route east and nothing else of theirs is on offer (premOnly). It costs the same + wherever you buy it: the Hong Kong price. */ +const premCity=(n,c)=>!!n.premium&&!!n.premAt&&n.premAt.includes(c),premOnlyAt=(n,c)=>!!n.premOnly&&n.premOnly.includes(c); +const premOn=t=>!!t.premium&&!!NET[t.net]&&premCity(NET[t.net],t.city); +// What a port costs per Gbps and month before the commit: the premium crossing at Hong Kong prices, anything else at the city's. +const transitPerG=(n,c,prem)=>prem&&premCity(n,c)?n.price*n.premium*netMult(n,'hkg'):n.price*netMult(n,c); +// Exchange lists are fixed once the page has loaded, so each is looked up through a Set built on first use. +const IX_SET=new WeakMap(),inIxList=(a,c)=>{let s=IX_SET.get(a);if(!s)IX_SET.set(a,s=new Set(a));return s.has(c);}; +const onIx=(n,c)=>CITY[c].au&&n.auIx?inIxList(n.auIx,c):n.ix==='ALL'||Array.isArray(n.ix)&&inIxList(n.ix,c); +function ixMembers(c){if(XIXM[c])return XIXM[c].members.slice();if(S.myIx[c])return S.myIx[c].members.slice();if(!CITY[c].ix)return [];return (IX_MEM[c]||(IX_MEM[c]=NETS.filter(n=>onIx(n,c)).map(n=>n.id))).slice();} +// A city exchange's members only depend on the networks, which are fixed after load. +const IX_MEM={}; +// LAG: several identical ports bundled into one logical link. Flow hashing is never perfectly even, so a bundle carries ~95% of the sum. +const LAG_MAX=8; +/* A PNI bundle grows with the routers it lands on (#323): eight members per router at the POP, so a PNI fatter than eight + ports costs another router (its price and its port slots), up to 32 members, the most the big LAG implementations + bundle. Only PNIs: transit, exchange and fabric ports stay at LAG_MAX. */ +const PNI_LAG_RT=8,PNI_LAG_MAX=32; +function pniLagMax(c){const p=S.pops[c];return Math.min(PNI_LAG_MAX,PNI_LAG_RT*((p&&p.routers)||1));} +function lagCap(g,n){n=n||1;return g*n*(n>1?0.95:1);} +function lagName(tier,n){return (n||1)>1?`${n}×${PORT[tier].n} LAG`:tr('common.port_port',{port:PORT[tier].n});} +function ixCap(c){return ixLagF(c)*(S.myIx[c]?myFab(c).g*(myIxLive(c)?1:0):liveCap(PORT[S.ixp[c]].g,ixCity(c),(S.ixSite||{})[c],(S.ixn||{})[c])*(isRemote(c)?REMOTE_CAP:1));} +function ixSessions(c){ + const s=new Set(); if(S.ixp[c]===undefined)return s; + // satNo() for every member, with the city's satellite circuit (most cities have none) looked up once. + const so=satOnly(ixCity(c)),orb=so&&SATS[so.bird].orb; + for(const id of ixMembers(c)){const n=NET[id]; + if(S.peers[id+'@'+c]&&!snub(id,c)&&!(isRemote(c)&&noRemote(id))&&!(so&&noSat(id,orb)))s.add(id); + else if(S.rs[c]&&n.pol==='open'&&ppol()==='open')s.add(id); + else if(S.myIx[c]&&(n.pol==='open'||n.pol==='selective'))s.add(id);} + return s; +} +function t1Club(){ + const miss=[];const pops=Object.keys(S.pops).length; + if(regionsCount()<3)miss.push(tr('exchanges.pops_on_3_continents')); + if(pops<10)miss.push(tr('exchanges.10_pops_n',{n:pops})); + if(R.served<1500)miss.push(tr('exchanges.serve_1_5_tbps_v',{v:fmtG(R.served)})); + if(R.sessions<20)miss.push(tr('exchanges.20_peering_sessions_n',{n:R.sessions})); + return {ok:!miss.length,missing:miss}; +} diff --git a/src/game/70-rules/30-pnis.js b/src/game/70-rules/30-pnis.js new file mode 100644 index 0000000..0b39e0b --- /dev/null +++ b/src/game/70-rules/30-pnis.js @@ -0,0 +1,21 @@ +/* ---------- PNIs with the big networks: slow orders and no small ports ---------- + Big content networks, Tier 1s and big eyeball networks usually deliver a PNI or an augment in about 30 days, but + 15% of orders get lost in provisioning for 6 to 12 months. The content networks and Tier 1s start at 100G. Doitsche Telekomm sells PNIs down to 1G, and takes its time too. */ +const pniBig=id=>{const n=NET[id];return n.type==='t1'||(n.type==='cdn'&&n.pol!=='open')||(n.type==='eye'&&n.share>=0.02);}; +const pniMin=id=>{const n=NET[id];return n.type==='t1'&&!pniG1(id)||(n.type==='cdn'&&n.pol!=='open')?1:0;}; +const pniG1=id=>id==='dtk'; +// A beer with their peering coordinator at a conference halves the wait. It is how it really works. +const PNI_SLOW=0.15,pniNow=()=>rule('pnis')==='instant',pniLead=id=>{if(pniNow())return 0;const n=pniBig(id)?(Math.random()S.day?Math.round(n/2):n);}; +const pniG=p=>p.g1?1:PORT[p.tier].g,pniPN=p=>p.g1?'1G':PORT[p.tier].n,pniOn=p=>!(p.ready>S.day); +const pniEta=id=>pniNow()?tr('pnis.up_the_moment_you_order'):pniBig(id)?tr('pnis.delivery_about_a_month_sometimes_6'):tr('pnis.delivery_2_to_6_weeks'); +const PNI_G1_COST=1200,pniWhen=n=>n<=0?tr('pnis.it_is_up_already'):n>=60?tr('pnis.their_team_quotes_m_months',{m:Math.round(n/30)}):tr('pnis.ready_in_about_n_days',{n}); +function pniWait(p,c){return `
${(p.n||1)>1?p.n+'×':''}${pniPN(p)} PNI${tr('common.on_order')}
${tr('pnis.about_n_days_to_go_nothing',{n:Math.max(0,p.ready-S.day)})}
${btn(tr('common.chase_it'),'pniChase',{id:p.id},'ghost sm')}${btn(UI.confirm===p.id?tr('common.really_remove'):tr('pnis.cancel_the_order'),'cancelPni',{id:p.id},'ghost sm')}
`;} +function pniDay(d){for(const p of S.pni){const nm=esc(NET[p.net].name),city=esc(CITY[p.city].name); + if(p.ready===d)toast(tr('pnis.pni_with_net_is_up_in',{net:nm,city,dc:esc(siteName(p.city,'a'))}),'good'); + if(p.up&&p.up.ready<=d){pniUpDone(p);toast(tr('pnis.augment_with_net_delivered_in_city',{net:nm,city,port:((p.n||1)>1?p.n+'×':'')+pniPN(p)}),'good');}}} +// An augment arrives: the new port size, LAG and 1G flag replace the old ones. +function pniUpDone(p){p.tier=p.up.tier;p.n=p.up.n;if(p.up.site==='ab'&&p.n>=2&&S.pops[p.city]&&S.pops[p.city].site2)p.site='ab';if(p.up.g1)p.g1=true;else delete p.g1;delete p.up;} +// Microsnoft has no capacity on the US east coast. Not for a PNI, not at an exchange, not for anyone. +const US_EAST=['ash','nyc','bos','atn','mia']; +const MSF_NOPE=[N_('pnis.no_capacity_in_us_east_you'),N_('pnis.us_east_is_sold_out_until'),N_('pnis.their_peering_team_says_us_east'),N_('pnis.a_new_region_is_coming_online')]; +const msfNope=(id,city)=>id==='msf'&&!!city&&US_EAST.includes(ixCity(city)); diff --git a/src/game/70-rules/35-pni-orders.js b/src/game/70-rules/35-pni-orders.js new file mode 100644 index 0000000..6539fad --- /dev/null +++ b/src/game/70-rules/35-pni-orders.js @@ -0,0 +1,38 @@ +/* Single and bulk orders share the same checks, prices and provisioning. */ +// at: for a batch, where to look up the PNI there already is and the ports in use, which the batch itself never changes. +function pniQuote(city,net,tier,reserved=0,at=null){tier=+tier;const g1=tier===-1;if(g1)tier=0; + if(!S||!S.pops[city]||!isNet(net)||!NET[net].pops.includes(city)||!Number.isInteger(tier)||!PORT[tier]||(g1&&!pniG1(net)))return null; + const ex=at?at.ex(city,net):S.pni.find(p=>p.city===city&&p.net===net),used=at?at.used:portsUsed; + if(ex&&(g1||!pniOn(ex)||ex.up||(!(ex.g1&&tier===0)&&tier<=ex.tier)))return null; + const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1),slots=ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier); + let why='';if(!portOk(city,tier))why=tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}); + else{const r=peerOk(net,'pni',city);if(!r.ok)why=tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)}); + else if(!g1&&tier0&&used(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(used(city)+reserved),m:portsMax(city)});} + return {city,net,tier,g1,ex,cost,slots,why};} +// A new PNI has every field sanitize() gives one, so live S is what a reload makes of it. +function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net); + if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1; + if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead,lacp:null,site:'a',n:1,sacrif:false}); + return lead;} +// The ports a pending augment will add, and those of every pending augment at a city: what an order there must leave free. +const pniUpSlots=p=>Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)); +const pniResv=c=>{let r=0;for(const p of S.pni)if(p.up&&p.city===c)r+=pniUpSlots(p);return r;}; +// A batch's order quoted again on the game as it is now: null if it no longer stands (ordered by hand meanwhile, say). +// Earlier orders of the batch, placed by now, are in the PNIs themselves: the same ports the batch reserved for them. +const pniRequote=q=>{const n=pniQuote(q.city,q.net,q.g1?-1:q.tier,pniResv(q.city));return n&&!n.why&&n.ex===q.ex?n:null;}; +function pniBatch(net,tier){const g=pniBatchRun(net,tier);for(;;){const s=g.next();if(s.done)return s.value;}} +// The same batch with a place to let a frame through every few networks: the intern's weekly round (95-standing-orders.js). +function* pniBatchRun(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null; + const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0,raised=0; + // Asked of every network at every shared POP: the PNIs by POP and network (the first one, as find() would), and the + // ports in use, counted for every POP in one pass the first time a quote needs them. + const exs=new Map();let use=null;for(const p of S.pni){const k=p.city+'|'+p.net;if(!exs.has(k))exs.set(k,p);} + const at={ex:(c,n)=>exs.get(c+'|'+n),used:c=>(use||(use=portsAt(Object.keys(S.pops)))).get(c)}; + // Pending augments and earlier orders in this batch already own their future ports. + for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+pniUpSlots(p); + let nn=0;for(const n of all?NETS:[NET[net]]){if(++nn%16===0)yield;for(const city of n.pops){if(!S.pops[city])continue;shared.push(city); + // Each network at its own minimum: asking everyone for 10G orders 100G from those that start at 100G. + const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0,at);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots; + mo+=pniMo({net:n.id,tier:q.tier,g1:q.g1,n:q.ex&&q.ex.n},0)-(q.ex?pniMo(q.ex,0):0);}} + return {shared,orders,blocked,kept,cost,mo,raised};} diff --git a/src/game/70-rules/38-pni-value.js b/src/game/70-rules/38-pni-value.js new file mode 100644 index 0000000..5d5d22c --- /dev/null +++ b/src/game/70-rules/38-pni-value.js @@ -0,0 +1,60 @@ +/* ---------- Is a PNI worth it? (#175, #172) ---------- + How you reach each network today, and what a PNI at one POP would take over: the traffic your users there send + to that network over transit, an exchange or a PNI elsewhere, priced with the real billing functions. Information + only: nothing here changes routing or billing. Built once per routing result (R.fl), not per row. */ +const PNI_HOT=0.8; +let PNIX=null; +function pniIdx(){if(PNIX&&PNIX.R===R)return PNIX; + const ix={},pn={}; + for(const c in S.ixp){const nm=ixName(c);for(const id of ixSessions(c)){const a=ix[id]||(ix[id]=[]);if(!a.includes(nm))a.push(nm);}} + for(const p of S.pni)(pn[p.net]||(pn[p.net]=[])).push(p); + return PNIX={R,fl:{},all:false,ix,pn};} +// One POP's flows by network, added up the first time that POP is asked about. +// Every POP at once, in one pass over the flows: the intern's weekly PNI round asks about all of them, and one POP at a +// time was a pass per POP. The flows are read straight from routing's columns (R.flc), not made into the objects of R.fl +// (tens of thousands on a big network); each POP's sums still add up its flows in their order. +function pniFlows(c){const X=pniIdx();if(!X.all){X.all=true;const F=X.fl,C=R.flc; + const add=(c,n,rem,gt,gi,gp,gh,ti,ii)=>{const m=F[c]||(F[c]={});let o=m[n];if(!o)o=m[n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}}; + o.u+=rem;o.t+=gt;o.ix+=gi;o.p+=gp;o.h+=gh;if(gt)o.T[ti]=(o.T[ti]||0)+gt;if(gi)o.I[ii]=(o.I[ii]||0)+gi;}; + if(C){const {NF,FREM,FCI,FNJ,FGT,FGI,FGP,FGH,FTI,FII,E}=C; + for(let i=0;ip.city===c):null; + if(h)return {k:'here',p:h}; + const el=[...new Set(ps.filter(p=>pniOn(p)).map(p=>p.city))];if(el.length)return {k:'else',cities:el}; + if(X.ix[id])return {k:'ix',ixs:X.ix[id]}; + if(R.cone[id])return {k:'cone',by:NET[R.cone[id]]||coneVia(id)}; + return {k:R.reachable[id]?'t':'none'};} +const pniList=a=>a.length>2?tr('pni_list.list_more',{list:a.slice(0,2).join(', '),n:a.length-2}):a.join(', '); +const PNI_ICON={here:'🔗',else:'🔗',ix:'🤝',cone:'🧺',t:'💸',none:'🚫'}; +function pniChip(id,c){const s=pniStat(id,c);let t; + if(s.k==='here'){const p=s.p;t=!pniOn(p)?tr('pni_list.chip_pni_here_on_order'):tr('pni_list.chip_pni_here',{port:((p.n||1)>1?p.n+'×':'')+pniPN(p),p:pct(Math.min(1,(R.usePni[p.id]||0)/lagCap(pniG(p),p.n)))});} + else if(s.k==='else'){const l=pniList(s.cities.map(x=>CITY[x].name));t=c?tr('pni_list.chip_pni_elsewhere',{list:l}):tr('pni_list.chip_pni_at',{list:l});} + else if(s.k==='ix')t=tr('pni_list.chip_peers_at',{list:pniList(s.ixs)}); + else if(s.k==='cone')t=s.by?tr('pni_list.chip_via_cone',{net:s.by.name}):tr('pni_list.chip_via_a_cone'); + else t=s.k==='t'?tr('pni_list.chip_via_transit'):tr('pni_list.chip_not_reached'); + return `${PNI_ICON[s.k]} ${esc(t)}`;} +/* What a new PNI with `id` at `c` would carry and save per month. It takes your users' traffic there that now + leaves over transit, an exchange or a PNI elsewhere, or does not leave at all for want of room, up to its port; transit is billed on the 95th percentile, + so the saving is the bill now minus the bill with that much less (commits included). */ +/* pniVal()'s want for network n at POP c (what the intern's weekly round sorts by), without the rest pniFlows() keeps + for the PNI list: the same four sums of the same flows in the same order, in columns by (city, network). One pass, + no objects; null when routing left no columns (an old R), then pniFlows() it is. */ +function pniWant(c,n){const X=pniIdx();if(X.w===undefined){const C=R.flc;X.w=null; + if(C){const {NF,FREM,FCI,FNJ,FGT,FGI,FGP}=C;let K=1;for(let i=0;i=K)K=FNJ[i]+1; + const n4=CITIES.length*K,U=new Float64Array(n4),T=new Float64Array(n4),I=new Float64Array(n4),P=new Float64Array(n4); + for(let i=0;i[id,j]))};}} + const W=X.w;if(!W){const o=pniFlows(c)[n];return o?o.t+o.ix+o.p+o.u:0;} + const ci=CIDX[c],j=W.ni.get(n);if(ci===undefined||j===undefined||j>=W.K)return 0;const k=ci*W.K+j;return W.T[k]+W.I[k]+W.P[k]+W.U[k];} +function pniVal(id,c){const o=pniFlows(c)[id]||{t:0,ix:0,p:0,h:0,u:0,T:{},I:{}},want=o.t+o.ix+o.p+o.u; + const lo=pniMin(id);let tier=-1;for(let i=lo;i=want)break;} + if(tier<0)tier=lo;const g=Math.min(want,PORT[tier].g),gt=Math.min(o.t,g);let saved=0; + if(gt>0)for(const tid in o.T){const t=S.transit.find(x=>x.id===tid);if(!t)continue;const q=R.p95[tid]??(R.useT[tid]||0),x=gt*o.T[tid]/o.t;saved+=transitMo(t,q)-transitMo(t,Math.max(0,q-x));} + const cost=pniMo({net:id,tier,n:1},g); + // Then what you drop today for want of room, then a hot exchange port's share. + const drop=Math.min(o.u,g-gt);let ixLeft=g-gt-drop,hot=0;for(const x in o.I){if(ixLeft<=0)break;const m=Math.min(ixLeft,o.I[x]);ixLeft-=m;const cp=S.ixp[x]!==undefined?ixCap(x):0;if(cp>0&&(R.useIx[x]||0)>=PNI_HOT*cp)hot+=m;} + const val=saved-cost,worth=g>=1&&(val>0||hot>=1||drop>=1); + return {...o,want,g,tier,saved,cost,val,hot,drop,worth};} diff --git a/src/game/70-rules/40-peering-desk.js b/src/game/70-rules/40-peering-desk.js new file mode 100644 index 0000000..6ada987 --- /dev/null +++ b/src/game/70-rules/40-peering-desk.js @@ -0,0 +1,32 @@ +/* ---------- The peering desk ---------- + Every exchange port brings peering requests. Nobody answers them by hand any more: your peering policy does. + Open accepts everyone, Selective accepts the networks worth peering with and quietly declines the rest, Closed + declines them all. Once a week the NOC log gets one folded line about it. */ +const PPOL=['open','selective','closed'],ppol=()=>(S&&PPOL.includes(S.ppol))?S.ppol:'open'; +const PPOL_N={open:N_('peering_desk.open_to_all'),selective:N_('common.selective'),closed:N_('common.closed')}; +const PPOL_D={open:N_('peering_desk.open_desc'),selective:N_('peering_desk.selective_desc'),closed:N_('peering_desk.closed_desc')}; +// How often someone asks, against Open: a selective or closed network gets fewer requests. +const PDESK_ASK={open:1,selective:0.7,closed:0.5},PDESK_IX=12; +const pdeskNew=w=>({w,a:0,d:0,ix:[]}); +// Who is worth it: a real small network on the exchange, or a newcomer whose PeeringDB is up to date. +const pdeskWant=(p,net,fresh)=>p==='open'||(p==='selective'&&(!!net||fresh)); +function peeringDeskDay(d){const w=Math.floor(d/7);let D=S.pdesk; + // A new week: last week's tally becomes one line in the NOC log. + if(!D||D.w!==w){if(D&&D.w=Math.min(0.9,0.15*ixs.length)*PDESK_ASK[p])return; + const c=pick(ixs),real=ixMembers(c).filter(id=>{const n=NET[id];return !S.peers[id+'@'+c]&&!merged(id)&&n.type!=='t1'&&n.type!=='cdn'&&n.pol!=='paid'&&n.share<=0.006;}); + const net=real.length&&Math.random()<0.4?pick(real):null,fresh=Math.random()>=0.6; + // A network you already reach (route server, your own exchange) needs no session of its own (#265). + if(net&&ixSessions(c).has(net))return; + if(!pdeskWant(p,net,fresh)){D.d++;return;} + if(net)S.peers[net+'@'+c]=true;D.a++;if(!D.ix.includes(c)&&D.ix.length4?3:4).map(ixName);if(x.ix.length>4)nm.push(trn('peering_desk.n_more_exchanges',x.ix.length-3)); + let ix;try{ix=new Intl.ListFormat(LANG,{type:'conjunction'}).format(nm);}catch(e){ix=nm.join(', ');} + return x.d?trn('peering_desk.n_new_sessions_at_ix_declined',x.a,{ix,d:x.d,pol}):trn('peering_desk.n_new_sessions_at_ix',x.a,{ix,pol});} +// The policy picker, in the Networks tab. +function pdeskCard(){const p=ppol(),r=S.pdeskRep; + return `
🤝 ${tr('common.peering_policy')}: ${tr(PPOL_N[p])}
${PPOL.map(x=>btn(tr(PPOL_N[x]),'peerPol',{p:x},p===x?'sm':'ghost sm')).join('')}
+

${tr(PPOL_D[p])}

${r&&r.w>=Math.floor(S.day/7)-1&&(r.a||r.d)?`

${esc(pdeskLine(r))}

`:''}
`;} diff --git a/src/game/70-rules/50-peering-policy.js b/src/game/70-rules/50-peering-policy.js new file mode 100644 index 0000000..0633512 --- /dev/null +++ b/src/game/70-rules/50-peering-policy.js @@ -0,0 +1,41 @@ +/* Big networks sometimes refuse to peer in a particular city, for a while. Each (network, city) + pair gets a stable verdict per window, derived from a hash, so asking again does not reroll it. + It is part of the market: without one (Change Freeze, puzzles), nobody refuses or drops a session. */ +const SNUB_WIN=150,SNUB_P=0.22; +const SNUB_IX=[tr('peering_policy.only_peers_over_pnis_in_this'),tr('peering_policy.their_ix_port_here_is_full'),tr('peering_policy.moved_everything_in_this_city_to'),tr('peering_policy.the_peering_coordinator_for_this'),tr('peering_policy.their_policy_here_says_ix_peering')]; +const SNUB_ALL=[tr('peering_policy.not_accepting_new_peers_in_this'),tr('peering_policy.region_frozen_while_they_renegotiate'),tr('peering_policy.their_routers_in_this_city_are'),tr('peering_policy.already_reach_you_through_your'),tr('peering_policy.their_lawyers_are_reviewing_every'),tr('peering_policy.a_new_vp_wants_to_monetise')]; +function hstr(t){let h=2166136261;for(let i=0;i>>0;} +function bigPeer(n){return !!n&&n.pol==='selective'&&n.share>=0.03;} +function snub(id,c){ + const n=NET[id];if(!c||!bigPeer(n)||!S||S.myIx[c]||!rule('market'))return null; + const off=hstr(id+c)%SNUB_WIN,ep=Math.floor((S.day+off)/SNUB_WIN),h=hstr(S.asn+'|'+id+'|'+c+'|'+ep); + if(h%1000>=SNUB_P*1000)return null; + const all=(h>>>10)%5<2,list=all?SNUB_ALL:SNUB_IX; + return {all,why:list[(h>>>13)%list.length],until:(ep+1)*SNUB_WIN-off}; +} +/* Remote peering: offered, but discouraged. A reseller marks up the port, oversubscribes it, + and many selective networks refuse members who are not physically in the building. */ +const REMOTE_FEE=1.5,REMOTE_CAP=0.8; +const REMOTE_WARN=`

${tr('peering_policy.remote_peering_is_a_last_resort')}

`; +const REMOTE_WHY=[tr('peering_policy.policy_no_remote_peers_be_in'),tr('peering_policy.saw_your_session_come_in_over'),tr('peering_policy.only_peers_with_members_they_can'),tr('peering_policy.their_pearingdb_entry_says_remote'),tr('peering_policy.tried_a_remote_peer_once_it')]; +function isRemote(c){return S.ixp[c]!==undefined&&!S.pops[ixCity(c)]&&!S.myIx[c];} +function noRemote(id){const n=NET[id];if(!n||n.pol!=='selective')return false;return hstr(id+'|remote')%100<(n.share>=0.03?60:30);} +/* Satellite islands (#83): where a satellite circuit is your only way out of a city, many selective networks will not + peer there. They would hand you traffic for your whole network to haul through orbit: most refuse a GEO hop (about + 600 ms there and back), few a MEO one (about 130 ms). A stable verdict per network, like remote peering. */ +const SAT_NO={geo:60,meo:15}; +const noSat=(id,orb)=>{const n=NET[id];return !!n&&n.pol==='selective'&&own(SAT_NO,orb)&&hstr(id+'|sat')%100=SAT_NO.geo)return null;const l=satOnly(c);return l&&noSat(id,SATS[l.bird].orb)?l:null;} +function satPeerWhy(id,c){const l=satNo(id,c);return l?tr('peering_policy.not_while_a_satellite_is_your_only_way',{city:CITY[c].name,orb:SAT_ORB[SATS[l.bird].orb].n,ms:Math.round(2*satLat(l))}):'';} +/* Europe's peering market is crowded and competitive: ports are cheaper, and incumbents cut prices + when a challenger in the same metro gets too popular. DE-KICKS harmonises instead. */ +const IX_REG={EU:0.8}; +function ixMul(x){const X=XIXM[x],c=ixCity(x);return (X?X.cheap:(CITY[c].ixCheap||1))*(IX_REG[CITY[c].reg]||1)*(CITY[c].au?AU_IX:1)*((S&&S.ixCut&&S.ixCut[x])||1);} +function ixPortMo(c,tier){const X=XIXM[c];if(X&&tier<=(X.freeTo??-1))return 0;return Math.round(PORT[tier].ix*(S.pops[ixCity(c)]?1:REMOTE_FEE)*dkMult(c)*ixMul(c));} +function ixPriceWar(d){if(!S.ixp||Math.random()>=1/120)return; + const mine=Object.keys(S.ixp).filter(x=>{const c=ixCity(x);return CITY[c].reg==='EU'&&ixStatic(c).length>1;});if(!mine.length)return; + const x=pick(mine),c=ixCity(x),rival=pick(ixStatic(c).filter(y=>y!==x)); + if(isDk(x)){toast(tr('peering_policy.rival_is_poaching_de_kicks_members',{rival:esc(ixName(rival)),city:esc(CITY[c].name)}),'bad');return;} + S.ixCut=S.ixCut||{};const cur=S.ixCut[x]||1;if(cur<=0.62)return;S.ixCut[x]=+Math.max(0.6,cur*0.9).toFixed(3); + toast(tr('peering_policy.price_war_in_city_ix_cut',{city:esc(CITY[c].name),ix:esc(ixName(x)),rival:esc(ixName(rival))}),'good');} diff --git a/src/game/70-rules/55-mergers.js b/src/game/70-rules/55-mergers.js new file mode 100644 index 0000000..f7f0e8f --- /dev/null +++ b/src/game/70-rules/55-mergers.js @@ -0,0 +1,12 @@ +/* Mergers (#155): a year in, Spectre-um Cable finishes swallowing Coax; a year later Very-Zone does the same to Final + Frontear. The old brand's PNIs move to the new owner and come under its terms (Very-Zone charges for peering), its IX + sessions end, and it takes no new sessions. Its customers stay reachable through the new owner (its `up`). */ +const MERGERS=[{id:'cxc',into:'spc',day:365},{id:'ftr',into:'vzn',day:730}]; +const merged=id=>!!(S&&S.merged&&S.merged[id]); +function mergerDay(d){for(const m of MERGERS){if(dx!==p&&x.net===m.into&&x.city===p.city))S.pni=S.pni.filter(x=>x!==p);else p.net=m.into;} + for(const k in S.peers)if(k.startsWith(m.id+'@')){delete S.peers[k];ended++;} + const v={net:esc(NET[m.into].name),old:esc(NET[m.id].name)}; + toast(tr('mergers.net_has_swallowed_old',v)+(moved?' '+trn('mergers.n_pni_moves_to_net',moved,v):'')+(ended?' '+trn('mergers.n_ix_session_ended',ended,v):'')+(moved&&NET[m.into].pol==='paid'&&!paidFree(NET[m.into])?' '+tr('mergers.net_charges_for_peering',v):''),moved||ended?'bad':'');}} diff --git a/src/game/70-rules/60-de-kicks.js b/src/game/70-rules/60-de-kicks.js new file mode 100644 index 0000000..03438aa --- /dev/null +++ b/src/game/70-rules/60-de-kicks.js @@ -0,0 +1,35 @@ +/* DE-KICKS Group: runs several big exchanges and really, really hates open pricing. + No price list, personalised quotes, haggling, yearly "harmonisation", auto-enrolled add-ons + you have to opt out of, and a retention offer when you try to leave. */ +const DK_CITIES=['fra','mad','mrs','dxb','bom','nyc']; +const isDk=c=>(DK_CITIES.includes(c)||scnRule('dkAll'))&&!!CITY[c]&&!!CITY[c].ix&&!S.myIx[c]; +const DK_ADDONS=[['Blackholing Plus™',tr('de_kicks.like_blackholing_but_with_a_plus')],['Route Server Gold',tr('de_kicks.the_same_route_server_in_a')],['Premium Port LEDs',tr('de_kicks.your_port_light_now_blinks_in')],['Strategic Peering Insights',tr('de_kicks.a_monthly_pdf_of_your_own')],['GlobePeer Ready™',tr('de_kicks.makes_your_port_ready_for_a')],['Cloud Exchange Readiness Fee',tr('de_kicks.a_fee_for_being_ready_for')],['Account Manager Lunch Fund',tr('de_kicks.your_account_manager_is_hungry')]]; +const DK_STALL=[tr('de_kicks.your_account_manager_would_love_to'),tr('de_kicks.pricing_is_reviewed_by_the_global'),tr('de_kicks.they_sent_a_14_page_nda'),tr('de_kicks.your_account_manager_is_at_a')]; +// Harmonisation and ended promos raise the personal price, but only up to this multiple of the list price: uncapped, 8-15% a +// year turned a 60-year game into $100k ports. Saves are clamped in sanitize(), remembered quotes too. +const DK_MAX=4; +function dkMult(c){if(!S||!isDk(c)||!S.dk||!S.dk.m[c])return 1;const ret=S.dk.ret[c];return Math.min(S.dk.m[c],DK_MAX)*(ret&&ret>S.day?0.6:1);} +// The rise that actually happened (1 at the ceiling), so a toast never announces more than the bill shows. +function dkRaise(c,f){const dk=S.dk,was=Math.min(dk.m[c],DK_MAX);dk.m[c]=Math.min(DK_MAX,+(dk.m[c]*f).toFixed(3));return dk.m[c]/was;} +function dkAddonMo(c){return S.dk&&S.dk.add[c]?S.dk.add[c].reduce((a,x)=>a+x.mo,0):0;} +function dkState(){S.dk=S.dk||{m:{},add:{},ret:{},retUsed:{},stall:0,q:null};return S.dk;} +function dkQuoteMult(){const pops=Object.keys(S.pops).length,big=Math.min(1.2,pops*0.04+(R.served||0)/20000);return +(0.95+Math.random()*0.45+big).toFixed(2);} +function dkQuoteModal(){const q=S.dk.q,c=q.city,mo=Math.round(PORT[q.tier].ix*(S.pops[c]?1:REMOTE_FEE)*q.m*ixMul(c)); + openModal(`
${tr('de_kicks.de_kicks_group_sales')}

${tr('de_kicks.your_personalised_port_quote_for_ix',{port:PORT[q.tier].n,ix:esc(ixName(c))})}

+

${tr('de_kicks.thanks_for_your_interest_we_don')}

+
${tr('de_kicks.monthly_price_just_for_you')}${tr('common.price_mo',{price:fmt$(mo)})}
+
${tr('common.list_price')}${tr('common.confidential')}
+
${tr('de_kicks.what_others_pay')}${tr('de_kicks.covered_by_nda')}
+

${tr('de_kicks.quotes_go_up_with_how_big')} ${q.h>=3?tr('de_kicks.your_account_manager_has_stopped'):tr('de_kicks.haggles_left_n',{n:3-q.h})}

+
${btn(tr('de_kicks.sign_price_mo',{price:fmt$(mo)}),'dkAccept',{},'pink',S.cash=3)}${btn(tr('common.walk_away'),'dkWalk',{},'ghost')}
`);} +function dkTick(d){if(!S.dk)return;const dk=S.dk; + for(const c in S.ixp){if(!isDk(c))continue; + if(dk.ret[c]&&dk.ret[c]===d){dkRaise(c,1.1);toast(tr('de_kicks.your_ix_promo_ended_price_is',{ix:esc(ixName(c))}),'bad');} + if(dk.m[c]&&(d+hstr(c)%90)%365===0){const r=dkRaise(c,1.08+Math.random()*0.07),p=Math.round((r-1)*100);if(p>0)toast(tr('de_kicks.de_kicks_has_harmonised_its_prices',{ix:esc(ixName(c)),p}),'bad');} + const add=dk.add[c]=dk.add[c]||[]; + if(add.length<3&&Math.random()<1/150){const a=DK_ADDONS.filter(x=>!add.some(y=>y.n===x[0]));if(a.length){const [n,blurb]=pick(a),mo=Math.round((300+Math.random()*1200)/50)*50;add.push({n,blurb,mo,day:d}); + toast(tr('de_kicks.good_news_you_ve_been_enrolled',{addon:esc(n),blurb:esc(blurb),price:fmt$(mo),ix:esc(ixName(c))}),'bad');}}} +} + +function elephant(){S.phpDone=true;S.ev.php=S.day+4; + toast(tr('de_kicks.breaking_cve_2026_31337_just_took'),'bad');sfx('alert');renderMega();} diff --git a/src/game/70-rules/70-sold-out.js b/src/game/70-rules/70-sold-out.js new file mode 100644 index 0000000..820e268 --- /dev/null +++ b/src/game/70-rules/70-sold-out.js @@ -0,0 +1,26 @@ +/* Sold out: now and then a carrier has no spare capacity of a size on a route. Each route, size and 90-day window + gets a stable verdict from a hash, so asking again does not reroll it, and bigger waves sell out more often. */ +const SOLD_WIN=90,SOLD_WHY=[N_('sold_out.a_hyperscaler_bought_every_wave_of'),N_('sold_out.the_carrier_is_out_of_spectrum'),N_('sold_out.the_transponders_for_this_route_are'),N_('sold_out.the_capacity_is_available_in_the'),N_('sold_out.their_capacity_planner_is_on_holiday'),N_('sold_out.the_upgrade_is_planned_for_q3')]; +const soldP=tier=>Math.min(0.1,0.02+0.012*tier); +// Never in the first 90 days: a new network has enough on its plate. Never in the tutorial or a scenario's first quarter either. +function soldOut(a,b,tier,via){if(!S||netAge()=soldP(tier)*1000)return null;return {why:SOLD_WHY[(h>>>10)%SOLD_WHY.length],until:(ep+1)*SOLD_WIN-off};} +function snubWhy(sn){const d=Math.max(1,sn.until-S.day);return sn.why+' '+trn('sold_out.they_will_reconsider_in_n_day',d);} +// Paid-peering giants drop the fee for networks too big to ignore (freeLv: the customer level that does it). +const paidFree=n=>!!(n&&n.freeLv&&lvl()>=n.freeLv); +function peerOk(id,via,city){ + const n=NET[id],dem=R.demTo[id]||0; + if(merged(id)){const m=MERGERS.find(x=>x.id===id);return {ok:false,why:tr('mergers.now_part_of_net',{net:esc(NET[m.into].name)})};} + const sn=snub(id,city);if(sn&&(via==='ix'||sn.all))return {ok:false,snub:true,why:snubWhy(sn)}; + if(msfNope(id,city))return {ok:false,why:tr(MSF_NOPE[hstr(ixCity(city)+S.day)%MSF_NOPE.length])}; + if(via==='ix'&&city&&isRemote(city)&&noRemote(id))return {ok:false,remote:true,why:REMOTE_WHY[hstr(id)%REMOTE_WHY.length]}; + if(city&&(via==='ix'||via==='pni')){const w=satPeerWhy(id,ixCity(city));if(w)return {ok:false,sat:true,why:w};} + if(n.pol==='open')return {ok:true}; + // In the Cogentle Spat, Goggle's peering desk wants eight times the usual traffic first, so cheap Cogentle-only transit really costs you Goggle (playtest). + if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*salesPeerMul()*(id==='ggl'&&scnRule('spat')?8:1));return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};} + if(n.pol==='paid'&&paidFree(n))return via==='pni'?{ok:true,free:true}:{ok:false,why:tr('sold_out.peers_with_you_for_free_now')}; + if(n.pol==='paid')return via==='pni'?{ok:true,fee:n.paidFee}:{ok:false,why:n.perG?tr('sold_out.sender_pays_a_paid_pni_only',{fee:fmt$(n.paidFee),g:fmt$(n.perG)}):tr('sold_out.paid_peering_only_over_a_pni')}; + if(n.type!=='t1'){if(via!=='pni')return {ok:false,why:tr('sold_out.only_peers_over_pnis_and_only')};const need=Math.round(60*confBoost(id));return dem>=need||isTier2()?{ok:true}:{ok:false,why:tr('sold_out.wants_you_to_be_a_tier',{need,dem:dem.toFixed(1)})};} + if(via!=='pni')return {ok:false,why:tr('sold_out.tier_1s_never_peer_at_ixs')}; + const c=t1Club();return c.ok?{ok:true}:{ok:false,why:tr('sold_out.not_big_enough_yet_list',{list:c.missing.join(', ')})}; +} diff --git a/src/game/70-rules/80-hot-ports-and-rank.js b/src/game/70-rules/80-hot-ports-and-rank.js new file mode 100644 index 0000000..990cde3 --- /dev/null +++ b/src/game/70-rules/80-hot-ports-and-rank.js @@ -0,0 +1,24 @@ +// Everything that can fill up at a POP: transit ports, IX ports, PNIs, caches and the routers themselves. +const HOT=0.9,HOTL={t:'T',ix:'IX',p:'P',c:'C',r:'R'},HOTC={t:'#7B61FF',ix:'#FFD23F',p:'#2C7A7B',c:'#C8102E',r:'#FF4F9A'}; +function hotPorts(){const out=[];if(!R||!S)return out; + for(const t of S.transit){if(t.down>S.day)continue;const cap=lagCap(PORT[t.tier].g,t.n),u=(R.useT[t.id]||0)/cap;if(u>=HOT)out.push({k:'t',city:t.city,lab:tr('hot_ports_and_rank.net_transit_lag',{net:NET[t.net].name,lag:lagName(t.tier,t.n)}),u,tip:tr('hot_ports_and_rank.add_a_lag_member_upgrade_the')});} + for(const c in S.ixp){const cap=ixCap(c);if(!cap)continue;const u=(R.useIx[c]||0)/cap;if(u>=HOT)out.push({k:'ix',city:ixCity(c),lab:tr('common.port_port',{port:ixName(c)}),u,tip:tr('hot_ports_and_rank.upgrade_the_ix_port_or_add')});} + for(const p of S.pni){if(!pniOn(p))continue;const cap=lagCap(pniG(p),p.n),u=(R.usePni[p.id]||0)/cap;if(u>=HOT)out.push({k:'p',city:p.city,lab:tr('common.pni_with_net',{net:NET[p.net].name}),u,tip:tr('hot_ports_and_rank.add_a_lag_member_or_upgrade')});} + const cc={};for(const x of S.caches){const k=x.city+'|'+x.net;(cc[k]=cc[k]||{city:x.city,net:x.net,used:0,cap:0,n:0});cc[k].used+=R.useCache[x.id]||0;cc[k].cap+=cacheG(x);cc[k].n++;} + for(const k in cc){const x=cc[k],u=x.used/x.cap;if(u>=HOT)out.push({k:'c',city:x.city,lab:x.n>1?tr('hot_ports_and_rank.name_caches',{name:NET[x.net].cache.name}):tr('common.name_cache',{name:NET[x.net].cache.name}),u,tip:tr('hot_ports_and_rank.ask_for_another_box_the_overflow')});} + for(const c in S.pops){const cap=R.nodeCap[c];if(!cap)continue;const u=(R.nodeLoad[c]||0)/cap;if(u>=HOT)out.push({k:'r',city:c,lab:tr('common.routers'),u,tip:tr('hot_ports_and_rank.upgrade_the_router_or_add_a')});} + return out.sort((a,b)=>b.u-a.u);} +function hotByCity(){const m={};for(const h of hotPorts())(m[h.city]=m[h.city]||{})[h.k]=Math.max((m[h.city]||{})[h.k]||0,h.u);return m;} +function isTier2(){return Object.keys(S.pops).length>=5&&Object.keys(S.ixp).length>=3&&R.sessions>=15;} +// Sparkly Seabone joined the Tier 1s in 1.12. Older saves keep the five they were playing for. +// Tier 1s added later only count for games started after them, so old saves keep their win (#155, #194). +const T1_SINCE={att:3,dtk:4,skl:2,tng:4}; +const t1Need=()=>NETS.filter(n=>n.type==='t1'&&(!T1_SINCE[n.id]||(S&&S.t1v>=T1_SINCE[n.id]))); +/* Reach is counted through customer cones (#85): a PNI with a Tier 1 reaches everyone who buys transit from it, and + their customers. That only ever adds reach, so the rule is easier for every save, old ones included, and needs no + version: what was Tier 1 stays Tier 1. Networks in nobody's cone still need peering of their own. */ +function isTier1(){return t1Need().every(n=>S.pni.some(p=>p.net===n.id&&pniOn(p)))&&S.transit.length===0&&R.reach>0.999;} +// What you are now, not what you once were (#46): buying transit again or losing reach drops the label. +function tierLabel(){return S.won&&isTier1()?'Tier 1':isTier2()?'Tier 2':'Tier 3';} +function t1Why(){if(S.transit.length)return tr('hot_ports_and_rank.you_buy_transit_again');const miss=t1Need().filter(n=>!S.pni.some(p=>p.net===n.id&&pniOn(p)));if(miss.length)return tr('hot_ports_and_rank.no_pni_with_list',{list:miss.map(n=>n.name).join(', ')});{const lost=NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id]);if(lost.length)return tr('hot_ports_and_rank.you_cannot_reach_list_outside_cones',{list:lost.slice(0,3).map(n=>n.name).join(', ')+(lost.length>3?' '+tr('hot_ports_and_rank.and_n_more',{n:lost.length-3}):'')});}return tr('hot_ports_and_rank.your_reach_is_p_not_100',{p:reachPct(R.reach)});} + diff --git a/src/game/70-rules/90-backbone-core.js b/src/game/70-rules/90-backbone-core.js new file mode 100644 index 0000000..58e7971 --- /dev/null +++ b/src/game/70-rules/90-backbone-core.js @@ -0,0 +1,56 @@ +/* ---------- the backbone's technology: plain IGP, LDP, RSVP-TE, SR-MPLS or SRv6 ---------- + S.core.lv is the highest level paid for, S.core.run the one running (at most lv: one step down is safer). A POP + whose router can't run it stays outside the core: it routes plain IP, TE never steers through it and label + switching saves it nothing. Each level costs routers some CPU, from LDP's chatter down to SRv6's almost none. Label + switching makes traffic that only passes through a POP cheaper for its router. TE (Auto-TE, RouteScript) needs + RSVP-TE or above; RSVP tunnels detour less far than segment routing. Vendors interoperate less the higher you go: + a core of mixed vendors running at some router's very top level has interop incidents. + Saves from before this, with Auto-TE already bought, keep the old rules (legacy) until they change level. Puzzles, + Architect runs and scenarios set TE up themselves and ignore all of this. */ +const CORE_LV=[N_('core.plain_igp'),N_('core.ldp_mpls'),N_('core.rsvp_te_mpls'),N_('core.sr_mpls'),N_('core.srv6')]; +const CORE_COST=[0,80000,200000,400000,750000],CORE_REQ=[1,2,3,5,7]; +const CORE_CPU=[0,.10,.08,.05,.03],CORE_PASS=[1,.6,.6,.6,.6],CORE_TE=[0,0,1.5,2,2],CORE_IOP=[0,.15,.3,.6,1]; +// Can model g run level L? Every model runs everything up to its top, except noMpls boxes (SRv6 natively, no labels). +const rgCore=(g,L)=>{const G=RG[g];return !!G&&L<=G.cr&&!(G.noMpls&&L>=1&&L<=3);}; +// Do the core rules apply to this game at all? +const coreOn=()=>!!(S&&S.core&&!S.core.legacy&&S.mode!=='puzzle'&&!S.pz&&!S.ar&&!S.scn); +const coreRun=()=>coreOn()?S.core.run:0; +const inCore=c=>{const p=S.pops[c];return !!p&&rgCore(p.rgen||0,coreRun());}; +// May Auto-TE and RouteScript run? Legacy saves, puzzles and scenarios: as before. +const coreTE=()=>!coreOn()||S.core.run>=2; +// How far TE may detour, against the shortest path (the old controller: 2×). +const coreTeReach=()=>coreOn()?CORE_TE[S.core.run]:2; +// Share of a router's capacity left after the core's own protocols take their CPU. +const coreCpu=c=>coreOn()&&inCore(c)?1-CORE_CPU[S.core.run]:1; +// What traffic passing through (not starting or ending here) costs this POP's router: less once labels switch it. +const corePass=c=>coreOn()&&S.core.run>=1&&inCore(c)?CORE_PASS[S.core.run]:1; +// Vendors in the core, and whether it runs at the very top of any of its routers: then vendors trip over each other. +function coreVendors(){const v=new Set();for(const c in S.pops)if(inCore(c))v.add(RG[S.pops[c].rgen||0].v);return v;} +function coreEdge(){if(!coreOn()||S.core.run<1)return false;for(const c in S.pops)if(inCore(c)&&RG[S.pops[c].rgen||0].cr===S.core.run)return true;return false;} +// Daily odds of an interop incident: none for one vendor, or below every router's top level. +function coreIopRisk(){if(!coreOn()||S.core.run<1||coreVendors().size<2||!coreEdge())return 0;return CORE_IOP[S.core.run]*(S.core.lab?CORE_LAB_F:1);} +// POPs left out of the core (their router can't run it), for the panel. +const coreOut=()=>coreOn()&&S.core.run>=1?Object.keys(S.pops).filter(c=>!inCore(c)):[]; +// Links where the vendors meet: both ends in the core, different vendors. +const coreIopLinks=live=>live.filter(l=>S.pops[l.a]&&S.pops[l.b]&&inCore(l.a)&&inCore(l.b)&&RG[S.pops[l.a].rgen||0].v!==RG[S.pops[l.b].rgen||0].v); +// Vendor names as players see them (Junipurr has no badge, so this is where its name shows). +const RG_V={arrrhipster:'Arrrhipster',brocadabra:'Brocadabra',disco:'Disco',edge:'Edge Lord',extremely:'Extremely Networks',junipurr:'Junipurr',knockia:'Knockia',mikrowtik:'Mikrowtik',rusty:'Rusty',universe:'Universe',whitebox:'Whitebox'}; +// One line for a model: its vendor and the highest backbone it runs (SRv6-only boxes say so). +const coreMeta=g=>{const G=RG[g];return tr('core.vendor_v_backbone_up_to_lv',{v:RG_V[G.v],lv:tr(CORE_LV[G.cr])})+(G.noMpls?' · '+tr('core.no_mpls_srv6_only'):'');}; +/* ---------- what an upgraded backbone brings (only good things) ---------- + Customers who need it: offers of these appear once the backbone runs their level; a contract already signed keeps + paying whatever the backbone runs later. Real carriers sell L3VPNs over MPLS, low-latency planes with flex-algo + over segment routing, and slices over SRv6. */ +Object.assign(BIZ_T,{ + l3vpn:{l:tr('core.l3vpn_for_an_enterprise'),opts:[1,2,5,10],rate:0,l2:true,sdwan:true,siteRate:1100,km:0,lv:3,core:1,names:['Branch Office Bonanza','Head Office & Sons','Twelve Tills Retail','Regional Bank of Routes','Chain of Command Pharmacies','Franchise Fiesta']}, + flex:{l:tr('core.flex_algo_low_latency_link'),opts:[5,10,40],rate:0,l2:true,lat:true,km:9,lv:3,core:3,names:['Microsecond Mike Markets','Low-Ping Esports League','Latency Arbitrage Partners','Photon Finish Trading','Lag-Free Ladder Games']}, + slice:{l:tr('core.network_slice'),opts:[100,200,400],rate:0,l2:true,div:true,km:1.2,lv:3,core:4,names:['Fifth Gen Slices Ltd','Pizza-Slice Mobile','Sliced Bread Telecom','GPU Slice & Dice','Thin Crust Wireless']}, +}); +// The backbone's customer types now on offer (twice each, like the other types' weights). +function coreProducts(mine){if(!coreOn())return [];const run=S.core.run,out=[]; + if(run>=1&&mine.length>=3)out.push('l3vpn','l3vpn');if(run>=3&&mine.length>=2)out.push('flex','flex');if(run>=4&&mine.length>=2)out.push('slice','slice');return out;} +// Fast reroute (RSVP-TE FRR, TI-LFA): backup paths are ready before a cut, so customers barely notice one. +const coreFrr=()=>coreOn()&&S.core.run>=2; +// An interop lab: test the vendors against each other before they meet in production. +const CORE_LAB=150000,CORE_LAB_F=0.4; +const coreLab=()=>!!(S.core&&S.core.lab); diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js new file mode 100644 index 0000000..7fb07d9 --- /dev/null +++ b/src/game/70-rules/95-utilities.js @@ -0,0 +1,61 @@ +/* Utilities: plan from live state, then apply a whole batch with one recompute. */ +function utilityRouteServers(){return S?Object.keys(S.ixp).filter(ix=>isIx(ix)&&!S.myIx[ix]&&!S.rs[ix]):[];} +function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new Map(),moves=[]; + for(const c of S.caches)if(c.city===city){let g=groups.get(c.net);if(!g){g={a:[],b:[]};groups.set(c.net,g);}g[c.site==='b'?'b':'a'].push(c);} + const move=(g,from,n)=>{const to=from==='a'?'b':'a';for(const c of g[from].splice(0,n)){g[to].push(c);moves.push({id:c.id,site:to});}}; + for(const g of groups.values()){const from=g.a.length>g.b.length?'a':'b',to=from==='a'?'b':'a'; + move(g,from,Math.floor((g[from].length-g[to].length)/2));} + // Spread odd-provider extras too, so the overall site counts also differ by at most one. + let diff=0;for(const g of groups.values())diff+=g.a.length-g.b.length; + const from=diff>0?'a':'b',to=from==='a'?'b':'a';let left=Math.floor(Math.abs(diff)/2); + for(const g of groups.values())if(left&&g[from].length>g[to].length){move(g,from,1);left--;} + return moves;} +// A city's traffic to one network, split as routing splits it (#260): China, Russia and Korea's exit rule have their own +// list of networks, and Goggle is throttled to half in Russia. The world shares (NSH) would size boxes for networks the +// city cannot even reach, and too few for the ones it uses most. +const cityShTab=c=>cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH; +const cityNetSh=(c,id)=>{const j=LOC_NIX.get(id);return (j===undefined?0:cityShares(cityShTab(c),c)[j])*(id==='ggl'&&ruCity(c)?0.5:1);}; +// A city's total share only depends on its split (its table, localised for the city, #48) and on the Russian throttle, +// and those never change after load: summed once per split, not once per network asked about (that was cities × +// networks² every shift). +const CSH_SUM=new WeakMap(); +function cityShSum(c){const a=cityShares(cityShTab(c),c),k=ruCity(c)?1:0;let m=CSH_SUM.get(a);if(!m)CSH_SUM.set(a,m=[null,null]); + if(m[k]===null){const T=cityShTab(c);let t=0;for(const id in T)t+=cityNetSh(c,id);m[k]=t;}return m[k];} +function cacheDem(c,id){const t=cityShSum(c);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;} +// One box per site first, if the city sends the network anything at all; then more boxes while that demand outgrows them +// (100G each, #248). +// boxes: the city's own boxes in their order, when the caller has them sorted by city already (S.caches otherwise). +function cachePlan(city,boxes=S.caches){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have={}; + // One pass over the boxes: how many per network and site, and the capacity per network (summed in the same order). + const capN={};for(const c of boxes)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;capN[c.net]=(capN[c.net]||0)+cacheG(c);} + for(const n of NETS){if(!n.cache||!((R.demTo[n.id]||0)>=n.cache.min))continue;const dem=cacheDem(city,n.id);if(!(dem>1e-6))continue;const box=sites.map(st=>have[n.id+'@'+st]||0),a0=add.length; + sites.forEach((site,i)=>{if(!box[i]){add.push({net:n.id,site,...cacheBox(city)});box[i]=1;}}); + const nb=cacheBox(city); + let cap=(capN[n.id]||0)+(add.length-a0)*cacheG(nb); + while(cap+1e-9c.net+'@'+c.site).join(','),mo:add.reduce((a,x)=>a+cacheMo(x),0),free:Math.max(0,portsMax(city)-portsUsed(city))};} +// A total a window showed still holds within 1% either way: hardware prices drift a little every day under the market +// rule, and on a server-run network days go on while a window is open. A bigger change is a new plan, shown again. +const quoteNear=(shown,now)=>Math.abs(now-shown)<=Math.max(0.5,Math.abs(shown)*0.01); +function utilityKit(city){const p=S&&S.pops[city];if(!p)return null; + const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0; + return {gen,site,router,moves:utilityCacheMoves(city),cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), + mo:(gen?GEN_MO:0)+(site?SITE2_MO:0)+(router?routerMo(g):0)};} +// The kit at every POP that lacks part of it (#317): one quote, one button. From customer level 2, like the intern: early +// on, every generator is a choice about money. +const utilityKitAllOn=()=>!!S&&opsCanHire()&&!pzOn(); +function utilityKitAll(){if(!utilityKitAllOn())return null;const cities=[];let cost=0,mo=0,moves=0; + for(const c of Object.keys(S.pops)){const q=utilityKit(c);if(!q||(!q.cost&&!q.moves.length))continue;cities.push(c);cost+=q.cost;mo+=q.mo;moves+=q.moves.length;} + return {cities,cost,mo,moves};} +function utilityPeers(){if(!S)return [];return Object.keys(S.ixp).filter(isIx).map(ix=>{ + const sessions=ixSessions(ix),requests=[],blocked=[];let existing=0; + for(const id of ixMembers(ix)){ + // Existing but temporarily down sessions must not be repeatedly requested. + if(sessions.has(id)||S.peers[id+'@'+ix]){existing++;continue;} + const chk=peerOk(id,'ix',ix);if(chk.ok)requests.push(id);else blocked.push({id,why:chk.why}); + } + return {ix,requests,blocked,existing}; +});} diff --git a/src/game/80-simulation/10-dijkstra.js b/src/game/80-simulation/10-dijkstra.js new file mode 100644 index 0000000..59d9f01 --- /dev/null +++ b/src/game/80-simulation/10-dijkstra.js @@ -0,0 +1,34 @@ +/* ================= SIMULATION ================= */ +// Binary-heap Dijkstra over city indices: adj[i] lists [neighbour, edge]. wf(edge) gives the weight, skip(v,edge) can +// rule edges out, and the search stops early once `stop` is settled. D is the distance to each city (Infinity: no +// path) and P the edge it was reached by. The heap lives in two typed arrays, and equal distances always settle in the +// same order, so routes do not flip between runs. +function dijkstra(adj,src,wf,skip,stop){const n=adj.length,D=new Float64Array(n).fill(Infinity),P=new Array(n),done=new Uint8Array(n); + let cap=64,hd=new Float64Array(cap),hu=new Int32Array(cap),m=0; + const put=(d,u)=>{if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=a;hu=b;} + let i=m++;hd[i]=d;hu[i]=u;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}}; + D[src]=0;put(0,src); + while(m){const d=hd[0],u=hu[0];m--; + if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(lD[u])continue;done[u]=1;if(u===stop)break; + for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd2e9){DJ.n=n;DJ.D=new Float64Array(n);DJ.P=new Array(n);DJ.S=new Int32Array(n);DJ.done=new Int32Array(n);DJ.g=0;} + const g=++DJ.g,D=DJ.D,P=DJ.P,ST=DJ.S,DN=DJ.done;let hd=DJ.hd,hu=DJ.hu,cap=hd.length,m=0; + const put=(d,u)=>{if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=DJ.hd=a;hu=DJ.hu=b;} + let i=m++;hd[i]=d;hu[i]=u;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}}; + D[src]=0;ST[src]=g;put(0,src); + while(m){const d=hd[0],u=hu[0];m--; + if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(l(ST[u]===g?D[u]:Infinity))continue;DN[u]=g;if(u===stop)break; + for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd<(ST[v]===g?D[v]:Infinity)){D[v]=nd;ST[v]=g;P[v]=e;put(nd,v);}}} + return ST[stop]===g?D[stop]:Infinity;} +// The edges of a dijkstra() path back from city index B to A, and the cities on it (B first), as indices. +function walkI(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni};} +// The same for compute()'s sender, with the marks it keeps on a path (full, its latency, its far-exit traffic) there from the start: one object shape. +function walkP(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni,dead:0,ms:-1,fg:0,mt:0,se:null};} diff --git a/src/game/80-simulation/20-routescript.js b/src/game/80-simulation/20-routescript.js new file mode 100644 index 0000000..bd69f95 --- /dev/null +++ b/src/game/80-simulation/20-routescript.js @@ -0,0 +1,135 @@ +/* ---------- RouteScript: a tiny, safe rule language for the Auto-TE controller ---------- + Player scripts are parsed into plain data and never executed, so a shared or imported + save can't run code. One rule per line, # for comments. */ +const TE_KINDS={pni:'p',ix:'ix',transit:'t'}; +const TE_EXAMPLE=`# RouteScript for your Auto-TE controller. One rule per line. +# Keep Cogentle at its 20 Gbps commit; overflow goes elsewhere +cap transit cogentle at 20 gbps +# Goggle should come over peering, not transit +avoid transit for goggle +# Move traffic before links are completely full +spill at 85% +# Hot links spill early onto detours that cost little latency +# spill at 80% within 10 ms +# spill at 90% within 20 ms +# Local-pref: use the cheap upstream first, the pricey one last +# prefer transit cogentle +# avoid transit level tree +# AS-path prepending: ask the world to send less via one upstream (a hint, not an order) +# prepend transit drizzle electric 2 +# Business customers first when links are congested; home users get what is left +# protect customers +# Maintenance window? Drain a POP's exits, or steer around a link +# drain paris +# avoid link frankfurt-amsterdam +# Under DDoS: blackhole the target upstream (saves everyone else) +# blackhole ddos`; +function lev(a,b){const m=a.length,n=b.length,d=Array.from({length:m+1},(_,i)=>[i]);for(let j=1;j<=n;j++)d[0][j]=j;for(let i=1;i<=m;i++)for(let j=1;j<=n;j++)d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+(a[i-1]===b[j-1]?0:1));return d[m][n];} +function teFind(word,list,label){const w=slug(word);if(!w)return {err:tr('routescript.missing_what',{what:label})}; + for(const x of list)if(x.id===w||slug(x.name)===w)return {v:x.id}; + const pre=list.filter(x=>w.length>=3&&slug(x.name).startsWith(w));if(pre.length===1)return {v:pre[0].id}; + const best=list.map(x=>({x,d:Math.min(lev(w,slug(x.name)),lev(w,x.id))})).sort((a,b)=>a.d-b.d)[0]; + return {err:tr('routescript.unknown_what_word',{what:label,word})+(best&&best.d<=3?tr('routescript.did_you_mean_name',{name:best.x.name}):'')};} +function teParse(src){const out={spill:null,tiers:[],cap:{},net:{},up:{},prep:{},protect:false,drain:new Set(),avoid:new Set(),blackhole:false,errors:[],n:0}; + const lines=String(src||'').split('\n').slice(0,60); + lines.forEach((raw,i)=>{const line=raw.replace(/#.*/,'').trim().toLowerCase();if(!line)return;const L=i+1;let m; + // A spill tier (#136): from this load on, detours that add at most this many milliseconds. + if(m=line.match(/^spill\s+at\s+(\d{1,3})\s*%\s+within\s+(\d{1,3})\s*ms$/)){const v=+m[1],ms=+m[2];if(v<20||v>100)out.errors.push(tr('routescript.line_n_spill_must_be_between',{n:L}));else if(ms<1||ms>100)out.errors.push(tr('routescript.line_n_within_1_to_100_ms',{n:L}));else{out.tiers.push({at:v/100,ms});out.tiers.sort((a,b)=>a.at-b.at||a.ms-b.ms);out.n++;}return;} + if(m=line.match(/^spill\s+at\s+(\d{1,3})\s*%$/)){const v=+m[1];if(v<20||v>100)out.errors.push(tr('routescript.line_n_spill_must_be_between',{n:L}));else{out.spill=v/100;out.n++;}return;} + if(m=line.match(/^(prefer|avoid)\s+(pni|ix|transit)\s+for\s+(.+)$/)){const r=teFind(m[3],NETS,tr('common.network'));if(r.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:r.err}));return;}const o=out.net[r.v]=out.net[r.v]||{};o[m[1]]=TE_KINDS[m[2]];out.n++;return;} + if(m=line.match(/^cap\s+transit\s+(.+?)\s+at\s+(\d+(?:\.\d+)?)\s*(gbps|tbps|g|t)$/)){const r=teFind(m[1],NETS.filter(n=>n.price),tr('common.transit_provider'));if(r.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:r.err}));return;}out.cap[r.v]=+m[2]*(m[3][0]==='t'?1000:1);out.n++;return;} + if(m=line.match(/^(prefer|avoid)\s+transit\s+(?!for\s)(.+)$/)){const r=teFind(m[2],NETS.filter(n=>n.price),tr('common.transit_provider'));if(r.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:r.err}));return;}out.up[r.v]=m[1];out.n++;return;} + if(m=line.match(/^prepend\s+transit\s+(.+?)\s+(\d+)$/)){const v=+m[2];if(v<1||v>3){out.errors.push(tr('routescript.line_n_prepend_1_to_3',{n:L}));return;}const r=teFind(m[1],NETS.filter(n=>n.price),tr('common.transit_provider'));if(r.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:r.err}));return;}out.prep[r.v]=v;out.n++;return;} + if(line==='protect customers'){out.protect=true;out.n++;return;} + if(m=line.match(/^drain\s+(.+)$/)){const r=teFind(m[1],CITIES,tr('common.city'));if(r.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:r.err}));return;}out.drain.add(r.v);out.n++;return;} + if(m=line.match(/^avoid\s+link\s+(.+?)\s*(?:-|\bto\b|→)\s*(.+)$/)){const a=teFind(m[1],CITIES,tr('common.city')),b=teFind(m[2],CITIES,tr('common.city'));if(a.err||b.err){out.errors.push(tr('routescript.line_n_err',{n:L,err:a.err||b.err}));return;}out.avoid.add(a.v!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&!BIZ_T[b.type].event&&sfOf(R,b.city)<0.95))L.push('protect customers'); + const ups=[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S.transit.filter(t=>t.net===n).map(t=>NET[n].price*netMult(NET[n],t.city)))})).sort((a,b)=>a.p-b.p); + if(ups.length>1){L.push('prefer transit '+NET[ups[0].n].name.toLowerCase());L.push('avoid transit '+NET[ups[ups.length-1].n].name.toLowerCase());} + const tips=[]; + for(const n of NETS){const g=(R.netEg[n.id]||{}).t||0;if(g<1)continue;// The exchange where it is a member and you have no port yet, in a city where you have a POP. + let at=null;for(const c of Object.keys(S.pops)){at=ixIdsIn(c).find(x=>S.ixp[x]===undefined&&ixMembers(x).includes(n.id));if(at)break;} + if(at){const v={net:n.name,g:fmtG(g),ix:ixName(at),city:CITY[ixCity(at)].name};tips.push([g,ixNamesCity(at)?tr('routescript.net_g_over_transit_but_it',v):tr('routescript.net_g_over_transit_but_it_e707',v)]);}} + for(const n of NETS){const g=(R.netEg[n.id]||{}).ix||0;if(g>=50&&!S.pni.some(p=>p.net===n.id))tips.push([g,tr('routescript.net_g_over_the_ix_a',{net:n.name,g:fmtG(g)})]);} + tips.sort((a,b)=>b[0]-a[0]).slice(0,5).forEach(x=>L.push(x[1])); + return L.join('\n');} +// Ready-made RouteScripts, filled in from the live network. Players load them from the help; the AI button picks them too. +const teUps=()=>[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S.transit.filter(t=>t.net===n).map(t=>NET[n].price*netMult(NET[n],t.city)))})).sort((a,b)=>a.p-b.p); +const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>ddosAll().length>0; +const teSad=()=>S.biz.some(b=>!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&!BIZ_T[b.type].event&&sfOf(R,b.city)<0.95); +const TE_RECIPES=[ + {id:'shield',n:N_('common.shields_up'),d:N_('routescript.for_a_ddos_rtbh_the_target'),fit:()=>teAtk()?9:0.3, + src:()=>[tr('routescript.shields_up_for_the_length_of'),'blackhole ddos','protect customers','spill at 80%']}, + {id:'care',n:N_('common.customer_care'),d:N_('routescript.business_customers_first_when_links'),fit:()=>teSad()?5:0.5, + src:()=>[tr('routescript.customer_care_the_people_who_pay'),'protect customers','spill at 75%']}, + {id:'peer',n:N_('common.peering_first'),d:N_('routescript.big_networks_you_can_reach_over'),fit:()=>S.pni.length||Object.keys(S.ixp).length?3:0, + src:()=>{const L=[tr('routescript.peering_first_free_paths_before_paid'),'spill at 85%'],seen=new Set(),ix=new Set(),eg=n=>(R.netEg[n]||{}).t||0; + for(const p of S.pni)if(!seen.has(p.net)){seen.add(p.net);L.push('prefer pni for '+teNm(p.net));} + for(const c in S.ixp)for(const n of ixSessions(c))ix.add(n); + NETS.filter(n=>!seen.has(n.id)&&ix.has(n.id)&&eg(n.id)>=1).sort((a,b)=>eg(b.id)-eg(a.id)).slice(0,4).forEach(n=>L.push('prefer ix for '+teNm(n.id))); + if(L.length===2)L.push(tr('routescript.nothing_to_move_yet_get_an'));return L.slice(0,12);}}, + {id:'pinch',n:N_('common.penny_pincher'),d:N_('routescript.cheapest_upstream_first_priciest'),fit:()=>teUps().length>1?2+(R.cost.transit||0)/1e5:0, + src:()=>{const u=teUps(),L=[tr('routescript.penny_pincher_cheapest_upstream'),'spill at 85%']; + if(u.length>1)L.push('prefer transit '+teNm(u[0].n),'avoid transit '+teNm(u[u.length-1].n));else L.push(tr('routescript.buy_transit_from_a_second_upstream'));return L;}}, + {id:'diet',n:N_('common.prepend_diet'),d:N_('routescript.ask_the_rest_of_the_internet'),fit:()=>teUps().length>1?1.5:0, + src:()=>{const u=teUps();return [tr('routescript.prepend_diet_a_hint_to_the'),'spill at 85%',...(u.length>1?['prepend transit '+teNm(u[u.length-1].n)+' 2']:[tr('routescript.prepending_needs_two_upstreams_to')])];}}, + {id:'maint',n:N_('common.maintenance_window'),d:N_('routescript.drain_a_pop_and_steer_around'),fit:()=>0.2, + src:()=>{const l=S.links.find(x=>!linkDown(x)),c=l?CITY[l.a].name.toLowerCase():'paris';return [tr('routescript.maintenance_window_change_the_names'),'drain '+c,...(l?['avoid link '+c+'-'+CITY[l.b].name.toLowerCase()]:[]),'spill at 80%'];}}, + {id:'calm',n:N_('common.keep_calm'),d:N_('routescript.one_rule_move_traffic_before_links'),fit:()=>1, + src:()=>[tr('routescript.keep_calm_one_rule_hard_to'),'spill at 85%']}]; +// The AI button: the two recipes that fit best, merged, with an AI's confidence on top. +const AI_NAMES=['Large Latency Model','Stochastic Parrot Pro','Co-Pilot Error','Autocomplete Ultra','Hallucinet 4o','Artificial Ignorance']; +const AI_SAY=[N_('routescript.great_question_here_is_a_production'),N_('routescript.as_a_large_language_model_i'),N_('routescript.i_have_optimised_your_network_you'),N_('routescript.done_i_vibe_checked_your_bgp'),N_('routescript.here_you_go_i_was_trained'),N_('routescript.i_asked_myself_to_review_my')]; +function aiSlop(bad){const ai=pick(AI_NAMES),fits=TE_RECIPES.map(r=>({r,f:r.fit()})).filter(x=>x.f>0).sort((a,b)=>b.f-a.f).map(x=>x.r); + // It really does dry-run its three favourite ideas (and one merge) against live traffic, and keeps the best. + const merge=rs=>{const L=[],seen=new Set();for(const r of rs)for(const x of r.src()){const k=/^spill/.test(x)?'spill':x;if(!seen.has(k)){seen.add(k);L.push(x);}}return L;}; + const cands=fits.slice(0,3).map(r=>merge([r])).concat([merge(fits.slice(0,2))]),val=x=>x.served*EYE_RATE-x.tc; + const keep=S.te&&S.te.script,on=S.te&&S.te.on;if(!S.te)S.te={on:false,day:S.day,tmp:1};let best=null,bv=-Infinity; + for(const L of cands){if(teParse(L.join('\n')).errors.length)continue;S.te.script=L.join('\n');S.te.on=true;compute();const v=val({served:R.served,tc:R.cost.transit||0});if(v>bv){bv=v;best=L;}} + if(S.te.tmp)delete S.te;else{S.te.script=keep;S.te.on=on;}compute(); + const L=[tr('routescript.written_by_ai_prompt_make_my',{ai})].concat(best||merge([TE_RECIPES.find(r=>r.id==='calm')])); + // Very occasionally it is just as sure of itself and completely wrong. Nothing says so. + const u=teUps();if(bad&&u.length)L.splice(2,0,tr('routescript.a_cap_of_0_gbps_means'),...u.map(x=>'cap transit '+teNm(x.n)+' at 0 gbps')); + L.push(tr('common.confidence_100'));return {src:L.join('\n'),ai,say:pick(AI_SAY)};} +function teHelpModal(){const rule=(code,what)=>`
${code}
${what}
`; + openModal(`
${tr('routescript.auto_te_controller')}

${tr('routescript.how_routescript_works')}

+

${tr('routescript.every_gigabit_leaving_your_network_picks')}

+

${tr('routescript.writing_a_script')}

    +
  • ${tr('routescript.one_rule_per_line_a_starts')}
  • +
  • ${tr('routescript.networks_providers_and_cities_go_by')}
  • +
  • ${tr('routescript.check_dry_run_replays_today_s')}
  • +
  • ${tr('routescript.deploy_makes_it_live_for_the')}
+

${tr('common.rules')}

+ ${rule('spill at 85%',tr('routescript.move_traffic_to_the_next_exit'))} + ${rule('spill at 80% within 10 ms',tr('routescript.from_this_load_on_spill_onto'))} + ${rule('prefer pni for goggle',tr('routescript.send_one_network_s_traffic_over'))} + ${rule('avoid transit for netchill',tr('routescript.use_that_kind_of_exit_for'))} + ${rule('cap transit cogentle at 20 gbps',tr('routescript.a_ceiling_on_one_provider_so'))} + ${rule('prefer transit cogentle',tr('routescript.rank_your_upstreams_preferred_ones'))} + ${rule('prepend transit drizzle electric 2',tr('routescript.as_path_prepending_1_to_3'))} + ${rule('protect customers',tr('routescript.when_links_are_congested_business'))} + ${rule('drain paris',tr('routescript.move_traffic_off_a_pop_s'))} + ${rule('avoid link frankfurt-amsterdam',tr('routescript.steer_traffic_around_one_link_unless'))} + ${rule('blackhole ddos',tr('routescript.during_an_attack_rtbh_the_target'))} +

${tr('routescript.ready_made_scripts')}

${tr('routescript.filled_in_from_your_network_as')}

+ ${TE_RECIPES.map(r=>`
${tr(r.n)}
${tr(r.d)}
${btn(tr('common.load'),'teRecipe',{id:r.id},'sm')}
`).join('')}
+
${btn(tr('routescript.back_to_the_editor'),'teBack',{},'big')}
`);} +let TE_CACHE={src:null,p:null}; +function teRules(){if(!S||!S.te||!S.te.on||!S.te.script||!coreTE())return null;if(TE_CACHE.src!==S.te.script)TE_CACHE={src:S.te.script,p:teParse(S.te.script)};return TE_CACHE.p.errors.length?null:TE_CACHE.p;} +function teModal(msg){const src=UI.teDraft!==undefined?UI.teDraft:(S.te.script||TE_EXAMPLE); + openModal(`
${tr('routescript.auto_te_controller')}

RouteScript

+

${tr('routescript.write_rules_check_them_against_live')}

+ + ${msg||''}
${btn(tr('routescript.check_dry_run'),'teCheck',{},'')}${btn(tr('common.deploy'),'teDeploy',{},'pink')}${S.te.script?btn(tr('common.remove_script'),'teClear',{},'ghost sm'):''}${btn(tr('common.optimize'),'teOpt',{},'ghost sm')}${btn(tr('routescript.reset_to_example'),'teExample',{},'ghost sm')}
${btn('✨ '+tr('routescript.slop_it_with_ai'),'teSlop',{},'aibtn')}${btn(tr('routescript.help_and_ready_made_scripts'),'teHelp',{},'ghost sm')}
+

${tr('common.rules_7b18')} spill at 80% · spill at 80% within 10 ms · prefer pni|ix|transit for NETWORK · avoid pni|ix|transit for NETWORK · cap transit PROVIDER at 20 gbps · prefer|avoid transit PROVIDER · prepend transit PROVIDER 1-3 · protect customers · drain CITY · avoid link CITY-CITY · blackhole ddos

+ ${S.te.script?`

${tr('routescript.live_state_rules',{state:S.te.on?tr('common.deployed'):tr('routescript.controller_is_off'),rules:teRules()?tr('routescript.n_rules_active',{n:teRules().n}):tr('common.not_active')})}

`:''}`);} +function teTrial(src){const keep=S.te.script,on=S.te.on,before={served:R.served,tc:R.cost.transit||0,moved:R.teMoved||0}; + S.te.script=src;S.te.on=true;compute();const after={served:R.served,tc:R.cost.transit||0,moved:R.teMoved||0,bh:R.teBlack||0}; + S.te.script=keep;S.te.on=on;compute();return {before,after};} diff --git a/src/game/80-simulation/25-ddos-flood.js b/src/game/80-simulation/25-ddos-flood.js new file mode 100644 index 0000000..fcf7b49 --- /dev/null +++ b/src/game/80-simulation/25-ddos-flood.js @@ -0,0 +1,81 @@ +/* ---------- where a flood goes (compute() calls these) ---------- + A flood comes from botnets everywhere, so it reaches you over every network that reaches you, on the exits that + network would use: private peering first, then the exchanges, then transit, spread by port size. Each tool then + acts where it does in a real network: RTBH and clean pipes upstream, before your port; the port carries what fits + and everyone on it loses the same share; Flowspec drops matching junk on each ingress router, within that router's + rule budget; what is left rides the backbone to the target. An engaged scrubbing center takes the flood on its own + ingress instead (magnet) and cleans up to its tier (sponge); what it cannot take hurts only the target. */ +// Does this private peer honour blackhole communities? About half do, the same ones in every game. +function pniHonours(n){let h=0;for(let i=0;ie.k==='p'?1:e.k==='ix'?2:e.k==='t'?3:9; +// Adds to `out` (exit -> Gbps) the share of g that reaches you on each exit, before upstream tools. +function ddosSpread(g,E,okBy,out){if(g<=0)return;let tot=0;const pick=[]; + for(const n of NETS){const s=NSH[n.id]||0,L=okBy[n.id];if(s<=0||!L||!L.length)continue;let best=9,sac=false; + for(const e of L){if(e.id==='~grace')continue;const r=ddRank(e);if(r{const p=S.pops[c];return p?(RG[p.rgen||0].fsN||0):0;}; +// The bandwidth the target itself uses: a customer's port, or a city's broadband subscribers. +function ddosTb(a,R2){if(a.tgt&&a.tgt.startsWith('bb:'))return Math.max(1,(R2.cityEye||{})[a.city]||1);const b=S.biz.find(x=>x.id===a.tgt);return b?Math.max(0.1,b.bw):1;} +/* Before routing: spread each live attack, clip it at the ports, filter it on the routers and load what is left onto + the backbone ahead of everyone's traffic. X.haul(A,B,g,ek) moves up to g from city A to city B and returns what fit. */ +function ddosLoad(X){const {E,okBy,R2}=X;R2.ddos=[];R2.haul=[];R2.tgtF={};R2.bbF={};R2.fsUse={};R2.ddosHot={}; + const live=ddosAll().slice().sort((a,b)=>(a.start||0)-(b.start||0)||(a.idb.id?1:0));if(!live.length)return null; + const recs=[],room={}; + for(const a of live){const c=a.city,m={attack:a,tgt:a.tgt,g:a.gbps,bh:!!(a.bh||X.autoBh),ports:new Map(),up:0,fs:0,fsAt:[],fsFull:[],fsNone:[],deliv:0,pulled:0,cleaned:0,over:0,parts:[],tf:1,col:0,slowed:0,eng:0}; + recs.push(m);R2.ddos.push(m);if(!popUp(c)||!S.pops[c]){m.offline=true;continue;} + m.eng=m.bh?0:scrubEng(a);const pull=a.gbps*m.eng,sp=new Map();ddosSpread(a.gbps-pull,E,okBy,sp); + for(const [e,g] of sp){let left=g; + if(m.bh)left*=e.k==='p'?(pniHonours(e.net)?0:1):RTBH_LEFT[e.k]??1;else if(e.clean)left*=0.1; + m.up+=g-left;if(left>1e-9){m.ports.set(e,{off:left,in:0});e.J+=left;}} + if(pull>0){const xs=S.scrubs.filter(x=>popUp(x.city));let tot=0;for(const x of xs)tot+=SCRUB_TIERS[x.tier||0].g; + for(const x of xs){const cap=SCRUB_TIERS[x.tier||0].g,share=pull*cap/tot,can=Math.max(0,room[x.city]??cap),cl=Math.min(share,can);room[x.city]=can-cl; + m.parts.push({city:x.city,tier:x.tier||0,a:share,cleaned:cl});m.cleaned+=cl;m.over+=share-cl;} + m.pulled=pull;}} + // The ports: each carries what fits, shared out by what each attack offers it. + for(const m of recs)for(const [e,p] of m.ports)p.in=p.off*Math.min(1,e.cap/e.J); + // Flowspec, oldest attack first, within each router's rule budget; what is left heads for the target. + const fsLeft={}; + for(const m of recs){if(m.offline)continue;const a=m.attack,V=DDOS_VEC[a.vec],need=V&&V.fs?(a.carpet?FS_CARPET:1):0,byCity=new Map(); + for(const [e,p] of m.ports)byCity.set(e.city,(byCity.get(e.city)||0)+p.in); + for(const [city,g] of byCity){let rest=g; + if(need&&S.pops[city]){const cap=fsCap(city),left=fsLeft[city]??cap; + if(!cap)m.fsNone.push(city);else if(left>=need){fsLeft[city]=left-need;rest=g*(1-FS_DROP);m.fs+=g-rest;m.fsAt.push(city);}else{fsLeft[city]=left;m.fsFull.push(city);}} + m.deliv+=X.haul(city,a.city,rest,'ddos:'+city,city);} + // Clean traffic comes back from each center to the target, the long way round if the center is far. + const tb=ddosTb(a,R2); + for(const x of m.parts){const v=tb*x.a/Math.max(m.pulled,1e-9),h=x.city===a.city?v:X.haul(x.city,a.city,v,'scrub:'+a.city+'>'+x.city,null,true); + R2.haul.push({city:a.city,to:x.city,tier:x.tier,a:x.a,h:v>0?h/v:1,ms:x.city===a.city?0:X.ms(a.city,x.city)*2,attack:a.id});} + // The target: blackholed, or what its own port and the scrubbing centers let through. + const fa=Math.min(1,2*tb/(m.deliv+tb)),fsc=m.pulled>0?m.cleaned/m.pulled:1; + m.tf=m.bh?0:fa*((1-m.eng)+m.eng*fsc); + if(a.tgt&&a.tgt.startsWith('bb:'))R2.bbF[a.city]=Math.min(R2.bbF[a.city]??1,m.tf);else if(a.tgt)R2.tgtF[a.tgt]=Math.min(R2.tgtF[a.tgt]??1,m.tf);} + for(const c in S.pops){const cap=fsCap(c);if(fsLeft[c]!==undefined)R2.fsUse[c]={used:cap-fsLeft[c],cap};} + if(X.autoBh)R2.teBlack=recs.reduce((n,m)=>n+m.up,0); + return recs;} +/* After routing: a port offered more than it carries drops the same share of everyone's traffic on it. Then what the + attacks cost everyone else (collateral) and the target. X.lost(ci,g,bz,e) takes served traffic away again. */ +function ddosAfter(recs,X){const {E,R2}=X;if(!recs)return;const lostC={};let lost=0; + for(const e of E){if(!(e.J>0))continue;const L=e.used,fac=Math.min(1,e.cap/(e.J+L)); + if(fac<1&&e.byC)for(const [ci,v] of e.byC){const x=v[0]*(1-fac),y=v[1]*(1-fac);X.lost(ci,x,y,e);lostC[ci]=(lostC[ci]||0)+x;lost+=x;} + if(fac<0.97){R2.ddosHot[e.city]=1;} + e.fac=fac;e.used=Math.min(e.cap,L+e.J);} + const tot=recs.reduce((n,m)=>n+(m.offline?0:m.attack.gbps),0)||1; + for(const m of recs){if(m.offline)continue;const a=m.attack,ci=CIDX[a.city],tb=ddosTb(a,R2),dem=R2.cityDem[a.city]||0; + // The target's own traffic lost at the ports is not collateral. + const own=dem>1e-6?(lostC[ci]||0)*Math.min(1,tb/dem):0; + m.col=Math.max(0,(lost-own+X.squeeze)*a.gbps/tot); + m.portList=[...m.ports].map(([e,p])=>({lab:e.lab,city:e.city,k:e.k,off:p.off,cap:e.cap,fac:e.fac??1})).sort((x,y)=>x.fac-y.fac||y.off-x.off); + m.full=m.portList.filter(p=>p.fac<0.97).length; + // Customers who felt it: in a city that lost more than 1% to full ports, other than the target. + let n=0;for(const c in S.pops){const i=CIDX[c],d=R2.cityDem[c]||0;if(d<=1e-6||(lostC[i]||0)/d<0.01)continue; + for(const b of S.biz)if(b.city===c&&b.id!==a.tgt&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber)n++;if(R2.cityEye[c]>0&&a.tgt!=='bb:'+c)n++;} + m.slowed=n;}} diff --git a/src/game/80-simulation/25-direct-egress.js b/src/game/80-simulation/25-direct-egress.js new file mode 100644 index 0000000..4ae0eff --- /dev/null +++ b/src/game/80-simulation/25-direct-egress.js @@ -0,0 +1,14 @@ +/* A carrier's own transit port beats other transit ports for traffic bound for that carrier (tier 1) or for a network + that buys transit from it (tier 2): the shorter AS path. A port set to carry pulls that traffic from every POP; any + other only takes it at the POP it sits in. These ranks come after RouteScript's `prefer transit` (2.9) and before plain + transit (3), and each port stays in the plain transit list too, so POPs far from it can still use it. + DIRECT_RANK[tier] = [carries, this POP only]. compute() and traceroute() share this. */ +const DIRECT_RANK=[null,[2.92,2.93],[2.94,2.95]]; +const directTier=(carrier,dest)=>carrier===dest?1:(NET[dest].up&&NET[dest].up.includes(carrier))?2:0; +// What compute() needs of the rule, built once per call and kept out of compute(), whose size the JIT is sensitive to. +// prefc[ci]: 1 where a Prefer-marked transit port has the say, so the rule is off for flows from that POP. +// dirOf(id): the carriers you buy from that are direct for network id (itself: tier 1; one of its upstreams: tier 2), or null. +function directSetup(E,NC){const cars=new Set(),prefc=new Uint8Array(NC); + for(const e of E)if(e.k==='t'){cars.add(e.net);if(e.pref==='high')prefc[e.ci]=1;} + const dirOf=id=>{let m=null;if(cars.has(id))(m=new Map()).set(id,1);const up=NET[id].up;if(up)for(const u of up)if(cars.has(u)&&!(m&&m.has(u)))(m||(m=new Map())).set(u,2);return m;}; + return {prefc,dirOf};} diff --git a/src/game/80-simulation/28-route-worker.js b/src/game/80-simulation/28-route-worker.js new file mode 100644 index 0000000..d05ebfa --- /dev/null +++ b/src/game/80-simulation/28-route-worker.js @@ -0,0 +1,148 @@ +/* Routing off the main thread. The worker is this page's own game script run a second time + from a Blob URL: nothing is fetched, so GitHub Pages still serves one page. In the worker, DOM globals are inert + stand-ins and boot() never runs; the catalogs (cities, networks, cones) are rebuilt from the same code. + Only the day uses it: the day is a generator (dayRun(), 10-day-tick.js) whose every yield is a routing it needs. + Each one goes to the worker with S, the day waits (no next day starts) and goes on when R is back, so a day sees + exactly the routing it would have had in one go. An action in between routes synchronously as always (compute() + bumps RW.gen); then the worker's answer is stale and the action's R stands. + Tests (no Worker in jsdom, __TUBES_TEST__) and any worker failure take the synchronous path. */ +const RW_IN=!!self.__TUBES_WORKER__; +const RW_EL=!RW_IN&&typeof document!=='undefined'?document.currentScript:null; +// RW_SLOW: a frame time (ms) above which the device does not keep up anyway, and a day may take longer slices (99-loop.js). +const RW_SLOW=20; +const RW={w:null,dead:false,seq:0,gz:0,gzq:new Map(),svq:new Map(),gen:0,job:null,desc:null,wR:null,wseq:0,last:null,budget:8,later:f=>rwLater(f),stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}}; +function rwOn(){return !RW_IN&&!RW.dead&&!window.__TUBES_TEST__&&!window.__TUBES_SYNC__&&typeof Worker==='function'&&!!RW_EL;} +function rwStart(){if(RW.w)return RW.w; + try{const L=LANG,dict=L!=='en'&&window.I18N[L]?JSON.stringify(window.I18N[L]):'null'; + const pre=`'use strict';self.__TUBES_WORKER__=1;self.window=self; +const _n=new Proxy(function(){},{get:(t,k)=>k===Symbol.toPrimitive?()=>0:k==='then'?undefined:_n,apply:()=>_n,construct:()=>_n,set:()=>true}); +const _st={getItem:()=>null,setItem(){},removeItem(){},key:()=>null,length:0}; +Object.assign(self,{document:_n,localStorage:_st,sessionStorage:_st,requestAnimationFrame:()=>0,cancelAnimationFrame(){},innerWidth:1280,innerHeight:800,devicePixelRatio:1, + matchMedia:()=>({matches:false,addEventListener(){},addListener(){}}),Image:_n,Audio:_n,screen:_n,visualViewport:_n,history:_n,getComputedStyle:_n,ResizeObserver:_n,MutationObserver:_n,IntersectionObserver:_n,Path2D:_n,scrollTo(){},SOT_LANG:${JSON.stringify(L)},SOT_LANGS:{},I18N:{}}); +if(${dict})self.I18N[${JSON.stringify(L)}]=${dict}; +`; + const url=URL.createObjectURL(new Blob([pre,RW_EL.textContent,'\n;self.onmessage=e=>rwServe(e.data);'],{type:'text/javascript'})); + const w=RW.w=new Worker(url);URL.revokeObjectURL(url); + w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwMsg(m,t);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();}; + }catch(e){console.error('[tubes] no route worker',e);rwKill();} + return RW.w;} +// Gone for good this session: the routing in flight is done here instead, and the day goes on without the worker. +// (A day resting between steps goes on by itself, on the page from then on.) +function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;rwGzBack();rwSaveBack();const j=RW.job;if(!j||j.rest)return;RW.job=null; + if(j.state!==S){rwDayDone();return;}let v;try{if(j.tr)v=dayAgain(j.tr);else compute();}catch(e){tickErr(e);}rwGo(j.g,v);} +// One day in play (dayRun(), 10-day-tick.js): its steps run here, every routing it asks for runs in the worker. +function rwDay(){rwGo(dayRun());} +// Runs the day's steps up to the next routing, posts it, and returns: rwDone() picks the day up when R is back. At a +// DAY_REST, a day that has run RW.budget ms already goes on after the next frame (RW.later), so a phone gets its frames +// between the steps of a big network's day. The day is still in flight meanwhile: no next day starts, nothing saves. +// v: what the step it resumes asked for (a sales trial's or the intern's fiber test's answer, dayAnswer()). +function rwGo(g,v){const t0=performance.now();for(;;){let s;try{s=dayStep(g,v);}catch(e){tickErr(e);s={done:true};}v=undefined; + if(s.done){rwDayDone();return;} + if(s.value===DAY_REST){if(performance.now()-t0{if(tr)v=dayAnswer(tr);else compute();}; + const w=rwOn()&&rwStart();if(!w){try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;} + const t=performance.now(),seq=++RW.seq; + // The worker also needs what compute() reads from yesterday's R: link loads, and the scenic circuits' paths. + // While R is the worker's own last answer (RW.wR), it keeps its R.efg rather than getting it back (efg 0, rwServe()). + const mine=R===RW.wR; + try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:mine?0:rwEfgOut(R.efg),wseq:mine?RW.wseq:0,...(tr?{trial:tr.dark?{dark:tr.dark,s0:tr.s0,L0:tr.L0}:{b:tr.trial,hx:tr.hx}}:{})});} + catch(e){console.error('[tubes] route worker post',e);rwKill();try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;} + const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,g,gen:RW.gen,t:t1,state:S,tr};return;}} +/* Where a resting day goes on. A frame drawn moments ago leaves time before the next one: the day goes on in a task of + its own, and the browser draws the next frame between two tasks when it is due. Otherwise the day waits for that + frame. (Waiting for a frame every time made a day of many short steps take many frames: a slow phone fell behind.) */ +const RW_CH=typeof MessageChannel==='function'&&!RW_IN?new MessageChannel():null,RW_TQ=[]; +if(RW_CH)RW_CH.port1.onmessage=()=>{const f=RW_TQ.shift();if(f)f();}; +function rwLater(f){if(RW_CH&&performance.now()-(RW.lf||-1e9)<(RW.fms||16)*0.75){RW_TQ.push(f);RW_CH.port2.postMessage(0);} + else requestAnimationFrame(()=>setTimeout(f,0));} +// The day rests: it goes on after the next frame, still in flight meanwhile (no next day, no save). +function rwRest(g,v){const j=RW.job={rest:true,g,state:S};RW.later(()=>{if(RW.job!==j)return;RW.job=null;if(j.state!==S){rwDayDone();return;}rwGo(g,v);});} +// Every answer from the worker, in order. +function rwMsg(m,t0){if(m.gz!==undefined){rwGzDone(m);return;}if(m.sv!==undefined){rwSaveDone(m);return;}if(m.R){const d=m.R.egDesc;if(d===0)m.R.egDesc=RW.desc;else RW.desc=m.R.egDesc=d&&d.dK!==undefined?rwDescIn(d,RW.desc):d;}rwDone(m,t0);} +/* A changed R.egDesc comes as its keys, in order, and only the entries that changed (rwDescOut()): a few among thousands. + The rest are yesterday's entries, so the page holds the same object, key for key and in the same order. */ +// dK 0: the keys are yesterday's, in yesterday's order (most days), so they do not come along either. +function rwDescOut(d,old){if(!old)return d;const K=Object.keys(d),O=Object.keys(old),ch={}; + for(const k of K){const x=d[k],y=old[k];if(!y||x.lab!==y.lab||x.city!==y.city||x.k!==y.k)ch[k]=x;} + let same=K.length===O.length;for(let i=0;same&&iRW.budget/2)rwRest(j.g,v);else rwGo(j.g,v);} +function rwDayDone(){paceEnd(performance.now());UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}} +/* A save's compression (91-save.js) runs in the worker too: deflating a big network held the page about as long as + writing it plain. The text goes over as it is (a string is copied flat, without walking a game), the compressed + text comes back. In order with the routings, so a save may wait for one. */ +function rwGzip(txt){const w=rwOn()&&rwStart();if(!w)return null;const k=++RW.gz; + return new Promise((res,rej)=>{RW.gzq.set(k,{res,rej,txt});try{w.postMessage({gz:k,txt});}catch(e){RW.gzq.delete(k);rej(e);}});} +function rwGzDone(m){const q=RW.gzq.get(m.gz);if(!q)return;RW.gzq.delete(m.gz);if(m.err)q.rej(new Error(m.err));else q.res(m.data);} +/* A whole save in the worker (save(), 91-save.js): the game as it was when saved (the copy postMessage makes), packed, + turned into text, stamped and compressed there. Back come the text (the slot keeps it, to spot an unchanged game) and + what to write. The worker lost meanwhile: that save is gone, so the next frame saves again, here. */ +function rwSave(st,seq){const w=rwOn()&&rwStart();if(!w)return null;const k=++RW.gz; + return new Promise((res,rej)=>{RW.svq.set(k,{res,rej});try{w.postMessage({sv:k,S:st,seq});}catch(e){RW.svq.delete(k);rej(e);}});} +function rwSaveDone(m){const q=RW.svq.get(m.sv);if(!q)return;RW.svq.delete(m.sv);if(m.err)q.rej(new Error(m.err));else q.res({txt:m.txt,data:m.data});} +function rwSaveBack(){const q=[...RW.svq.values()];RW.svq.clear();if(q.length)UI.lastSave=0;for(const x of q)x.rej(new Error('route worker lost'));} +function rwSaveServe(m){let txt;try{txt=JSON.stringify(packSave(m.S));}catch(e){postMessage({sv:m.sv,err:String(e)});return;} + const st=slotStamp(txt,m.seq);(txt.length>=GZ_BG?gzB64(st).then(b=>GZ+b):Promise.resolve(st)).then(data=>postMessage({sv:m.sv,txt,data}),e=>postMessage({sv:m.sv,err:String(e)}));} +// The worker gone: what it was compressing is compressed here. +function rwGzBack(){const q=[...RW.gzq.values()];RW.gzq.clear();for(const x of q)gzB64(x.txt).then(x.res,x.rej);} +/* R as plain data. R.ef and R.fl are lazy getters, sent as the pieces they are built from (R.efp, R.flc, see efBuild() + and flDefine() in 30-compute.js), their typed arrays moved, not copied. Exits become their ids (all R.fl reads), and an + attack record names its attack in S by id. */ +const FL_COLS=['FREM','FCI','FNJ','FCA','FBZ','FGT','FGI','FGP','FGH','FTI','FII']; +function rwPack(R){const o={};for(const k in R)o[k]=k==='ef'?0:k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k]; + const p=R.efp,c={...R.flc,E:R.flc.E.map(e=>e.id)},L=rwLOut(p.L),tr=[p.ACN.buffer,p.ACD.buffer,...L.tr];for(const k of FL_COLS)tr.push(c[k].buffer); + return {o,p:{...p,L:L.o,flc:c},tr};} +function rwUnpack(o,p){o.ef={};p.flc.E=p.flc.E.map(id=>({id}));efBuild(o,rwLIn(p.L),p.ACN,p.ACD,p.NKN,p.NC,p.NN);flDefine(o,p.flc); + const as=ddosAll(S,false);for(const m of o.ddos){m.attack=as.find(a=>a.id===m.attack)||null;m.ports=new Map();}return o;} +/* What crossed each link (efp.L: [link id, edge index, t], t = {g: exit key → slot, v: sums by slot, n, d}) is the + biggest part of R, and as plain objects it took longer to read on the page than all the rest. It crosses as typed + arrays instead, the exit keys once each, and the page decodes a link's t only when something reads it: the link panel + (R.ef) or a scenic circuit routed on the page (R.efg). Decoded, it is the same t, Map order included. */ +function rwLOut(L){const n=L.length,K=[],ki=new Map(),ID=new Array(n),EI=new Int32Array(n),OG=new Int32Array(n+1),ON=new Int32Array(n+1),OD=new Int32Array(n+1); + let ng=0,nn=0,nd=0;for(const x of L){const t=x[2];ng+=t.g.size;nn+=t.n.length;nd+=t.d.length;} + const G=new Int32Array(2*ng),V=new Float64Array(ng),N=new Int32Array(nn),D=new Int32Array(nd);ng=nn=nd=0; + for(let j=0;j{if(!t){const g=new Map(),v=[];for(let a=OG[j];a{if(!efg)return null;const o={};for(const k in efg)o[k]=efg[k].t;return o;}; +const rwEfgIn=o=>{const efg={};for(const k in o)efg[k]=new EgSums(o[k]);return efg;}; +// In the worker: route the state it was sent, answer with R. +/* R.egDesc names every exit that carried traffic (about two thirds of R on a big network) and only changes with the + network. When it is yesterday's again, key for key, the worker sends 0 and the page keeps the one it has (RW.desc): + every answer is read in order, the stale ones too, so both sides always hold the same last one. */ +function rwSameDesc(a,b){if(!a||!b)return false;const ka=Object.keys(a),kb=Object.keys(b);if(ka.length!==kb.length)return false; + for(let i=0;ipostMessage({gz:m.gz,data}),e=>postMessage({gz:m.gz,err:String(e)}));return;} + if(m.sv!==undefined){rwSaveServe(m);return;} + try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{}; + if(m.efg===0){if(!RW.last||RW.last.seq!==m.wseq)throw new Error('route worker: no R.efg for answer '+m.wseq);Object.defineProperty(R,'efg',{value:RW.last.efg});} + else if(m.efg)Object.defineProperty(R,'efg',{value:rwEfgIn(m.efg)}); + // A sales trial (offerTrial()) or the intern's fiber test (opsDarkTrial()): its answer only. What the worker keeps + // for the next routing (RW.last, RW.desc) stays. + if(m.trial){const t=performance.now(),ok=m.trial.dark?opsDarkTrial(m.trial):!!offerTrial(m.trial.b,m.trial.hx);postMessage({seq:m.seq,ok,ms:performance.now()-t});return;} + const t=performance.now();compute();const ms=performance.now()-t,{o,p,tr}=rwPack(R);RW.last={seq:m.seq,efg:R.efg}; + if(rwSameDesc(RW.desc,o.egDesc))o.egDesc=0;else{const d=o.egDesc;o.egDesc=rwDescOut(d,RW.desc);RW.desc=d;}postMessage({seq:m.seq,R:o,ef:p,hot:UI.hotMap,ms},tr);} + catch(e){postMessage({seq:m.seq,err:String(e&&e.stack||e)});}} diff --git a/src/game/80-simulation/29-route-cache.js b/src/game/80-simulation/29-route-cache.js new file mode 100644 index 0000000..a7340e6 --- /dev/null +++ b/src/game/80-simulation/29-route-cache.js @@ -0,0 +1,65 @@ +/* What compute() works out from the network's shape alone, kept from one call to the next: most days only demand moves, + and on a big network these are a third of the work. Each part has a key made of everything it is built from, and any + other key rebuilds it, so it is never stale: + - the graph (RC.gk): the POPs, the remote cities and every edge with its ends and weight, in the order compute() made + them. Kept: the shortest-path tables from every POP, ALONE and the islands (COMP). + - the exits (RC.xk): the graph key, RouteScript, the events that change who reaches whom, and every exit in order with + its kind, id, network, city, preference, rank, carry and prepend marks and what it can reach. Kept: okBy, what is + reachable, and each network's exit lists by rank (BRJ, with the lists networks share) with DSEL and RSET. + Only numbers are kept (exit and edge indices): compute() makes fresh exits, lists and paths from them every call, + since routing writes on those. RC.on=false (the equivalence tests) always rebuilds. */ +const RC={on:true,gk:null,g:null,xk:null,x:null}; +// The graph key: EA lists the edges in the order compute() made them (so adj, and the order Dijkstra settles ties, follow). +function rcGraphKey(pops,remote,EA){let k=pops.join(',')+'|'+remote.join(',');for(let i=0;i=0)P[x]=EA[k];}SDi[i]=SPD[s]=G.D[i];SPi[i]=SPP[s]=P;} + return {SPD,SPP,SDi,SPi,ALONE:G.ALONE,COMP:G.COMP,NCOMP:G.NCOMP};} + // ALONE[i]: no other city lies within 1e-6 of POP i (so only its own exits can be at distance 0 from it). + const ALONE=new Uint8Array(NC),PIs=[]; + for(const s of pops){const i=CIDX[s],r=dijkstra(adj,i,wW);SDi[i]=SPD[s]=r.D;SPi[i]=SPP[s]=r.P;ALONE[i]=1;for(let x=0;x=0)continue;const D=SDi[i],k=NCOMP++;for(let x=0;x{k+=n+(d&&!d.has(n)?'^,':',');});}else if(e.k==='c')k+=e.nets[0];} + return k;} +// The exits' lists, with a sort key: an exit's index in E. +const rcIx=(L,E)=>{const a=new Int32Array(L.length);for(let i=0;i{const L=new Array(a.length);for(let i=0;ie.hp===0);L.mx=L.some(e=>e.dt>0)&&L.some(e=>e.dt===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}} +// What reaching networks gave R (taken right after compute() worked it out, before anything else adds to R). +function rcReachTake(R2){return {reachable:{...R2.reachable},nt:{...R2.nt},cone:{...R2.cone},reach:R2.reach,reachNT:R2.reachNT};} +function rcReachPut(X,R2){const r=X.reach;Object.assign(R2.reachable,r.reachable);Object.assign(R2.nt,r.nt);Object.assign(R2.cone,r.cone);R2.reach=r.reach;R2.reachNT=r.reachNT;} +// Keep what was built (on a miss): okBy, the exit lists (each shared list once), each network's lists by rank, DSEL, RSET. +/* A list's orders (by source city) follow from its exits in list order, each exit's city and preference, and the graph's + distances. When the exits change (a PNI comes up, a network leaves an exchange), most lists do not: one with the same + exits, cities and preferences on the same graph keeps the orders it had, and uses them today already. Only the lists + that changed start again (scanned today, sorted from tomorrow). */ +function rcExitKeep(key,E,okBy,reach,LIST,BRJ,DSEL,RSET,bk=''){const ok=[];for(let j=0;j0?1:0); + const P=RC.x&&RC.x.gk===RC.gk&&RC.x.bk===bk&&RC.x.sig?RC.x:null,old=new Map(); + if(P)for(const d of P.lists){if(d.cs){for(let k=0;k{for(let i=0;i=P.sig.length||P.sig[x]!==sig[x])return false;}return true;}; + const kept=(k,a)=>{if(!P)return null;const o=old.get(k);return o&&same(a)?o:null;}; + const id=new Map(),lists=[];for(const V of LIST.values()){id.set(V,lists.length); + if(V.cs){const cs=[],ord=[];for(let k=0;k{const o=[];for(const r in m)o.push(r,id.get(m[r]));return o;}); + RC.xk=key;RC.x={ok,reach,lists,brj,DSEL,RSET:[...RSET],gk:RC.gk,bk,sig};} +// Fresh lists for today's exits from a kept build. +// Each list also gets the orders kept with it (ord: by source city, the list in the order routing tries it, see xOrder() +// in 30-compute.js), filled in as routing asks for them. +function rcExitLists(X,E,BRJ,DSEL,RSET){const V=X.lists.map(d=>{if(d.cs){const cs={cs:[]};for(let k=0;ke.w; + // Each network's list at one rank, in an array by network index: BRX[j] are objects of as many shapes as networks have + // sets of ranks, and reading one per flow made the loop's code give up on them. + const byRank=rank=>{const B=new Array(BRX.length);for(let j=0;j{const o=NRES[i];NRES[i]=o-a;if(o>1e-3&&NRES[i]<=1e-3)EP++;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;}; + // t.g gives each egress a slot in t.v, so adding to it allocates nothing (a Map of numbers boxes every new sum). + const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),v:[],n:[],d:[]};EL.push(l);}const s=t.g.get(eg);if(s===undefined){t.g.set(eg,t.v.length);t.v.push(0+a);}else t.v[s]+=a; + let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;}; + // TEF[src*NC+dst]: 1 once no detour exists for that pair (capacity only shrinks, so there never will be one again). + // Most calls are those: a byte read, not a Map lookup. The kept path is still valid while every edge and node on it has room. + const altPath=(src,dst,base)=>{const key=src*NC+dst;if(TEF[key]===1)return null;const c0=teCache.get(key); + if(c0){let ok=true;const p=c0.path,ni=c0.ni;for(let k=0;k1e-3)){ok=false;break;} + if(ok)for(let k=0;k1e-3)){ok=false;break;}} + if(ok)return c0;} + const d=teSearch(src,dst); + if(d===Infinity||d>REACH*base+60){teCache.set(key,false);TEF[key]=1;return null;} + const Q=walkP(DJ.P,src,dst);teCache.set(key,Q);return Q;}; + /* Auto-TE's detour search (the one 10-dijkstra.js does to a stop), step for step: neighbours in the same order, the same heap, written into the + same DJ (walkP() reads its paths, the reuse above its marks). Only on the graph as flat arrays (TEO offsets by city, + TEN neighbours, TEE edges, made once per routing in run()) and with the test of an edge written out: no pairs to + unpack and no call for each edge. On a big network with Auto-TE these searches were most of the routing. */ + /* A search from one POP picks up where the last one from there stopped (LR*), as a search of its own would run: every + city closer than the last exit is settled and the heap holds the rest, so the next exit has its answer already or + the search goes on from there, the last exit's neighbours first (it stops before them). One that found nothing has + walked all src reaches and answers the next ones at once. Only on the same graph: EP counts the edges and routers + that run out of room (capacity only shrinks while routing, so none comes back), and another search in DJ moves its + mark. An exit out of the core is let into a graph of its own (OUT[dst]): that search neither resumes nor is resumed. + On a big network nearly all detours of a flow are found from one search (extreme: 3.6 M heap steps a routing → 0.17 M). */ + let TEO=null,TEN=null,TEE=null,LRs=-1,LRe=-1,LRg=-1,LRD=null,LRu=-1,LRm=0; + const teSearch=(src,dst)=>{const n=TEO.length-1,core=CORE,cut=!!(core&&OUT[dst]),go=LRs===src&&LRe===EP&&LRg===DJ.g&&LRD===DJ.D&&!cut; + let g,m=0,u=-1; + if(go){g=LRg;if(DJ.done[dst]===g)return DJ.D[dst];m=LRm;u=LRu;} + else{if(DJ.n!==n||DJ.g>2e9){DJ.n=n;DJ.D=new Float64Array(n);DJ.P=new Array(n);DJ.S=new Int32Array(n);DJ.done=new Int32Array(n);DJ.g=0;}g=++DJ.g;} + const D=DJ.D,P=DJ.P,ST=DJ.S,DN=DJ.done;let hd=DJ.hd,hu=DJ.hu,cap=hd.length; + if(!go){D[src]=0;ST[src]=g; + if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=DJ.hd=a;hu=DJ.hu=b;} + let i=m++;hd[i]=0;hu[i]=src;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}} + for(;;){ + if(u>=0){const d=D[u];for(let k=TEO[u],K=TEO[u+1];k0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}}}} + if(!m){u=-1;break;} + const d=hd[0];u=hu[0];m--; + if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(l(ST[u]===g?D[u]:Infinity)){u=-1;continue;}DN[u]=g;if(u===dst)break;} + // An exit out of the core that was found sits in the heap of its own graph; one never found was never let in. + if(cut&&u>=0)LRs=-1;else{LRs=src;LRe=EP;LRg=g;LRD=D;LRu=u;LRm=m;} + return ST[dst]===g?D[dst]:Infinity;}; + /* The routing loops work on exits by number (xi, their index in E): what they read for every exit they look at sits in + columns, USED, CAPX, CIX, HPX, DTX and VISX, and the lists they scan hold numbers (lst.x, lst.xat). Scanning objects of + thirty fields each read one cache line per exit; the columns keep a list's exits side by side. The objects are only + read for an exit that takes traffic (push()), and e.used is written back once routing is done (run()). */ + // An exit the flow can still try: not visited yet, not full when the flow started, reachable, and not on a saturated path. + const usable=x=>VISX[x]!==vis&&USED[x]HPX[a]-HPX[b]||Dv[CIX[a]]-Dv[CIX[b]]+(DTX[a]-DTX[b]); + // Push up to `want` along one path to exit e; returns what fitted. Index loops: for…of allocates an iterator until optimised. Capacity only shrinks while routing, so a + // path with one full link or node fits nothing for the rest of this pass: mark it, and later tries cost nothing + // (most tries are into paths that filled up earlier). + const push=(x,P,want,keep=0)=>{if(P.dead)return 0;const e=E[x];const path=P.path,ni=P.ni;let amt=want; + const PN=path.length;for(let k=0;k1e-3&&l.res<=1e-3)EP++;l.ld+=amt;carry(l,ek,nr,ci,amt);} + USED[x]+=amt;FREM[F]-=amt; + {let ok=amt;const cf=CNB[ci],ce=e.cn,cn=NCN[nr],bz=FBZ[F]===1; + if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);} + SRV[ci]+=ok;R2.served+=ok;if(bz)R2.bizSrv[CITIES[ci].id]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const k=e.ts*NN+nr;if(!TNS[k]){TNS[k]=1;if(!TNK[e.ts]){TNK[e.ts]=[];TORD.push(e);}TNK[e.ts].push(nr);}TNA[k]+=ok;} + // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then + // it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays, + // Korean users notice any exit far away, transit or not, and much sooner. + // Over a satellite users notice too, whatever the exit: the path's edges with one (se) keep what this flow would lose + // on each orbit, and satAfter() charges the share the satellite really carried. The haul to transit counts on the ground (mt). + if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr||SATN)){pathMs(P);const rtt=2*P.mt,kl=snd&&CITIES[ci].kr; + const tl=(e.k==='t'||kl)&&rtt>(kl?KR_LAT_OK:LAT_OK)?(kl?krLatLoss(rtt):latLoss(rtt)):0; + if(tl>0){LATP[ci]+=ok*tl;if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}if(P.se)satNote(P.se,ci,ok,tl);}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok; + // Where each flow left (the PNI list asks what a PNI here would take over, #175). + if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);} + if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}} + return amt; + }; + // Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths + // with free capacity, as long as they are no more than twice as long. + const send=(x,want)=>{ + let room=Math.min(want,FREM[F],CAPX[x]-USED[x]);if(room<=1e-6)return;const ci=CIX[x]; + const P=PP[ci]||(PP[ci]=walkP(Pv,fci,ci));if(TT&&ci!==fci){room=tiers(x,P,room,ci);if(room<=1e-6)return;} + if(!P.dead)room-=push(x,P,room,TE&&SPILL<1?1-SPILL:0); + if(TE&&room>1e-6&&FREM[F]>1e-6&&USED[x]1e-6;k++){const P=altPath(fci,ci,Dv[ci]);if(!P)break;const m=push(x,P,Math.min(room,CAPX[x]-USED[x]));if(m<=1e-6)break;room-=m;R2.teMoved+=m;} + }; + /* Spill tiers (#136, `spill at 80% within 10 ms`): the shortest path fills up to a tier's line, then what does not fit + takes the fastest detour whose links are all still under that line, if it adds no more than the tier's milliseconds; + the next tier lets links run hotter and detours longer. After the last tier the usual rules above take over. A detour + is searched by latency over the links under the line (tierSearch), and kept per pair and tier while it still is: + links only fill up while routing, so a pair with no detour under a line never gets one. */ + // A path's latency, worked out once: ms in all, mt on the ground (the haul to transit), se the edges with a satellite + // on them. push() reads all three, so whichever asks first fills them all (a tier's detour is timed before it is used). + const pathMs=P=>{let ms=P.ms;if(ms<0){ms=0;let mt=0,se=null;const p=P.path;for(let k=0;k{const n=TEO.length-1,core=CORE;if(!TSD||TSD.length!==n){TSD=new Float64Array(n);TSP=new Array(n);TSS=new Int32Array(n);TSG=0;} + const g=++TSG,D=TSD,P=TSP,ST=TSS;let m=0;D[src]=0;ST[src]=g;TH[0]=0;THU[0]=src;m=1; + while(m){let best=0;for(let i=1;iD[u])continue;if(u===dst)break; + for(let k=TEO[u],K=TEO[u+1];ke.cap*keep+1e-3)||(HAS[v]&&NRES[v]<=1e-3)||(core&&OUT[v]&&v!==dst))continue; + const nd=d+e.lat;if(nd>lim||!(nd<(ST[v]===g?D[v]:Infinity)))continue;D[v]=nd;ST[v]=g;P[v]=e;TH[m]=nd;THU[m]=v;m++;}} + return ST[dst]===g?walkP(P,src,dst):null;}; + const tierPath=(t,keep,src,dst,lim)=>{const key=(src*NC+dst)*TT.length+t,c=TC.get(key);if(c===false)return null; + if(c){let ok=true;const p=c.path,ni=c.ni;for(let k=0;kp[k].cap*keep+1e-3)){ok=false;break;} + if(ok)for(let k=0;k1e-3)){ok=false;break;}} + if(ok)return pathMs(c)<=lim?c:null;} + const Q=tierSearch(src,dst,keep,Infinity);TC.set(key,Q||false);return Q&&pathMs(Q)<=lim?Q:null;}; + const tiers=(x,P,room,ci)=>{for(let t=0;t1e-6;t++){const T=TT[t],keep=1-T.at; + room-=push(x,P,room,keep); + if(room<=1e-6||FREM[F]<=1e-6||!(USED[x]1e-6){room-=m;R2.teMoved+=m;}} + return room;}; + // Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over + // them by free capacity (like several transits in one city), then top up in order if one fills. + // The group is g[i0..i1): plain loops and one scratch array, since this runs for most flows (same sums, same order). + // Without Auto-TE an exit whose path from here is full takes nothing: skip the call (and the numbers it boxes). + const gone=x=>{if(TE)return false;const P=PP[CIX[x]];return !!P&&P.dead===1;}; + // Every exit of a remembered group still has room (a loop, not every(): no closure per flow). NOG: no group. + const allRoom=c=>{for(let k=0;k{const ci=CIX[x],P=PP[ci];return P!==undefined&&P.dead===1&&(!TE||ci===fci||TEF[fci*NC+ci]===1);}; + const ROOM=[],sendGroup=(g,i0=0,i1=g.length)=>{let live=false;for(let k=i0;k1){let tot=0;for(let k=i0;k1e-6)for(let k=i0;k{if(n>24){if(n===a.length)a.sort(byDist);else{const t=a.slice(0,n).sort(byDist);for(let i=0;i=0&&byDist(a[j],x)>0){a[j+1]=a[j];j--;}a[j+1]=x;}}; + // The direct ranks (25-direct-egress.js) have short lists, one carrier's ports, so they take the plain way: the usable exits + // nearest first, tried in groups of equal distance, as the reference loop in the tests does. A direct rank only concerns the + // networks that have an exit there, and nothing from a POP where Prefer has the say; a port that is not set to carry only takes + // its own POP's traffic. Kept in a function of its own so the loop below stays as it was: the JIT is sensitive to its shape. + const directPass=(rank,pass)=>{const DS=DSEL.get(rank),LOC=rank===DIRECT_RANK[1][1]||rank===DIRECT_RANK[2][1],BR=byRank(rank); + for(F=0;F1e-6;){let j=i+1;while(j{const BR=byRank(rank); + for(F=0;F=CAPX[A[k]]||gone(A[k])))k++;cur[fci]=k; + if(k===N){gc[fci]=NOG;continue;} + const bh=HPX[A[k]],bd=Dv[CIX[A[k]]]+DTX[A[k]]; + for(let i=k;i=1e-6)break;if(USED[x]=CAPX[e]||gone(e)){full++;continue;}const d=Dv[CIX[e]]+DTX[e];if(d===Infinity)continue;const h=HPX[e]; + if(h=L.length&&full){let k=0;for(let li=0;li1){gc[fci]=NOG;continue;} + if(GN>1)sortD(G,GN);gc[fci]=G.slice(0,GN);}}} + sendGroup(G,0,GN); + if(FREM[F]<=1e-6)continue; + // What is left, nearest first: with a kept order, the usable exits in it (the order sorting them gives). + REST.length=0;if(lst.ord){const A=xOrder(lst,fci);for(let i=lst.cur[fci]|0;i1e-6;){ + let j=i+1;while(j{let a=lst.ord[ci];if(a===undefined){const b=[],L=lst.x; + for(let i=0;i{let w=W.get(A);if(w)return w; + if(A.cs)w={x:null,xat:null,hi:false,mx:false,gc:null,ord:null,cur:null,cs:A.cs.map(s=>s&&lx(s,W))}; + else{const xat=new Map();for(const [c,h] of A.at)xat.set(c,h.map(e=>e.xi));w={x:A.map(e=>e.xi),xat,hi:!!A.hi,mx:!!A.mx,gc:[],ord:A.ord||null,cur:[],cs:null};} + W.set(A,w);return w;}; + return {nodeTake,carry, + nodes(o){({NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD}=o);}, + run(o,PASSES,RANKS,RSET){({E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP, + TE,SPILL,TT,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff,SATN}=o); + NX=E.length;USED=new Float64Array(NX);CAPX=new Float64Array(NX);CIX=new Int32Array(NX);HPX=new Uint8Array(NX);DTX=new Float64Array(NX);VISX=new Int32Array(NX); + for(let x=0;xe.dir.has(u))||null;}return by||1;} +// Scratch columns compute() gathers its flows in, kept between calls: it copies out what it keeps, so no R shares them. +const FLB={n:0,cap:0,rem:null,ci:null,nj:null,ca:null,bz:null}; +function flbGrow(){const c=Math.max(4096,FLB.cap*2),g=(A,o)=>{const a=new A(c);if(o)a.set(o);return a;}; + FLB.rem=g(Float64Array,FLB.rem);FLB.ci=g(Int32Array,FLB.ci);FLB.nj=g(Int32Array,FLB.nj);FLB.ca=g(Uint8Array,FLB.ca);FLB.bz=g(Uint8Array,FLB.bz);FLB.cap=c;} +// R.efg[link]: what each egress put on that link, read by scenic routing the next day (t.g gives each egress its slot in t.v). +class EgSums{constructor(t){this.t=t;}get(k){const s=this.t.g.get(k);return s===undefined?undefined:this.t.v[s];}} +/* R.ef and R.efg from what routing added up per edge (L: [link id, edge index, its sums t]), and R.fl from the flow + columns (c). Also how a route worker's answer is put back together (28-route-worker.js): getters do not cross + threads, so it sends these plain pieces (R.efp, R.flc) and the page rebuilds the same lazy R. */ +function efBuild(R2,L,ACN,ACD,NKN,NC,NN){const efg={};for(const [id,i,t] of L){let rec=null;efg[id]=new EgSums(t); + Object.defineProperty(R2.ef,id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,s] of t.g)rec.eg[k]=t.v[s]; + for(const j of t.n)rec.net[jadj[CIDX[p]]=[]); + const edges={},EA=[],TRX=teRules(),live=[];let NE=0,SE=null;R2.bizDem={};R2.bizSrv={}; + for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.ae.w,wLat=e=>e.lat+0.05,RCON=RC.on,GK=RCON?rcGraphKey(pops,remote,EA):null, + G0=rcGraph(GK,pops,adj,EA,NC,wW),{SPD,SPP,SDi,SPi,ALONE,NCOMP}=G0;let COMP=G0.COMP; + // Orbit (35-pie-paths.js): sky nodes and edges, after the IGP paths, which never use them; a POP cut off from the backbone + // that backhauls through a dish gets its paths again with that edge (pieRelink, on copies: the cached graph stays as it was). + const PX=S.pie?pieGraph(adj,edges,COMP,pops,NE):null;if(PX){NE=PX.ne;if(PX.bh.length)COMP=pieRelink(PX,SPD,SPP,SDi,SPi,COMP);} + const ev=S.ev; + const depeer=ev.depeer>day||scnRule('spat'), leak=ev.leak&&ev.leak.until>day?ev.leak.net:null; + // Sender pays (Gangnam Style Peering): no carrier hands traffic to the Korean incumbents for you, only a paid PNI does. + const snd=scnRule('sender'); + // Stages with loops run as functions of their own (see rankPass below), here the exits. + const E=(()=>{const E=[]; + for(const t of S.transit){if(!popUp(t.city)||t.down>day||!liveN(t.city,t.site,t.n))continue; + // AS-path prepending (#96) moves part of the port to a last-resort exit of its own. + const cap=Math.min(liveCap(PORT[t.tier].g,t.city,t.site,t.n)*lagF(t),TRX&&TRX.cap[t.net]!==undefined?TRX.cap[t.net]:Infinity),pf=TRX&&TRX.prep[t.net]?PREPEND_F[TRX.prep[t.net]]:0; + const ex=mkEx('t',t.id,t.city,cap*(1-pf),3,t.pref||'normal',labOf(N_('common.net_transit'),'net',NET[t.net].name),n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak&&!(snd&&NET[n].kr),null,t.net); + ex.clean=!!t.clean;ex.prem=premOn(t);ex.carry=!!t.carry;E.push(ex);if(pf){const x=Object.assign(mkEx(),ex);x.cap=cap*pf;x.prep=true;E.push(x);}} + // `nets`: every network ok() can say yes to, so it need not be asked about the other hundred. + for(const c in S.ixp){const ct=ixCity(c);if(!(popUp(ct)||remote.includes(ct))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||!(S.myIx[c]?myIxLive(c):liveN(ct,(S.ixSite||{})[c],(S.ixn||{})[c])))continue;const set=ixSessions(c);R2.sessions+=set.size; + // A peer announces its customers too (#85): the session reaches its cone, after the networks peering directly. + let all=set;for(const id of set)if(DOWN[id].length){if(all===set)all=new Set(set);for(const x of DOWN[id])all.add(x);} + const x=mkEx('ix',c,ct,ixCap(c),2,(S.ixPref&&S.ixPref[c])||'normal',labOf(N_('common.ix_peering'),'ix',ixName(c)),n=>all.has(n),all);x.dir=all===set?null:set;E.push(x);} + for(const p of S.pni){if(!pniOn(p)||!popUp(p.city)||!liveN(p.city,p.site,p.n))continue;R2.sessions++; + const x=mkEx('p',p.id,p.city,liveCap(pniG(p),p.city,p.site,p.n)*lagF(p)*(p.sacrif?0.5:1),2,p.pref||'normal',labOf(N_('common.pni_with_net'),'net',NET[p.net].name),n=>CONE_S[p.net].has(n),CONE[p.net],p.net);x.sac=!!p.sacrif;x.pnc=!!NET[p.net].cn;E.push(x);} + for(const c of S.caches){if(!popUp(c.city)||siteDown(c.city,c.site==='b'?'b':'a'))continue;E.push(mkEx('c',c.id,c.city,cacheG(c),0,'normal',labOf(N_('common.name_cache'),'name',NET[c.net].cache.name),n=>n===c.net,[c.net]));} + // After an update adds networks, a free courtesy route reaches the new ones you have no other way to (#46). + R2.graceNets=0;if(S.grace&&S.grace.until>day){const gs=new Set(S.grace.nets.filter(n=>NET[n]&&!E.some(e=>e.k!=='c'&&e.ok(n)))),hc=popUp(S.home)?S.home:pops.find(popUp); + R2.graceNets=gs.size;if(gs.size&&hc)E.push(mkEx('ix','~grace',hc,1e9,2,'normal',tr('compute.courtesy_route_to_new_networks'),n=>gs.has(n),gs));} + return E;})(); + const rp=ev.rpki&&ev.rpki.until>day?new Set(ev.rpki.nets):null;if(rp)for(const e of E){if(e.k==='c')continue;const o=e.ok;e.ok=n=>!rp.has(n)&&o(n);} + // Who reaches whom and each network's exit lists, kept while the exits are the same (XC, 29-route-cache.js). + // A backhaul through a dish changes a cut-off POP's distances: lists kept in order (29-route-cache.js) only for the same one. + const BHK=PX&&PX.bh.length?PX.bh.map(e=>e.bh.city+'>'+e.bh.land).join(','):''; + const XK=RCON?rcExitKey(GK,E,(depeer?1:0)+'|'+leak+'|'+(snd?1:0)+'|'+(rp?ev.rpki.nets.join(','):'')+'|'+(TRX?S.te.script:'')+'|'+BHK):null,XC=XK!==null&&RC.xk===XK?RC.x:null; + // coneOf: does exit e reach network n only through a peer's customer cone (#85)? + const coneOf=(e,n)=>e.k==='p'?e.net!==n:!!e.dir&&!e.dir.has(n); + // ok() cannot change during one compute, so ask each exit once per network, not once per flow and rank. + // okBy[net] lists the exits that reach it in E's order, like E.filter(e=>e.ok(net)). + const okBy=XC?rcOkBy(XC,E):{};if(!XC)for(const id of NET_IDS)okBy[id]=[]; + const okAdd=(e,n)=>{const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}; + // TSL: a slot per transit port id, for what it carries to each network (R.tNet, added up in TNA). + const ekN={},TSL=new Map();(()=>{for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;} + // dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last. + for(let i=0;i1;e.told=false;e.hp=e.pref==='high'?0:1;e.dt=e.k==='ix'?PNI_TIE:0;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.ts=-1;if(e.k==='t'){let t=TSL.get(e.id);if(t===undefined)TSL.set(e.id,t=TSL.size);e.ts=t;} + if(XC)continue; + // Index loops or forEach (same order): for…of here made an iterator result per exit and network. + const ns=e.nets||NET_IDS;if(Array.isArray(ns)){for(let q=0;qokAdd(e,n));} + if(XC)rcReachPut(XC,R2);else for(const n of NETS){let any=false,nt=false;for(const e of okBy[n.id])if(e.rank>0){any=true;if(e.k!=='t'){nt=true;break;}}R2.reachable[n.id]=any;if(any)R2.reach+=NSH[n.id];if(nt){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id]; + // Reached without transit only through the customers of networks you peer with (#85). R.cone[id]: the peer that + // carries it, the first PNI's network or else the nearest upstream that is a member of an exchange you are on. + if(!okBy[n.id].some(e=>(e.k==='p'||e.k==='ix')&&!coneOf(e,n.id)))R2.cone[n.id]=coneBy(okBy[n.id],n.id);}}})(); + const RCH=XK!==null&&!XC?rcReachTake(R2):null; + const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net)); + const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1); + /* Flows are columns, not objects (tens of thousands of them on a big network): flow F starts in city FCI[F] for network + index FNJ[F] and has FREM[F] left to place. Gathered in FLB here, then copied into this call's own columns below. */ + FLB.n=0;const NN=NETS.length,CNB=[],NCN=NETS.map(n=>!!n.cn),flow=(ci,j,rem,cache,bz)=>{const k=FLB.n;if(k===FLB.cap)flbGrow();FLB.rem[k]=rem;FLB.ci[k]=ci;FLB.nj[k]=j;FLB.ca[k]=cache?1:0;FLB.bz[k]=bz?1:0;FLB.n=k+1;}; + // Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give). + const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){if(T.orbit){const g=PX&&PX.gs[b.id];if(g)bizBw[g]=(bizBw[g]||0)+PX.term[b.id];continue;}const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}} + // Traffic shares by network index, and their sums, for each share table (and with Russia's throttle). + const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'); + // Island Wi-Fi (46-wisp-zones.js): a zone's homes are its city's demand, as far as its backhaul reaches them. Its + // fields are only in R while you run a zone, so every other game routes to the same R as before. + const WZI=wispOn()?wispIn(viral):null;if(WZI){R2.wispL=WZI.L;R2.cityWisp={};R2.wisp={};} + (()=>{for(const c of Object.keys(S.pops)){ + const p=S.pops[c],ci=CIDX[c],cn=cnCity(c),SH=cn?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cn&&ev.golden>day?1.4:1);const biz=bizBw[c]??0; + const wz=WZI?WZI.by[c]||0:0;if(wz)R2.cityWisp[c]=wz;const d0=eye+wz+biz; + // Goggle video is throttled in Russia (#70): people there get half of it, so they ask for half. It is not + // traffic you failed to deliver, and it does not cross your links only to be thrown away. + const ru=ruCity(c),thr=n=>n==='ggl'&&ru?0.5:1;let sa=shArr.get(SH),sm=shSum.get(SH);if(!sa){shArr.set(SH,sa=NETS.map(n=>SH[n.id]||0));shSum.set(SH,sm=[]);} + // This city's own split: its traffic to networks that sell to homes goes mostly to the ones whose users are near (#48). + const ls=cityShares(SH,c); + const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?ls[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf; + R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d; + for(let j=0;jday?ev.pmtud:null,kr=CITY[c].kr; + for(let j=0;jday&&n.id==='fbk'?0.8:1);if(a<=0)continue; + // With `protect customers`, the business part first, then the rest (no arrays: this runs per city and network). + const bf=d0>0?biz/d0:0,sp=!!(TRX&&TRX.protect&&bf>0),cn2=cacheNets.has(n.id); + for(let q=0;q<(sp?2:1);q++){const x=sp?(q?a*(1-bf):a*bf):a,bz=sp&&!q;if(x<=0)continue;if(cn2){flow(ci,j,x*0.85,true,bz);flow(ci,j,x*0.15,false,bz);} + else flow(ci,j,x,false,bz);}} + R2.bizDem[c]=biz*d/(d0||1);R2.bizSrv[c]=0; + }})(); + if(Object.keys(S.pops).length)for(let j=0;j=1;if(CORE)for(const c of pops){const i=CIDX[c];PASS[i]=corePass(c);OUT[i]=inCore(c)?0:1;} + const TNA=new Float64Array(TSL.size*NN),TNS=new Uint8Array(TSL.size*NN),TNK=[],TORD=[]; + const NKN=NN+3,ACN=new Float64Array(NE*NKN),SEN=new Uint8Array(NE*NKN),ACD=new Float64Array(NE*NC),SED=new Uint8Array(NE*NC),EL=[]; + // The routing core (29-route-core.js) adds up what floods and circuits carry too. + ROUTE.nodes({NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD});const nodeTake=ROUTE.nodeTake,carry=ROUTE.carry; + R2.l2route={};R2.l2split={}; + /* compute() reads only S, except here: scenic circuits remember yesterday's path in R.l2route and R.efg (deliberate + hysteresis, so they do not flap). A second call can still move one; the third gives the same answer as the second. */ + /* Scenic routing (#28). "Busy" is judged without the customer's own traffic, or it flees its own load and + flips paths every day. Two paths that are about as quiet share the load, and yesterday's choice is kept + unless today's is clearly better. */ + const fastSP={},divMemo={},cityIds=ni=>ni.map(i=>CITIES[i].id); + // disjointRoutes() over today's live links, on city indices: the links are listed per city once, not twice per customer. + const LA=[];for(const l of live){const ai=CIDX[l.a],bi=CIDX[l.b];(LA[ai]||(LA[ai]=[])).push([bi,l]);(LA[bi]||(LA[bi]=[])).push([ai,l]);} + // An express runs in the trenches of every fiber it rides: one backhoe in any of them takes it out. + const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id),hitR=(s,l)=>l.kind==='xp'?xpRisk(l).some(r=>s.has(r)):s.has(srlg(l)); + const bfsI=(a,b,skip)=>{const prev=[],seen=new Uint8Array(NC),q=[a];seen[a]=1; + for(let h=0;h{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.flatMap(l=>l.kind==='xp'?xpRisk(l):[srlg(l)])));}; + for(const k in edges){const e=edges[k];let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;e.pl=ld;} + const l2Routes=(A,B,b)=>{if(b.pin){const r=pinRoute(b.pin,edges);if(r)return [r];}const m=b.route||'normal',Ai=CIDX[A],Bi=CIDX[B]; + if(PX&&m==='fast')return pieFast(PX,fastSP,A,B,b,wLat); + if(m!=='scenic')return [{...walkI(m==='fast'?(fastSP[A]||(fastSP[A]=dijkstra(adj,Ai,wLat))).P:SPP[A],Ai,Bi),share:1}]; + const ek='l2:'+b.id,own=e=>(R.efg&&R.efg[e.id]&&R.efg[e.id].get(ek))||0; + const wf=e=>e.w*(1+10*(e.cap?Math.max(0,e.pl-own(e))/e.cap:0)); + const cost=r=>r.path.reduce((x,e)=>x+wf(e),0)*r.share; + const s1=dijkstra(adj,Ai,wf,null,Bi);if(s1.D[Bi]===Infinity)return [{...walkI(SPP[A],Ai,Bi),share:1}]; + const p1=walkI(s1.P,Ai,Bi),c1=cost({path:p1.path,share:1}),used=new Set(p1.path.map(e=>e.id));let pick2=[{...p1,share:1}]; + const s2=dijkstra(adj,Ai,wf,(v,e)=>used.has(e.id),Bi); + if(s2.D[Bi]!==Infinity){const p2=walkI(s2.P,Ai,Bi);if(cost({path:p2.path,share:1})<=c1*1.15)pick2=[{...p1,share:0.5},{...p2,share:0.5}];} + const key=b.id+'>'+A+'>'+B,old=R.l2route&&R.l2route[key];let out=pick2; + if(old&&old.every(r=>r.keys.every(k=>edges[k]))){const prev=old.map(r=>{const path=r.keys.map(k=>edges[k]);return {path,ni:r.ns.map(c=>CIDX[c]),share:r.share};}); + if(prev.reduce((x,r)=>x+cost(r),0)<=pick2.reduce((x,r)=>x+cost(r),0)*1.1)out=prev;} + R2.l2route[key]=out.map(r=>({keys:r.path.map(e=>e.id),ns:cityIds(r.ni),share:r.share}));return out;}; + (()=>{for(const b of S.biz){if(!BIZ_T[b.type].l2)continue; + // An SD-WAN is hub-and-spoke: one circuit from the first site to each of the others. + const pairs=b.sites?b.sites.slice(1).map(x=>[b.sites[0],x]):[[b.city,b.city2]];let minF=1,maxLat=0,tot=0,noPath=false; + for(let [A,B] of pairs){let amt=0; + // A circuit to a POP that reaches the backbone only by its own backhaul starts there (only its paths cross that edge). + if(PX&&PX.bh.length&&SPD[B]&&!(SPD[A]&&SPD[A][CIDX[B]]1)R2.l2split[b.id]=routes.length; + for(const {path,ni,share} of routes){let a=b.bw*share;for(const l of path)a=Math.min(a,l.res);for(const i of ni)if(HAS[i])a=Math.min(a,NRES[i]);a=Math.max(0,a);amt+=a;maxLat=Math.max(maxLat,path.reduce((x,e)=>x+e.lat,0)+path.length*0.05); + for(const i of ni)if(HAS[i])nodeTake(i,a); + for(const l of path){l.res-=a;l.ld+=a;carry(l,ek,NN+1,CIDX[B],a);}}} + else noPath=true; + minF=Math.min(minF,amt/b.bw);tot+=amt;} + R2.l2lat[b.id]=noPath?Infinity:maxLat;R2.l2[b.id]=b.bw*minF;R2.egT.l2=(R2.egT.l2||0)+tot; + // Same answer as diversePaths(), which would rebuild today's live links for every customer. + if((b.reqs||[]).includes('diverse')){const k=b.city+'>'+b.city2;R2.div[b.id]=divMemo[k]??(divMemo[k]=disjointI(b.city,b.city2));}}})(); + /* Floods ride the backbone ahead of everyone's traffic (25-ddos-flood.js). haul: up to g from city A to POP B over the + shortest path, as far as links and routers have room. What a scrubbing center sends back is the target's own clean + traffic, counted apart from the junk (#289). */ + const msOf=(A,B)=>{const Bi=CIDX[B],Ai=CIDX[A];return SPD[B]&&SPD[B][Ai]n+e.lat,0):0;}; + let JK=0;const haul=(A,B,g,ek,from,clean)=>{if(!(g>0))return 0;const Ai=CIDX[A],Bi=CIDX[B];if(!SPD[B]||!(SPD[B][Ai]e.pref==='low'?4:e.rank>0&&e.rank<3&&coneOf(e,n)?CONE_RANK:e.rank; + // LOCAL_PREF on an upstream moves it ahead of or behind the other transits, never ahead of peering (#96). + const eff=(e,n)=>{let r=base(e,n);if(TR){if(e.k==='t'&&TR.up[e.net])r=TR.up[e.net]==='prefer'?2.9:3.5;if(e.prep)r=4.4;if(e.k!=='c'&&TR.drain.has(e.city))r=4.6;const o=TR.net[n];if(o){if(o.prefer===e.k)r=0.5;else if(o.avoid===e.k)r=4.5;}}return r;}; + // A carrier's own port for traffic bound for it or for its customers (25-direct-egress.js): tried before plain transit, but + // never over RouteScript or a port set to backup, which keep the say they had, and not from a POP with a Prefer-marked + // transit port (PREFC), where Prefer keeps it. Such a port is also an ordinary transit exit (rank 3), so POPs without one of + // its own can still use it. DSEL: for each direct rank, the networks that have an exit there. + const DIR=directSetup(E,NC),PREFC=DIR.prefc,dirOf=DIR.dirOf,DSEL=new Map(); + const RANKS=TR?[0,0.5,1,2,CONE_RANK,2.9,2.92,2.93,2.94,2.95,3,3.5,4,4.4,4.5,4.6]:[0,1,2,CONE_RANK,2.92,2.93,2.94,2.95,3,4]; + // With `protect customers`, business flows take every rank first; home users get what is left. + // Passes by FBZ: 0 every flow, 1 business only, 2 the rest. + const PASSES=TR&&TR.protect?[1,2]:[0]; + // Each network's exits by the rank they route at (RouteScript can move an exit per network), in E's order. + // Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order. + // With several islands (POPs no backbone joins), each list is split by island: a flow only scans exits it can reach. + // Networks with the same exits at a rank share one list (LIST, by content), so what one flow learns serves them all. + // A kept build (XC) gives the same lists, made fresh for today's exits. + const LIST=new Map(),idx=exIdx,byRank={},BRJ=[],RSET=new Set();if(XC)rcExitLists(XC,E,BRJ,DSEL,RSET);else(()=>{for(let j=0;je.xi).join(','),o=LIST.get(key);if(o){m[r]=o;continue;} + let V=L;if(NCOMP>1){const cs=[];for(const e of L){const k=COMP[e.ci];if(k>=0)(cs[k]||(cs[k]=[])).push(e);}for(const s of cs)if(s)idx(s);V={cs};}else idx(L);LIST.set(key,V);m[r]=V;}} + if(RCH)rcExitKeep(XK,E,okBy,RCH,LIST,BRJ,DSEL,RSET,BHK);})(); + /* What each kind of exit served, in all (EGT) and per network (NEA, by network index and kind): numbers in typed arrays, + where a sum by key would box every new value. EGO and NEO keep the order each first got traffic, which is the order + R.egT and R.netEg list them in; both are written back after routing. NEG: each network's R.netEg record. */ + const EGT=new Float64Array(4),EGO=[],NEA=new Float64Array(NN*4),NEO=[],NEG=[]; + ROUTE.run({E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP, + TE,SPILL,TT,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff,SATN},PASSES,RANKS,RSET); + for(const i of NORD)R2.nodeLoad[CITIES[i].id]=NLOAD[i]; + for(const k of EGO)R2.egT[EXK[k]]=EGT[k];for(const j of NEO){const ne=NEG[j];for(let k=0;k<4;k++)ne[EXK[k]]=NEA[j*4+k];} + (()=>{ + if(DD){let rem=0,jf=0;for(let i=0;i1e-6)rem+=FREM[i];if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;} + ddosAfter(DD,{E,R2,squeeze:Math.min(rem,jf), + lost:(ci,x,y,e)=>{SRV[ci]-=x;R2.served-=x;const c=CITIES[ci].id;if(y)R2.bizSrv[c]-=y;R2.egT[e.k]-=x;if(e.rank<=2)R2.peered-=x;}});} + // R.satU only when a circuit is in the graph, so R stays as it was for networks without one. + const SATU=SATN?new Float64Array(NC):null;if(SATU){R2.satU={};satAfter(SE,LATP,SATU);} + for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i]; + if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);if(SATU&&SATU[i]>1e-9)R2.satU[c]=SATU[i];} + // Each city's slowest big exit: (path, source, exit) triples, one per path that went far, in the order they first did. + {const G=new Map();for(let k=0;kcur.g)R2.latFar[c]={to:CITIES[o.to].id,g:o.g,ms:o.ms,share:SRV[o.src]>0?o.g/SRV[o.src]:0};}} + // R.ef is read for the link you inspect: each edge's record is put together the first time it is asked for. Scenic + // routing only needs the egress amounts, so R.efg keeps those as they are (not listed, so R reads the same). + efBuild(R2,EL.map(l=>[l.id,l.i,l.tr]),ACN,ACD,NKN,NC,NN); + // Active links fill first, by capacity; standby links take what is left over. + for(const k in edges){const e=edges[k],ld=e.ld||0,ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;for(const l of e.links){const c=capOf(l);R2.load[l.id]=l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0);}} + for(const e of TORD){const m=R2.tNet[e.id]={},b=e.ts*NN;for(const j of TNK[e.ts])m[NET_IDS[j]]=TNA[b+j];} + R2.peerShare=R2.served>0?R2.peered/R2.served:0; + for(const e of E){if(e.k==='t')R2.useT[e.id]=(R2.useT[e.id]||0)+e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;}})(); + computeMoney(R2,PX); + // R.fl: from this call's own columns, made into objects only when something asks. + flDefine(R2,{NF,FREM,FCI,FNJ,FCA,FBZ,FGT,FGI,FGP,FGH,FTI,FII,E,CNB,NCN}); + R=R2;UI.hotMap=hotByCity(); +} +// What the network costs and earns per month, from what compute() routed. +function computeMoney(R2,PX=null){ + const C=R2.cost,V=R2.rev,pm=S.priceMul; + C.pops=Object.entries(S.pops).reduce((a,[c,p])=>a+popMo(c)+((p.routers||1)-1)*ROUTER_MO+cageMo(p.routers)+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0); + C.optical=S.links.filter(l=>l.kind==='df').reduce((a,l)=>a+(l.ready>S.day?0:ampCount(l.km)*AMP_MO*(l.own&&isRdm(l.sys)&&!l.sub?Math.max(1,l.pairs|0):1)+(l.regen|0)*REGEN_MO)+(l.spares?Math.round(150+(l.ch||[]).length*80):0),0); + C.links=S.links.reduce((a,l)=>a+(l.kind==='sat'?0:l.mo||0),0);{const m=satMoAll();if(m)C.sat=m;} + C.nni=(S.nni||[]).reduce((a,x)=>a+nniMo(x),0); + const htd=histToday();C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0,htd);R2.p95[t.id]=q;return a+transitMo(t,q);},0); + C.ix=Object.keys(S.ixp).reduce((a,c)=>a+ixMo(c),0); + C.pni=S.pni.reduce((a,p)=>a+pniMo(p,R2.usePni[p.id]||0),0); + C.caches=cachesMo(); + C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.model==='transit'?Math.round((C.transit||0)*(l.cut||0.3)):l.pay)+loanFees(l),0); + C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.ops&&S.ops.intern?INTERN_MO:0)+salesMo(); + if(S.pie&&S.mode!=='sandbox')C.pie=pieMo(); + V.eyeballs=0;V.business=0;V.ix=0; + C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c)*(R2.bbF[c]??1),v=R2.cityEye[c]*sf*EYE_RATE*arpuOf(c);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}} + const ids=linkIds();for(const b of S.biz){if(capPend(b)||BIZ_T[b.type].orbit)continue;const sf=BIZ_T[b.type].fiber?(fiberOk(b,ids)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city)*(R2.tgtF[b.id]??1);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);} + for(const c in S.myIx)V.ix+=S.myIx[c].members.length*MYIX_FEE; + wispMoney(R2,C,V); + ip4Money(C,V); + if(PX)pieMoney(PX,R2,V); + // The UK grant for Pitcairn, its satellite tier once orbit is known; the Rural Digital Pie Fund (99-pie-subsidies.js). + {const on=grantOn(R2),sky=!on&&!!PX&&grantSky(R2);V.grant=on?GRANT_MO:sky?GRANT_SKY_MO:0;if(PX)V.gov=pieGovMo();if(PX)R2.pie.gov={rdf:V.gov||0,sky:sky?GRANT_SKY_MO:0};} + // A late joiner's first year: home broadband matched (81-late-joiners.js), outside the investors' share like a grant. + lateMoney(V,C); + // Investors take their share of what customers and tenants pay (an IPv4 block leased out too, as a leased fiber pair), + // not of grants or one-off sales. + C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix+(V.orbit||0)+(V.ip4||0)+(V.wisp||0)); + R2.costMo=Object.values(C).reduce((a,b)=>a+b,0); + R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0)+(V.ip4||0)+(V.wisp||0)+(V.late||0); +} diff --git a/src/game/80-simulation/35-pie-paths.js b/src/game/80-simulation/35-pie-paths.js new file mode 100644 index 0000000..9126cf7 --- /dev/null +++ b/src/game/80-simulation/35-pie-paths.js @@ -0,0 +1,150 @@ +/* ---------- Pie in the Sky: routing through orbit (rules O2-O4, docs/plans/pie-in-the-sky.md) ---------- + compute() calls pieGraph() once, only when S.pie exists (saves without it pay one falsy check). It adds to the + routing graph, after the IGP shortest paths are known: + - a sky node per connected pie dish (a virtual city index past NC), joined to its POP by an uplink edge: the dish's + antennas (x rain, jamming… from pieDishes()) less what its terminals and backhaul use; latency one hop up, alt/c + 1 ms; + - with lasers (a crust over 40% lasered), a space edge between every two sky nodes at least PIE_MIN_KM apart, priced + along the great circle at the shell's height at c in vacuum, capacity the crust's (pieCap(): g x coverage, x the share a half-baked one carries) left after terminals. + Orbit edges have IGP weight Infinity: bulk IP traffic and scenic circuits never see them, only latency-routed + circuits (lat:true customers, route 'fast') do, and only where the sky is faster. Space edges under 3,000 km do not + exist, so orbit never beats fiber there (O4). A dish whose POP is not on the backbone's island is flagged (R.pie.isl) + and gets no sky node: it carries no transit (O3). A crust carries nothing under 40% and is not a hub; from + there it carries a share that grows to all of its capacity at 60% (pieCarry(), O2). + Backhaul (O3): a cut-off dish lifts its own POP's traffic, all of it, to a landing dish on the backbone: one virtual + edge, POP to landing POP ('pie:bh:'+city, e.bh), through a crust covering both (bent pipe within PIE_BENT km, lasers + past that). Its capacity is booked after terminals and before sky circuits: min(the dish's room, the landing dish's room, + the crust's room); its latency is the orbit path (pieSkyMs). Its IGP weight is Infinity like every orbit edge, so no + POP on the backbone ever routes through it; pieRelink() then reruns the shortest paths of that one POP with the edge at + PIE_BH_W (its other backhauls stay Infinity), and joins its island to the backbone's in COMP, so its flows see the + backbone's exits (further than any of its own: local exits first). The backbone's POPs keep their old paths, which do + not reach the island, so they skip its exits. Nothing of this runs when no dish is cut off, so routing is unchanged. + Terminal customers (BIZ_T[].orbit: pizza, flywifi, boat, marsorb) sit anywhere a baked crust covers, with no POP of + theirs; their traffic lands on a ground dish (bent pipe within PIE_BENT km, or lasers to any connected dish) and + enters the network there as business demand. Spats: pieSpatHome(cc) keeps a country's customers on its own dishes, + pieAirBlock(a,b) keeps country a's traffic off country b's dishes; both apply to backhaul as to terminals. */ +const PIE_C=300,PIE_RE=6371,PIE_MIN_KM=3000,PIE_BENT=1000,PIE_HOP=1,PIE_FOOT=3,PIE_LAT_PREM=0.5,PIE_BH_W=1e5; +const pieKm=(a,b)=>{const A=CITY[a],B=CITY[b];return hav(A.lon,A.lat,B.lon,B.lat);}; +// Does crust id cover city c? A shell reaches a few degrees past its inclination; a polar one reaches everywhere. +const pieCovers=(id,c)=>!!CRUSTS[id].polar||Math.abs(CITY[c].lat)<=CRUSTS[id].inc+PIE_FOOT; +const pieLased=id=>pieLiveLas(id)>CRUSTS[id].full*PIE_RAW; +// One way through space between two dishes km apart, at shell height alt: up, along the great circle, down. +const pieSkyMs=(km,alt)=>2*(alt/PIE_C+PIE_HOP)+km*(PIE_RE+alt)/PIE_RE/PIE_C; +// May a customer in country ca land on a dish in country dc? (spats) +const pieLandOk=(ca,dc)=>!(pieSpatHome(ca)&&dc!==ca)&&!pieAirBlock(ca,dc); +/* Where a terminal customer in city c lands: {k (index in ds), cr} or null. ds: dishes with .ok (on the backbone). + The nearest dish with room left (for all of bw if any has it) that a crust over c also covers: within PIE_BENT km (bent pipe, any dish), else with lasers on that + crust any dish on the backbone. Some customers need lasers (flywifi, marsorb: T.las). */ +function pieLand(c,t,ds,hubs,bw=0){const T=BIZ_T[t],cc=CITY[c].cc;let best=null,bk=Infinity; + for(const id of hubs){if(!pieCovers(id,c))continue;const las=pieLased(id);if(T.las&&!las)continue; + for(let k=0;k0&&(km<=PIE_BENT||(las&&d.ok))){const v=km+(d.ok?0:1)+(d.left=0)cnt.set(k,(cnt.get(k)||0)+1);} + let main=-1,mn=0;const hk=S.home&&S.pops[S.home]?COMP[CIDX[S.home]]:-1;for(const [k,n] of cnt)if(n>mn||(n===mn&&k===hk)){main=k;mn=n;}X.main=main; + for(const d of ds){const ci=CIDX[d.city];d.ok=COMP[ci]>=0&&COMP[ci]===main;d.left=d.g;if(!d.ok)X.isl.push(d.city);} + // Terminals first: each takes what its dish and its crust have left, in S.biz order. + if(hubs.length)for(const b of S.biz){const T=BIZ_T[b.type];if(!T.orbit)continue;const L=pieLand(b.city,b.type,ds,hubs,b.bw);if(!L)continue;const d=ds[L.k]; + const a=Math.max(0,Math.min(b.bw,d.left,X.cr[L.cr]));d.left-=a;X.cr[L.cr]-=a;X.term[b.id]=a;X.gs[b.id]=d.city;X.gsBw[d.city]=(X.gsBw[d.city]||0)+a;} + // Backhaul for cut-off POPs, after terminals and before sky circuits (see the top). + if(X.isl.length)for(const d of ds){if(d.ok)continue;const ci=CIDX[d.city];if(!adj[ci]||!pops.includes(d.city))continue;const L=pieBhLand(d,ds,hubs,X.cr); + if(L.why){X.bhNo.push({city:d.city,why:L.why});continue;} + const D=ds[L.k],a=Math.min(d.left,D.left,X.cr[L.cr]),li=CIDX[D.city];d.left-=a;D.left-=a;X.cr[L.cr]-=a;X.res[d.city]=(X.res[d.city]||0)+a;X.res[D.city]=(X.res[D.city]||0)+a; + const e={id:'pie:bh:'+d.city,a:d.city,b:D.city,ai:ci,bi:li,i:X.ne++,km:Math.round(L.km),cap:a,scap:0,w:Infinity,lat:L.ms,slat:Infinity,links:[],res:0,ld:0,tr:null,pl:0,jk:0,f:1,bh:{city:d.city,ci,land:D.city,cr:L.cr,las:L.las,km:L.km}}; + edges[e.id]=e;adj[ci].push([li,e]);adj[li].push([ci,e]);X.bh.push(e);} + const las=hubs.filter(pieLased).sort((a,b)=>CRUSTS[a].alt-CRUSTS[b].alt); + if(las.length){const sky=[]; + for(const d of ds){if(!d.ok||!(d.left>0))continue;const cs=las.filter(id=>pieCovers(id,d.city));if(!cs.length)continue;const ci=CIDX[d.city],n=NC+sky.length;adj[n]=[]; + const e={id:'pie:'+d.city,a:d.city,b:d.city,ai:ci,bi:n,i:X.ne++,km:0,cap:d.left,scap:0,w:Infinity,lat:CRUSTS[cs[0]].alt/PIE_C+PIE_HOP,slat:Infinity,links:[],res:0,ld:0,tr:null,pl:0,jk:0,f:1,sky:d}; + edges[e.id]=e;adj[ci].push([n,e]);adj[n].push([ci,e]);X.up.push(e);X.sk[n-NC]=d.city;sky.push({d,n,cs});} + for(let i=0;iq.cs.includes(id));if(!cs.length)continue;const cap=cs.reduce((a,id)=>a+X.cr[id],0);if(!(cap>0))continue; + const e={id:'pie:'+p.d.city+'~'+q.d.city,a:p.d.city,b:q.d.city,ai:p.n,bi:q.n,i:X.ne++,km:Math.round(km),cap,scap:0,w:Infinity,lat:km*(PIE_RE+CRUSTS[cs[0]].alt)/PIE_RE/PIE_C,slat:Infinity,links:[],res:0,ld:0,tr:null,pl:0,jk:0,f:1,sky:'las',cs}; + edges[e.id]=e;adj[p.n].push([q.n,e]);adj[q.n].push([p.n,e]);} + // Every Gbps through space goes up one dish and down another: the uplinks together carry at most twice what the crusts have left. + const room=2*las.reduce((a,id)=>a+X.cr[id],0),up=X.up.reduce((a,e)=>a+e.cap,0);if(up>room)for(const e of X.up)e.cap*=room/up;} + return X;} +/* Where cut-off dish d lands its POP's backhaul: {k (index in ds), cr, las, km, ms}, the fastest way down on the backbone, or + {why}: 'nocrust' (no baked crust over it), 'noland' (no dish on the backbone under that crust), 'nolas' (none within + PIE_BENT km and no lasers), 'spat' (the spats keep it off every dish in reach), 'full' (every dish or crust in reach is full). */ +const PIE_BH_WHY=['noland','nolas','spat','full']; +function pieBhLand(d,ds,hubs,cr){const cs=hubs.filter(id=>pieCovers(id,d.city));if(!cs.length)return {why:'nocrust'};let best=null,bm=Infinity,w=0; + for(const id of cs){const las=pieLased(id),alt=CRUSTS[id].alt; + for(let k=0;kPIE_BENT&&!las){w=Math.max(w,1);continue;}if(!pieLandOk(d.cc,L.cc)){w=Math.max(w,2);continue;} + if(!(L.left>0)||!(cr[id]>0)||!(d.left>0)){w=3;continue;} + const ms=pieSkyMs(km,alt);if(msPIE_BENT,km,ms};}}} + return best||{why:PIE_BH_WHY[w]};} +// compute(), only when some POP backhauls: that POP's shortest paths with its own backhaul edge, and its island on the backbone. +function pieRelink(X,SPD,SPP,SDi,SPi,COMP0){const isl=new Set(),COMP=COMP0.slice(); + for(const e of X.bh){const i=e.ai,r=dijkstra(X.adj,i,x=>x.bh?(x===e?PIE_BH_W:Infinity):x.w);SDi[i]=SPD[e.a]=r.D;SPi[i]=SPP[e.a]=r.P;isl.add(COMP[i]);} + for(let x=0;x!!e.bh&&e.bh.ci!==Ai:null; + if(!BIZ_T[b.type].lat||pieKm(A,B)!!e.sky||nb(e):(v,e)=>!!e.sky));return [{...walkI(r.P,Ai,Bi),share:1}];} + const r=fastSP[A]||(fastSP[A]=dijkstra(X.adj,Ai,wLat,nb?(v,e)=>nb(e):undefined));let w=walkI(r.P,Ai,Bi);if(!w.path.some(e=>e.sky))return [{...w,share:1}]; + const ca=CITY[A].cc,cb=CITY[B].cc,home=pieSpatHome(ca)||pieSpatHome(cb),bad=e=>e.sky!=='las'&&(pieAirBlock(ca,e.sky.cc)||pieAirBlock(cb,e.sky.cc)||(home&&e.sky.cc!==ca&&e.sky.cc!==cb)); + if(w.path.some(e=>e.sky&&bad(e)))w=walkI(dijkstra(X.adj,Ai,wLat,(v,e)=>!!e.sky&&bad(e)||!!nb&&nb(e),Bi).P,Ai,Bi); + if(w.path.some(e=>e.sky)){X.l2o[b.id]=1;X.l2p[b.id]={w,A,B};} + return [{...w,share:1}];} +// After routing: what orbit earns (terminals, a premium on circuits riding the sky, patchy-sky customers) and what each dish carries. +function pieMoney(X,R2,V){let rev=0;const sf={},flows=[]; + for(const b of S.biz){const T=BIZ_T[b.type]; + if(T.orbit){const a=X.term[b.id]||0,s=b.bw>0?a/b.bw*(X.gs[b.id]?sfOf(R2,X.gs[b.id]):0):0,v=b.bw*b.rate*Math.min(1,s/0.95);sf[b.id]=s;rev+=v; + flows.push({k:'t',id:b.id,type:b.type,city:b.city,dish:X.gs[b.id]||null,g:s*b.bw,rev:v});} + else if(X.l2o[b.id]&&T.l2){const g=R2.l2[b.id]||0,v=b.bw*b.rate*PIE_LAT_PREM*clamp(g/b.bw,0,1);rev+=v;flows.push(pieCircuit(X,b,g,v,R2.l2lat[b.id]));}} + // A dish's use: its terminals (what they took from d.left, not the backhaul booked there), then what crossed its edges. + const used={},term={},bhG={};for(const d of X.ds){const t=d.g-d.left-(X.res[d.city]||0);used[d.city]=t;term[d.city]=t;}for(const e of X.up)used[e.sky.city]+=e.ld||0; + const bh=[];for(const e of X.bh){const g=e.ld||0,b=e.bh;used[e.a]+=g;used[e.b]+=g;bhG[e.a]=(bhG[e.a]||0)+g;bhG[e.b]=(bhG[e.b]||0)+g; + bh.push({city:e.a,land:e.b,g,cap:e.cap,ms:e.lat,cr:b.cr,las:b.las,km:e.km});flows.push({k:'b',id:'bh:'+e.a,city:e.a,dish:e.b,g,cap:e.cap,ms:e.lat,cr:b.cr,hops:pieBhHops(e,true)});} + for(const o of X.bhNo)bh.push({city:o.city,land:null,g:0,cap:0,why:o.why}); + // Patchy-sky customers (99-pie-patchy.js): a revenue line before a crust carries anything, handed over as it does. + const patchy=piePatchy(X.ds);rev+=patchy.mo; + // The billing database is down (the Founder's antics, 99-pie-jitters.js): the sky carries on, nobody is invoiced. + const billOff=pieBillOff()?rev:0;if(billOff)rev=0; + V.orbit=rev;R2.pie={rev,billOff,patchy,sf,gs:X.gs,isl:X.isl,used,term:X.gsBw,hubs:X.hubs,sky:X.up.length,flows,bh,...pieLoads(X,flows,used,term,bhG)}; + // For the lazy fiber comparison (pieFiberMs): the graph of this compute, kept out of JSON. + Object.defineProperty(R2.pie,'_x',{value:{adj:X.adj,fm:{}}});} +// A sky circuit for the Traffic tab and the traceroute: entry and exit, the dishes it lands at, and each hop through space. +// Hops in order from A: 'f' fiber to a city, 'up' to the crust at a dish, 'las' across space, 'down' at a dish; ms one way. +function pieCircuit(X,b,g,v,ms){const {w,A,B}=X.l2p[b.id],path=w.path.slice().reverse(),ni=w.ni.slice().reverse(),hops=[],via=[];let cr=null; + path.forEach((e,i)=>{const to=ni[i+1];if(e.bh){for(const h of pieBhHops(e,CITIES[to].id===e.bh.land))hops.push(h);}else if(e.sky==='las'){if(!cr)cr=e.cs[0];hops.push({k:'las',km:e.km,ms:e.lat,cr:e.cs[0]});} + else if(e.sky){if(to>=X.nc){hops.push({k:'up',city:e.sky.city,ms:e.lat});}else{hops.push({k:'down',city:e.sky.city,ms:e.lat});}} + else hops.push({k:'f',city:CITIES[to].id,ms:e.lat,id:e.id});}); + for(const h of hops)if(h.k==='down'||h.k==='up'){via.push(h.city);h.cr=h.cr||cr;} + return {k:'c',id:b.id,type:b.type,a:A,b:B,via:[...new Set(via)],hops,cr,g,ms:isFinite(ms)?ms:null,rev:v};} +// Load per crust and per dish, and why a dish carries nothing. Crust use: terminals took theirs from X.cr; each sky circuit +// is counted once, on the crusts of its first laser hop, never past what they hold. +function pieLoads(X,flows,used,term,bhG){const P=S.pie,cu={},crust=[],dish=[],load={}; + // Backhaul booked its capacity from X.cr; count what it carried instead. + const bx={};for(const e of X.bh){const id=e.bh.cr;bx[id]=(bx[id]||0)+Math.min(e.cap,e.ld||0)-e.cap;} + for(const f of flows)if(f.k==='c'&&f.g>0){let r=f.g;const e=X.l2p[f.id].w.path.find(x=>x.sky==='las');for(const id of e?e.cs:[]){const t=Math.min(r,Math.max(0,X.cr[id]-(cu[id]||0)));cu[id]=(cu[id]||0)+t;r-=t;}} + for(const id in CRUSTS){if(!(pieLive(id)>0))continue;const cv=pieCov(id),hub=X.hubs.includes(id),pot=hub?pieCap(id):CRUSTS[id].g*cv; + crust.push({id,cov:cv,pot,cap:hub?pot:0,used:hub?Math.min(pot,pot-X.cr[id]+(cu[id]||0)+(bx[id]||0)):0,las:hub&&pieLased(id),st:hub?(pieBaked(id)?'ok':'part'):!(pieCarry(id)>0)?'half':P.safe?'safe':'down'});} + const ok=new Map(X.ds.map(d=>[d.city,d])),isl=new Set(X.isl),las=X.hubs.filter(pieLased),bh=new Set(X.bh.map(e=>e.a)); + for(const x of P.dishes){const c=x.city,d=ok.get(c),tm=d?term[c]:0,u0=d?used[c]:0,cap=d?d.g:0,cc=CITY[c].cc,l=P.lic[cc];let st; + if(!S.pops[c])st='nopop';else if(x.down>S.day)st='down';else if(!d)st=l&&l.until>S.day&&l.state==='sus'?'spat':l&&l.until>S.day&&l.state==='refused'?'ref':'lic'; + else if(!X.hubs.some(id=>pieCovers(id,c)))st='nocrust';else if(isl.has(c))st=bh.has(c)?'backhaul':'isl';else if(u0>1e-9)st='ok'; + else if(pieIncOf('pierain',c))st='rain';else if(P.spat.jam&&(P.spat.jam.cc===cc||P.spat.jam.cc2===cc))st='jam'; + else st=las.some(id=>pieCovers(id,c))?'idle':'nolas'; + const u=cap>0?Math.min(1,u0/cap):0;load[c]=u;const b=d?bhG[c]||0:0;dish.push({city:c,cap,term:tm,bh:b,transit:Math.max(0,u0-tm-b),used:u0,u,st});} + return {crust,dish,load};} +// Fiber-only latency of a sky circuit, for "orbit 26 ms vs fiber 29 ms": worked out only when asked (the Traffic tab), once +// per compute. Infinity when no fiber path exists. +function pieFiberMs(f){const P=R&&R.pie,x=P&&P._x;if(!x||!f||f.k!=='c')return Infinity;if(f.id in x.fm)return x.fm[f.id]; + const Ai=CIDX[f.a],Bi=CIDX[f.b],r=dijkstra(x.adj,Ai,e=>e.lat+0.05,(v,e)=>!!e.sky||!!e.bh,Bi);let ms=Infinity; + if(r.D[Bi]a+e.lat,0)+w.path.length*0.05;}return x.fm[f.id]=ms;} +// What the network could sell from orbit today (offers, F3 spirit): a city a baked crust covers and a dish with room left +// can land; read from the last compute (R.pie), never computed here. +function pieServe(c,t){if(!S.pie||!R||!R.pie)return null;const ds=pieDishes();if(!ds.length)return null;const isl=new Set(R.pie.isl);for(const d of ds){d.ok=!isl.has(d.city);d.left=d.g-(R.pie.term[d.city]||0);}return pieLand(c,t,ds,R.pie.hubs.filter(pieUp));} +// Book what orbit earned, day by day. +PIE_ON.day.push(()=>{if(R&&R.pie&&R.pie.rev>0)S.pie.book.earned+=R.pie.rev/30;}); diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js new file mode 100644 index 0000000..778eabc --- /dev/null +++ b/src/game/80-simulation/40-billing.js @@ -0,0 +1,23 @@ +// The last 29 days plus today. Once dayTick() has written today into t.hist (S.hist then ends on today too), that +// sample is today's own: leave it out, or every recompute later that day counts today twice and drops a day. +const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;}; +function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} +const gulfPair=(a,b)=>!!((CITY[a].qa&&(CITY[b].gcc||CITY[b].uae))||(CITY[b].qa&&(CITY[a].gcc||CITY[a].uae))); +// A link a closed border has taken dark ('runet', 'gulf' or ''): no repair for it, so the panels name it instead (#329). +const borderShut=l=>S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b)?'runet':S.ev.gulf>S.day&&gulfPair(l.a,l.b)?'gulf':''; +// Cut, or cut off by an event between its two countries, whatever runs on it (an express asks this of each fiber it rides). +function linkCut(l){return l.cut>S.day||!!borderShut(l);} +function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&!dfOn(l))||(l.kind==='xp'&&xpDown(l))||(l.kind==='sat'&&(l.ready>S.day||leoDown(l)));} +function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);} +function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);} +// Monthly price of one connection; compute() sums these, the connections overview lists them. +function transitMo(t,q){const n=t.n||1;return Math.max(q,PORT[t.tier].g*n*0.2)*transitPerG(NET[t.net],t.city,premOn(t))*S.priceMul+PORT[t.tier].tmo*n+(t.clean?cleanMo(t):0)+krFee(t,q);} +// Sender pays (Gangnam Style Peering): on top of the price, every Gbps delivered into Korea (95th percentile). +const krFee=(t,q)=>CITY[t.city].kr&&scnRule('sender')?Math.round(q*KR_FEE):0; +function pniMo(p,use){if(!pniOn(p))return 0;return (p.g1?Math.round(PORT[0].pni/2):PORT[p.tier].pni)*(p.n||1)+(NET[p.net].pol==='paid'&&!paidFree(NET[p.net])?NET[p.net].paidFee:0)+(NET[p.net].perG?Math.round(NET[p.net].perG*use):0);} +function ixMo(c){return S.myIx[c]?Math.round(myFab(c).mo*((S.ixSite||{})[c]==='ab'?1.5:1)):ixPortMo(c,S.ixp[c])*((S.ixn||{})[c]||1)+dkAddonMo(c);} +function nniPort(c,prov){return (S.nni||[]).find(x=>x.city===c&&x.prov===prov);} +// What a fabric port can book: its speed times its members, a LAG at 95% like every bundle (lagCap). +function nniCap(pt){return pt&&NNI[pt.tier]?lagCap(NNI[pt.tier].g,pt.n):0;} +const nniMo=x=>NNI[x.tier]?NNI[x.tier].mo*(x.n||1):0; +function repayCost(l,B){return B.equity?Math.round(l.amount*3):Math.round(Math.max(l.bal,B.crypto&&l.got?l.got:0)*1.02);} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js new file mode 100644 index 0000000..864147a --- /dev/null +++ b/src/game/80-simulation/50-sanitize.js @@ -0,0 +1,146 @@ +const own=(o,k)=>Object.prototype.hasOwnProperty.call(o,k); +const isCity=c=>typeof c==='string'&&own(CITY,c),isIx=x=>typeof x==='string'&&(own(CITY,x)||own(XIXM,x)),isNet=n=>typeof n==='string'&&own(NET,n); +const num=(v,d=0)=>{v=+v;return Number.isFinite(v)?v:d;},int=(v,lo,hi,d)=>{v=Math.round(num(v,d));return Math.min(hi,Math.max(lo,v));}; +/* Saves come from localStorage or from imported files, so treat them as untrusted: fill in anything + missing, drop references to cities, networks or types that do not exist, and force numbers to be numbers. */ +function sanitize(s){ + // A puzzle is never saved; a save that says otherwise is played as a normal game. + if(s.mode==='puzzle')s.mode='normal';delete s.pz; + const arr=k=>{if(!Array.isArray(s[k]))s[k]=[];},obj=k=>{if(!s[k]||typeof s[k]!=='object'||Array.isArray(s[k]))s[k]={};}; + ['links','nni','transit','pni','caches','biz','offers','inc','usedNames','loans','loanOffers','hist','log'].forEach(arr); + ['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach','pairMet'].forEach(obj); + s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.day0=int(s.day0,0,s.day,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000); + s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0); + for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'||k==='ddT'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);} + for(const k of ['survived','incidents','peak'])s.stats[k]=num(s.stats[k],0); + // The chaos monkey (2.0): saves without one get their first visit scheduled on the next day tick. + {const m=s.monkey&&typeof s.monkey==='object'&&!Array.isArray(s.monkey)?s.monkey:{},on=m.on?1:0,o={next:m.next==null?null:int(m.next,0,1e7,s.day+90),on}; + if(on){o.start=int(m.start,0,s.day,s.day);o.until=int(m.until,o.start,o.start+400,s.day+30);o.snip=int(m.snip,0,1e7,s.day+3);o.n=int(m.n,0,1e4,0);o.hurt=int(m.hurt,0,o.n,0);o.c=isCity(m.c)?m.c:isCity(s.home)?s.home:null;} + s.monkey=o;} + for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object'){p.bb.d=num(p.bb.d,0);ip6Fix(p.bb,s.day);}else p.bb=null;} + if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; + opsSanitize(s); + const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),plag=v=>int(v,1,PNI_LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); + s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);if(l.list!==undefined){const L=l.kind==='df'?cmClean(l.list):null;if(L)l.list=L;else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss){const g=l.loss.glass===true;l.loss=deg(l.loss);if(g&&l.loss)l.loss.glass=true;}return l;}); + for(const l of s.links)repairSubUpgradeDates(l,s.day); + xpSanitize(s); + /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its + links, with all of them carrying traffic, so the pair keeps that metric and nothing goes on standby. */ + {const pm=s.pairMet,lo={};for(const l of s.links){if(l.metric!==undefined){const k=edgeKey(l),m=own(MET,l.metric)?l.metric:'normal';if(!lo[k]||MET[m].fv&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null; + s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.lacp=degO(t.lacp),t.site=['a','b','ab'].includes(t.site)?t.site:'a',t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t.clean=!!t.clean,t.carry===true||delete t.carry,t.premium=premOnlyAt(NET[t.net],t.city)||!!t.premium&&premCity(NET[t.net],t.city),t)); + s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=plag(x.n),x.sacrif=!!x.sacrif,x)); + // PNIs on order (#…): delivery day, a pending augment, and 1G for the one network that sells it + for(const x of s.pni){if(x.ready!==undefined)x.ready=num(x.ready,0);if(x.g1)x.g1=x.tier===0&&x.net==='dtk'?true:undefined;else delete x.g1;if(x.up){const u=x.up;x.up=u&&typeof u==='object'?{tier:tier(u.tier),n:plag(u.n),ready:num(u.ready,0),g1:!!u.g1&&x.net==='dtk'&&tier(u.tier)===0,...(u.site==='ab'?{site:'ab'}:{})}:undefined;if(!x.up)delete x.up;}} + // Supply chain: a shortage and a price lock, both optional. + {const H=s.hw&&typeof s.hw==='object'&&!Array.isArray(s.hw)?s.hw:{},o={};const sh=H.shock,lk=H.lock; + if(sh&&typeof sh==='object'&&own(HW_SHOCK,sh.k))o.shock={k:sh.k,until:num(sh.until,0),mul:clamp(num(sh.mul,1),1,2)}; + if(lk&&typeof lk==='object')o.lock={until:num(lk.until,0),mul:clamp(num(lk.mul,1),1,HW_CAP)};s.hw=o;} + // 2.0 replaced the peering inbox with the peering desk: keep the policy, drop the mail, max-prefix state and the AI. + {const I=s.inbox&&typeof s.inbox==='object'&&!Array.isArray(s.inbox)?s.inbox:{},pol=s.ppol!==undefined?s.ppol:I.pol;s.ppol=PPOL.includes(pol)?pol:'open';delete s.inbox; + const wk=(x,rep)=>{if(!x||typeof x!=='object'||Array.isArray(x))return null;const o={w:int(x.w,0,1e7,0),a:int(x.a,0,1e5,0),d:int(x.d,0,1e5,0),ix:[...new Set((Array.isArray(x.ix)?x.ix:[]).filter(isIx))].slice(0,PDESK_IX)};if(rep)o.p=PPOL.includes(x.p)?x.p:'open';return o;}; + s.pdesk=wk(s.pdesk);s.pdeskRep=wk(s.pdeskRep,1);} + {const sp={};if(s.spares&&typeof s.spares==='object')for(const k in s.spares)if(own(OPT,k)){const v=Math.floor(+s.spares[k]);if(v>0)sp[k]=Math.min(999,v);}s.spares=sp;} + s.caches=s.caches.filter(x=>x&&isCity(x.city)&&isNet(x.net)&&NET[x.net].cache).map(x=>(x.id=sid(x.id),x.site=x.site==='b'&&s.pops[x.city]&&s.pops[x.city].site2?'b':'a',x.g===CACHE_BIG?x.g=CACHE_BIG:delete x.g,x)); + for(const c of Object.keys(s.ixp)){if(!isIx(c))delete s.ixp[c];else s.ixp[c]=tier(s.ixp[c]);} + // DE-Kicks personal prices: only numbers, and none above the ceiling (older saves compounded them without one). + if(s.dk&&typeof s.dk==='object'){const dk=s.dk;for(const k of ['m','lastQ'])if(dk[k]&&typeof dk[k]==='object'){for(const c of Object.keys(dk[k])){const v=k==='m'?dk[k][c]:dk[k][c]&&dk[k][c].m; + if(!(typeof v==='number'&&v>0&&isFinite(v)))delete dk[k][c];else if(k==='m')dk.m[c]=Math.min(v,DK_MAX);else dk.lastQ[c].m=Math.min(v,DK_MAX);}}else if(k==='m')dk.m={};} + for(const k of ['rs','ixn','ixPref','ixSite'])for(const c of Object.keys(s[k]))if(!isIx(c))delete s[k][c];if(s.ixCut&&typeof s.ixCut==='object'){for(const c of Object.keys(s.ixCut))if(!isIx(c))delete s.ixCut[c];else s.ixCut[c]=Math.min(1,Math.max(0.6,num(s.ixCut[c],1)));}else delete s.ixCut; + for(const c of Object.keys(s.ixn))s.ixn[c]=lag(s.ixn[c]);for(const c of Object.keys(s.ixSite))if(!['a','b','ab'].includes(s.ixSite[c]))s.ixSite[c]='a'; + for(const k of Object.keys(s.peers)){const [n,c]=k.split('@');if(!isNet(n)||!isIx(c))delete s.peers[k];} + for(const c of Object.keys(s.myIx)){const m=s.myIx[c];if(!isCity(c)||!m||typeof m!=='object'){delete s.myIx[c];continue;}m.members=Array.isArray(m.members)?m.members.filter(isNet):[];m.name=String(m.name||tr('common.your_ix')).slice(0,40);m.next=num(m.next,s.day);m.fab=int(m.fab,0,MYIX_FAB.length-1,0);} + const okBiz=b=>b&&own(BIZ_T,b.type)&&(!BIZ_T[b.type].nni||own(FAB,b.prov))&&isCity(b.city)&&(!b.city2||isCity(b.city2))&&(!b.sites||Array.isArray(b.sites)&&b.sites.every(isCity)); + const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;if(b.pin!==undefined){const p=b.pin;if(!Array.isArray(p)||p.length<2||p.length>64||!p.every(isCity)||new Set(p).size!==p.length||!BIZ_T[b.type].l2||b.sites||p[0]!==b.city||p[p.length-1]!==b.city2)delete b.pin;}return b;}; + {const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>clFix(s,unpackBiz(fixBiz(b),ids)));}s.offers=s.offers.filter(okBiz).map(fixBiz); + // Contracts (#178): the bandwidth market an offer was priced in, who referred it, and the month-by-month tally. + for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);salesFix(s); + // Sponsorships and capacity conferences (#168): registrations are true or 'sp', the glow and the pending deals are checked. + for(const k of Object.keys(s.confReg))s.confReg[k]=s.confReg[k]==='sp'?'sp':!!s.confReg[k]; + if(s.conf){const c=s.conf;if(typeof c!=='object'||!own(REG,c.reg))s.conf=null;else s.conf={until:num(c.until,0),reg:c.reg,name:String(c.name||'').slice(0,40),sp:!!c.sp};} + // The backbone's technology: a save from before it with Auto-TE bought keeps the old rules on RSVP-TE (legacy). + // The build standard (#240): a router model and how many, and since then every other target; odd values read as "keep". + popStdSanitize(s); + // POP standards by kind (#315): micro, medium, regional hub, and which POP is which. + ptSanitize(s); + {const c=s.core&&typeof s.core==='object'?s.core:null,lv=c?int(c.lv,0,4,0):(s.te?2:0);s.core={lv,run:c?int(c.run,0,lv,lv):lv};if(c?c.legacy===true:!!s.te)s.core.legacy=true;if(c&&c.lab===true)s.core.lab=true;if(c&&c.since!==undefined)s.core.since=num(c.since,0);} + s.capDeal=s.capDeal&&typeof s.capDeal==='object'&&own(CAP_ROUTES,s.capDeal.c)?{at:num(s.capDeal.at,0),c:s.capDeal.c}:null; + s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.type==='maxpfx'&&(i.type='ixloop'),i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i)); + // Cable ships (85-incidents/50-cable-ships.js): voyages of known ships, and what a subsea cut knows about its ship. + {const F=s.fleet&&typeof s.fleet==='object'&&!Array.isArray(s.fleet)?s.fleet:{},o={}; + for(const id of Object.keys(F)){const f=F[id];if(!own(SHIP,id)||!f||typeof f!=='object')continue;const n=k=>num(f[k],s.day); + const v={inc:typeof f.inc==='string'?f.inc.slice(0,40):null,link:typeof f.link==='string'?f.link.slice(0,40):'',t:clamp(num(f.t,0.5),0,1),e:f.e==='b'?'b':'a',dep:n('dep'),arr:n('arr'),done:n('done'),back:n('back'),fx:num(f.fx,0),fy:num(f.fy,0)}; + if(f.rs!=null){v.rs=n('rs');v.rt=clamp(num(f.rt,0),0,1);}v.arr=Math.max(v.arr,v.dep);v.done=Math.max(v.done,v.arr);v.back=Math.max(v.back,v.done);if(v.back>s.day)o[id]=v;} + s.fleet=o; + for(const i of s.inc){if(i.type!=='cut'||i.st==null){for(const k of ['ship','seaq','st','sw','sp','sl'])delete i[k];continue;} + i.st=clamp(num(i.st,0.5),0.03,0.97);i.sw=int(i.sw,1,30,4);i.sp=int(i.sp,0,60,0);i.sl=typeof i.sl==='string'?i.sl.slice(0,40):'';i.rushed=!!i.rushed||undefined; + if(i.ship!=null&&!(own(SHIP,i.ship)&&o[i.ship]&&o[i.ship].inc===i.id))i.ship=null;if(i.ship==null){i.ship=null;i.seaq=1;}else delete i.seaq;} + for(const l of s.links)if(l.ship2&&l.kind==='df'&&l.own&&l.sub)l.ship2=1;else delete l.ship2; + // A lay ship held by a delay (#322): only on your own subsea cable still being laid. + for(const l of s.links){const v=l.lay;if(v===undefined)continue;if(!(v&&typeof v==='object'&&!Array.isArray(v)&&l.kind==='df'&&l.own&&l.sub&&l.ready>s.day)){delete l.lay;continue;} + const t=Math.round(clamp(num(v.t,s.day),0,l.ready));l.lay={s:Math.round(clamp(num(v.s,s.day),0,Math.min(s.day,t))),q:clamp(num(v.q,0),0,1),t};}} + s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));for(const l of s.loans){if(l.model!==undefined&&!['balloon','storm','transit','astro'].includes(l.model))delete l.model;for(const k of ['apr0','cut','share'])if(l[k]!==undefined&&!isFinite(+l[k]))delete l[k];if(!Array.isArray(l.covs))l.covs=[];l.covs=l.covs.filter(c=>own(COVS,c));}s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank)); + s.usedNames=[...new Set(s.usedNames.filter(x=>typeof x==='string'))];s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&e.o.a==='inbox'?{a:'tab',v:'nets'}:e&&e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'||e.o.a==='ip4'||e.o.a==='ops'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null; + return {id:typeof e.id==='string'&&e.id.length<=40?e.id:uid(),d:num(e.d,0),t:e.t.slice(0,600),h:typeof e.h==='string'?e.h.slice(0,200):'',k:LOG_KINDS.includes(e.k)?e.k:'',at:Number.isFinite(+e.at)?+e.at:0,o,n:int(e.n,1,9999,1)};}); + // One scrubbing center became a list (#117): older saves carry theirs over. + if(!Array.isArray(s.scrubs))s.scrubs=s.scrubAt&&isCity(s.scrubAt)?[{city:s.scrubAt,tier:s.scrubTier}]:[];delete s.scrubAt;delete s.scrubTier; + {const seen=new Set();s.scrubs=s.scrubs.filter(x=>x&&typeof x==='object'&&isCity(x.city)&&s.pops[x.city]&&!seen.has(x.city)&&seen.add(x.city)).map(x=>({city:x.city,tier:int(x.tier,0,SCRUB_TIERS.length-1,0)}));} + s.scrubMode=s.scrubMode==='ondemand'?'ondemand':'always'; + {const A=s.ddosAuto&&typeof s.ddosAuto==='object'?s.ddosAuto:{};s.ddosAuto={rtbh:A.rtbh===true,scrub:A.scrub!==false};} + if(s.stats&&s.stats.ddT&&typeof s.stats.ddT==='object')s.stats.ddT={port:s.stats.ddT.port?1:0,fs:s.stats.ddT.fs?1:0,rtbh:s.stats.ddT.rtbh?1:0};else if(s.stats)delete s.stats.ddT; + // Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it. + // An attack whose POP or customer went during the day stays as it is: the next morning ends it (ddosExpire), as in play. + const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!own(DDOS_VEC,a.vec))return null; + a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+Math.ceil(7*SPICY_LONG)); + // Attacks before 2.2 hit a city and came in on one port: they now hit someone in it, and spread (#242). + delete a.entries;delete a.entry;delete a.ixbh;delete a.fresh; + if(typeof a.tgt!=='string'||a.tgt.length>40||own(Object.prototype,a.tgt)||(a.tgt.startsWith('bb:')&&a.tgt!=='bb:'+a.city)){ + const bs=s.biz.filter(b=>b.city===a.city&&BIZ_T[b.type]&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber).sort((x,y)=>(DD_W[y.type]||1)-(DD_W[x.type]||1)||y.bw-x.bw);a.tgt=bs.length?bs[0].id:'bb:'+a.city;} + a.carpet=!!a.carpet;a.sac=a.sac?1:0;a.colMax=clamp(num(a.colMax,0),0,1);if(a.worst!==undefined)a.worst=clamp(num(a.worst,1),0,1); + if(a.eng!==undefined){a.eng=num(a.eng,a.start);a.eng=Math.max(a.start,Math.min(s.day,a.eng));} + if(a.who!==undefined&&!FLOOD_WHO.includes(a.who))delete a.who; // a label from the list, never text from the file + a.sla=Array.isArray(a.sla)?a.sla.filter(x=>typeof x==='string').slice(0,s.biz.length):[];return a;}; + const attacks=[s.ev.ddos,...(Array.isArray(s.ev.ddosMore)?s.ev.ddosMore:[])].map(repairAttack).filter(Boolean).slice(0,14); + if(attacks.length)s.ev.ddos=attacks[0];else delete s.ev.ddos;s.ev.ddosMore=attacks.slice(1); + s.ddosStarts=(Array.isArray(s.ddosStarts)?s.ddosStarts:attacks.map(a=>a.start)).filter(d=>typeof d==='number'||typeof d==='string').map(Number).filter(d=>Number.isFinite(d)&&d>s.day-7&&d<=s.day).sort((a,b)=>a-b).slice(-14); + s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews; + // Badges: S.ach[id] is the day it was earned (any save); S.achP[id] the variant (2.0). A missing variant is the standard one. + for(const k of Object.keys(s.ach))s.ach[k]=num(s.ach[k],0); + {const p=s.achP&&typeof s.achP==='object'&&!Array.isArray(s.achP)?s.achP:{};s.achP={};for(const k of Object.keys(s.ach))s.achP[k]=typeof p[k]==='string'&&own(BVAR,p[k])?p[k]:'oncall';} + if(s.merged){const o={};if(typeof s.merged==='object')for(const m of MERGERS)if(isFinite(s.merged[m.id]))o[m.id]=+s.merged[m.id];s.merged=Object.keys(o).length?o:undefined;} + /* The rules (2.0) follow from the mode, as the doors set them, and nothing else: a save without them is the classic + game, On-call. Scenarios and the weekly run on On-call; a sandbox keeps only its chaos; a Normal game one of the + three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */ + {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; + const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} + specSanitize(s);mpSanitize(s);lcSanitize(s); + cmFix(s); + pieSanitize(s);pieIncFix(s);volFix(s); + ip4Fix(s); + satSanitize(s);wispSanitize(s); + if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} + return s;} +function migrate(s){sanitize(s); + // Older saves have one contract per broker sale: fold a carrier's alien waves on one fiber into one contract. + {const one=new Map();s.biz=s.biz.filter(b=>{if(b.type!=='wwave')return true;const k=b.link+'|'+b.name,a=one.get(k);if(!a){one.set(k,b);return true;} + a.slots=(a.slots||0)+(b.slots||0);a.rate=(a.rate||0)+(b.rate||0);a.since=Math.min(a.since??0,b.since??0);a.mood=Math.min(a.mood??100,b.mood??100);a.folded=true;return false;}); + for(const a of one.values())if(a.folded){delete a.folded;const l=s.links.find(x=>x.id===a.link);if(l)a.what=wwWhat(l,a.slots);}}if(s.scn&&s.scn.id==='stg'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.local=true;if(s.scn&&s.scn.id==='gangnam'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.sender=true; + // A published weekly scenario keeps its file in the save: checked again here; a bad one plays on as the in-browser weekly. + if(s.scn&&typeof s.scn==='object'&&s.scn.wk!==undefined){const d=wsValid(s.scn.wk,s.scn.key);if(d){s.scn.wk=d;s.scn.home=d.city;s.scn.run=Number.isInteger(s.scn.run)&&s.scn.run>=0?s.scn.run:0;}else{delete s.scn.wk;delete s.scn.home;delete s.scn.run;}} + for(const b of [...s.biz,...s.offers])if(Array.isArray(b.reqs))b.reqs=b.reqs.filter(k=>!REQS[k]||!REQS[k].can||(isCity(b.city)&&(!b.city2||isCity(b.city2))&&REQS[k].can(b,s)));if(s.ltv!==2){for(const l of s.links)if(l.kind==='wave'&&l.tier>=3)l.tier=Math.min(LT.length-1,l.tier+1);s.ltv=2;}if(s.dk){s.dk.m=s.dk.m||{};s.dk.add=s.dk.add||{};s.dk.ret=s.dk.ret||{};s.dk.retUsed=s.dk.retUsed||{};}s.hist=s.hist||[];s.loans=s.loans||[];s.loanOffers=s.loanOffers||[];s.loanStrikes=s.loanStrikes||0;for(const l of s.links||[])if(!l.kind)l.kind='wave'; + for(const c in s.pops){const p=s.pops[c];if(p.rgen===undefined){let g=0;const need=(i,key)=>{const k=RG.findIndex(r=>r[key]>=i);if(k>g)g=k;}; + for(const l of s.links||[])if((l.a===c||l.b===c)&&l.kind==='wave')need(l.tier,'maxLT'); + for(const t of s.transit||[])if(t.city===c)need(t.tier,'maxP');for(const x of s.pni||[])if(x.city===c)need(x.tier,'maxP');if(s.ixp&&s.ixp[c]!==undefined)need(s.ixp[c],'maxP');p.rgen=g;}}for(const b of s.biz||[])if(!b.reqs)b.reqs=BIZ_T[b.type]&&BIZ_T[b.type].div?['diverse']:[];for(const o of s.offers||[])if(!o.reqs)o.reqs=[];if(!s.lvl)s.lvl=1;s.nni=(Array.isArray(s.nni)?s.nni:[]).filter(x=>x&&own(FAB,x.prov)&&isCity(x.city)&&Number.isInteger(x.tier)&&!!NNI[x.tier]);for(const x of s.nni){const n=Math.floor(+x.n||1);if(n>1)x.n=Math.min(LAG_MAX,n);else delete x.n;}s.cnLic=s.cnLic||{state:'none'};s.ev=s.ev||{};for(const l of s.links){if(!l.kind)l.kind='wave';if(l.mo===undefined)l.mo=Math.round(waveMo(l.km,l.sub,l.tier)*(l.mult||1));}for(const c in s.pops){if(!s.pops[c].routers)s.pops[c].routers=1;} + {const all=NETS.map(n=>n.id),seen=Array.isArray(s.seen)?s.seen.filter(x=>typeof x==='string'):null,fresh=seen?all.filter(id=>!seen.includes(id)):all; + if(fresh.length&&s.day>s.day0){const g=s.grace&&s.grace.until>s.day?s.grace:{nets:[]};s.grace={until:s.day+GRACE_DAYS,nets:[...new Set(g.nets.concat(fresh))],fresh:seen?fresh.length:0};} + s.seen=all;} + // Australian pricing and peering changed in place (#148): a save that was already there gets told once. + if(s.auV!==1){if((s.day||0)>0&&Object.keys(s.pops).some(c=>CITY[c].au))s.auNews=true;s.auV=1;} + // Months were 30 days before #257: the intern's budget month counts calendar months now, so it does not reset early. + if(s.calV!==1){if(s.ops&&s.ops.mon===Math.floor((s.day||0)/30))s.ops.mon=monthIdx(s.day||0);s.calV=1;} + if(s.grace&&(typeof s.grace!=='object'||!isFinite(s.grace.until)||!Array.isArray(s.grace.nets)))s.grace=null;if(s.grace)s.grace.nets=s.grace.nets.filter(isNet); + return s;} diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js new file mode 100644 index 0000000..7fc7d81 --- /dev/null +++ b/src/game/80-simulation/60-requirements.js @@ -0,0 +1,115 @@ +const GRACE_DAYS=60; +const REQS={ + lat:{only:true,l2:true,bonus:0,l:o=>tr('requirements.one_way_latency_within_max_ms',{max:o.latMax,best:(()=>{const v=R.l2lat[o.id]!==undefined?R.l2lat[o.id]:bestLat(o.city,o.city2);return isFinite(v)?v.toFixed(1)+' ms':tr('common.no_path')})()}),ok:b=>(R.l2lat[b.id]!==undefined?R.l2lat[b.id]:bestLat(b.city,b.city2))<=b.latMax}, + nni:{only:true,bonus:0,l:o=>tr('requirements.comes_in_over_fab_needs_your',{fab:FAB[o.prov]?FAB[o.prov].name:'?',city:CITY[o.city].name,bw:fmtG(o.bw)}),ok:b=>{const pt=nniPort(b.city,b.prov);return !!pt&&nniUsed(b.city,b.prov)+(S.biz.includes(b)?0:b.bw)<=nniCap(pt)+1e-9;}}, + diverse:{l:tr('requirements.two_paths_that_share_no_trench'),bonus:.25,l2:true,can:(b,s=S)=>diversityPossible(b.city,b.city2,s),ok:b=>R.div[b.id]!==undefined?!!R.div[b.id]:diversePaths(b.city,b.city2)}, + sharks:{l:tr('requirements.afraid_of_sharks_needs_a_path'),bonus:.2,l2:true,ok:b=>terrestrialPath(b.city,b.city2),can:b=>!!b.city2&&!isSub(b.city,b.city2)}, + nocog:{l:tr('requirements.refuses_cogentle_transit_anywhere_on'),bonus:.15,ok:()=>!S.transit.some(t=>t.net==='cog')}, + ipv6:{l:tr('requirements.ipv6_or_bust_you_must_peer'),bonus:.1,ok:()=>Object.keys(S.ixp).some(c=>ixSessions(c).has('drz'))||S.pni.some(p=>p.net==='drz'&&pniOn(p))}, + netchill:{l:tr('requirements.wants_netchill_on_net_a_cache'),bonus:.15,ok:()=>S.caches.some(c=>c.net==='nfx')||S.pni.some(p=>p.net==='nfx'&&pniOn(p))}, + gen:{l:tr('requirements.backup_generator_in_every_city_they'),bonus:.15,ok:b=>[b.city,b.city2].filter(Boolean).every(c=>S.pops[c]&&S.pops[c].gen)}, + routers:{l:tr('requirements.insists_on_two_routers_in_their'),bonus:.15,ok:b=>((S.pops[b.city]&&S.pops[b.city].routers)||1)>=2}, + local:{l:tr('requirements.local_breakout_transit_or_an_ix'),bonus:.2,ip:true,ok:b=>S.transit.some(t=>t.city===b.city)||hasIxAt(b.city)||(isTier1()&&S.pni.some(p=>p.city===b.city))}, + metro:{l:tr('requirements.two_data_centers_in_every_metro'),bonus:.2,only:true,ok:b=>[b.city,b.city2].filter(Boolean).every(c=>S.pops[c]&&S.pops[c].site2)}, + twoup:{l:tr('requirements.wants_two_different_transit'),bonus:.15,ip:true,ok:()=>new Set(S.transit.map(t=>t.net)).size>=2||S.transit.length===0}, + china:{l:tr('requirements.needs_low_loss_reach_into_china'),bonus:.3,ip:true,ok:()=>S.transit.some(premOn)||S.links.some(l=>l.premium)||S.pni.some(p=>NET[p.net].cn&&pniOn(p))}, + scrubbed:{l:tr('requirements.will_only_sign_with_a_network'),bonus:.15,ok:()=>hasScrub()}, + scrubnear:{l:tr('requirements.wants_a_scrubbing_center_on_its'),bonus:.15,ip:true,ok:b=>S.scrubs.some(x=>CITY[x.city].reg===CITY[b.city].reg)}, + // The shark's orbit promise (99-pie-sales.js): a full sky, a crust at least PIE_PROMISE in orbit. Never on an ordinary offer. + skyfull:{only:true,bonus:0,l:()=>tr('requirements.promised_a_full_sky',{p:pct(PIE_PROMISE)}),ok:()=>pieHubs().some(id=>pieCov(id)>=PIE_PROMISE)}, + puns:{l:tr('requirements.their_ceo_hates_puns_please_do'),bonus:.05,ok:()=>true}, +}; +/* terrestrialPath() asked for many customers at once (the daily mood check, 10-day-tick.js): the islands the live land + links make, worked out the first time one asks (TERR.m: city -> island), and two cities with a land path are two + cities of one island. Walking the links is what costs (a dark fiber's capacity, every one of them), not the question. + TERR names the game and the routing count it was made for: an action between two steps of the day changes a link + only through after(), which routes, so the islands are worked out again; another game, and each question walks. */ +let TERR=null; +function terrIslands(){const adj={};for(const l of S.links)if(!l.sub&&!linkDown(l)){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);} + const m=new Map();let n=0;for(const c in adj){if(m.has(c))continue;const q=[c];m.set(c,n);for(let h=0;h!l.sub&&!linkDown(l));const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;} +const reqOk=b=>(b.reqs||[]).every(k=>REQS[k]&&REQS[k].ok(b)); +// Some requirements only make sense for some customers: nobody can reach another continent without getting wet. +const reqCan=(k,b)=>!REQS[k].can||REQS[k].can(b); +function reqList(o){return (o.reqs||[]).map(k=>{const ok=REQS[k].ok(o),lab=typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l;return `
${ok?'✓':'✗'} ${esc(lab)}
`;}).join('');} +/* diversePaths(): a shortest path by hops over the live links (and VXCs to remote cities), then another one that shares + none of its risks. divGraph() numbers the cities and the risks and lists each city's links once, in list order, as + disjointOn() reads them; divOn() asks it, so many pairs on one network (spots0(), opsDecomSafe()) share one graph. The + second search skips the first path's risks rather than rebuilding the graph without them: the same lists in the same + order, so the same answer. An express runs in the trenches of every fiber it rides (xpRisk()): one backhoe in any of + them takes it out, so its link carries the list of those risks. */ +const srlgOf=l=>l.kind==='vxc'?'fab:'+l.prov:l.kind==='xp'?xpRisk(l):(l.trench||l.id); +function divGraph(live){if(!live){const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));} + const ix=new Map(),rk=new Map(),adj=[],id=c=>{let i=ix.get(c);if(i===undefined){ix.set(c,i=adj.length);adj.push([]);}return i;}, + rid=s=>{let r=rk.get(s);if(r===undefined)rk.set(s,r=rk.size);return r;}; + for(const l of live){const s=srlgOf(l),r=Array.isArray(s)?(s.length===1?rid(s[0]):s.map(rid)):rid(s);const u=id(l.a),v=id(l.b);adj[u].push(v,r);adj[v].push(u,r);}return {ix,adj};} +function divOn(g,a,b){if(a===b)return true;const i=g.ix.get(a),j=g.ix.get(b);return i!==undefined&&j!==undefined&&disjointOn(g.adj,i,j);} +function diversePaths(a,b){return divOn(divGraph(),a,b);} +function disjointRoutes(a,b,live){return divOn(divGraph(live),a,b);} +// Check buildable geography, not today's POPs, capacity or outages. Parallel land +// routes can use separate trenches; all segments of one cable share its risk. +let diversityMap=null; +function diversityPossible(a,b,state=S){ + if(!CITY[a]||!CITY[b]||a===b)return false; + const rules=state.scn&&state.scn.rules||{},key=JSON.stringify([!!state.won,rules]); + if(!diversityMap||diversityMap.key!==key){if(!DIVW||DIVW.key!==key)DIVW={key,g:diversityBuild(key,rules,!!state.won)}; + for(;;){const s=DIVW.g.next();if(s.done){diversityMap=s.value;DIVW=null;break;}}} + const pair=[a,b].sort().join(':'),M=diversityMap; + return M.answers[pair]??(M.answers[pair]=M.ix.has(a)&&M.ix.has(b)&&disjointOn(M.adj,M.ix.get(a),M.ix.get(b))); +} +/* Built once per ruleset, over every city pair, so it runs on the first load of every save: on city indices, with + the cables between each pair from a table. A link is the number of its risk: each land trench and your own cable + on its own, every segment of one cable (or one fabric) the same; adj[i] lists [neighbour, risk] in the order the + links were added, as a graph built from a list of them would. It only follows from the catalog and the key, so idle + frames build it a few rows at a time (diversityWarm()) before the first offer asks; one that asks first finishes it. */ +let DIVW=null; +function* diversityBuild(key,rules,won){ + const cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id),N=cities.length,ix=new Map(cities.map((c,i)=>[c,i])); + const cab=new Map();for(const c of CABLE_PAIRS){const k=c.aFABS.filter(f=>f.cities.includes(c))),ban=rules.banPairs||[]; + const adj=cities.map(()=>[]),grp=new Map();let n=0,k=0;const add=(i,j,g)=>{let r;if(g===undefined)r=k++;else{r=grp.get(g);if(r===undefined)grp.set(g,r=k++);}adj[i].push(j,r);adj[j].push(i,r);n++;}; + for(let i=0;ip===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(i,j,'cab:'+c.cid); + if(won&&land[i]&&land[j]&&(sub||cs)&&!cn[i]&&!cn[j])add(i,j); + if(fab[i].length&&fab[j].length)for(const f of FABS)if(fab[i].includes(f)&&fab[j].includes(f))add(i,j,'fab:'+f.id); + }} + return {key,ix,adj,links:n,answers:{}};} +// A frame's spare time on it: at most ms, until it is built for the game's current rules. +function diversityWarm(ms){if(!S||!S.pops)return;const rules=S.scn&&S.scn.rules||{},key=JSON.stringify([!!S.won,rules]); + if(diversityMap&&diversityMap.key===key)return;if(!DIVW||DIVW.key!==key)DIVW={key,g:diversityBuild(key,rules,!!S.won)}; + const t=performance.now();for(;;){const s=DIVW.g.next();if(s.done){diversityMap=s.value;DIVW=null;return;}if(performance.now()-t>ms)return;}} +// disjointRoutes() on such a graph: a shortest path by hops, then another one that shares none of its risks. +// A link's risk is a number, or a list of them for an express (divGraph()); pk: where each city's arriving link sits in adj. +function disjointOn(adj,a,b){const N=adj.length,bfs=skip=>{const prev=new Int32Array(N).fill(-1),pk=new Int32Array(N),q=[a];prev[a]=a; + for(let h=0;h=0)continue;const r=L[k+1]; + if(skip&&(typeof r==='number'?skip.has(r):r.some(x=>skip.has(x))))continue;prev[v]=u;pk[v]=k+1;q.push(v);}} + if(prev[b]<0)return null;const used=new Set();for(let v=b;v!==a;v=prev[v]){const r=adj[prev[v]][pk[v]];if(typeof r==='number')used.add(r);else for(const x of r)used.add(x);}return used;}; + const p1=bfs(null);return !!p1&&!!bfs(p1);} +// Big networks have thousands of links and customers: callers that ask about all of them (compute(), the daily mood +// check, new offers) look links up and add up what is sold in one pass (linkIds(), fiberUse()), not once per item. +const linkIds=()=>{const m=new Map();for(const l of S.links)if(!m.has(l.id))m.set(l.id,l);return m;}; +function fiberUse(){const sold=new Map(),dfp=new Map(),pairs=new Set(); + for(const b of S.biz){if(b.type==='wwave')sold.set(b.link,(sold.get(b.link)||0)+(b.slots||0));else if(b.type==='dfpair')dfp.set(b.link,(dfp.get(b.link)||0)+1);else if(b.type==='pairs'||b.type==='capfib')pairs.add(b.link);} + return {sold,dfp,pairs};} +// Fiber customers come in two kinds: glass (a leased pair, an IRU, a hyperscaler's pairs) needs only the fiber; the rest +// (alien and managed waves) ride its line system too, and go dark with it for the day a line-system swap takes. +const FIB_GLASS=new Set(['dfpair','pairs','capfib']); +function fiberOk(b,ids){const l=ids?ids.get(b.link):S.links.find(x=>x.id===b.link);if(!l)return false;if(FIB_GLASS.has(b.type))return l.ready<=S.day&&!(l.cut>S.day);return l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day)&&(b.type!=='mwave'||dfLit(l)>=mwG(l));} +// A customer rides this fiber's line system: a swap would take it dark (the build standard and the intern wait for the +// player). ws: the fibers that carry one (dfWaveSet()), when many fibers are asked about at once. +const dfOnSys=b=>!!b.link&&!!BIZ_T[b.type]&&!!BIZ_T[b.type].fiber&&!FIB_GLASS.has(b.type); +const dfWaveSet=()=>{const s=new Set();for(const b of S.biz)if(dfOnSys(b))s.add(b.link);return s;}; +const dfWaveCust=(l,ws)=>ws?ws.has(l.id):S.biz.some(b=>b.link===l.id&&dfOnSys(b)); +function soldSlots(l,u){return u?u.sold.get(l.id)||0:S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);} +// Spare capacity other carriers can rent on a dark fiber (#51): free channels for alien waves, and on your own build +// a spare pair in the trench. Random offers and broker listings follow the same rules and the same prices. +const freeCh=(l,u)=>chMax(l)-(l.ch||[]).length-soldSlots(l,u)-xpSlots(l),pairFree=(l,u)=>!!l.own&&(u?u.dfp.get(l.id)||0:S.biz.filter(b=>b.type==='dfpair'&&b.link===l.id).length)<2&&!(u?u.pairs.has(l.id):S.biz.some(b=>(b.type==='pairs'||b.type==='capfib')&&b.link===l.id)); +const wwWhat=(l,n)=>trn('requirements.n_400g_alien_wave_on_your',n,{a:CITY[l.a].name,b:CITY[l.b].name}); +function fiberOffer(t,l,nm,cut=1){ + if(t==='wwave'){const slots=1+Math.floor(Math.random()*Math.min(4,freeCh(l))); + return {id:uid(),city:l.a,city2:l.b,link:l.id,slots,what:wwWhat(l,slots),name:nm(),type:t,bw:1,rate:wwRate(l,slots,cut),reqs:[],exp:S.day+30};} + return {id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('requirements.a_spare_fiber_pair_in_your',{a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*0.9*cut),reqs:[],exp:S.day+30};} diff --git a/src/game/80-simulation/65-express.js b/src/game/80-simulation/65-express.js new file mode 100644 index 0000000..6918f42 --- /dev/null +++ b/src/game/80-simulation/65-express.js @@ -0,0 +1,92 @@ +/* Express lightpaths (#58): a wave from A to C over your own (or leased) dark fibers A–B, B–C… that passes B through its + ROADM as light, so B's routers never see it: no ports there, no hop, a little less latency. It is a link of its own + (kind 'xp') between A and C: via lists the fibers it rides in order from a, ch its optics. Every channel takes one + slot on each of those fibers, and the light has to make the whole run between regen sites in one go. */ +const XP_HOPS=6,XP_PASS=5000,XP_BUDGET=4000,XP_CH=64; +// The fibers an express can ride: dark fiber on land with a ROADMaster (your own build or an IRU). Subsea line +// systems end at the landing station, so a wave never runs through one into the land network. +const xpSpanOk=s=>!!s&&s.kind==='df'&&!s.sub&&isRdm(s.sys); +/* What the expresses take on each fiber, and the links by id, kept while S.links and every express's optics and path + are the same: the map, compute() and the free-channel checks ask often, and most networks have no express at all. */ +const XPX={L:null,n:-1,xs:[],m:null,ids:null}; +function xpIdx(){const L=S.links;let ok=XPX.L===L&&XPX.n===L.length; + if(ok)for(const x of XPX.xs)if((x[0].ch||[]).length!==x[1]||x[0].via!==x[2]){ok=false;break;} + if(!ok){const m=new Map(),xs=[];for(const l of L)if(l.kind==='xp'){const n=(l.ch||[]).length;xs.push([l,n,l.via]);for(const id of l.via||[])m.set(id,(m.get(id)||0)+n);} + XPX.L=L;XPX.n=L.length;XPX.xs=xs;XPX.m=m;XPX.ids=null;} + return XPX;} +function xpLink(id){const X=xpIdx();if(!X.ids){X.ids=new Map();for(const l of S.links)if(!X.ids.has(l.id))X.ids.set(l.id,l);}return X.ids.get(id);} +// Channel slots express channels take on fiber l. +function xpSlots(l){return xpIdx().m.get(l.id)||0;} +// The expresses riding fiber id, and a list of links with every express that rides one of them added. +const xpOver=id=>xpIdx().xs.filter(x=>(x[0].via||[]).includes(id)).map(x=>x[0]); +function xpWith(ls){const ids=new Set(ls.map(l=>l.id)),out=ls.slice();for(const [x] of xpIdx().xs)if(!ids.has(x.id)&&(x.via||[]).some(id=>ids.has(id))){out.push(x);ids.add(x.id);}return out;} +// The fibers of an express, in order (null when one is gone). +function xpSpans(l){const v=l.via;if(!Array.isArray(v)||!v.length)return null;const out=[];for(const id of v){const s=xpLink(id);if(!xpSpanOk(s))return null;out.push(s);}return out;} +// The cities a chain of fibers passes from a, end included; null when they do not chain or come back to a city. +function xpCities(a,sp){const cs=[a];let c=a;for(const s of sp){const n=s.a===c?s.b:s.b===c?s.a:null;if(!n||cs.includes(n))return null;cs.push(n);c=n;}return cs;} +// Free slots on a fiber for one more express channel: what its line system holds, less lit, sold and express channels. +const xpFree=s=>chMax(s)-(s.ch||[]).length-soldSlots(s)-xpSlots(s); +/* The longest stretch the light runs without being regenerated. Regen sites split each fiber into equal spans, as for + its own channels; through a city the light goes on, so the last span of one fiber and the first of the next add up. */ +function xpRunKm(sp){let cur=0,mx=0;for(const s of sp){const r=s.regen|0,p=s.km/(r+1);if(!r){cur+=s.km;continue;}cur+=p;if(cur>mx)mx=cur;if(p>mx)mx=p;cur=p;}return Math.ceil(Math.max(mx,cur));} +// What optic o carries over that run (0: out of reach), cached like every channel (optG). +const xpOptG=(o,run)=>OPT[o]?optG(o,{km:run}):0; +function xpG(l){const sp=xpSpans(l);if(!sp)return 0;const run=xpRunKm(sp);let g=0;for(const o of l.ch||[])g+=xpOptG(o,run);return g;} +/* What still gets through: a dirty connector in the glass of a fiber under it dims every wave there, this one's too. An + MTU mismatch, microbursts or a marginal optic on that fiber belong to its routers and optics, which the express skips. */ +function xpGlassF(l){const sp=xpSpans(l);if(!sp)return 1;let f=1;for(const s of sp){const x=s.loss;if(x&&x.glass&&x.until>S.day)f*=x.f;}return f;} +// The fibers under it with a dirty connector today, for its panel. +const xpDim=l=>(xpSpans(l)||[]).filter(s=>s.loss&&s.loss.glass&&s.loss.until>S.day); +// The fastest single channel, as a scenario's fast path asks of every hop. +function xpHopG(l){const sp=xpSpans(l);if(!sp)return 0;const run=xpRunKm(sp);return Math.max(0,...(l.ch||[]).map(o=>xpOptG(o,run)));} +// Dark when a fiber under it is cut, still being built or has its line system down, or nothing lit reaches. +function xpDown(l){const sp=xpSpans(l);if(!sp)return true;const d=S.day;for(const s of sp)if(linkCut(s)||s.ready>d||s.eqDown>d)return true;return xpG(l)<=0;} +// The cities an express passes without touching a router, for its labels. +function xpVia(l){const sp=xpSpans(l),cs=sp&&xpCities(l.a,sp);return cs?cs.slice(1,-1).map(c=>CITY[c].name).join(', '):'';} +// A fiber that carries only expresses is dark as a link of its own, but there is light in it: a backhoe or a monkey +// that cuts fibers still finds it. Fibers only: linkDown() of an express asks xpDown(), never this. +const xpBare=l=>l.kind==='df'&&!l.sub&&xpSlots(l)>0&&linkDown(l)&&!linkCut(l)&&!(l.ready>S.day)&&!(l.eqDown>S.day); +// The light runs the whole way in glass: the fibers' own latency added up, and no router in between. +function xpLat(l){const sp=xpSpans(l);return sp?sp.reduce((a,s)=>a+linkLat(s),0):l.km*1.1/200;} +// What one backhoe can take out: every trench the express runs in (diverse paths and redundancy checks). +function xpRisk(l){const sp=xpSpans(l);return sp?sp.map(s=>s.trench||s.id):[l.id];} +// The furthest any optic reaches at its slowest setting: a longer run is never worth listing. +let XP_REACH=0;const xpReachMax=()=>XP_REACH||(XP_REACH=Math.max(...Object.values(OPT).map(O=>O.modes.at(-1)[1]))); +/* Ways to chain ROADM fibers from city a: to b (every path, shortest first, k of them) or, with b null, the shortest + path to each city two or more fibers away. first: the path starts on that fiber. The search is bounded: a few dozen + fibers is a big optical network, and XP_HOPS and XP_BUDGET keep it small on the biggest. */ +function xpPaths(a,b,first,k=3){const adj=new Map();for(const s of S.links)if(xpSpanOk(s))for(const c of [s.a,s.b]){let L=adj.get(c);if(!L)adj.set(c,L=[]);L.push(s);} + if(!adj.has(a))return [];for(const L of adj.values())L.sort((x,y)=>x.km-y.km); + const out=[],best=new Map(),seen=new Set([a]),path=[];let budget=XP_BUDGET; + const go=(c,km)=>{for(const s of adj.get(c)||[]){if(--budget<0)return;if(!path.length&&first&&s!==first)continue;const n=s.a===c?s.b:s.a;if(seen.has(n))continue; + const d=km+s.km;path.push(s);seen.add(n); + if(path.length>=2){if(b==null){const o=best.get(n);if(!o||dx.km-y.km||x.sp.length-y.sp.length).slice(0,k);} +// The express already lit on this path, either way round. +function xpFind(a,b,ids){const k=ids.join(','),r=ids.slice().reverse().join(',');return xpIdx().xs.map(x=>x[0]).find(x=>(x.a===a&&x.b===b&&(x.via||[]).join(',')===k)||(x.a===b&&x.b===a&&(x.via||[]).join(',')===r))||null;} +// A typed order's path: fiber ids, comma-separated, chaining from a to b (null when it does not). +function xpParse(a,b,via){if(!isCity(a)||!isCity(b)||a===b||!S.pops[a]||!S.pops[b]||typeof via!=='string')return null;const ids=via.split(','); + if(ids.length<2||ids.length>XP_HOPS||new Set(ids).size!==ids.length)return null;const sp=ids.map(id=>S.links.find(x=>x.id===id)); + if(!sp.every(xpSpanOk))return null;const cs=xpCities(a,sp);return cs&&cs[cs.length-1]===b?sp:null;} +// Why one more channel of optic o cannot run from a to b over these fibers ('' when it can). +function xpWhy(a,b,sp,o){const O=OPT[o];if(!O)return '';if(!techOk('opt',o,O.lvl))return tr('action_helpers.unlocks_at_customer_level_n',{n:O.lvl}); + const run=xpRunKm(sp);if(!xpOptG(o,run))return tr('express.too_far',{run:run.toLocaleString(),max:O.modes.at(-1)[1].toLocaleString()}); + for(const s of sp)if(xpFree(s)<1)return tr('express.fiber_full',{a:CITY[s.a].name,b:CITY[s.b].name,max:chMax(s)}); + for(const c of [a,b]){const p=S.pops[c];if(!p)return linkFromWhy(c);if(RG[p.rgen||0].clsa+(s.regen|0),0);return Math.round(optCost(o)*(spareN(o)>0?r:1+r))+(fresh?XP_PASS*(sp.length-1):0);} +// Taking a regen site off fiber l (to n sites) must leave every express on it in reach. +function xpRegenBad(l,n){return xpOver(l.id).some(x=>{const sp=xpSpans(x);if(!sp)return false;const run=xpRunKm(sp.map(s=>s===l?{km:s.km,regen:n}:s));return (x.ch||[]).some(o=>!xpOptG(o,run));});} +/* Saves: an express must ride fibers that are still there, chain from a to b and carry real optics; anything else is + dropped and its optics go back on the shelf. km is worked out again from the fibers. */ +function xpSanitize(s){const ids=new Map();for(const l of s.links)if(!ids.has(l.id))ids.set(l.id,l);const drop=new Set(); + for(const l of s.links){if(l.kind!=='xp')continue;const via=Array.isArray(l.via)?l.via.map(String):[],sp=via.map(id=>ids.get(id)),ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)).slice(0,XP_CH):[]; + let ok=via.length>=2&&via.length<=XP_HOPS&&new Set(via).size===via.length&&sp.every(xpSpanOk)&&ch.length>0; + if(ok){const cs=xpCities(l.a,sp);ok=!!cs&&cs[cs.length-1]===l.b;} + if(!ok){drop.add(l);if(ch.length){if(!s.spares||typeof s.spares!=='object'||Array.isArray(s.spares))s.spares={};for(const o of ch)s.spares[o]=(Math.floor(+s.spares[o])||0)+1;}continue;} + for(const k of ['cable','trench','seat','own','list','regen','sys','ready','eqDown','chFail','pairs','tier','premium','border','mult','prov','vt','spares','sub'])delete l[k]; + l.via=via;l.ch=ch;l.km=Math.max(1,Math.round(sp.reduce((a,x)=>a+num(x.km,0),0)));l.mo=0;} + if(drop.size)s.links=s.links.filter(l=>!drop.has(l));} diff --git a/src/game/80-simulation/70-customers-and-events.js b/src/game/80-simulation/70-customers-and-events.js new file mode 100644 index 0000000..da70bd0 --- /dev/null +++ b/src/game/80-simulation/70-customers-and-events.js @@ -0,0 +1,90 @@ +function bizSf(b,ids){const T=BIZ_T[b.type];return T.orbit?((R.pie&&R.pie.sf[b.id])||0):T.fiber?(fiberOk(b,ids)?1:0):T.l2?clamp((R.l2[b.id]||0)/b.bw,0,1):bizSfOf(R,b.city)*((R.tgtF&&R.tgtF[b.id])??1);} +// Protected business traffic has its own served share; without the rule it shares the city's. +function bizSfOf(r,c){const d=r.bizDem&&r.bizDem[c];return teRules()&&teRules().protect&&d>1e-6?clamp(r.bizSrv[c]/d,0,1):sfOf(r,c);} +function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);} +function bHas(o){return !!BIZ_T[o.type].cap||!!BIZ_T[o.type].orbit||bCities(o).every(c=>S.pops[c]);} +function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day⚠️ ${tr('customers_and_events.gaming_attracts_attacks')}
`:'')+lcNote(b);} +function bTerms(o){const T=BIZ_T[o.type];if(T.cap)return capTerms(o); + if(T.event){const live=S.day>=o.start;return tr('customers_and_events.bw_extra_for_d_days_when',{bw:fmtG(o.bw),d:o.dur,when:live?tr('customers_and_events.day_n_of_d',{n:S.day-o.start+1,d:o.dur}):tr('customers_and_events.starting_in_n_d',{n:o.start-S.day}),fee:fmt$(o.fee)});} + if(T.sdwan)return tr('customers_and_events.n_sites_list_bw_per_site',{n:o.sites.length,list:o.sites.map(c=>CITY[c].name).join(', '),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)}); + if(T.fiber)return esc(o.what)+' · '+tr('common.price_mo',{price:fmt$(o.rate)}); + return fmtG(o.bw)+' · '+tr('common.price_mo',{price:fmt$(o.bw*o.rate)});} +// Events are paid once at the end, prorated by how much of the crowd you served. +function eventTick(b,d){if(!BIZ_T[b.type].event)return false;if(d=0.95)S.stats.evFull=(S.stats.evFull||0)+1;const pay=avg>=0.95?b.fee:avg>=0.7?Math.round(b.fee*avg):-Math.round(b.fee*0.2);S.cash+=pay;S.biz=S.biz.filter(x=>x!==b); + toast(pay>=0?tr('customers_and_events.name_is_over_pay_you_delivered',{name:esc(b.name),pay:fmt$(pay),pct:pct(avg)})+(avg>=0.95?' '+tr('common.flawless'):''):tr('customers_and_events.name_was_a_disaster_only_pct',{name:esc(b.name),pct:pct(avg),pay:fmt$(-pay)}),pay>=0?'good':'bad');sfx(pay>=0?'coin':'err');return true;} +/* Where the giants actually build: gigawatt AI campuses and cloud regions, mapped to the nearest city on the map (#61: + not just five metros; real campuses sit all over, from Oregon to Wyoming to Querétaro). w: a hub that draws more. */ +const MEGA=[ + {c:'ash',n:'Data Center Alley',w:2}, + {c:'atn',n:'Peach-flops Georgia'}, + {c:'auh',n:'Star-Gait UAE'}, + {c:'aus',n:'Taylor-Made Texas Campus'}, + {c:'chi',n:'Fairweather Wisconsin'}, + {c:'chi',n:'Project Rainy-er Indiana'}, + {c:'cmh',n:'Prome-the-mess Ohio'}, + {c:'csn',n:'Biggest Little Cluster Reno'}, + {c:'cys',n:'Wind Chill Wyoming Campus'}, + {c:'dal',n:'Star-Gait Abilene'}, + {c:'doh',n:'Lusail Data Oasis'}, + {c:'dsm',n:'Cornfield Cluster Iowa'}, + {c:'dub',n:'Bring-Your-Own-Power Dublin'}, + {c:'for',n:'Short-Video Ceará Campus'}, + {c:'hyd',n:'Vizag AI Hub'}, + {c:'icn',n:'Ulsan AI Campus'}, + {c:'jan',n:'Hyperbole Louisiana'}, + {c:'kcy',n:'Burnt Ends Bit Barn'}, + {c:'kul',n:'Johor Overflow'}, + {c:'lit',n:'Colossus of Blues Memphis'}, + {c:'mad',n:'Aragón Mega-shed'}, + {c:'mel',n:'AirDrunk Melbourne West'}, + {c:'mty',n:'Norteño Nodes Nuevo León'}, + {c:'nyc',n:'Neocloud New Jersey'}, + {c:'phx',n:'Mesa-ive Compute Arizona'}, + {c:'qro',n:'Querétaro Cluster'}, + {c:'ric',n:'Henrico Hyperscale Hustle'}, + {c:'ruh',n:'Desert Kingdom AI Campus'}, + {c:'scl',n:'Quilicura Region'}, + {c:'sea',n:'Quincy-dence Washington'}, + {c:'sle',n:'Dilly-Dalles Oregon'}, + {c:'sto',n:'Star-Gait Fjord-way'}, + {c:'syd',n:'AirDrunk Western Sydney'}, + {c:'syd',n:'Star-Gait Down Under'}, + {c:'tok',n:'Hokkaido Snow DC'}, + {c:'yqb',n:'Hydro-Chill Québec'}, +]; +/* A campus is picked by its weight, less where giant circuits already crowd the city (#61): a metro that carries as much + as the average busy one draws half as often, three times as much a quarter. Hubs stay a bit busier, never the only ones. */ +function megaLoad(){const m=new Map(),add=(c,v)=>{if(c)m.set(c,(m.get(c)||0)+v);}; + for(const o of S.biz.concat(S.offers||[])){const T=BIZ_T[o.type];if(!T||!T.mega||!T.l2)continue;for(const c of bCities(o))add(c,o.bw||0);}return m;} +function megaPick(list,ld){let tot=0,k=0;for(const v of ld.values()){tot+=v;k++;}const avg=k?tot/k:0,w=list.map(m=>(m.w||1)/(1+(avg>0?(ld.get(m.c)||0)/avg:0))); + let r=Math.random()*w.reduce((a,b)=>a+b,0);for(let i=0;imine.includes(m.c));if(!megaMine.length)return;const ld=megaLoad(); + if(t==='ingest'){const m=megaPick(megaMine,ld),bw=pick(T.opts),dur=3+Math.floor(Math.random()*4),start=S.day+10+Math.floor(Math.random()*12); + S.offers.push({id:uid(),city:m.c,city2:null,name:tr('customers_and_events.name_at_site',{name:nm(),site:m.n}),type:t,bw,rate:0,reqs:[],start,dur,fee:Math.round(bw*dur*55),exp:start-2,mega:true});return;} + if(t==='aiwan'||t==='agi'){const a=megaPick(megaMine,ld),others=MEGA.filter(m=>m.c!==a.c&&(Math.random()<0.7?mine.includes(m.c):true));if(!others.length)return;const b=megaPick(others,ld);if(!reqCan('diverse',{city:a.c,city2:b.c}))return;const km=kmBetween(a.c,b.c),bw=pick(T.opts); + const reqs=['diverse'];if(Math.random()<0.4)reqs.push('metro'); + S.offers.push({id:uid(),city:a.c,city2:b.c,name:`${nm()}: ${a.n} ⇄ ${b.n}`,type:t,bw,rate:Math.round((150+km*0.08)*T.km),reqs,exp:S.day+45,mega:true});return;} + if(t==='mtrain'){const hub=megaPick(megaMine,ld),reg=CITY[hub.c].reg,pool=[...new Set(MEGA.filter(m=>m.c!==hub.c&&CITY[m.c].reg===reg).map(m=>m.c))];if(pool.length<2)return; + const sites=[hub.c];while(sites.lengthx+kmBetween(hub.c,c),0)/(sites.length-1),bw=pick(T.opts); + S.offers.push({id:uid(),city:hub.c,city2:null,sites,name:tr('customers_and_events.name_hub_site',{name:nm(),site:hub.n}),type:t,bw,rate:Math.round((150+avg*0.08)*0.6),reqs:[],exp:S.day+45,mega:true});return;} + if(t==='pairs'){const ls=S.links.filter(l=>l.kind==='df'&&l.own&&l.ready<=S.day&&!S.biz.some(b=>(b.type==='pairs'||b.type==='dfpair')&&b.link===l.id)&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;const l=pick(ls),n=100+50*Math.floor(Math.random()*7); + S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('customers_and_events.n_fiber_pairs_in_your_a',{n,a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*n*0.2),reqs:[],exp:S.day+30,mega:true});} +} +function spawnSpecial(t){const T=BIZ_T[t],mine=Object.keys(S.pops).filter(bizCity),lv=lvl(); + const nm=(city)=>{const all=city?T.names.filter(n=>nogOk(n,city)):T.names,list=all.filter(n=>!S.usedNames.includes(n));const n=list.length?pick(list):pick(all);useName(n);return n;}; + if(T.mega){spawnMega(t,T,nm,mine);return;} + if(T.event){const city=Math.random()<0.85&&mine.length?pick(mine):pick(OFFC);const bw=pick(T.opts.slice(0,Math.min(T.opts.length,lv+2)));const dur=3+Math.floor(Math.random()*5),start=S.day+12+Math.floor(Math.random()*14); + S.offers.push({id:uid(),city,city2:null,name:tr('customers_and_events.name_in_city',{name:nm(city),city:CITY[city].name}),type:t,bw,rate:0,reqs:[],start,dur,fee:Math.round(bw*dur*70),exp:start-2});return;} + if(T.sdwan){const hub=pick(mine),n=3+Math.floor(Math.random()*4),pool=(Math.random()<0.85?mine:OFFC).filter(c=>c!==hub),sites=[hub]; + while(sites.lengthl.kind==='df'&&l.ready<=S.day); + if(t==='wwave'){const u=fiberUse(),ls=ready.filter(l=>freeCh(l,u)>=1&&brFree(l)>=1&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;S.offers.push(fiberOffer(t,pick(ls),nm));return;} + if(t==='dfpair'){const u=fiberUse(),ls=ready.filter(l=>pairFree(l,u)&&brFree(l)>=BR_PAIR&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;S.offers.push(fiberOffer(t,pick(ls),nm));} +} diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js new file mode 100644 index 0000000..7a3a0da --- /dev/null +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -0,0 +1,168 @@ +/* ---------- Customers come and go (#178) ---------- + Every customer signs for a term. When it ends, most renew at today's market price, happy ones often grow, a few haggle + for a discount, and some leave for reasons that are not your fault (or, when they were unhappy, because they were). + Nothing changes during a customer's first term. Every roll is a hash of the customer and its term, never + Math.random, so seeded games and tests keep their random stream. */ + +/* The bandwidth market: what a Gbps sells for, 1 when you start. Flat for the first six months, then about 10% cheaper + a year (transit really does fall: 11–17% a year in the big hubs), slowed by dearer hardware, moving up and down in a + slow three-year cycle, and pushed up while a shortage lasts. Without the market rule it stays at 1. */ +const MK_YR=0.10,MK_FREE=180,MK_FLOOR=0.3,MK_SHOCK={opt:1.15,rt:1.1,build:1.08}; +function mktBase(d){if(d<=MK_FREE)return 1;const y=(d-MK_FREE)/365; + return Math.max(MK_FLOOR,Math.pow(1-MK_YR,y)*Math.sqrt(hwTrend(d))*(1+0.06*Math.sin(2*Math.PI*y/3)));} +function mkt(){if(!S||!rule('market'))return 1;const s=hwShock();return mktBase(S.day)*(s?MK_SHOCK[s.k]||1:1);} +// The market against the network's own first day (a late joiner's start), as the "since you started" lines say it. +const mktRel=()=>S&&rule('market')?mkt()/mktBase(S.day0|0):mkt(); + +// Terms in months: enterprise and hosting 1–3 years, wholesale and circuits 2–5, IRUs and fiber pairs 10–20. +const CL_TERMS={ip:[12,24,36],whole:[24,36,48,60],iru:[120,180,240]}; +// Events, capacity deals and scripted scenario customers have their own endings. +const clKind=t=>{const T=BIZ_T[t];if(!T||T.event||T.cap)return null;if(t==='dfpair'||t==='pairs')return 'iru';return T.l2||T.fiber||t==='isp'||t==='gpu'?'whole':'ip';}; +const clOn=b=>!!b&&!b.scripted&&!!clKind(b.type); +// A stable roll in [0,1) for this customer, this term and this question. +// Who the customer is (names are unique), not its id: ids come from the clock and would differ every time a game is replayed. +const clKey=b=>[b.type,b.city,b.city2||'',b.name].join('|'); +const clR=(b,q)=>(hstr(((S&&S.asn)||0)+'|'+clKey(b)+'|'+b.te+'|'+q)%100000)/100000; +const clPick=(a,b,q)=>a[Math.floor(clR(b,q)*a.length)]; +function clTerm(b,from){const m=clPick(CL_TERMS[clKind(b.type)],{type:b.type,city:b.city,city2:b.city2,name:b.name,te:from},'term');return from+Math.round(m*365/12);} +// What this customer's contract would be priced at today: its price moved by the market since it was signed. +// A renewal moves at most 25% down or 10% up at once, so an old save is not repriced in one go. +const clFair=b=>rule('market')&&b.mk>0?Math.round(b.rate*clamp(mkt()/b.mk,0.75,1.1)):b.rate; +// Competition where the customer is: carriers selling transit there (a fiber or circuit customer counts both ends). +const clComp=b=>{const cs=bCities(b);let n=0;for(const n2 of NETS)if(cs.some(c=>sellsAt(n2,c)))n++;return n;}; + +// Why they leave when it is not your fault: which reasons fit which customers. Moved and multihomed may keep them. +const CL_WHY={ + acq:{l:N_('lifecycle.why_acquired'),left:N_('lifecycle.left_acquired'),ok:()=>true}, + bust:{l:N_('lifecycle.why_bust'),left:N_('lifecycle.left_bust'),ok:t=>['gpu','stream','game','cgame','metav','ai','agi','hft','provedor','dia','host','mars'].includes(t)}, + insrc:{l:N_('lifecycle.why_insourced'),left:N_('lifecycle.left_insourced'),ok:t=>['isp','hyper','onramp','provedor','edu','sov','aiwan','stream'].includes(t)}, + moved:{l:N_('lifecycle.why_moved'),left:N_('lifecycle.left_moved'),ok:t=>{const T=BIZ_T[t];return !T.l2&&!T.fiber&&!T.nni;}}, + multi:{l:N_('lifecycle.why_multihomed'),left:N_('lifecycle.left_multihomed'),ok:t=>{const T=BIZ_T[t];return !T.l2&&!T.fiber;}}, + ended:{l:N_('lifecycle.why_project_ended'),left:N_('lifecycle.left_project_ended'),ok:t=>{const T=BIZ_T[t];return T.l2||T.fiber||t==='bulk';}}, + cheap:{l:N_('lifecycle.why_cheaper_bid'),left:N_('lifecycle.left_cheaper'),ok:()=>true}, + sad:{l:N_('lifecycle.why_unhappy'),ok:()=>false}, + odd:{l:N_('lifecycle.why_other'),ok:()=>false}, +}; +// The other reasons: now and then (never more than once every two months) a customer leaves for one of these. +const CL_ODD=[N_('lifecycle.odd_asn_six'),N_('lifecycle.odd_bad_holiday'),N_('lifecycle.odd_rdns'),N_('lifecycle.odd_too_many_feet'),N_('lifecycle.odd_dead_beef'),N_('lifecycle.odd_looking_glass'), + N_('lifecycle.odd_communities'),N_('lifecycle.odd_quadrant'),N_('lifecycle.odd_spreadsheet_cell'),N_('lifecycle.odd_fewer_vendors'),N_('lifecycle.odd_the_cloud'),N_('lifecycle.odd_bought_thrice'), + N_('lifecycle.odd_alphabetical'),N_('lifecycle.odd_goat_farmer'),N_('lifecycle.odd_mate'),N_('lifecycle.odd_95th'),N_('lifecycle.odd_holiday_card'),N_('lifecycle.odd_raccoon'),N_('lifecycle.odd_espresso'), + N_('lifecycle.odd_landlord'),N_('lifecycle.odd_wrong_blue'),N_('lifecycle.odd_space'),N_('lifecycle.odd_4g_dongle'),N_('lifecycle.odd_center'),N_('lifecycle.odd_wireguard')]; +const CL_ODD_GAP=60,CL_HAG_MAX=3,CL_MONTHS=24; + +// The month's tally for the dashboard: won, renewed, grew, haggled and who left why. +function clNote(k,why){const C=S.cl||(S.cl={odd:-1e9,mo:[]}),c=cal(S.day),m=c.y*12+c.m;let e=C.mo[C.mo.length-1]; + if(!e||e.m!==m){e={m,won:0,ren:0,grew:0,hag:0,lost:{}};C.mo.push(e);if(C.mo.length>CL_MONTHS)C.mo.shift();} + if(k==='lost')e.lost[why]=(e.lost[why]||0)+1;else e[k]=(e[k]||0)+1;} +// A new customer: its first term and the market it signed in. +function clSign(b){if(!clOn(b))return b;b.mk=b.mk>0?b.mk:mkt();b.te=clTerm(b,S.day);clNote('won');return b;} +function clRenew(b,rate){b.rate=Math.max(0,Math.round(rate));b.mk=mkt();delete b.hag;delete b.hr;b.te=clTerm(b,b.te);} +function clGone(b,why){S.biz=S.biz.filter(x=>x!==b);clNote('lost',why);} +const clWhere=b=>bCities(b).map(c=>CITY[c].name).join(' ⇄ '); + +// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. Not +// when the bigger IPv4 block it needs is not free (#150): out.v4 lists them for the day's news. +// A type with a most (max) never grows past it (#137). +function clGrow(b,out){const T=BIZ_T[b.type];if(T.fiber||(T.max&&b.bw>=T.max))return false;const up=(T.opts||[]).find(x=>x>b.bw),bw=T.max?Math.min(T.max,up||b.bw*2):up||b.bw*2; + if(!ip4GrowOk(b,bw)){if(out)out.v4.push([b,bw]);return false;}b.bw=bw;return true;} +// Leaving, or one of the not-your-fault turns that keeps them. Returns what the log says. +function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clWhere(b))}; + if(b.mood<50){clGone(b,'sad');out.lost.push(tr('lifecycle.left_unhappy',v));return;} + const C=S.cl;if(d-C.odd>=CL_ODD_GAP&&clR(b,'odd')<0.25){C.odd=d;clGone(b,'odd');out.lost.push(tr('lifecycle.left_odd',{...v,why:tr(clPick(CL_ODD,b,'oddline'))}));return;} + const ks=Object.keys(CL_WHY).filter(k=>CL_WHY[k].ok(b.type)),k=clPick(ks,b,'why'); + if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b,out)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;} + if(k==='moved'){const reg=CITY[b.city].reg,to=Object.keys(S.pops).filter(c=>c!==b.city&&CITY[c].reg===reg&&bizCity(c)).sort(); + const c2=to.length&&clR(b,'stay')<0.5?clPick(to,b,'to'):null; + if(c2){const from=CITY[b.city].name;b.city=c2;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.moved_stays',{name:v.name,from:esc(from),to:esc(CITY[c2].name)}));return;}} + if(k==='multi'&&b.bw>=2){const keep=(T.opts||[]).filter(x=>x<=b.bw/2).pop()||b.bw/2;b.bw=keep;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.multihomed_keeps',{...v,bw:fmtG(b.bw)}));return;} + clGone(b,k);out.lost.push(tr(CL_WHY[k].left,v));} + +/* A day of contracts, after the moods. 30 days before a term ends a customer with competitors around may ask for a + discount (at most three open at a time); at the end, the rest renew, grow or leave. An unanswered haggle renews at + the asked price. */ +function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[],v4:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0); + const pat=rule('moods')==='patient'?0.5:1; + for(const b of S.biz.slice()){if(!b.te||!clOn(b))continue; + if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;} + if(d=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(salesAsk()+0.12*clR(b,'ask'))); + if(ask>0&&ask=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b,out)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}} + clRenew(b,clFair(b));clNote('ren');out.ren++;} + clNews(out);clReferral(d);} +// What the day says: haggles one by one (they want an answer), the rest in a few lines so a big network is not a wall of toasts. +function clNews(out){ + for(const b of out.hag){const was=bizMo(b),now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate; + toast(tr('lifecycle.haggle',{name:esc(b.name),city:esc(clWhere(b)),price:fmt$(now),p:pct(1-now/Math.max(1,was)),n:b.hag.until-S.day}),'',[{l:tr('common.deals'),act:'leftTab',args:{t:'deals'}}],{a:'cust',v:b.id});} + const few=(list,kind)=>{for(const t of list.slice(0,3))toast(t,kind);if(list.length>3)toast(trn('lifecycle.n_more',list.length-3),kind);}; + few(out.ok,'good');ip4News(out.v4);few(out.lost,''); + if(out.ren)toast(trn('lifecycle.n_renewed',out.ren,{p:mktTxt()}),'');} +const mktTxt=()=>{const m=mktRel();return Math.abs(m-1)<0.005?tr('lifecycle.market_as_start'):m<1?tr('lifecycle.market_below',{p:pct(1-m)}):tr('lifecycle.market_above',{p:pct(m-1)});}; + +/* Growth by word of mouth: about every six weeks the happiest long-standing customer (a year or more, 90%+ happy) + tells someone like them, who shows up in Deals asking for the smallest size at today's price. */ +const CL_REF=['dia','game','host','isp','stream','edu','scrub','provedor','gpu','cgame','metav']; +function clReferral(d){if(d%45!==0||S.offers.length>=6)return; + const b=S.biz.filter(x=>clOn(x)&&CL_REF.includes(x.type)&&x.mood>=90&&d-(x.since||0)>=365&&bizCity(x.city)&&lvl()>=(BIZ_T[x.type].lv||1)).sort((a,c)=>c.mood-a.mood||(a.since||0)-(c.since||0)||(a.ido.ref===b.id))return;const T=BIZ_T[b.type],list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));if(!list.length)return; + const name=clPick(list,{type:b.type,city:b.city,city2:b.city2,name:b.name,te:d},'refname');useName(name); + S.offers.push({id:uid(),city:b.city,city2:null,name,type:b.type,bw:(T.opts||[1])[0],rate:Math.round((CITY[b.city].au?T.rate*AU_ARPU:T.rate)*mkt()),mk:mkt(),reqs:[],exp:d+40,ref:b.id,refN:b.name});} +// New offers are priced at today's market (spawnOffer and friends price at 1; this moves them). +function mktPrice(from){const m=mkt();for(let i=from;iMath.round((b.rate+b.hag.rate)/2); +const clBill=(b,rate)=>BIZ_T[b.type].fiber?rate:b.bw*rate; +const clHags=()=>S?S.biz.reduce((a,b)=>a+(b.hag?1:0),0):0; +/* What is at stake in a renewal (#292): how much traffic they book and get, the price per Gbps now and asked, and the + path terms they signed for (latency, diverse, no subsea), each ticked as it stands today. Two short lines for a phone. */ +function clRenInfo(b){const T=BIZ_T[b.type],tick=v=>`${v?'✓':'✗'} `,top=[],rq=[]; + if(!T.fiber){const sf=bizSf(b),srv=`${fmtG(b.bw*sf)}`; + top.push(b.sites?trn('lifecycle.ren_sites_traffic',b.sites.length,{bw:fmtG(b.bw),srv}):tr('lifecycle.ren_traffic',{bw:fmtG(b.bw),srv})); + top.push(tr('lifecycle.ren_per_g',{was:fmt$(b.rate),price:fmt$(b.hag.rate)}));} + for(const k of b.reqs||[]){const Q=REQS[k];if(!Q)continue;const ok=Q.ok(b); + if(k==='lat'){const v=R.l2lat[b.id]!==undefined?R.l2lat[b.id]:bestLat(b.city,b.city2);rq.push(tick(ok)+tr('lifecycle.ren_lat',{max:b.latMax,now:isFinite(v)?tr('common.ms_ms_one_way',{ms:v.toFixed(1)}):tr('common.no_path')}));} + else rq.push(tick(ok)+(k==='diverse'?tr('lifecycle.ren_diverse'):k==='sharks'?tr('lifecycle.ren_no_subsea'):esc(typeof Q.l==='function'?Q.l(b):Q.l)));} + return (top.length?`
${top.join(' · ')}
`:'')+(rq.length?`
${rq.join(' · ')}
`:'');} +// The renewals waiting for an answer, at the top of Deals. +function clDealsHtml(){const hs=S.biz.filter(b=>b.hag).sort((a,b)=>a.hag.until-b.hag.until);if(!hs.length)return ''; + return `

${tr('lifecycle.renewals')}

${tr('lifecycle.unanswered_matches')}

`+hs.map(b=>{const now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate,was=bizMo(b); + return `
${esc(b.name)}
${esc(BIZ_T[b.type].l)} · ${esc(clWhere(b))} · ${tr('ui.n_d_left',{n:b.hag.until-S.day})}
+
${tr('lifecycle.wants_price',{was:fmt$(was),price:fmt$(now),p:pct(1-now/Math.max(1,was))})}
${clRenInfo(b)}${slRenRow(b)} +
${btn(tr('lifecycle.match'),'renewMatch',{id:b.id},'green sm')}${btn(tr('lifecycle.meet_halfway',{price:fmt$(clBill(b,clMid(b)))}),'renewMeet',{id:b.id},'sm')}${btn(tr('lifecycle.let_them_go'),'renewLet',{id:b.id},'ghost sm')}
`;}).join('');} +// The contract line on a customer row. +const clTermTxt=b=>clOn(b)&&b.te?(b.hag?tr('lifecycle.renewal_haggle',{date:dateStr(b.te)}):tr('lifecycle.contract_until',{date:dateStr(b.te)})):''; + +/* Dashboard: customers won and lost per month (and why), renewals coming up, and the bandwidth market. */ +function clPanel(){const C=S.cl||{mo:[]},mo=C.mo.slice(-12);const soon=S.biz.filter(b=>clOn(b)&&b.te&&b.te-S.day<=30&&b.te>=S.day).length; + const sum=k=>mo.reduce((a,e)=>a+(k==='lost'?Object.values(e.lost).reduce((x,y)=>x+y,0):e[k]||0),0),why={};for(const e of mo)for(const k in e.lost)why[k]=(why[k]||0)+e.lost[k]; + let h=`

${tr('lifecycle.won_and_lost')}

${tr('lifecycle.won_and_lost_note')}

+
${tr('lifecycle.won')}
${sum('won')}
${tr('lifecycle.last_12_months')}
+
${tr('lifecycle.lost')}
${sum('lost')}
${trn('lifecycle.n_grew',sum('grew'))}
+
${tr('lifecycle.renewals_soon')}
${soon}
${tr('lifecycle.next_30_days')}
+
${tr('lifecycle.bandwidth_market')}
${Math.round(mktRel()*100)}
${mktTxt()}
`; + if(mo.length){const max=Math.max(1,...mo.map(e=>Math.max(e.won,Object.values(e.lost).reduce((x,y)=>x+y,0)))),W=600,H=120,mid=H/2,bw=W/12; + let g=``; + mo.forEach((e,i)=>{const lost=Object.values(e.lost).reduce((x,y)=>x+y,0),x=(i+12-mo.length)*bw+bw*0.2,w=bw*0.6,hw=(mid-12)*e.won/max,hl=(mid-12)*lost/max; + g+=`${MONTHS[e.m%12]} · ${tr('lifecycle.won')} ${e.won}${MONTHS[e.m%12]} · ${tr('lifecycle.lost')} ${lost}${MONTHS[e.m%12]}`;}); + h+=`${g}`;} + const ks=Object.keys(why).sort((a,b)=>why[b]-why[a]); + h+=ks.length?`

${tr('lifecycle.why_they_left')}

`+ks.map(k=>`
${tr(CL_WHY[k]?CL_WHY[k].l:CL_WHY.odd.l)}${why[k]}
`).join(''):`

${tr('lifecycle.nobody_left_yet')}

`; + return h+`
`;} + +/* Saves from before contracts: renewals spread over the next year (from the customer's id, so they do not all fall on + one day), and the market they signed in from the day they signed. */ +function clFix(s,b){if(b.scripted||!clKind(b.type)){delete b.te;delete b.mk;delete b.hag;delete b.hr;return b;} + const day=Math.max(0,Math.floor(+s.day||0)),ok=v=>typeof v==='number'&&isFinite(v); + if(!ok(b.te)||b.teday+365*21)b.te=day+30+hstr('te|'+b.id)%335;b.te=Math.floor(b.te); + if(!ok(b.mk)||b.mk<=0||b.mk>5)b.mk=mktBase(Math.max(0,Math.floor(+b.since||0))); + if(b.hag&&(typeof b.hag!=='object'||!ok(b.hag.rate)||b.hag.rate<0||!ok(b.hag.until)))delete b.hag;else if(b.hag)b.hag={rate:Math.round(b.hag.rate),until:Math.floor(Math.min(b.hag.until,b.te))}; + if(b.hr!==undefined&&b.hr!==b.te)delete b.hr;return b;} +function clFixState(s){const C=s.cl&&typeof s.cl==='object'&&!Array.isArray(s.cl)?s.cl:{},o={odd:typeof C.odd==='number'&&isFinite(C.odd)?C.odd:-1e9,mo:[]}; + if(Array.isArray(C.mo))for(const e of C.mo.slice(-CL_MONTHS)){if(!e||typeof e!=='object'||!Number.isInteger(e.m))continue;const n=v=>Math.max(0,Math.min(1e7,Math.floor(+v)||0)),lost={}; + if(e.lost&&typeof e.lost==='object')for(const k in e.lost)if(own(CL_WHY,k))lost[k]=n(e.lost[k]);o.mo.push({m:e.m,won:n(e.won),ren:n(e.ren),grew:n(e.grew),hag:n(e.hag),lost});} + s.cl=o;} diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js new file mode 100644 index 0000000..9811e52 --- /dev/null +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -0,0 +1,94 @@ +function cnOk(){return S.cnLic&&S.cnLic.state==='ok';} +// Few networks in the building means few transit sellers to haggle with: up to 1.8× where almost nobody is present. +// Hand-set markets (Korea, Australia, Belgian red tape) keep their own price. +const txComp=c=>{const q=CITY_PDB[c];return q?clamp((1000/Math.max(q[1],10))**0.15,1,1.8):1;}; +// No neutral data center means building your own room: POPs cost more to build and to run. +const colo=c=>{const q=CITY_PDB[c];return !q?1:q[0]===0?1.5:q[0]<=2?1.25:1;}; +const popMo=c=>Math.round(POP_MO*colo(c)); +function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.au)return AU_TRANSIT;if(C.ph)return PH_TRANSIT;if(C.tape)return 1.5;const base=C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;return Math.round(base*txComp(c)*10)/10;} +// A network's own markup on top of that, where it is far from home (Glowball Sakura Lager in Asia and New Zealand). +// What a home pays, against the usual bill. +const arpuOf=c=>CITY[c].arpu||(CITY[c].kr&&scnRule('sender')?KR_ARPU:1); +const netMult=(n,c)=>regionMult(c)*((n&&n.far&&CITY[c]&&n.far[CITY[c].reg])||1); +// Pairs nobody sells a circuit between, whoever builds it: two cities, or two countries (codes in capitals). +const NO_TALK=[['kyv','mos',N_('link_modal.nobody_sells_capacity_between_kyiv')],['KP','KR',N_('link_modal.no_circuit_crosses_between_north_and')]]; +const noTalk=(a,b)=>{const A=[a,CITY[a].cc],B=[b,CITY[b].cc],t=NO_TALK.find(([x,y])=>A.includes(x)&&B.includes(y)||A.includes(y)&&B.includes(x));return t?t[2]:'';}; +const uaePair=(a,b)=>!!CITY[a].uae&&!!CITY[b].uae; +const rainPair=(a,b)=>!!(CITY[a].rain||CITY[b].rain); +// Every city has a country (cc), but the border toll is Africa's: elsewhere a wave crosses borders at the plain price. +const borderPair=(a,b)=>CITY[a].reg==='AF'&&CITY[b].reg==='AF'&&CITY[a].cc!==CITY[b].cc; +// Perth to the east coast: the sea route round the south coast is domestic (AU_WAVE.ew), and the Nullarbor +// fiber costs a little more again because the incumbents own it. +const NULLARBOR=1.7,nullPair=(a,b)=>!!CITY[a].au&&!!CITY[b].au&&(a==='per')!==(b==='per'); +const andesPair=(a,b)=>!!CITY[a].andes&&!!CITY[b].andes&&CITY[a].andes!==CITY[b].andes; +// A pair an anchor-prone cable serves (the Baltic): the map calls it overland, but the fibre lies on the seabed (Anchors Away). +let ANCHOR_P=null;const anchorPair=l=>(ANCHOR_P||(ANCHOR_P=new Set(CABLE_PAIRS.filter(p=>CAB[p.cid]&&CAB[p.cid].anchor).map(p=>edgeKey(p))))).has(edgeKey(l)); +/* Overland between continents (Europe to the Middle East and Asia) crosses a dozen borders and as many + carriers, each taking a cut: in real life it costs ten times the subsea route or more (#40). */ +// Overland between continents is dear and DIY is out, except inside one country (Moscow–Vladivostok, Istanbul–Ankara). +const LAND_X=45,landX=(a,b)=>!isSub(a,b)&&CITY[a].reg!==CITY[b].reg&&CITY[a].cc!==CITY[b].cc; +function landMult(a,b){if(isSub(a,b))return 1;if(uaePair(a,b))return 3;return (landX(a,b)?LAND_X:1)*(andesPair(a,b)?2:1)*(nullPair(a,b)?NULLARBOR:1)*(rainPair(a,b)?2:1)*(borderPair(a,b)?2:1);} +function landWhy(a,b){if(isSub(a,b))return '';if(uaePair(a,b))return tr('geography_and_latency.inside_the_uae_only_the_two'); + const r=[];if(landX(a,b))r.push(tr('geography_and_latency.overland_between_continents_crosses',{x:LAND_X}));if(andesPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_andes_2'));if(nullPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_nullarbor_x',{x:NULLARBOR}));if(borderPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_a_border_in'));if(rainPair(a,b))r.push(tr('geography_and_latency.this_route_goes_into_the_amazon'));return r.join(' ');} +function linkLat(l){if(l.kind==='xp')return xpLat(l);if(l.kind==='sat')return satLat(l);const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} +/* Wave prices differ a lot by market (TeleGeography): Europe's dense, competitive metro and + long-haul routes are cheap (Frankfurt–London 100G ≈ $1,150/mo), the US costs more, and + routes into Africa are several times dearer (Africa–Europe ≈ 5.9× London–New York). + Each route also gets its own market mood, and new leases get cheaper every year (~8%). */ +const WAVE_LAND={EU:0.65,AM:1,SA:1.6,AS:1.4,OC:1.2,AF:2.2},WAVE_SUB={EU:0.8,AM:1,SA:2,AS:1.5,OC:1.5,AF:4.5}; +const WAVE_NAME={EU:tr('common.europe'),AM:tr('common.north_america'),SA:tr('common.south_america'),AS:tr('common.asia'),OC:tr('common.oceania'),AF:tr('common.africa')}; +// New leases on day d against day 0: 8% cheaper each year, down to 55%. +const waveEro=d=>Math.max(0.55,Math.pow(0.92,Math.floor(d/360))); +function waveMarket(a,b,sub){const ra=CITY[a].reg,rb=CITY[b].reg,T=sub?WAVE_SUB:WAVE_LAND,au=sub?AU_WAVE.sub:AU_WAVE.land; + const fa=CITY[a].au?au:(T[ra]||1),fb=CITY[b].au?au:(T[rb]||1),reg=sub&&nullPair(a,b)?AU_WAVE.ew:sub&&CITY[a].ph&&CITY[b].ph?PH_WAVE:sub?Math.max(fa,fb):(fa+fb)/2; + const key=a1.03?tr('geography_and_latency.where_lvl_this_route_is_p_0196',{where,lvl,p:Math.round((k.mood-1)*100),since}):tr('geography_and_latency.where_lvl_this_route_is_right',{where,lvl,since});} +function waveRoute(a,b,mult,border){const cabs=cablesOk(a,b),sub=isSub(a,b);let via=UI.via; + if(!cabs.find(c=>c.cid===via))via=sub?(cabs[0]?cabs[0].cid:null):(via==='land'||!via?'land':'land'); + if(!via)return null;const bf=border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1; + if(via==='land')return {via,cabs,cab:null,km:kmBetween(a,b),sub:false,wm:mult*landMult(a,b)*waveMarket(a,b,false).m}; + const c=cabs.find(x=>x.cid===via);return {via,cabs,cab:via,km:c.km,sub:true,wm:bf*CAB[via].price*waveMarket(a,b,true).m};} +function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)return landMult(a,b)>1?`

${landWhy(a,b)}

`:'';const wr=waveRoute(a,b,1,false); + const opts=(sub?[]:[{v:'land',l:`${tr('common.overland')} ${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} ${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · '+tr('geography_and_latency.old_cuts_often'):''}`}))); + return `

${tr('common.route')}

${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}
${wr&&wr.cab?`

${esc(CAB[wr.cab].blurb)} ${tr('geography_and_latency.all_your_waves_on_one_cable')}

`:''}`;} +/* bestLat(a,b,f): the lowest one-way latency over the live links (f: only those), +0.05 ms a hop. latGraph() numbers the + cities with a live link (ix) and lists each one's links once, in S.links order, with their latency (off/nb/w). latRun() is + the search itself: the next city is the closest found so far, the first found among equals, and the sums are the same + (d + latency + 0.05), so the same answers. Stopped at b, or run whole (no b): distances by city number, which is what + asking from a for several cities takes (latAt(): solRoutes(), spots0(), opsDecomSafe()). */ +function latGraph(f){const ix=new Map(),deg=[],E=[],id=c=>{let i=ix.get(c);if(i===undefined){ix.set(c,i=deg.length);deg.push(0);}return i;}; + for(const l of S.links){if(linkDown(l)||f&&!f(l))continue;const u=id(l.a),v=id(l.b);E.push(u,v,linkLat(l));deg[u]++;if(v!==u)deg[v]++;} + const n=deg.length,off=new Int32Array(n+1);for(let i=0;i{if(a===b)return 0;const k=g.ix.get(b);return d&&k!==undefined?d[k]:Infinity;}; +function bestLat(a,b,f){return latRun(latGraph(f),a,b);} +// From each of these cities to the ones after it in the list: [[a,b,ms]…], one search per city. +function latPairs(f,g){const G=latGraph(g),o=[];for(let i=0;iCITY[c]&&!LATF.has(c));if(!a)return;LATW={a,g:latFloorRun(a)};} + const s=LATW.g.next();if(s.done){if(!LATF.has(LATW.a))LATF.set(LATW.a,s.value);LATW=null;}if(performance.now()-t>ms)return;}} +function* latFloorRun(a){const n=CITIES.length,D=new Float64Array(n).fill(Infinity),done=new Uint8Array(n);let k=0; + if(!LATC){LATC=new Map();for(const c of CABLE_PAIRS){const k=Math.min(CIDX[c.a],CIDX[c.b])*4096+Math.max(CIDX[c.a],CIDX[c.b]),w=c.km*Math.min(0.9,CAB[c.cid].lat||1);if(!(LATC.get(k)<=w))LATC.set(k,w);}} + D[CIDX[a]]=0;for(;;){if((++k&15)===0)yield;let u=-1,ud=Infinity;for(let i=0;i${tr('common.route_4a2e')}${Object.keys(RT).map(m=>btn(RT[m],'setRoute',{id:b.id,m},(b.route||'normal')===m?'pink sm':'ghost sm')).join('')}
${tr('sites_and_service.path_latency_lat',{lat:lt!==undefined&&isFinite(lt)?tr('common.ms_ms_one_way',{ms:lt.toFixed(1)}):tr('sites_and_service.no_path_right_now')})}${b.route==='scenic'&&R.l2split&&R.l2split[b.id]?' · '+tr('sites_and_service.split_over_two_equally_quiet_paths'):''}${b.latMax?' · '+tr('sites_and_service.budget_ms_ms',{ms:b.latMax}):''}
`;} +function nodeCap(c){const p=S.pops[c];if(!p)return Infinity;const eff=(p.routers||1)-(p.rdown>S.day?1:0);return RG[p.rgen||0].cap*coreCpu(c)*Math.max(1,eff)*(p.hot>S.day?(p.site2?0.75:0.5):1)*(p.site2&&(siteDown(c,'a')||siteDown(c,'b'))?0.5:1);} +// With a second site, one building can be dark (or cut off by a ring cut) while the other carries on. +function siteDown(c,s){const p=S.pops[c];if(!p||!p.site2)return false;if(S.inc.some(i=>i.type==='site'&&i.ref===c&&i.site===s&&i.until>S.day))return true;return s==='b'&&p.ringcut>S.day;} +// Ports can live in site A, site B, or be split across both ('ab'): a LAG with members in each +// building, so one dark building only takes out its half. +function liveN(c,site,n){n=n||1;const p=S.pops[c];if(!p||!p.site2)return n;if(site==='ab'){const a=Math.ceil(n/2),b=n-a;return (siteDown(c,'a')?0:a)+(siteDown(c,'b')?0:b);}return siteDown(c,site==='b'?'b':'a')?0:n;} +// Your own IX is a switch, not a port: it lives in building A or B, or in both with a second switch (#36). +const myIxLive=c=>{const ct=ixCity(c),st=(S.ixSite||{})[c]||'a';return st==='ab'?!(siteDown(ct,'a')&&siteDown(ct,'b')):!siteDown(ct,st);}; +const liveCap=(g,c,site,n)=>{const k=liveN(c,site,n);return k?lagCap(g,k):0;}; +const onSite=(site,s)=>(site||'a')===s||site==='ab'; +function siteCtl(k,id,c,cur){const p=S.pops[c];if(!p||!p.site2)return '';cur=cur||'a';const n=k==='t'?(S.transit.find(x=>x.id===id)||{}).n:k==='p'?(S.pni.find(x=>x.id===id)||{}).n:(S.ixn||{})[id];return `
${tr('common.site')}${['a','b'].map(x=>btn(`${x.toUpperCase()} ${esc(siteName(c,x))}`,'siteSet',{k,id,s:x},cur===x?'pink sm':'ghost sm')).join('')}${btn(k==='ix'&&S.myIx[id]?tr('sites_and_service.both_a_second_switch_price_mo',{price:fmt$(Math.round(myFab(id).mo/2))}):(n||1)<2?tr('sites_and_service.both_adds_a_lag_member'):tr('sites_and_service.both_split_the_lag'),'siteSet',{k,id,s:'ab'},cur==='ab'?'pink sm':'ghost sm')}
`;} +function portOk(c,i){const p=S.pops[c];return i<=RG[p?(p.rgen||0):0].maxP;} +function waveOk(a,b,i){return [a,b].every(c=>i<=RG[S.pops[c]?(S.pops[c].rgen||0):0].maxLT);} +function waveNeed(i){const g=RG.find(r=>r.maxLT>=i);return g?tr('sites_and_service.pn_routers',{pn:g.pn}):'?';} +function routerModels(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1; + return `
${RG.map((M,i)=>{if(i===g)return '';const why=modelFits(c,i),lk=!techOk('rg',i,M.lvl); + return `
${esc(M.n)} ${M.pn} · ${tr('sites_and_service.n_ports',{n:M.ports})} · ${fmtG(M.cap)} · ${tr('sites_and_service.boots_in_n_min',{n:M.boot})}${M.flaky?' · '+tr('common.crashes_more'):''}
${esc(M.blurb)}
${coreMeta(i)}${coreOn()&&coreRun()>0&&!rgCore(i,coreRun())?' · '+tr('core.can_t_run_your_lv',{lv:tr(CORE_LV[coreRun()])})+'':''}
${why?`
${esc(why)}
`:''}
${lk?demoBtn('rg',i,M.lvl,tr('sites_and_service.level_n',{n:M.lvl}),'sm'):btn(tr('sites_and_service.swap_cost_mo_mo',{cost:fmt$(swapCost(c,i)),mo:fmt$(M.mo*rt)}),'upRouter',{city:c,g:i},'sm',!!why||S.cash`;}).join('')}
`;} +function portNote(c){const p=S.pops[c];if(!p)return '';const g=p.rgen||0;return RG[g].maxP${tr('sites_and_service.your_model_here_tops_out_at',{model:esc(RG[g].n),pn:RG[g].pn})}

`:'';} +// Service: what you deliver, times how it feels. Traffic backhauled far to transit is slow, and users notice. +const latSlow=c=>!!(R&&R.latF&&R.latF[c]<0.97&&R.latFar[c]); +function latNote(c){if(!latSlow(c))return '';const f=R.latFar[c];const v={p:pct(Math.min(1,f.share)),city:esc(CITY[c].name),to:esc(CITY[f.to].name),ms:Math.round(f.ms)};return `
🐢 ${CITY[c].kr&&scnRule('sender')?tr('sites_and_service.p_of_city_s_traffic_comes_from_kr',v):tr('sites_and_service.p_of_city_s_traffic_is',v)}
`;} +const LAT_OK=20,LAT_BAD=50,latLoss=rtt=>rtt<=LAT_OK?0:rtt<=LAT_BAD?0.2*(rtt-LAT_OK)/(LAT_BAD-LAT_OK):0.5; +const krLatLoss=rtt=>rtt<=KR_LAT_OK?0:rtt<=KR_LAT_BAD?0.25*(rtt-KR_LAT_OK)/(KR_LAT_BAD-KR_LAT_OK):0.5; +function sfOf(r,c){const d=r.cityDem[c]||0;return d<=1e-6?1:clamp(r.citySrv[c]/d,0,1)*((r.latF&&r.latF[c])??1);} + diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js new file mode 100644 index 0000000..d5f1f07 --- /dev/null +++ b/src/game/85-incidents/10-incidents-and-ddos.js @@ -0,0 +1,163 @@ +/* ---------- failures & events ---------- */ +// A few badges read the incident text: callers whose message mentions a shark, anchor, crocodile or llama pass its English as en. +function addInc(o,en=o.msg||''){if(S.loans&&S.loans.some(l=>(l.covs||[]).includes('pizza'))){S.cash-=COVS.pizza.each;S.stats.pizza=(S.stats.pizza||0)+1;}o.id=uid();o.start=S.day;S.inc.push(o);S.stats.incidents++;S.stats.by=S.stats.by||{};S.stats.by[o.type]=(S.stats.by[o.type]||0)+1;if(/shark/i.test(en))S.stats.sharks=(S.stats.sharks||0)+1;const f=S.stats.f=S.stats.f||{};if(/anchor/i.test(en))f.anchor=1;if(/crocodile/i.test(en))f.croc=1;if(/beaver/i.test(en))f.beaver=1;if(/llama/i.test(en))f.llama=1;if(S.rules&&S.rules.chaos==='spicy')stretchInc(o);} +const HARMLESS=[ + [tr('common.certificate_expired'),tr('incidents_and_ddos.the_tls_certificate_on_your_noc')], + [tr('incidents_and_ddos.it_was_dns'),tr('incidents_and_ddos.someone_deleted_the_dns_record_for')], + [tr('common.leap_second'),tr('incidents_and_ddos.a_leap_second_convinced_one_of')], + [tr('common.change_freeze'),tr('incidents_and_ddos.management_declared_a_change_freeze')], + [tr('incidents_and_ddos.ticket_of_the_week'),tr('incidents_and_ddos.a_customer_opened_a_p1_ticket')], + [tr('common.monitoring'),tr('incidents_and_ddos.your_monitoring_system_went_down_you')], + [tr('incidents_and_ddos.load_bearing_typo'),tr('incidents_and_ddos.someone_named_a_vlan_prodcution_it')], + [tr('common.ipv6_milestone'),tr('incidents_and_ddos.your_ipv6_traffic_grew_400_from')], + [tr('common.mystery_link'),tr('incidents_and_ddos.you_found_a_10g_link_in')], + [tr('common.spreadsheet_ipam'),tr('incidents_and_ddos.your_ip_address_spreadsheet_hit_1')], + [tr('common.goose_incident'),tr('incidents_and_ddos.a_goose_attacked_the_technician_on')], + [tr('common.latency_test'),tr('incidents_and_ddos.a_carrier_pigeon_beat_one_of')], + [tr('common.zombie_route'),tr('incidents_and_ddos.a_route_you_withdrew_in_year')], + [tr('common.auditor_visit'),tr('incidents_and_ddos.an_auditor_asked_for_a_network')], + [tr('incidents_and_ddos.open_to_work'),tr('incidents_and_ddos.your_peering_coordinator_updated')], + [tr('common.hold_music'),tr('incidents_and_ddos.your_upstream_support_line_plays_the')], + [tr('common.naming_committee'),tr('incidents_and_ddos.a_two_hour_meeting_about_router')], + [tr('common.vendor_tac'),tr('incidents_and_ddos.vendor_support_asked_you_to_try')], +]; +function lagsN(){const o=[];for(const t of S.transit)if((t.n||1)>=2&&!(t.down>S.day))o.push({k:'t',id:t.id,o:t,n:t.n,lab:tr('incidents_and_ddos.name_transit_lag_in_city',{name:NET[t.net].name,city:CITY[t.city].name})}); + for(const p of S.pni)if((p.n||1)>=2)o.push({k:'p',id:p.id,o:p,n:p.n,lab:tr('incidents_and_ddos.pni_lag_with_name_in_city',{name:NET[p.net].name,city:CITY[p.city].name})}); + for(const x in S.ixp){const n=(S.ixn||{})[x]||1;if(n>=2&&!S.myIx[x])o.push({k:'ix',id:x,n,lab:ixNamesCity(x)?tr('incidents_and_ddos.ix_lag',{ix:ixName(x)}):tr('incidents_and_ddos.ix_lag_in_city',{ix:ixName(x),city:CITY[ixCity(x)].name})});}return o;} +// Several attacks can be live at once: the primary slot keeps older saves compatible, the rest overlap it. +function ddosAll(s=S,live=true){return [s.ev.ddos,...(s.ev.ddosMore||[])].filter(a=>a&&(!live||a.until>s.day));} +const ddosFind=id=>ddosAll().find(a=>id===undefined||a.id===id); +// No primary attack is no ddos key at all, as sanitize() leaves it. +function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);if(left[0])S.ev.ddos=left[0];else delete S.ev.ddos;S.ev.ddosMore=left.slice(1);} +const ddosBb=a=>!a.tgt||a.tgt.startsWith('bb:'); +const ddosBiz=a=>ddosBb(a)?null:S.biz.find(b=>b.id===a.tgt)||null; +// An attack ends on its day, when its city is gone, or when its target is no longer your customer. +function ddosExpire(){for(const a of ddosAll(S,false))if(a.until<=S.day||!S.pops[a.city]||(!ddosBb(a)&&!ddosBiz(a))){ddosDone(a);ddosDrop(a);}} +function ddosReport(a){return (R.ddos||[]).find(m=>m.attack===a)||null;} +// How well the target is doing: what reached it, times how its city is doing. +function ddosSf(a){const m=ddosReport(a),tf=m?m.tf:1;if(ddosBb(a))return Math.min(tf,sfOf(R,a.city));return tf*bizSfOf(R,a.city);} +// What the attack costs everyone else, as a share of all your traffic. +const ddosCol=a=>{const m=ddosReport(a);return m&&R.demand>0?m.col/R.demand:0;}; +// Who is under attack, in words. +function ddosWho(a){const b=ddosBiz(a);return b?tr('ddos.who_customer',{name:b.name,what:BIZ_T[b.type].l,city:CITY[a.city].name}):tr('ddos.who_subscribers',{city:CITY[a.city].name});} +// Flowspec capability of a POP's router: 0 none, 1 basic, 2 full (its rule budget is fsCap). +const fsAt=c=>{const p=S.pops[c];return p?(RG[p.rgen||0].fs||0):0;}; +// A DDoS-protection customer whose attacks ride far to be cleaned (#117). +const scrubFar=c=>{for(const a of ddosAll())if(a.city===c){const q=(R.haul||[]).find(q=>q.attack===a.id&&q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS);if(q)return q;}return null;}; +/* ---------- who gets attacked, how hard and how often ---------- + Most real floods are small and short; the giant ones are rare (Cloudflare, H1 2026: 96.6% under 500 Mbps; the record + is 31.4 Tbps). Sizes come from that world, never from how big your network is. Gamers and hosting attract them. */ +const DD_W={cgame:8,game:5,esport:5,host:3,metav:3,scrub:2},DD_REC=31000; +const ddGame=t=>{const b=t&&S.biz.find(x=>x.id===t);return !!b&&(!!BIZ_T[b.type].gaming||b.type==='esport');}; +const ddAttract=()=>S.biz.reduce((n,b)=>n+(b.type==='cgame'?2:BIZ_T[b.type].gaming||b.type==='esport'?1:b.type==='host'?0.25:0),0); +const ddosOff=()=>{const c=rule('chaos');return c==='calm'||c==='none'||S.mode==='sandbox'||S.mode==='puzzle';}; +const ddosSpicy=()=>!ddosOff()&&rule('chaos')==='spicy'; +// Expected attacks a day: one in 40, one more in 40 per attractive customer, at most one in 5; BGP at 3 a.m. doubles it. +const ddosRate=()=>Math.min(1/5,(1+ddAttract())/40)*(ddosSpicy()?2:1); +const ddosVectors=gm=>Object.keys(DDOS_VEC).filter(k=>!DDOS_VEC[k].gaming||gm); +function ddosTargets(){const o=[];for(const b of S.biz){const T=BIZ_T[b.type];if(!T||T.l2||T.fiber||!S.pops[b.city]||(T.event&&!eventLive(b)))continue;o.push([b.id,b.city,DD_W[b.type]||1]);} + for(const c in S.pops)if(S.pops[c].bb&&S.pops[c].bb.d>0)o.push(['bb:'+c,c,1]);return o;} +function ddosPickTgt(){const o=ddosTargets();if(!o.length){const c=pick(Object.keys(S.pops));return ['bb:'+c,c];} + let t=o.reduce((n,x)=>n+x[2],0)*Math.random();for(const x of o){t-=x[2];if(t<=0)return x;}return o[o.length-1];} +// The biggest port you have to the outside world. +function ddMaxPort(){let g=10;for(const t of S.transit)g=Math.max(g,PORT[t.tier].g*(t.n||1));for(const p of S.pni)g=Math.max(g,pniG(p)*(p.n||1));for(const x in S.ixp)g=Math.max(g,ixCap(x));return g;} +const ddEraMax=()=>LEVELS.reduce((a,L)=>a*(L.era||1),1); +/* 4 Gbps × the era × a heavy tail: a median near 9 G, one in ten over 50 G, one in a hundred over 650 G, at most the + era's record. A gaming target doubles it. For the first 180 days, and with one POP, never more than twice your + biggest port: the first lesson is a full port, not a dead company. Flood Season: a third are 0.8 to 3.4 T monsters + that grow through the year, the rest eight times the usual. One draw picks the size. */ +function ddosSize(a){const fl=scnRule('ddos'),r=Math.random(),cap=DD_REC*eraMul()/ddEraMax(); + if(fl&&r<1/3)return Math.round(Math.min(cap,(800+7800*r)*(1+S.day/365))); + const u=fl?(r-1/3)*1.5:r,base=4*eraMul()*(ddGame(a.tgt)?2:1)*(fl?8:1);let g=Math.min(cap,base*Math.pow(Math.max(u,1e-9),-1/0.9)); + if(!fl&&(netAge()<180||Object.keys(S.pops).length<2))g=Math.min(g,2*ddMaxPort()); + return Math.max(0.1,Math.round(g*10)/10);} +// Flood Season: 3 to 7 days apart, shrinking with age, level and gamers when attacks are spicy. +const floodGap=()=>!ddosSpicy()&&!ddAttract()?3+Math.floor(Math.random()*5):Math.max(0.05,(3+Math.random()*5)/(Math.sqrt(1+S.day/180)*(1+ddAttract()/10+Math.max(0,(S.lvl||1)-1)/12))); +function ddosTick(){if(scnRule('ddos')){if(S.mode==='sandbox')return;let next=+S.scn.nextDdos||3,n=0; + // Unless spicy, floods take turns: the next one waits until the last is over. + if(!ddosSpicy()&&ddosAll().length)return; + while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next=(ddosSpicy()?3:2))return;if(Math.random()x>d-7);} +// A new attack. With recompute, its outcome is worked out and announced now; otherwise after the day's routing. +function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire(); + S.ddosStarts=(S.ddosStarts||[]).filter(d=>d>S.day-7&&d<=S.day);if(S.ddosStarts.length>=14||!Object.keys(S.pops).length)return null;S.ddosStarts.push(S.day); + const [tgt,c]=ddosPickTgt(),vec=pick(ddosVectors(ddGame(tgt))),r=Math.random(),dur=r<0.7?1:r<0.95?2:3; + const a={id:uid(),city:c,tgt,vec,gbps:0,until:S.day+dur,bh:false,start:S.day,carpet:Math.random()<0.2,fresh:1,sac:0,colMax:0,sla:[]};a.gbps=ddosSize(a); + if(fl)a.who=pick(FLOOD_WHO); + if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a); + addInc({type:'ddos',ref:c,atk:a.id,until:a.until,msg:tr('ddos.started',{g:fmtG(a.gbps),vec:DDOS_VEC[vec].n,who:ddosWho(a)}),cost:0}); + if(recompute){compute();ddosNews();} + return a;} +/* After the day's routing: announce new attacks with what they are doing, pull the plug when Auto-RTBH says so, and + teach each lesson once. */ +function ddosNews(){runNow(ddosNewsRun());} +// The lessons taught once a game, in the shape sanitize() gives them. +const ddosTaught=()=>S.stats.ddT||(S.stats.ddT={port:0,fs:0,rtbh:0}); +// The same as a step of the day: its yield is the routing after Auto-RTBH pulled a plug. +function* ddosNewsRun(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh; + for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue; + if(auto&&!a.bh&&m.full>0&&ddosCol(a)>=0.01){a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);again=true; + toast(tr('ddos.auto_rtbh',{who:esc(ddosWho(a))}),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:a.city});}} + if(again)yield; + const T=ddosTaught(); + for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue; + if(a.fresh){delete a.fresh;const fl=scnRule('ddos'),col=ddosCol(a),sf=ddosSf(a),bad=col>=0.01||sf<0.97; + const how=a.bh?tr('ddos.news_rtbh'):col>=0.01?tr('ddos.news_ports',{n:m.full,k:m.slowed}):sf<0.97?tr('ddos.news_target',{p:pct(sf)}):tr('ddos.news_held'); + toast(`${incTitle('ddos')}: ${esc(ddosWho(a))}
${esc(tr('ddos.started',{g:fmtG(a.gbps),vec:DDOS_VEC[a.vec].n,who:ddosWho(a)}))} ${esc(how)}${fl&&a.who?`
${esc(tr('failures.attacker_who',{who:tr(a.who)}))}`:''}`,bad?'bad':'good',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:a.city}); + if(bad)sfx('alert');} + // Lessons, once a game each. + if(!T.port&&m.full>0&&!a.bh){T.port=1;toast(tr('ddos.learn_port'),'',[],{a:'tab',v:'noc'});} + if(!T.fs&&m.fsFull.length){T.fs=1;toast(tr('ddos.learn_fs',{city:CITY[m.fsFull[0]].name}),'',[],{a:'city',v:m.fsFull[0]});}}} +// What the day did to each live attack's score: the worst the target got, the most it cost everyone else. +function ddosTrack(list=ddosAll()){for(const a of list)if(S.pops[a.city]){a.worst=Math.min(a.worst??1,ddosSf(a));a.colMax=Math.max(a.colMax||0,ddosCol(a));}} +// RTBH costs the target: its service is gone while it lasts, and it remembers. +function ddosRtbhMood(a){const b=ddosBiz(a);if(b)b.mood=Math.max(0,b.mood-25);} +/* When an attack is over. Held: the target got 97% and nobody else lost more than 1%. Sacrificed: you blackholed the + target and saved everyone else. Anything else got through. */ +function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pops[a.city]&&R)ddosTrack([a]); + const w=a.worst===undefined?1:a.worst,col=a.colMax||0,held=!a.sac&&w>=0.97&&col<0.01,sac=!!a.sac&&col<0.01; + if(held){S.stats.ddosOk=(S.stats.ddosOk||0)+1;S.stats.ddosHeld=(S.stats.ddosHeld||0)+1;if(a.gbps>=1000){S.stats.ddosOkBig=(S.stats.ddosOkBig||0)+1;S.stats.ddosMonster=(S.stats.ddosMonster||0)+1;}} + else if(sac)S.stats.ddosSac=(S.stats.ddosSac||0)+1; + else{S.stats.ddosLost=(S.stats.ddosLost||0)+1;if(col>=0.01)S.stats.ddosCol=(S.stats.ddosCol||0)+1;} + if(scnRule('ddos')){const w2=tr(FLOOD_WHO.includes(a.who)?a.who:FLOOD_WHO[0]),who=esc(w2.charAt(0).toUpperCase()+w2.slice(1)); + toast(held?tr('failures.flood_held_g_who_gave_up',{g:fmtG(a.gbps),who}):sac?tr('ddos.flood_sacrificed',{g:fmtG(a.gbps),who:esc(ddosWho(a))}):tr('failures.that_one_got_through_g_city',{g:fmtG(a.gbps),city:esc(CITY[a.city]?CITY[a.city].name:tr('common.your_network')),p:pct(w),who:esc(w2)}),held||sac?'goal':'bad');}} +/* ---------- the NOC card: the flood's path, top to bottom, and the one thing to do now ---------- */ +function ddosPanel(){return S?ddosAll().filter(a=>S.pops[a.city]).map(ddosOne).join(''):'';} +const ddCities=l=>{const u=[...new Set(l)];return u.slice(0,3).map(c=>CITY[c].name).join(', ')+(u.length>3?' +'+(u.length-3):'');}; +function ddosOne(a){const V=DDOS_VEC[a.vec]||{n:'?',fs:false},m=ddosReport(a),row=(ok,t)=>`
${ok===true?'✓':ok===false?'~':'—'} ${t}
`; + let h=`
🚨 ${tr('ddos.card_title',{g:fmtG(a.gbps),vec:esc(V.n)})}
+
${esc(ddosWho(a))} · ${tr('ui.n_d_left',{n:Math.max(1,a.until-S.day)})}${a.carpet?' · '+tr('ddos.carpet'):''}
`; + if(!m)return h+'
'; + const engIdle=hasScrub()&&!a.bh&&m.eng<1&&S.scrubMode==='ondemand'&&S.ddosAuto&&S.ddosAuto.scrub===false&&a.eng===undefined; + // 1. Upstream and the ports. + if(a.bh)h+=row(true,tr('ddos.row_rtbh',{g:fmtG(m.up)})); + if(m.portList&&m.portList.length){const full=m.portList.filter(p=>p.fac<0.97); + h+=row(full.length?false:true,full.length?trn('ddos.row_ports_full',m.portList.length,{k:full.length,labs:esc(full.slice(0,2).map(p=>p.lab+' ('+CITY[p.city].name+')').join(', '))+(full.length>2?' +'+(full.length-2):'')}):trn('ddos.row_ports_ok',m.portList.length)); + if(m.slowed)h+=row(false,trn('ddos.row_slowed',m.slowed));} + // 2. Inside: Flowspec and scrubbing. + if(!a.bh){if(!V.fs)h+=row(null,tr('ddos.row_fs_none',{vec:esc(V.n)})); + else if(m.fs>1e-6)h+=row(true,tr('ddos.row_fs',{g:fmtG(m.fs),n:m.fsAt.length}))+(m.fsFull.length?row(false,tr('ddos.row_fs_full',{cities:esc(ddCities(m.fsFull))})):''); + else if(m.fsFull.length)h+=row(false,tr('ddos.row_fs_full',{cities:esc(ddCities(m.fsFull))})); + else if(m.portList&&m.portList.length)h+=row(null,tr('ddos.row_fs_no_router')); + if(m.pulled>0)h+=row(m.over>1e-6?false:true,tr('ddos.row_scrub',{g:fmtG(m.pulled),c:fmtG(m.cleaned),cities:esc(ddCities(m.parts.map(x=>x.city)))})); + else if(engIdle)h+=row(null,tr('ddos.row_scrub_idle')); + else if(!hasScrub())h+=row(null,tr('ddos.row_scrub_none')); + const far=(R.haul||[]).filter(q=>q.attack===a.id&&q.ms>0).sort((x,y)=>y.ms-x.ms)[0];if(far)h+=row(null,tr('ddos.row_detour',{ms:far.ms.toFixed(0),city:esc(CITY[far.to].name)}));} + // 3. The result. + const sf=ddosSf(a),col=ddosCol(a); + h+=`
${a.bh?tr('ddos.res_rtbh',{who:esc(ddosBiz(a)?ddosBiz(a).name:CITY[a.city].name)}):col>=0.01?tr('ddos.res_col',{p:pct(sf),g:fmtG(m.col)}):sf<0.97?tr('ddos.res_target',{p:pct(sf)}):tr('ddos.res_held')}
`; + // The one thing to do now, and the rest behind "More". + const rt=btn(tr('ddos.btn_rtbh'),'rtbh',{id:a.id},'red sm'),un=btn(tr('common.stop_blackholing'),'unrtbh',{id:a.id},'ghost sm'),eng=btn(tr('ddos.btn_engage'),'ddosEngage',{id:a.id},'green sm'),hb=btn(tr('incidents_and_ddos.hackback_3000tm_20k'),'hackback',{id:a.id},'sm',S.cash<20000); + const main=a.bh?un:engIdle?eng:m.full>0&&col>=0.01?rt:'',more=[a.bh||main===rt?'':rt,hb].filter(Boolean).join(''); + h+=`
${main}
${tr('ddos.more')}
${more}

${tr('ddos.rtbh_help')}

`; + return h;} +// The NOC's standing DDoS settings: where the scrubbing is, the routers' Flowspec rules, and the two automations. +function ddosSettings(){if(!S)return '';const pops=Object.keys(S.pops),fs=pops.filter(c=>fsCap(c)>0); + let h=`
${tr('common.ddos_scrubbing')}${hasScrub()?tr('hud_and_panels.on_city',{city:S.scrubs.map(x=>CITY[x.city].name).join(', ')}):tr('hud_and_panels.none_build_one_from_a_pop')}
`; + h+=`
${tr('ddos.fs_pops')}${fs.length}/${pops.length}
`; + if(fs.length${tr('ddos.fs_help')}

`; + const A=S.ddosAuto||{}; + h+=`
${btn(A.rtbh?tr('ddos.auto_rtbh_on'):tr('ddos.auto_rtbh_off'),'ddosAuto',{k:'rtbh'},A.rtbh?'green sm':'sm')}${hasScrub()&&S.scrubMode==='ondemand'?btn(A.scrub===false?tr('ddos.auto_scrub_off'):tr('ddos.auto_scrub_on'),'ddosAuto',{k:'scrub'},A.scrub===false?'sm':'green sm'):''}${S.mode==='sandbox'?btn(tr('ddos.test_flood'),'ddosTest',{},'sm'):''}
`; + return h;} diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js new file mode 100644 index 0000000..ad9f84f --- /dev/null +++ b/src/game/85-incidents/20-failures.js @@ -0,0 +1,174 @@ +// Anchors Away (Baltic): a link on an anchor-prone cable, or on a pair one serves (the map calls those overland). +const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair(l); +// The wet season in the tropical north (November to April): floods close the tracks, so a cut on land takes twice as long to reach. +const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason(); +/* failureRun() is a failure as a step of the day (10-day-tick.js): its yield is the routing that tells what it cost, + done by the route worker in play. fireFailure() is the same failure all at once, routed on the spot. */ +function fireFailure(only){runNow(failureRun(only));} +// A step of the day played all at once: every routing it asks for, on the spot (tests, a failure outside a day). +function runNow(g){dayGo(g,(g,v)=>g.next(v));} +function* failureRun(only){ + const opts=[]; + const live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; + // A fiber that only carries expresses is dark as a link of its own, but there is light in it: a backhoe still finds it. + const bare=S.links.filter(xpBare),dug=live.concat(bare); + if(dug.length){opts.push(['cut',2+Math.min(6,dug.length/2)]);} + if(Object.keys(S.pops).length)opts.push(['crash',3],['power',2]); + if(Object.values(S.pops).some(p=>p.site2))opts.push(['ring',1.2]); + if(S.transit.some(t=>!(t.down>S.day)))opts.push(['transit',3]); + if(Object.keys(S.ixp).length)opts.push(['ixloop',2]); + if(S.transit.length&&netAge()>60)opts.push(['leak',2]); + if(fabsUsed.length)opts.push(['fabric',1.5]); + // A geomagnetic storm: rare, and only while a LEO circuit of yours is in the sky. + if(!leoStorm()&&leoLive())opts.push(['leostorm',LEO_STORM_W]); + // An island zone's spur cable (46-wisp-zones.js): only while one is lit and whole, so other games draw as before. + const wsp=wispOn()?wispSpurs():[];if(wsp.length)opts.push(['wspur',WISP_CUT_W*wsp.length]); + // Amp huts and ROADMs carry every channel in the glass, the expresses' too; an optic of its own needs a channel of its own. + const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0&&!linkDown(l)),amps=lit.concat(bare);if(amps.length)opts.push(['amp',1.5+amps.length*0.3]);if(lit.length)opts.push(['optic',1.5+lit.length*0.3]); + // Two vendors' idea of the same protocol: the higher the backbone runs, the more often they disagree. + const iop=coreIopRisk()?coreIopLinks(live):[];if(iop.length)opts.push(['interop',3*coreIopRisk()]); + opts.push(['funny',4]); + if(!opts.length)return; + let tot=opts.reduce((a,o)=>a+o[1],0),r=Math.random()*tot,type=opts[0][0]; + for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}} + if(only)type=only; + if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');else if(bare.length)f.push('loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(S.transit.length)f.push('prepend');if(netAge()>30)f.push('rpki');if(amps.length)f.push('roadmff');type=pick(f);} + const before=R.served; + if(type==='harmless'){const m=pick(HARMLESS);S.stats.incidents++;S.stats.survived++;toast(`${m[0]}
${m[1]}`,'goal');sfx('alert');return;} + if(type==='ring'){const cs=Object.keys(S.pops).filter(c=>S.pops[c].site2),c=pick(cs),pp=S.pops[c],dur=2+Math.floor(Math.random()*3);pp.ringcut=S.day+dur; + addInc({type,ref:c,until:pp.ringcut,msg:pick([tr('failures.a_backhoe_cut_the_metro_ring',{city:CITY[c].name}),tr('failures.someone_pulled_the_wrong_cross',{city:CITY[c].name,siteB:siteName(c,'b'),siteA:siteName(c,'a')}),tr('failures.a_tram_line_construction_project_in',{city:CITY[c].name})]),cost:3000,fix:tr('failures.splice_it_tonight')});} + else if(type==='ac'){const c=pick(Object.keys(S.pops)),pp=S.pops[c];pp.hot=S.day+2; + addInc({type,ref:c,until:pp.hot,msg:CITY[c].lux&&Math.random()<0.7?tr('failures.a_forestry_strike_stopped_the_waste',{dc:siteName(c,'a'),city:CITY[c].name}):pick([tr('failures.the_a_c_at_dc_died',{dc:siteName(c,'a'),city:CITY[c].name}),tr('failures.someone_set_the_data_center',{city:CITY[c].name}),tr('failures.the_cooling_contractor_in_city',{city:CITY[c].name})]),cost:2000,fix:tr('failures.buy_40_desk_fans')}); + }else if(type==='interop'){ + const ls=coreIopLinks(live);if(!ls.length)return;const l=pick(ls),dur=1+Math.floor(Math.random()*2),A=CITY[l.a].name,B=CITY[l.b].name,va=RG_V[RG[S.pops[l.a].rgen||0].v],vb=RG_V[RG[S.pops[l.b].rgen||0].v],L=tr(CORE_LV[S.core.run]);l.cut=Math.max(l.cut||0,S.day+dur); + addInc({type,ref:l.id,until:l.cut,msg:pick([tr('core.va_and_vb_disagree_about',{va,vb,lv:L,a:A,b:B}),tr('core.a_firmware_update_on_the_va',{va,vb,lv:L,a:A,b:B}),tr('core.both_tacs_say_it_is',{va,vb,a:A,b:B})]),cost:2500,fix:tr('core.open_a_ticket_with_both')}); + }else if(type==='fatwave'||type==='label'){ + const l=pick(live),dur=1+Math.floor(Math.random()*2),A=CITY[l.a].name,B=CITY[l.b].name,W=pick(WAVECO);l.cut=Math.max(l.cut||0,S.day+dur); + const msg=type==='label'?pick([tr('failures.someone_in_dc_labeled_every_patch',{dc:siteName(l.a,'a'),a:A,b:B}),tr('failures.a_remote_hands_tech_in_a',{a:A,b:B}),tr('failures.a_new_tech_in_a_tidied',{a:A,b:B})]) + :l.kind==='df'?pick([tr('failures.the_landlord_in_a_re_routed',{a:A,b:B}),tr('failures.a_splicer_fusing_someone_else_s',{b:B})]) + :pick([tr('failures.co_fat_fingered_a_cross_connect',{co:W,a:A,b:B}),tr('failures.co_did_quick_maintenance_on_the',{co:W,a:A,b:B}),tr('failures.co_scheduled_maintenance_in_utc_your',{co:W,a:A,b:B}),tr('failures.an_engineer_at_co_swapped_tx',{co:W,a:A,b:B}),tr('failures.co_decommissioned_your_a_b_wave',{co:W,a:A,b:B})]); + addInc({type,ref:l.id,until:l.cut,msg,cost:1500,fix:tr('failures.bribe_their_noc_with_donuts')}); + }else if(type==='lacp'){ + const g=pick(lagsN()),n=g.n,dur=1+Math.floor(Math.random()*3),v=Math.floor(Math.random()*4); + const f=v===0?Math.max(0.3,1.4/n):v===3?0:(n-1)/n,until=S.day+(v===3?1:dur),lab=g.lab; + if(g.k==='ix'){S.ev.ixlacp=S.ev.ixlacp||{};S.ev.ixlacp[g.id]={until,f};}else g.o.lacp={until,f}; + const msg=[N_('failures.hash_polarisation_on_your_lab_nearly'), + N_('failures.lacp_fast_slow_timer_mismatch_on'), + N_('failures.one_member_of_your_lab_was'), + N_('failures.someone_set_min_links_on_your')][v]; + addInc({type,ref:g.k+':'+g.id,until,msg:tr(msg,{lab}),cost:600,fix:tr('failures.fix_the_lacp_config')},msg); + }else if(type==='loss'){ + const deep=l=>[l.a,l.b].every(c=>S.pops[c]&&/deep-buffer/.test(RG[S.pops[c].rgen||0].chip)); + // Only the dirty connector (v 0) is in the glass, so it dims the expresses riding the fiber too; microbursts and a + // marginal optic are its own routers' and optics'. A fiber that only carries expresses has nothing else to go wrong. + const l=pick(live.concat(bare)),r=Math.floor(Math.random()*3),v=xpBare(l)?0:r; + if(v===1&&deep(l)){S.stats.incidents++;S.stats.survived++;toast(tr('failures.microbursts_on_a_b_your_deep',{a:CITY[l.a].name,b:CITY[l.b].name}),'goal');return;} + const f=[0.6,0.8,0.7][v],dur=2+Math.floor(Math.random()*3);l.loss=v?{until:S.day+dur,f}:{until:S.day+dur,f,glass:true}; + const msg=[N_('failures.a_dirty_connector_on_a_b'), + N_('failures.microbursts_on_a_b_overflow_shallow'), + N_('failures.crc_errors_on_a_b_a')][v]; + addInc({type,ref:l.id,until:l.loss.until,msg:tr(msg,{a:CITY[l.a].name,b:CITY[l.b].name}),cost:900,fix:[tr('failures.clean_the_connector'),tr('failures.rate_limit_the_bursts'),tr('failures.swap_the_optic')][v]},msg); + }else if(type==='pmtud'){ + const top=NETS.filter(n=>(R.demTo[n.id]||0)>0.5).sort((a,b)=>(R.demTo[b.id]||0)-(R.demTo[a.id]||0)).slice(0,8),n=pick(top.length?top:NETS),dur=2+Math.floor(Math.random()*3); + S.ev.pmtud={net:n.id,until:S.day+dur,f:0.6}; + const msg=hasScrub()&&Math.random()<0.5?N_('failures.your_scrubbing_center_returns_clean') + :pick([N_('failures.someone_filtered_all_icmp_on_your'), + N_('failures.a_pppoe_hop_shaved_8_bytes')]); + addInc({type,ref:n.id,until:S.ev.pmtud.until,msg:tr(msg,{net:n.name}),cost:500,fix:tr('failures.clamp_the_mss_to_1360')},msg); + }else if(type==='mtu'){ + const l=pick(live);l.deg=S.day+3;addInc({type,ref:l.id,until:l.deg,msg:tr('failures.mtu_mismatch_on_a_b_jumbo',{a:CITY[l.a].name,b:CITY[l.b].name}),cost:800,fix:tr('failures.set_mtu_9216_everywhere')}); + }else if(type==='oops'||type==='cleaner'){ + const c=pick(Object.keys(S.pops)),pp=S.pops[c],C=CITY[c].name; + if(type==='cleaner'&&pp.site2&&(pp.routers||1)<2){S.stats.survived++;addInc({type:'site',ref:c,site:'a',until:S.day+1,msg:tr('failures.the_cleaner_unplugged_everything_at',{siteA:siteName(c,'a')}),cost:0});toast(tr('failures.vacuum_incident_in_city_the_cleaner',{city:C,siteA:esc(siteName(c,'a')),siteB:esc(siteName(c,'b'))}),'good');sfx('alert');return;} + if(type==='cleaner'&&(pp.routers||1)>=2){S.stats.incidents++;S.stats.survived++;toast(tr('failures.vacuum_incident_in_city_the_cleaner_47e0',{city:C,dc:siteName(c,'a')}),'good');sfx('alert');return;} + pp.down=Math.max(pp.down||0,S.day+1); + const msg=type==='cleaner'?tr('failures.the_cleaner_at_dc_unplugged_your',{dc:siteName(c,'a')}):pick([tr('failures.your_on_call_engineer_typed_clear',{city:C}),tr('failures.an_intern_pushed_an_acl_in',{city:C}),tr('failures.someone_ran_reload_on_the_city',{city:C}),tr('failures.a_config_template_rendered_router_id',{city:C}),tr('failures.someone_committed_a_config_in_city',{city:C}),tr('failures.someone_deployed_to_city_on_a',{city:C}),tr('failures.a_cosmic_ray_flipped_a_bit',{city:C}),tr('failures.an_automation_script_in_city_ran',{city:C})]); + addInc({type,ref:c,until:pp.down,msg:msg+(type==='oops'&&(pp.routers||1)>=2?' '+tr('failures.automation_pushed_it_to_every_router'):''),cost:1500,fix:type==='oops'?tr('failures.roll_back_the_config'):tr('failures.hide_the_vacuum')}); + }else if(type==='prepend'){ + const t=pick(S.transit);t.down=Math.max(t.down||0,S.day+2);addInc({type,ref:t.id,until:t.down,msg:tr('failures.net_fat_fingered_a_route_map',{net:NET[t.net].name,n:30+Math.floor(Math.random()*60),city:CITY[t.city].name}),cost:0}); + }else if(type==='rpki'){ + S.ev.rpki={until:S.day+3,nets:NETS.map(n=>n.id).filter(()=>Math.random()<0.5)};addInc({type,ref:'rpki',until:S.day+3,msg:tr('failures.your_roa_expired_over_the_weekend'),cost:1000,fix:tr('failures.renew_the_roa')}); + }else if(type==='amp'||type==='roadmff'){ + if(!amps.length)return;const l=pick(amps),A=CITY[l.a].name,B=CITY[l.b].name,dur=type==='roadmff'?1:(l.spares?1:2+Math.floor(Math.random()*3));l.eqDown=S.day+dur; + const msg=type==='roadmff'?tr('failures.you_fat_fingered_the_channel_plan',{a:A,b:B}):pick([tr('failures.an_in_line_amplifier_hut_between',{a:A,b:B}),tr('failures.someone_stole_the_copper_grounding',{a:A,b:B}),tr('failures.a_firmware_bug_in_the_sys',{sys:DF_SYS[l.sys].n,a:A}),tr('failures.lightning_hit_an_amp_site_on',{a:A,b:B})]); + addInc({type,ref:l.id,until:l.eqDown,msg:msg+(type==='amp'&&l.spares?' '+tr('failures.your_spares_kit_gets_it_back'):''),cost:type==='amp'&&!l.spares?AMP_COST:0,fix:tr('failures.truck_a_spare_amp_out')}); + }else if(type==='optic'){ + const l=pick(lit),A=CITY[l.a].name,B=CITY[l.b].name,o=pick(l.ch),dur=l.spares?1:4;l.chFail={n:1,o,until:S.day+dur}; + addInc({type,ref:l.id,until:S.day+dur,msg:pick([tr('failures.a_optic_on_a_b_overheated',{optic:OPT[o].n,a:A,b:B}),tr('failures.the_laser_in_a_optic_on',{optic:OPT[o].n,a:A,b:B}),tr('failures.a_optic_on_a_b_started',{optic:OPT[o].n,a:A,b:B})])+(l.spares?' '+tr('failures.swapped_from_your_spares_kit_by'):''),cost:l.spares?0:OPT[o].cost,fix:tr('failures.buy_a_replacement')}); + }else if(type==='cut'){ + const mon=cal(S.day).m,monsoon=mon>=5&&mon<=8,tw=x=>(x.sub&&(x.a==='tpe'||x.b==='tpe'||(x.cable&&CAB[x.cable].anchor)))||(scnRule('anchors')&&anchorProne(x)),vn=x=>x.sub&&(x.a==='sgn'||x.b==='sgn'),inl=x=>!x.sub&&(CITY[x.a].india||CITY[x.b].india); + const pool=only&&scnRule('anchors')?dug.filter(anchorProne):dug;if(!pool.length)return;const l=pick(pool.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=(10+Math.floor(Math.random()*8))*(wetCut(l)?2:1),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur)); + const A=CITY[l.a].name,B=CITY[l.b].name,au=CITY[l.a].au&&CITY[l.b].au,auSummer=mon>=11||mon<=1; + const en=wetCut(l)?N_('failures.the_wet_season_washed_out_the'):l.sub&&(CITY[l.a].au||CITY[l.b].au)&&!(l.cable&&CAB[l.cable].fragile)&&Math.random()<0.35?pick([N_('failures.box_jellyfish_season_at_the_a'),N_('failures.a_great_white_took_an_interest')]):l.cable&&CAB[l.cable].fragile&&Math.random()<0.8?pick([N_('failures.your_a_b_cable_is_cut'),N_('failures.a_b_is_down_same_cable')]):!l.sub&&CITY[l.a].land==='nzs'&&CITY[l.b].land==='nzs'&&Math.random()<0.75?pick([N_('failures.a_kea_pulled_the_rubber_seals'),N_('failures.the_sandflies_drove_your_splicing'),N_('failures.a_farmer_s_post_hole_digger')]):l.cable==='cook'&&Math.random()<0.6?N_('failures.a_ferry_dropped_anchor_in_cook'):!l.sub&&au&&Math.random()<0.75?pick([N_('failures.a_sulphur_crested_cockatoo_chewed'),N_('failures.a_kangaroo_hit_the_fiber_hut'),N_('failures.thieves_dug_up_your_a_b'),N_('failures.a_kilometre_of_copper_went_missing'),N_('failures.a_backhoe_putting_in_a_new'),N_('failures.the_emus_won_again_a_mob'),N_('failures.a_kangaroo_boxed_your_field_tech'),N_('failures.a_drop_bear_fell_on_the'),N_('failures.an_eastern_brown_snake_moved_into'),...((S.day%365)/30.42>=8&&(S.day%365)/30.42<11?[N_('failures.magpie_swooping_season_the_field')]:[]),...(auSummer?[N_('failures.bushfire_season_the_fiber_along_a')]:[]),...(nullPair(l.a,l.b)?[N_('failures.your_a_b_fiber_broke_somewhere')]:[])]):l.sub&&(l.a==='bda'||l.b==='bda')&&Math.random()<0.7?pick([N_('failures.your_a_b_cable_went_quiet'),N_('failures.the_repair_ship_s_compass_spun')]):l.sub&&(l.a==='tbu'||l.b==='tbu')&&Math.random()<0.7?pick([N_('failures.an_undersea_volcano_erupted_next_to'),N_('failures.the_seabed_off_tonga_slid_down')]):vn(l)&&Math.random()<0.8?pick([N_('failures.another_of_vietnam_s_subsea_cables'),N_('failures.your_a_b_cable_broke_in')]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([N_('failures.a_crocodile_took_a_bite_out'),N_('failures.termites_ate_the_duct_on_a')]):tw(l)&&Math.random()<0.8?pick([N_('failures.a_cargo_ship_forgot_to_raise'),N_('failures.another_anchor_another_cut_your_a'),N_('failures.a_fishing_boat_with_an_unusually')]):l.sub&&(l.a==='oos'||l.b==='oos')&&Math.random()<0.8?pick([N_('failures.a_trawler_off_ostend_dragged_its'),N_('failures.a_wind_farm_service_vessel_dropped')]):!l.sub&&(CITY[l.a].ca||CITY[l.b].ca)&&Math.random()<0.4?pick([N_('failures.a_beaver_chewed_through_your_a'),N_('failures.your_a_b_fiber_is_down'),N_('failures.frost_heave_cracked_the_duct_on')]):!l.sub&&andesPair(l.a,l.b)?pick([N_('failures.a_landslide_in_the_andes_buried'),N_('failures.snow_closed_the_mountain_pass_and'),N_('failures.an_earthquake_shook_your_a_b'),N_('failures.a_llama_herd_trampled_the_fiber')]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([N_('failures.road_widening_near_a_cut_your'),N_('failures.the_monsoon_flooded_a_manhole_on'),N_('failures.a_digger_found_your_a_b')]):l.sub?pick([N_('failures.a_curious_shark_bit_your_subsea'),N_('failures.a_ship_dragged_its_anchor_across'),N_('failures.an_undersea_landslide_snapped_a_b')]):pick([N_('failures.a_backhoe_found_your_fiber_between'),N_('failures.squirrels_chewed_through_a_b_they'),N_('failures.road_works_cut_a_b_nobody')]); + addInc({type,ref:trc,until:S.day+dur,msg:tr(en,{a:A,b:B})+(hit.length>1?' '+tr('failures.all_n_links_in_that_trench',{n:hit.length}):''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},en); + // At sea a cable ship sails out to it (50-cable-ships.js): it sets how long the cut lasts and what a charter costs. + // Without ships (Best Effort) a sea cut mends on the same clock as one on land. + if(l.sub&&!pzOn()&&shipsOn())shipCut(S.inc[S.inc.length-1],l); + }else if(type==='crash'||type==='power'){ + const c=pick(Object.keys(S.pops).flatMap(x=>type==='power'&&(CITY[x].za||CITY[x].blackout)?[x,x,x]:type==='crash'&&RG[S.pops[x].rgen||0].flaky?[x,x,x]:[x])),pp=S.pops[c],slow=slowBoot(c),dur=(type==='crash'?2+Math.floor(Math.random()*2):3+Math.floor(Math.random()*3))*(type==='crash'&&S.ev.sanction>S.day?2:1)+(slow?2+Math.floor(Math.random()*3):0); + if(type==='crash'&&(pp.routers||1)>=2){pp.rdown=S.day+dur;S.stats.incidents++;S.stats.survived++;toast(tr('failures.router_crash_in_city_one_router',{city:CITY[c].name,slow:slow?' '+tr('failures.the_crashed_one_what',{what:esc(pick(SLOW_BOOT))}):'',d:dur}),'good');sfx('alert');return;} + if(type==='power'&&!pp.gen&&pp.site2){const sd=Math.random()<0.5?'a':'b';addInc({type:'site',ref:c,site:sd,until:S.day+dur,msg:(CITY[c].za?tr('failures.load_shedding_took_out_site_in',{site:siteName(c,sd),city:CITY[c].name,other:siteName(c,sd==='a'?'b':'a')}):tr('failures.a_power_cut_took_out_site',{site:siteName(c,sd),city:CITY[c].name,other:siteName(c,sd==='a'?'b':'a')})),cost:5000,fix:tr('incidents.rent_a_generator')});S.stats.survived++;return;} + if(type==='power'&&pp.gen&&CITY[c].blackout){S.stats.incidents++;S.stats.survived++;S.stats.shed=(S.stats.shed||0)+1;toast(tr('failures.blackout_in_city_the_grid_went',{city:CITY[c].name}),'good');sfx('alert');return;} + if(type==='power'&&pp.gen){S.stats.incidents++;S.stats.survived++;if(CITY[c].za)S.stats.shed=(S.stats.shed||0)+1;toast(CITY[c].za?tr('failures.load_shedding_in_city_stage_n',{city:CITY[c].name,n:2+Math.floor(Math.random()*5)}):tr('failures.power_cut_in_city_your_backup',{city:CITY[c].name}),'good');sfx('alert');return;} + pp.down=Math.max(pp.down||0,S.day+dur); + const auc=CITY[c].au&&Math.random()<0.5,msg=type==='power'&&c==='ivc'&&Math.random()<0.6?tr('failures.the_smelter_at_tiwai_point_pulled',{city:CITY[c].name}):type==='crash'&&auc&&!slow?pick([tr('failures.a_routine_overnight_upgrade_took',{city:CITY[c].name}),tr('failures.a_huntsman_spider_the_size_of',{city:CITY[c].name}),tr('failures.a_new_tech_in_city_used',{city:CITY[c].name}),tr('failures.a_visiting_engineer_from_london',{city:CITY[c].name})]):type==='power'&&auc&&!CITY[c].blackout?((S.day%365)/30.42>=11||(S.day%365)/30.42<2?tr('failures.a_45_c_heatwave_in_city',{city:CITY[c].name,dc:siteName(c,'a')}):(c==='bne'&&Math.random()<0.6?tr('failures.the_four_o_clock_storm_rolled',{dc:siteName(c,'a')}):tr('failures.a_possum_got_into_the_substation',{city:CITY[c].name,dc:siteName(c,'a')}))):type==='crash'?(slow?tr('failures.your_router_in_city_crashed_and',{city:CITY[c].name,what:pick(SLOW_BOOT),min:bootMin(c),n:2+Math.floor(Math.random()*5)}):pick([tr('failures.your_router_in_city_crashed_kernel',{city:CITY[c].name}),tr('failures.a_firmware_update_bricked_your',{city:CITY[c].name})])):CITY[c].blackout?tr('failures.a_blackout_hit_city_and_your',{city:CITY[c].name}):CITY[c].za?tr('failures.load_shedding_stage_n_in_city',{n:3+Math.floor(Math.random()*4),city:CITY[c].name}):tr('failures.power_outage_at_dc_in_city',{dc:siteName(c,'a'),city:CITY[c].name}); + addInc({type,ref:c,until:S.pops[c].down,msg,slow:type==='crash'&&slow,cost:type==='crash'?2500:7000,fix:type==='crash'?(slow?tr('failures.turn_it_off_and_on_again'):tr('failures.turn_it_off_and_on_again_0872')):tr('incidents.rent_a_generator')}); + }else if(type==='transit'){ + const t=pick(S.transit.filter(t=>!(t.down>S.day)));t.down=S.day+3+Math.floor(Math.random()*3); + addInc({type,ref:t.id,until:t.down,msg:tr('failures.net_is_having_an_outage_in',{net:NET[t.net].name,city:CITY[t.city].name}),cost:0}); + }else if(type==='ixloop'){ + const c=pick(Object.keys(S.ixp));S.ev.ixdown=S.ev.ixdown||{};S.ev.ixdown[c]=Math.max(S.ev.ixdown[c]||0,S.day+2+Math.floor(Math.random()*2)); + addInc({type,ref:c,until:S.ev.ixdown[c],msg:tr('failures.someone_plugged_a_loop_into_the',{ix:ixName(c)}),cost:0}); + }else if(type==='leak'){ + const n=pick(['nfx','ggl','fbk','amz','msf']);S.ev.leak={net:n,until:S.day+4}; + addInc({type,ref:n,until:S.day+4,msg:tr('failures.bgp_route_leak_a_small_isp',{net:NET[n].name}),cost:0}); + }else if(type==='fabric'){ + const f=pick(fabsUsed);S.ev.fab=S.ev.fab||{};S.ev.fab[f]=S.day+2+Math.floor(Math.random()*3); + addInc({type,ref:f,until:S.ev.fab[f],msg:tr('failures.fabric_is_having_a_bad_day',{fabric:FAB[f].name}),cost:0}); + }else if(type==='leostorm'){leoStormGo(); + }else if(type==='wspur'){ + // The repair ship comes from far away: weeks, unless cuts mend on a timer (Best Effort). + if(!wsp.length)return;const z=pick(wsp),Z=wispZ(z),c=WISP[z].c,dur=rule('sea')==='timer'?3+Math.floor(Math.random()*5):14+Math.floor(Math.random()*22), + en=pick([N_('wisp.cut_anchor'),N_('wisp.cut_trawler'),N_('wisp.cut_slide'),...(WISP[z].v?[N_('wisp.cut_volcano')]:[])]),up=!!Z.sat&&!(Z.sat.ready>S.day); + addInc({type,ref:c,z,until:S.day+dur,msg:tr(en,{zone:WISP[z].n,city:CITY[c].name})+' '+(up?tr('wisp.cut_sat'):tr('wisp.cut_dark')),cost:WISP_RUSH,fix:tr('wisp.rush')},en); + }else if(type==='ddos'){ddosAttack(false);yield;yield* ddosNewsRun();return; + } + // This failure's incident, kept before the routing: the player may repair it (or another) while the worker routes. + const last=S.inc[S.inc.length-1]; + yield; + if(!last)return; + last.impact=Math.max(0,before-R.served); + if(before>1&&last.impact${incTitle(type)}
${esc(last.msg)} ${tr('failures.traffic_rerouted_customers_barely')}`,'good',[],incOpen(last));} + else{const paused=pref('pauseIncident')&&autoPause();toast(`${incTitle(type)}
${esc(last.msg)}${paused?`
${tr('common.game_paused')}`:''}`,'bad',(last.cost&&S.inc.includes(last)?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(type==='wspur'?[{l:tr('common.open'),act:'wispOpen',args:{z:last.z}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));} + sfx('alert'); +} +const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0); +const FLOOD_WHO=[N_('failures.a_botnet_of_40_000_smart'),N_('failures.every_unpatched_baby_monitor_in'),N_('failures.a_gaming_clan_that_lost_one'),N_('failures.a_fridge_that_achieved_sentience_and'),N_('failures.a_crypto_bro_shorting_your_stock'),N_('failures.a_teenager_with_a_stolen_credit'),N_('failures.a_rival_isp_s_stress_test'),N_('failures.ten_thousand_smart_light_bulbs'),N_('failures.a_printer_just_one_printer_nobody'),N_('failures.a_botnet_run_from_a_cloud'),N_('failures.somebody_who_did_not_like_your'),N_('failures.the_internet_connected_kettles_of_a')]; +function incTitle(t){return {ring:tr('failures.metro_ring_cut'),site:tr('common.site_outage'),cut:tr('common.fiber_cut'),crash:tr('common.router_crash'),power:tr('common.power_outage'),transit:tr('common.upstream_outage'),ixloop:tr('common.ix_meltdown'),leak:tr('common.route_leak'),ddos:tr('common.ddos_attack'),fabric:tr('common.fabric_outage'),depeer:tr('common.peering_spat'),fatwave:tr('failures.fat_fingered_wave'),label:tr('failures.patch_panel_mishap'),interop:tr('core.interop_failure'),mtu:tr('common.mtu_mismatch'),krroute:tr('failures.rerouted_via_hong_kong'),ctrlplane:tr('failures.control_plane_meltdown'),lacp:tr('common.lacp_trouble'),loss:tr('common.packet_loss'),pmtud:tr('failures.pmtud_black_hole'),oops:tr('common.oops'),cleaner:tr('common.vacuum_incident'),prepend:tr('common.prepend_ageddon'),rpki:tr('common.rpki_invalid'),amp:tr('common.amplifier_failure'),roadmff:tr('failures.fat_fingered_roadm'),optic:tr('common.dead_optic'),maint:tr('common.maintenance_window_3a92'),ac:tr('common.cooling_failure'),hijack:tr('common.bgp_hijack'),shutdown:tr('common.government_shutdown'),redsea:tr('failures.geopolitical_cable_cut'),leostorm:tr('pie_inc.t_storm'),wspur:tr('wisp.inc_title')}[t]||pieIncTitle(t)||tr('common.incident');} +const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label','interop'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic']; +function remainUntil(pred){let u=0;for(const x of S.inc)if(pred(x))u=Math.max(u,x.until);return u;} +// Remove an incident, then restore each affected thing to whatever other incidents still hold it down. +function clearInc(i){ + S.inc=S.inc.filter(x=>x!==i);const T=i.type; + if(LINKCUT_TR.includes(T)||LINKCUT_ID.includes(T)){const ls=LINKCUT_TR.includes(T)?S.links.filter(l=>(l.trench||l.id)===i.ref):S.links.filter(l=>l.id===i.ref); + for(const l of ls)l.cut=remainUntil(x=>(LINKCUT_TR.includes(x.type)&&x.ref===(l.trench||l.id))||(LINKCUT_ID.includes(x.type)&&x.ref===l.id));} + else if(POPDOWN.includes(T)){if(S.pops[i.ref])S.pops[i.ref].down=remainUntil(x=>POPDOWN.includes(x.type)&&x.ref===i.ref);} + else if(IXDOWN.includes(T)){if(S.ev.ixdown)S.ev.ixdown[i.ref]=remainUntil(x=>IXDOWN.includes(x.type)&&x.ref===i.ref);} + else if(TDOWN.includes(T)){const t=S.transit.find(x=>x.id===i.ref);if(t)t.down=remainUntil(x=>TDOWN.includes(x.type)&&x.ref===i.ref);} + else if(T==='rpki'||T==='hijack'){if(!S.inc.some(x=>x.type==='rpki'||x.type==='hijack'))S.ev.rpki=null;} + else if(T==='leak'){S.ev.leak=null;} + else if(T==='ddos'){const a=ddosAll(S,false).find(a=>i.atk?a.id===i.atk:a.city===i.ref&&(a.start===undefined||a.start===i.start));if(a){ddosDone(a);ddosDrop(a);}} + else if(T==='fabric'){if(S.ev.fab)S.ev.fab[i.ref]=remainUntil(x=>x.type==='fabric'&&x.ref===i.ref);} + else if(T==='leostorm'){S.ev.sky=remainUntil(x=>x.type==='leostorm');} + else if(T==='mtu'){const l=S.links.find(x=>x.id===i.ref);if(l)l.deg=remainUntil(x=>x.type==='mtu'&&x.ref===i.ref);} + else if(T==='loss'){const l=S.links.find(x=>x.id===i.ref);if(l&&!S.inc.some(x=>x.type==='loss'&&x.ref===i.ref))l.loss=null;} + else if(T==='lacp'){if(!S.inc.some(x=>x.type==='lacp'&&x.ref===i.ref)){const [k,...r]=String(i.ref).split(':'),id=r.join(':');if(k==='ix'){if(S.ev.ixlacp)delete S.ev.ixlacp[id];}else{const o=(k==='t'?S.transit:S.pni).find(x=>x.id===id);if(o)o.lacp=null;}}} + else if(T==='ctrlplane'){for(const id of Array.isArray(i.links)?i.links:[]){const l=S.links.find(x=>x.id===id);if(l)l.cut=Math.max(remainUntil(x=>(LINKCUT_TR.includes(x.type)&&x.ref===(l.trench||l.id))||(LINKCUT_ID.includes(x.type)&&x.ref===l.id)||(x.type==='ctrlplane'&&Array.isArray(x.links)&&x.links.includes(l.id))),0);}} + else if(T==='pmtud'){if(!S.inc.some(x=>x.type==='pmtud'))S.ev.pmtud=null;} + else if(T==='ring'){if(S.pops[i.ref])S.pops[i.ref].ringcut=remainUntil(x=>x.type==='ring'&&x.ref===i.ref);} + else if(T==='ac'){if(S.pops[i.ref])S.pops[i.ref].hot=remainUntil(x=>x.type==='ac'&&x.ref===i.ref);} + else if(T==='amp'||T==='roadmff'){const l=S.links.find(x=>x.id===i.ref);if(l)l.eqDown=remainUntil(x=>(x.type==='amp'||x.type==='roadmff')&&x.ref===i.ref);} + else if(T.startsWith('pie'))pieIncClear(i); + else if(T==='optic'){const l=S.links.find(x=>x.id===i.ref);if(l&&!S.inc.some(x=>x.type==='optic'&&x.ref===i.ref))l.chFail=null;} +} +function purgeInc(){S.inc=S.inc.filter(i=>{const T=i.type;if(LINKCUT_TR.includes(T))return S.links.some(l=>(l.trench||l.id)===i.ref);if(LINKCUT_ID.includes(T)||LINKEQ.includes(T))return S.links.some(l=>l.id===i.ref);if(TDOWN.includes(T))return S.transit.some(t=>t.id===i.ref);if(IXDOWN.includes(T))return S.ixp[i.ref]!==undefined;if(POPDOWN.includes(T)||T==='ac')return !!S.pops[i.ref];if(T==='wspur')return wispIncOk(i);return true;});} diff --git a/src/game/85-incidents/30-events.js b/src/game/85-incidents/30-events.js new file mode 100644 index 0000000..bce28d6 --- /dev/null +++ b/src/game/85-incidents/30-events.js @@ -0,0 +1,62 @@ +/* An event that cuts cables or power routes at once, as its last move (evRoute()). As a step of the day (eventRun()) + that routing is the day's next yield instead: nothing reads R in between, so it is the same routing. */ +let EV_DEFER=null; +const evRoute=()=>{if(EV_DEFER)EV_DEFER.n++;else compute();}; +function* eventRun(){const k={n:0};EV_DEFER=k;try{fireEvent();}finally{EV_DEFER=null;}for(let i=0;i50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic'); + // Without a market (Change Freeze), no shortages and no trade war on optics. + if(!rule('market')&&opts.includes('tariff'))opts.splice(opts.indexOf('tariff'),1); + if(netAge()>HW_FREE&&!hwShock()&&rule('market'))opts.push('hwshock'); + if(netAge()>90&&S.links.filter(l=>l.kind==='wave'&&!l.sub).length>=3)opts.push('ctrlplane'); + if(Object.keys(S.pops).some(ruCity))opts.push('runet','runet'); + if(S.pops.doh&&Object.keys(S.pops).some(c=>CITY[c].gcc||CITY[c].uae)&&!(S.ev.gulf>S.day))opts.push('gulf'); + if(Object.keys(S.pops).some(c=>CITY[c].saudi))opts.push('mega'); + if(['mnl','ceb','hkg','tok','icn','sha','jkt'].some(c=>S.pops[c]))opts.push('typhoon'); + if(S.pops.icn&&!S.krExit)opts.push('krexit');if(S.pops.icn&&!(S.ev.krroute>S.day))opts.push('krroute'); + if(Object.keys(S.pops).some(cnCity)||R.gfwCross>1)opts.push('golden','gfw'); + if(S.transit.some(t=>t.net==='cog'))opts.push('depeer','depeer'); + if(Object.keys(S.peers).some(k=>k.startsWith('drz@'))||Object.keys(S.rs).length)opts.push('cake'); + const e=pick(opts); + if(e==='gulf'){const dur=60+Math.floor(Math.random()*60);S.ev.gulf=S.day+dur;toast(tr('events.the_neighbours_have_fallen_out_a',{n:dur}),'bad');sfx('alert');} + /* A wave supplier pushes one bad update to its optical control plane, and every wave it sells you in a + region goes dark for a day or two. Your own dark fiber, subsea waves and fabric circuits keep working. */ + if(e==='ctrlplane'){const by={};for(const l of S.links)if(l.kind==='wave'&&!l.sub&&!(l.cut>S.day)){const r=CITY[l.a].reg;(by[r]=by[r]||[]).push(l);} + const reg=Object.keys(by).sort((a,b)=>by[b].length-by[a].length)[0];if(!reg)return;const hit=by[reg],until=S.day+2; + for(const l of hit)l.cut=Math.max(l.cut||0,until); + const RN={EU:tr('common.europe'),AM:tr('common.north_america'),SA:tr('common.south_america'),AS:tr('common.asia'),OC:tr('common.oceania'),AF:tr('common.africa')}; + addInc({type:'ctrlplane',ref:'reg:'+reg,links:hit.map(l=>l.id),until,msg:tr('events.your_wave_supplier_pushed_one',{n:hit.length,reg:RN[reg]||reg}),cost:Math.round(hit.reduce((a,l)=>a+l.mo,0)*0.3),fix:tr('events.escalate_to_their_cto')},'ctrlplane'); + toast(tr('events.optical_control_plane_meltdown_every',{reg:RN[reg]||reg}),'bad');sfx('alert');return;} + if(e==='krexit'){S.krExit=S.day+1;S.stats.incidents++;S.stats.survived++; + toast(tr('events.glitch_is_leaving_korea_the_game'),'bad');sfx('alert');return;} + if(e==='krroute'){S.ev.krroute=S.day+20;addInc({type:'krroute',ref:'icn',until:S.day+20,msg:tr('events.faceplant_got_tired_of_korean_usage'),cost:0},'krroute'); + toast(tr('events.faceplant_rerouted_korea_via_hong'),'bad');sfx('alert');return;} + if(e==='mega'){const c=pick(Object.keys(S.pops).filter(x=>CITY[x].saudi)),bw=pick([800,1600,3200]),start=S.day+15;S.offers.push({id:uid(),city:c,city2:null,name:tr('events.a_futuristic_city_that_is_not',{city:CITY[c].name}),type:'event',bw,rate:0,reqs:[],start,dur:4,fee:bw*4*90,exp:start-2});toast(tr('events.a_gigaproject_wants_a_demo_bw',{bw:fmtG(bw),city:CITY[c].name}),'goal');} + if(e==='sanction'){S.ev.sanction=S.day+60;toast(tr('events.sanctions_the_republic_of'),'bad');sfx('alert');return;} + if(e==='hwshock'){hwShockStart();return;} + if(e==='tariff'){S.ev.tariff=S.day+90;toast(tr('events.trade_war_on_optics_two_governments'),'bad');sfx('alert');return;} + if(e==='hijack'){const nh=NETS.map(n=>n.id).filter(()=>Math.random()<0.6),old=S.ev.rpki&&S.ev.rpki.until>S.day?S.ev.rpki:null;S.ev.rpki=old?{until:Math.max(old.until,S.day+1),nets:[...new Set(old.nets.concat(nh))]}:{until:S.day+1,nets:nh};addInc({type:'hijack',ref:'rpki',until:S.day+1,msg:tr('events.a_big_isp_fat_fingered_your'),cost:1500,fix:tr('events.call_everyone_you_know')});toast(tr('events.bgp_hijack_someone_else_is'),'bad');sfx('alert');return;} + if(e==='landban'){const lc=[...new Set(CABLE_PAIRS.flatMap(c=>[c.a,c.b]))];const c=pick(lc);S.ev.landban={city:c,until:S.day+45};toast(tr('events.landing_permit_dispute_in_city_two',{city:CITY[c].name}),'bad');return;} + if(e==='shutdown'){const ps=Object.keys(S.pops).filter(c=>c!==S.home);if(!ps.length)return;const c=pick(ps);S.pops[c].down=Math.max(S.pops[c].down||0,S.day+1);addInc({type:'shutdown',ref:c,until:S.day+1,msg:tr('events.regulators_ordered_every_network_in',{city:CITY[c].name}),cost:0});toast(tr('events.ordered_offline_in_city_a_government',{city:CITY[c].name}),'bad');sfx('alert');return;} + if(e==='typhoon'){const c=pick(['mnl','ceb','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick([tr('common.typhoon_bandwidth'),tr('common.typhoon_latency'),tr('common.typhoon_jitter'),tr('events.typhoon_packet_loss')]); + if(p.gen){S.stats.survived++;toast(tr('events.name_hits_city_the_grid_is',{name:nm,city:CITY[c].name}),'good');sfx('alert');return;} + p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');evRoute();return;} + if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');evRoute();return;} + if(e==='baltic'){const BAL=['clion','havf','danice'];const hit=S.links.filter(l=>l.cable&&BAL.includes(l.cable)&&!(l.cut>S.day)); + if(!hit.length){toast(tr('events.baltic_cable_damaged_a_cargo_ship'),'goal');return;} + const dur=15+Math.floor(Math.random()*15),en=N_('events.a_cargo_ship_dragged_its_anchor');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);} + toast(tr('events.baltic_cable_damaged_n_of_your',{n:hit.length,d:dur}),'bad');sfx('alert');evRoute();return;} + if(e==='redsea'){const RED=['twoaf','smw6','peace','aae','eig','eassy'];const hit=S.links.filter(l=>l.cable&&RED.includes(l.cable)&&!(l.cut>S.day)); + if(!hit.length){toast(tr('events.cables_cut_in_the_red_sea'),'goal');return;} + const dur=20+Math.floor(Math.random()*15),en=N_('events.a_ship_drifting_without_power');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);} + toast(tr('events.cables_cut_in_the_red_sea_03e8',{n:hit.length,d:dur}),'bad');sfx('alert');evRoute();return;} + if(e==='golden'){S.ev.golden=S.day+7;toast(tr('events.golden_week_demand_in_mainland_china'),'goal');return;} + if(e==='gfw'){S.ev.gfw=S.day+10;toast(tr('events.the_border_got_stricter_cross_border'),'bad');sfx('alert');return;} + if(e==='viral'){S.ev.viral=S.day+8;toast(tr('events.new_season_of_stranger_pings_just'),'goal');} + else if(e==='price'){S.priceMul*=0.92;toast(tr('events.transit_prices_fell_8_they_do'),'good');} + else if(e==='grant'){S.cash+=30000;toast(tr('events.rural_broadband_grant_30k_the'),'good');sfx('coin');} + else if(e==='depeer'){S.ev.depeer=S.day+20;addInc({type:'depeer',ref:'cog',until:S.day+20,msg:tr('events.cogentle_and_goggle_are_in_a'),cost:0});toast(tr('events.peering_spat_cogentle_de_peered'),'bad');sfx('alert');} + else if(e==='cake'){S.cash+=8000;toast(tr('events.drizzle_electric_sent_you_an_ipv6'),'good');sfx('coin');} +} + diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js new file mode 100644 index 0000000..b2a90ef --- /dev/null +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -0,0 +1,59 @@ +/* ---------- the chaos monkey: a visitor that breaks things on purpose ---------- + Like the real one (Netflix, 2011): something switches off random bits of production so you find out whether the + rest copes. Now and then, in On-call and BGP at 3 a.m. only, a monkey moves in for 120 to 240 days and snips a tube + every couple of weeks, preferring tubes with no other path round them. Its snips stand in for the usual random + failures while it is here, so the visit is a test, not a pile-on. Get through it without a customer noticing and + there is a bonus; a banana sends it home early. S.monkey: next (day of the next visit, null until the first tick), + on, start, until, snip (day of the next snip), n (snips), hurt (snips customers felt), c (city it last snipped by). */ +const MK_SNIPS=[N_('chaos_monkey.snip_unplugged'),N_('chaos_monkey.snip_sprayed'),N_('chaos_monkey.snip_to_see')]; +const mkSpicy=()=>rule('chaos')==='spicy'; +// Only the real game with real chaos: not Change Freeze (calm), Sandbox, puzzles or scenarios. +function mkElig(){return !!S&&S.mode!=='sandbox'&&S.mode!=='puzzle'&&!S.scn&&!S.lost&&['normal','spicy'].includes(rule('chaos'));} +const mkOn=()=>!!(S&&S.monkey&&S.monkey.on&&mkElig()); +const rint=(a,n)=>a+Math.floor(Math.random()*n); +// A quarter of a month's revenue to send it home; half a month's as the bonus for outlasting it. +const mkBananaCost=()=>Math.round(Math.min(1e6,Math.max(10000,(R.revMo||0)*0.25))/1000)*1000; +const mkBonus=()=>Math.round(Math.min(2e6,Math.max(20000,(R.revMo||0)*0.5))/1000)*1000; +// Is there another way between this tube's ends once its whole trench is gone? If not, it is a weak spot. +function mkWeak(l){const trc=l.trench||l.id,adj={}; + for(const x of S.links){if(x===l||(x.trench||x.id)===trc||linkDown(x))continue;(adj[x.a]||(adj[x.a]=[])).push(x.b);(adj[x.b]||(adj[x.b]=[])).push(x.a);} + const seen=new Set([l.a]),q=[l.a];while(q.length){const c=q.pop();if(c===l.b)return false;for(const n of adj[c]||[])if(!seen.has(n)){seen.add(n);q.push(n);}}return true;} +function mkTick(d){runNow(mkTickRun(d));} +// The monkey's day as a step of the day: a snip's yield is the routing that tells what it cost. +function* mkTickRun(d){const M=S.monkey;if(!M)return; + if(!mkElig()){if(M.on)mkLeave('quiet');return;} + // The first visit is spread by the ASN, not the dice, so a game's other luck stays exactly as it was. + if(M.next==null)M.next=d+(mkSpicy()?180:270)+(S.asn||0)%120; + if(!M.on){if(dl.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l))).length<3){M.next=d+30;return;}mkArrive(d);return;} + if(d>=M.until){mkLeave();return;} + if(d>=M.snip){yield* mkSnipRun();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}} +function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121); + S.stats.mkMet=(S.stats.mkMet||0)+1; + Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home}); + toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive'); + if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);} +function mkSnip(){runNow(mkSnipRun());} +function* mkSnipRun(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l)));if(!live.length)return; + // Weak spots first: a sample keeps this cheap on big networks. + const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x])); + const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served; + hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));M.n++;M.c=l.a; + addInc({type:'cut',ref:trc,until:S.day+dur,msg:tr(pick(MK_SNIPS),{a:A,b:B}),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},''); + // The snip's incident, kept before the routing: the player may repair it (or another) while the worker routes. + const i=S.inc[S.inc.length-1];yield;const imp=Math.max(0,before-R.served);if(i)i.impact=imp; + const felt=before>1&&imp>=before*0.03;if(felt)M.hurt++;else S.stats.survived++; + toast(felt?`🐒 ${incTitle('cut')}
${esc(i?i.msg:'')}`:tr('chaos_monkey.rerouted',{a:A,b:B}),felt?'bad':'good',[],i?incOpen(i):null);sfx(felt?'err':'alert'); + if(typeof mkRun==='function'){if(!UI.mk&&CITY[M.c])mkStart(M.c);mkRun(l,1400,felt);}} +// why: 'banana' (bribed), 'quiet' (the rules or the game changed under it), or nothing (its time was up). +function mkLeave(why){const M=S.monkey,d=S.day,ok=!why&&M.n>0&&M.hurt===0;M.on=0;M.next=d+(mkSpicy()?rint(220,181):rint(360,361)); + // The usual failures were paused for the visit; give the NOC a breather before they start again. + S.nextFail=Math.max(S.nextFail,d+15); + if(why==='banana')toast(tr('chaos_monkey.bribed'),'good'); + else if(ok){const b=mkBonus();S.cash+=b;S.stats.mkSurv=(S.stats.mkSurv||0)+1;toast(tr('chaos_monkey.survived',{n:M.n,cash:fmt$(b)}),'goal');sfx('coin');track('monkey_survived');} + else if(!why)toast(tr('chaos_monkey.went_home',{n:M.n,hurt:M.hurt}),''); + // Away, it is only its next visit: what a reload keeps of it (sanitize), so the live game is its own save. + S.monkey={next:M.next,on:0}; + if(typeof mkEnd==='function')mkEnd(ok,true);} +// The NOC tab's card while it is here. +function mkCard(){if(!mkOn())return '';const M=S.monkey,c=mkBananaCost(); + return `
🐒 ${tr('chaos_monkey.loose')}
${tr('chaos_monkey.card',{n:Math.max(1,M.until-S.day),s:M.n,hurt:M.hurt})}
${btn(tr('chaos_monkey.banana',{cost:fmt$(c)}),'mkBanana',{},'sm',S.cash
`;} diff --git a/src/game/85-incidents/50-cable-ships.js b/src/game/85-incidents/50-cable-ships.js new file mode 100644 index 0000000..d83ca62 --- /dev/null +++ b/src/game/85-incidents/50-cable-ships.js @@ -0,0 +1,90 @@ +/* ---------- cable ships at work (data and real numbers: 20-world/70-cable-ships.js) ---------- + A subsea cut sends a ship from its club's port: it leaves a day after the call, sails the cable routes at about + 500 km a day, may wait for a permit, splices for days, and sails home before it can take the next job. The cut lasts + until the splice is done. With every ship of the zone's club out, the cut waits; a private charter (any free ship, + from anywhere) jumps the queue for $1M plus $200 per km it sails. Voyages live in S.fleet so a ship on its way + home stays busy after the cut is mended; positions are worked out from them, so the map needs no state of its own. */ +let SHIP_G=null; +// The cable routes as a graph of landing cities: ships sail where the cables are, which is open sea. +function shipGraph(){if(SHIP_G)return SHIP_G;const g=new Map(),add=(u,e)=>{let L=g.get(u);if(!L)g.set(u,L=[]);L.push(e);}; + CABLE_PAIRS.forEach((p,i)=>{add(p.a,{to:p.b,km:p.km,i});add(p.b,{to:p.a,km:p.km,i});});return SHIP_G=g;} +// Shortest sailing distance from the sources ({city: km already to go}) to every port, with the way back. +function shipDij(src){const G=shipGraph(),dist=new Map(),prev=new Map(),h=[];for(const c in src){dist.set(c,src[c]);h.push([src[c],c]);} + while(h.length){let b=0;for(let i=1;idist.get(u))continue; + for(const e of G.get(u)||[]){const nd=d+e.km;if(nd<(dist.get(e.to)??Infinity)){dist.set(e.to,nd);prev.set(e.to,{from:u,e});h.push([nd,e.to]);}}} + return {dist,prev};} +const shipFree=s=>{const f=S.fleet[s.id];return !f||S.day>=f.back;}; +const shipLink=i=>S.links.find(x=>x.id===i.sl)||S.links.find(x=>(x.trench||x.id)===i.ref); +const shipSea=i=>i.type==='cut'&&(i.ship!=null||!!i.seaq); +// Where on the cable the fault is (share of the way from l.a): mostly in shallow water near a shore, where anchors and +// trawls reach the cable; sometimes out in the deep. +function shipFaultT(l){const near=Math.min(0.45,SHIP_SHALLOW/Math.max(1,l.km||1)); + if(Math.random()<0.75){const d=Math.random()*near;return Math.random()<0.5?0.03+d:0.97-d;}return 0.03+Math.random()*0.94;} +const shipShallow=(l,t)=>Math.min(t,1-t)*(l.km||0)<=SHIP_SHALLOW; +// A fault seen from the sea: sailing distances from it to every port. +const shipFrom=(i,l)=>shipDij({[l.a]:i.st*l.km,[l.b]:(1-i.st)*l.km}); +// The club whose zone the fault is in: the one with the nearest port. +function shipZone(D){let best=null,bd=Infinity;for(const s of SHIPS){if(s.club==='prv')continue;const d=D.dist.get(s.home)??Infinity;if(d(LINKCUT_TR.includes(x.type)&&x.ref===(l.trench||l.id))||(LINKCUT_ID.includes(x.type)&&x.ref===l.id));} +function shipSend(i,l,P,D){const g=linkGeom(l),pt=polyAt(g.pts,g.cum,i.st); + S.fleet[P.s.id]={inc:i.id,link:l.id,t:i.st,e:shipEnd(P.s,l,D),dep:P.dep,arr:P.arr,done:P.done,back:P.back,fx:pt[0],fy:pt[1]}; + i.ship=P.s.id;delete i.seaq;shipUntil(i,P.done);} +// A cut waiting for its club: when the first of the club's ships home again would have it mended. +function shipWait(i,l,D){const z=shipZone(D);let best=Infinity;for(const s of SHIPS)if(s.club===z){const f=S.fleet[s.id];best=Math.min(best,shipPlan(s,i,l,D).done+(f?Math.max(0,f.back-S.day):0));}return best;} +// The quickest free ship from anywhere, if it would finish sooner than the plan (or than waiting): what a private charter offers. +function shipQuote(i,l,D){D=D||shipFrom(i,l);let best=null;const cur=i.ship!=null&&S.fleet[i.ship]?S.fleet[i.ship].done:i.seaq?shipWait(i,l,D):Infinity; + for(const s of SHIPS)if(shipFree(s)){const P=shipPlan(s,i,l,D);if(!best||P.done=f.done)return;const m=f.dep+SHIP_MOB_D; + if(S.day>=f.arr){const sail=f.back-f.done;f.done=S.day;f.back=S.day+sail;f.inc=null;return;} + const out=Math.max(0,S.day-m);f.rt=+(out/Math.max(1,f.arr-m)).toFixed(4);f.rs=S.day;f.arr=f.done=S.day;f.back=S.day+out;f.inc=null;} +// Pay for the charter: the quickest free ship goes, whichever club or company it sails for. +function shipRush(i){const l=shipLink(i);if(!l||!shipSea(i))return false;const D=shipFrom(i,l),P=shipQuote(i,l,D);if(!P||!i.cost)return false; + if(!spend(i.cost))return false;if(i.ship!=null)shipRecall(i.ship);shipSend(i,l,P,D);i.cost=0;delete i.fix;i.rushed=true;return true;} +// Every day: ships home from a voyage are free again, waiting cuts get one, charter prices follow the fleet. +function shipDay(){if(!S.fleet)S.fleet={}; + for(const id in S.fleet){const f=S.fleet[id];if(S.day>=f.back){delete S.fleet[id];continue;}if(f.inc&&S.dayi.id===f.inc&&i.ship===id))shipRecall(id);} + for(const i of S.inc.filter(shipSea).sort((a,b)=>(a.start||0)-(b.start||0))){const l=shipLink(i);if(!l)continue;if(i.seaq)shipAssign(i,l);else if(!i.rushed)shipQuote(i,l);}} +// What the ship on a cut is doing, for the panels and the NOC. +function shipStatus(i){if(!shipSea(i))return '';const l=shipLink(i);if(!l)return ''; + if(i.seaq){const D=shipFrom(i,l),z=shipZone(D);return tr('cable_ships.every_club_ship_is_out',{club:SHIP_CLUBS[z]?SHIP_CLUBS[z].n:''});} + const s=SHIP[i.ship],f=S.fleet[i.ship];if(!s||!f)return '';const d=S.day,home=CITY[s.home].name,end=Math.max(1,f.done-d); + if(dMath.max(1,Math.ceil((l.km||0)/LAY_KMD)),layLen=l=>l.ship2?Math.ceil(layDays(l)/2):layDays(l),layStart=l=>l.lay?l.lay.s:l.ready-layLen(l); +/* A delay once the ship is at sea (#322) holds it where it is: l.lay = {s: the day laying began, q: the share laid, + t: the day it lays on}. Without it, laying is simply the last layLen() days before ready. */ +function layHold(l,shift,day){if(!layOwn(l)||!(shift>0)||l.ready<=day||dayl.kind==='df'&&l.own&&l.sub; +const layName=(l,k=0)=>{let h=0;for(const ch of String(l.id))h=(h*31+ch.charCodeAt(0))>>>0;return LAY_SHIPS[(h+k)%LAY_SHIPS.length];}; +function layQuote(l){if(!layOwn(l)||l.ship2||S.day>=layStart(l)||l.ready<=S.day+1)return null;const save=Math.floor(layDays(l)/2);if(save<1)return null;return {save,cost:SHIP_MOB+save*LAY_DAY};} +// How much of the cable is on the seabed, 0 to 1. +/* Money hurries the survey, the permits and the factory (#258), 30 days a step, but only so far: the cable still has to + be made, about two months plus a day for every 80 km of it, before the ships can sail and lay it. */ +const PREP_STEP=30,prepMin=l=>leadDays(Math.round(60+(l.km||0)*0.012)),prepCost=l=>Math.round((500000+(l.km||0)*60)*hwMul('build')), + prepFloor=l=>Math.max(S.day+1,(l.day||0)+prepMin(l))+layLen(l), + prepSteps=l=>layOwn(l)&&l.ready>S.day&&S.dayl.lay?l.lay.q+(1-l.lay.q)*clamp((T-l.lay.t)/Math.max(1,l.ready-l.lay.t),0,1):clamp((T-layStart(l))/layLen(l),0,1); diff --git a/src/game/85-incidents/60-pie.js b/src/game/85-incidents/60-pie.js new file mode 100644 index 0000000..ec40211 --- /dev/null +++ b/src/game/85-incidents/60-pie.js @@ -0,0 +1,76 @@ +/* ---------- Pie in the Sky: incidents in orbit (docs/plans/pie-in-the-sky.md) ---------- + Rule O5: only with chaos on (chaosMul() reads rule('chaos')), never in the first 90 days after the unlock, so a quiet + ruleset (and a sandbox without chaos) has a quiet sky. Each one is an ordinary S.inc entry: the NOC list, fixInc + (paying for a fix ends it), the day tick's "resolved", spicy stretching and standing orders all work as for cables. + What an incident does is read back from S.inc, so nothing else has to be undone. A booster that tips over on the drone + ship is in pieFly(); the astronomers ask a question, so they live with the spats (65-pie-spats.js). */ +const PIE_INC=['piedig','piefood','pielaser','pierain','piestorm'],PIE_TROPIC=23.5,PIE_ROOMBA=120e6,PIE_FOOD_MUL=0.25,PIE_INC_RATE=1/40, + PIE_DIG_FIX=300000,PIE_RAIN=0.3,PIE_ASTRO_N=200,PIE_HIT=0.1; +// PIE_HIT: the most of a crust one incident may take (a storm 2 to 10% over its week, a food fight 5 to 10%), so a bad +// week hurts but never empties the sky. +FOUNDER_POSTS.push(N_('pie.fp_3am'),N_('pie.fp_astro'),N_('pie.fp_debris'),N_('pie.fp_spat'),N_('pie.fp_storm')); +// Chaos on, a company to annoy, and the 90 quiet days are over. +function pieChaos(){const P=S&&S.pie;return !!P&&!!P.co&&chaosMul()>0&&S.day-P.born>=PIE_QUIET;} +const pieIncOf=(t,r)=>S.inc.find(i=>i.type===t&&i.ref===r&&i.until>S.day)||null; +const pieLiveAll=()=>Object.keys(CRUSTS).reduce((a,id)=>a+pieLive(id),0); +// Read by pieDishes(), pieQuote() and pieLiveLas() in 60-features/99-pie-in-the-sky.js. +function pieDishMul(x){let m=1;for(const i of S.inc)if(i.type==='pierain'&&i.ref===x.city&&i.until>S.day)m=PIE_RAIN;return m*pieSpatDishMul(x);} +function pieCrMul(cr){return 1+(pieIncOf('piefood',cr)?PIE_FOOD_MUL:0)+pieGrabMul();} +function pieLasCut(id){return !!S.inc.length&&!!pieIncOf('pielaser',id);} +function pieIncTitle(t){return {piedig:tr('pie_inc.t_dig'),piefood:tr('pie_inc.t_food'),pielaser:tr('pie_inc.t_laser'),pierain:tr('pie_inc.t_rain'),piestorm:tr('pie_inc.t_storm')}[t]||'';} +// clearInc(): a dish dug up comes back when no other backhoe still holds it. +function pieIncClear(i){if(i.type!=='piedig'||!S.pie)return;const x=S.pie.dishes.find(d=>d.city===i.ref);if(x)x.down=remainUntil(o=>o.type==='piedig'&&o.ref===i.ref);} +// sanitize(): orbit incidents point at a crust or a city, and go when the company does. +function pieIncFix(s){const ok=!!s.pie;s.inc=s.inc.filter(i=>{if(!PIE_INC.includes(i.type))return true;if(!ok)return false; + if(['piefood','pielaser','piestorm'].includes(i.type)?!own(CRUSTS,i.ref):!isCity(i.ref))return false; + i.start=int(i.start,0,s.day,s.day);i.until=int(i.until,0,s.day+400,s.day);if(i.type==='piestorm')i.f=clamp(num(i.f,0),0,PIE_HIT);return true;});} +// One day of a storm (its first is the day it starts; the day tick resolves it on its last). +function pieStormBite(i){if(!own(CRUSTS,i.ref))return;const n=Math.max(1,i.until-i.start),q=(1-Math.pow(1-i.f,1/n))*(S.pie.safe?0.25:1);i.lost=(i.lost|0)+pieLose(i.ref,q);} +// Pies lost from every cohort of a crust alike (counted as they fly: a worn cohort loses its worn share). +function pieLose(cr,q){const c=S.pie.crusts[cr],life=CRUSTS[cr].life;let lost=0;for(const k of c.cohorts){const x=Math.min(k.n,Math.round(k.n*q));lost+=x?pieAlive(k,life)*x/k.n:0;k.n-=x;}c.cohorts=c.cohorts.filter(k=>k.n>=1);return Math.round(lost);} +function pieIncToast(i,press,acts=[]){toast(`🛰️ ${pieIncTitle(i.type)}
${esc(i.msg)}
${esc(press)}`,'bad',(i.cost?[{l:`${i.fix||tr('common.rush_repair')} ${fmt$(i.cost)}`,act:'fixInc',args:{id:i.id}}]:[]).concat(acts),incOpen(i));sfx('alert');} +const pieAdd=o=>{addInc(o);return S.inc[S.inc.length-1];}; +function pieIncDay(d){ + // A storm drags pies down a little every day; safe mode saves three quarters of them, and carries nothing meanwhile. + for(const i of S.inc){if(i.type==='piestorm'&&i.until>d&&d>i.start)pieStormBite(i); + // spicy chaos stretches an incident (stretchInc); the dish it holds down follows it + else if(i.type==='piedig'&&i.until>d){const x=S.pie.dishes.find(o=>o.city===i.ref);if(x&&!(x.down>=i.until))x.down=i.until;}} + if(!pieChaos())return; + // Rule F4: while the chaos monkey visits, it snips laser links too. + if(mkOn()&&Math.random()<1/20)pieIncFire('laser'); + if(Math.random()pieLive(id),dish=x=>!!S.pops[x.city]; + if(Object.keys(CRUSTS).some(id=>live(id)>0&&!pieIncOf('piestorm',id)))o.push(['storm',2]); + if(Object.keys(CRUSTS).some(id=>live(id)>=100&&!pieIncOf('piefood',id)))o.push(['food',0.4]); + if(P.dishes.some(x=>dish(x)&&Math.abs(CITY[x.city].lat)<=PIE_TROPIC&&!pieIncOf('pierain',x.city)))o.push(['rain',3]); + if(P.dishes.some(x=>dish(x)&&!(x.down>S.day)))o.push(['dig',2]); + if(pieLiveAll()>=PIE_ASTRO_N&&!P.spat.astro)o.push(['astro',1]); + o.push(['founder',2]);return o;} +// Fires one orbit incident (k forces which, for tests and the monkey); true when something happened. +function pieIncFire(k){const P=S.pie;if(!P||!P.co)return false;const d=S.day; + if(!k){const o=pieIncOpts();let r=Math.random()*o.reduce((a,x)=>a+x[1],0);k=o[o.length-1][0];for(const x of o){r-=x[1];if(r<=0){k=x[0];break;}}} + const crs=f=>Object.keys(CRUSTS).filter(f); + if(k==='storm'){const c=crs(id=>pieLive(id)>0&&!pieIncOf('piestorm',id));if(!c.length)return false;const cr=pick(c),f=+(PIE_HIT/5+Math.random()*PIE_HIT*4/5).toFixed(3); + const i=pieAdd({type:'piestorm',ref:cr,until:d+7,f,lost:0,cost:0,msg:tr('pie_inc.storm_msg',{crust:tr(CRUSTS[cr].n),p:pct(f)})});pieFounder(N_('pie.fp_storm'),{c:cr});pieStormBite(i); + // One sun: Starblink's satellites go to safe mode in the same storm (the rented LEO circuits you still have), for a + // day or two as the storm is weak or strong, so no dice are thrown that a sky without them would not throw. + if(!leoStorm()&&leoLive()){leoStormGo(f>=PIE_HIT*0.6?2:1);const x=S.inc[S.inc.length-1];toast(`🛰️ ${incTitle('leostorm')}
${esc(x.msg)}`,'bad',[],incOpen(x));} + pieIncToast(i,tr('pie_inc.storm_press'),P.safe?[]:[{l:tr('pie_inc.safe_now'),act:'pieSafe',args:{}}]);return true;} + if(k==='food'){const c=crs(id=>pieLive(id)>=100&&!pieIncOf('piefood',id));if(!c.length)return false;const cr=pick(c),n=pieLose(cr,PIE_HIT/2+Math.random()*PIE_HIT/2); + const i=pieAdd({type:'piefood',ref:cr,until:d+360,cost:piePrice(PIE_ROOMBA),fix:tr('pie_inc.food_fix'),msg:tr('pie_inc.food_msg',{crust:tr(CRUSTS[cr].n),n,p:pct(PIE_FOOD_MUL)})}); + pieFounder(N_('pie.fp_debris'),{c:cr});pieIncToast(i,tr('pie_inc.food_press'));compute();return true;} + if(k==='rain'){const c=P.dishes.filter(x=>S.pops[x.city]&&Math.abs(CITY[x.city].lat)<=PIE_TROPIC&&!pieIncOf('pierain',x.city));if(!c.length)return false;const x=pick(c); + const i=pieAdd({type:'pierain',ref:x.city,until:d+rint(2,4),cost:0,msg:tr('pie_inc.rain_msg',{city:CITY[x.city].name})});pieIncToast(i,tr('pie_inc.rain_press'));compute();return true;} + if(k==='dig'){const c=P.dishes.filter(x=>S.pops[x.city]&&!(x.down>S.day));if(!c.length)return false;const x=pick(c); + const i=pieAdd({type:'piedig',ref:x.city,until:d+rint(2,3),cost:PIE_DIG_FIX,msg:tr('pie_inc.dig_msg',{city:CITY[x.city].name})});x.down=Math.max(x.down||0,i.until); + pieIncToast(i,tr('pie_inc.dig_press'));compute();return true;} + if(k==='laser'){const c=crs(id=>pieLiveLas(id)>0);if(!c.length)return false;const cr=pick(c); + const i=pieAdd({type:'pielaser',ref:cr,until:d+rint(3,4),cost:0,msg:tr('pie_inc.laser_msg',{crust:tr(CRUSTS[cr].n)})});i.until=Math.min(i.until,d+7); + if(S.monkey)S.monkey.n++;pieIncToast(i,tr('pie_inc.laser_press'));compute();return true;} + if(k==='astro')return pieSpatStart('astro'); + if(k==='founder'){S.stats.incidents++;S.stats.survived++;pieFounder(N_('pie.fp_3am')); + if(Math.random()<0.5){for(const b of S.biz)b.mood=Math.max(1,b.mood-5);toast(`📱 ${tr('pie_inc.t_founder')}
${tr('pie_inc.founder_dip')}
${tr('pie_inc.founder_press')}`,'bad');} + else{S.ev.viral=Math.max(S.ev.viral||0,d+5);toast(`📱 ${tr('pie_inc.t_founder')}
${tr('pie_inc.founder_spike')}
${tr('pie_inc.founder_press')}`,'goal');} + sfx('alert');return true;} + return false;} +PIE_ON.day.push(pieIncDay); diff --git a/src/game/85-incidents/65-pie-spats.js b/src/game/85-incidents/65-pie-spats.js new file mode 100644 index 0000000..a4d0cce --- /dev/null +++ b/src/game/85-incidents/65-pie-spats.js @@ -0,0 +1,129 @@ +/* ---------- Pie in the Sky: geopolitical spats (docs/plans/pie-in-the-sky.md) ---------- + Cartoon diplomacy, even-handed: countries come from the city table (CITIES[].cc, named by the browser), never a + leader or a party, and the jokes are about paperwork, food, weather and national pride. Like every incident they need + chaos on and 90 quiet days (rule O5); each asks one question with two answers (a bottom sheet, pieSpatSheet()), and an + unanswered one decides itself on its deadline. State: S.pie.spat[id] = {st:'ask'|'on', cc, cc2?, ask, until, c, hold…}, + repaired by pieSpatFix() on load and ended by pieSpatDay() on o.until (then D.end()). + Landing rights a spat takes away ('refused' or 'sus' in S.pie.lic) are held in o.hold {cc: days of rights left} and given + back, those days and all, when the spat ends. For routing: pieSpatHome(cc) (that country's customers must land on a dish + inside it) and pieAirBlock(a,b) (traffic from a must not use a dish in b), on top of pieDishes()' landing rights. */ +const PIE_SPAT_ASK=20,PIE_SPAT_RATE=1/90,PIE_SPAT_MAX=2,PIE_BAND_DAYS=180,PIE_KILL_DAYS=90,PIE_KILL_MOOD=15,PIE_ASTRO_MOOD=20,PIE_VISOR=50000, + PIE_HOME_DAYS=90,PIE_PAD_DISHES=3,PIE_PAD_DAYS=180,PIE_PAD_AID=0.75,PIE_GRAB_N=5,PIE_GRAB_FEE=40e6,PIE_JAM=0.4,PIE_JAM_FILTER=0.8,PIE_JAM_ANT=2e6, + PIE_AIR=0.75,PIE_AIR_DAYS=120,PIE_AIR_SUS=60,PIE_LOBBY_DAYS=30; +// Country centroids from the city table, once; a neighbour is the nearest other one. +let PIE_CC=null; +function pieCcAll(){if(PIE_CC)return PIE_CC;const m={};for(const c of CITIES){const o=m[c.cc]||(m[c.cc]={lat:0,lon:0,n:0});o.lat+=c.lat;o.lon+=c.lon;o.n++;} + for(const k in m){m[k].lat/=m[k].n;m[k].lon/=m[k].n;}return PIE_CC=m;} +function pieNb(cc){const A=pieCcAll(),a=A[cc];let b=null,m=1e9;if(!a)return null;for(const k in A){if(k===cc)continue;const d=hav(a.lon,a.lat,A[k].lon,A[k].lat);if(d[...new Set(S.pie.dishes.filter(x=>S.pops[x.city]).map(x=>CITY[x.city].cc))].sort(); +const piePopCc=()=>[...new Set(Object.keys(S.pops).map(c=>CITY[c].cc))].sort(); +const pieDishesIn=cc=>S.pie.dishes.filter(x=>S.pops[x.city]&&CITY[x.city].cc===cc).length; +// A country nobody is already holding hostage. +const pieFree=cc=>{const l=S.pie.lic[cc];return !(l&&l.state!=='ok'&&l.until>S.day);}; +const pieCcN=cc=>esc(pieLicCountry(cc)); +function pieMood(f,dv){let n=0;for(const b of S.biz)if(f(b)){b.mood=clamp(b.mood+dv,1,100);n++;}return n;} +const pieInCc=cc=>b=>isCity(b.city)&&CITY[b.city].cc===cc; +// Take a country's landing rights away until o.until, remembering the days left; pieRelease() gives them back. +function pieHold(o,cc,state){const P=S.pie,l=P.lic[cc],h=o.hold||(o.hold={});if(!(cc in h))h[cc]=l&&l.state==='ok'&&l.until>S.day?l.until-S.day:0;P.lic[cc]={state,until:o.until};} +function pieRelease(o){const P=S.pie;for(const cc in o.hold||{}){const l=P.lic[cc];if(!l||l.state==='ok'||l.until!==o.until)continue;const r=o.hold[cc];if(r>0)P.lic[cc]={state:'ok',until:S.day+r};else delete P.lic[cc];}o.hold={};} +const pieSpatEnd=o=>{o.until=S.day+1;}; +// Read by pieDishMul() (60-pie.js): jamming and a split network turn dishes down. +function pieSpatDishMul(x){const sp=S.pie.spat;if(!sp.jam&&!sp.air)return 1;const cc=CITY[x.city].cc;let m=1; + if(sp.jam&&(sp.jam.cc===cc||sp.jam.cc2===cc))m*=sp.jam.c===0?PIE_JAM_FILTER:PIE_JAM; + if(sp.air&&sp.air.st==='on'&&sp.air.c===0&&(sp.air.cc===cc||sp.air.cc2===cc))m*=PIE_AIR;return m;} +function pieGrabMul(){const o=S.pie&&S.pie.spat.grab;return o&&o.st==='on'&&o.left>0?o.m:0;} +function pieSpatHome(cc){const o=S&&S.pie&&S.pie.spat.home;return !!o&&o.cc===cc&&!o.ok;} +function pieAirBlock(a,b){const o=S&&S.pie&&S.pie.spat.air;return !!o&&o.st==='on'&&o.c===0&&((o.cc===a&&o.cc2===b)||(o.cc===b&&o.cc2===a));} +// The spats. pick(o,c): c is 0, 1 or -1 (nobody answered); cost(o,c): what that answer costs now; def: the answer on the deadline. +const PIE_SPAT_DEF={ + air:{n:2,def:0,can:()=>pieDishCc().filter(pieFree).filter(cc=>{const b=pieNb(cc);return b&&pieFree(b);}), + start:(o,cc)=>{o.cc=cc;o.cc2=pieNb(cc);}, + txt:o=>({t:tr('pie_spat.air_t'),b:tr('pie_spat.air_b',{a:pieCcN(o.cc),b:pieCcN(o.cc2)}),p:tr('pie_spat.air_p'), + c:[tr('pie_spat.air_c0',{p:pct(PIE_AIR),n:PIE_AIR_DAYS}),tr('pie_spat.air_c1',{n:PIE_AIR_SUS})]}), + pick:(o,c)=>{if(c===0){o.until=S.day+PIE_AIR_DAYS;compute();return tr('pie_spat.air_r0',{n:PIE_AIR_DAYS});} + o.until=S.day+PIE_AIR_SUS;pieHold(o,o.cc,'sus');pieHold(o,o.cc2,'sus');compute();return tr('pie_spat.air_r1',{a:pieCcN(o.cc),b:pieCcN(o.cc2),d:dateStr(o.until)});}}, + astro:{n:0,def:1,can:()=>pieLiveAll()>=PIE_ASTRO_N?['']:[],start:o=>{o.n=pieLiveAll();}, + cost:(o,c)=>c===0?piePrice(o.n*PIE_VISOR):0, + txt:o=>({t:tr('pie_spat.astro_t'),b:tr('pie_spat.astro_b',{n:o.n}),p:tr('pie_spat.astro_p'), + c:[tr('pie_spat.astro_c0',{cost:fmt$(piePrice(o.n*PIE_VISOR))}),tr('pie_spat.astro_c1',{n:PIE_ASTRO_MOOD})]}), + pick:(o,c)=>{pieSpatEnd(o);if(c===0)return tr('pie_spat.astro_r0');pieMood(b=>b.type==='edu'||b.type==='mars',-PIE_ASTRO_MOOD);pieFounder(N_('pie.fp_astro'));return tr('pie_spat.astro_r1');}}, + band:{n:2,def:-1,can:()=>pieDishCc().filter(pieFree).filter(cc=>{const b=pieNb(cc);return b&&pieFree(b);}), + start:(o,cc)=>{o.cc=cc;o.cc2=pieNb(cc);}, + txt:o=>({t:tr('pie_spat.band_t'),b:tr('pie_spat.band_b',{a:pieCcN(o.cc),b:pieCcN(o.cc2)}),p:tr('pie_spat.band_p'), + c:[tr('pie_spat.band_c',{a:pieCcN(o.cc),b:pieCcN(o.cc2),n:PIE_BAND_DAYS}),tr('pie_spat.band_c',{a:pieCcN(o.cc2),b:pieCcN(o.cc),n:PIE_BAND_DAYS})]}), + pick:(o,c)=>{if(c<0){o.until=S.day+PIE_BAND_DAYS/2;pieHold(o,o.cc,'sus');pieHold(o,o.cc2,'sus');compute();return tr('pie_spat.band_r_none',{a:pieCcN(o.cc),b:pieCcN(o.cc2),n:PIE_BAND_DAYS/2});} + const lose=c===0?o.cc2:o.cc;o.until=S.day+PIE_BAND_DAYS;pieHold(o,lose,'sus');compute();return tr('pie_spat.band_r',{a:pieCcN(c===0?o.cc:o.cc2),b:pieCcN(lose),d:dateStr(o.until)});}}, + grab:{n:0,def:1,can:()=>S.pie.fac?['']:[],start:()=>{},cost:(o,c)=>c===0?piePrice(PIE_GRAB_FEE):0, + txt:()=>({t:tr('pie_spat.grab_t'),b:tr('pie_spat.grab_b'),p:tr('pie_spat.grab_p'), + c:[tr('pie_spat.grab_c0',{cost:fmt$(piePrice(PIE_GRAB_FEE)),n:PIE_GRAB_N,p:'10%'}),tr('pie_spat.grab_c1',{n:PIE_GRAB_N,p:'30%'})]}), + pick:(o,c)=>{o.m=c===0?0.1:0.3;o.left=PIE_GRAB_N;o.until=S.day+720;return tr('pie_spat.grab_r',{n:PIE_GRAB_N,p:pct(o.m)});}}, + home:{n:1,def:0,can:()=>S.pie.dishes.length?piePopCc().filter(cc=>!pieDishesIn(cc)):[],start:(o,cc)=>{o.cc=cc;}, + cost:(o,c)=>c===1?Math.round(pieLicPrice(o.cc)*0.5):0, + txt:o=>({t:tr('pie_spat.home_t'),b:tr('pie_spat.home_b',{a:pieCcN(o.cc)}),p:tr('pie_spat.home_p'), + c:[tr('pie_spat.home_c0',{n:PIE_HOME_DAYS}),tr('pie_spat.home_c1',{cost:fmt$(Math.round(pieLicPrice(o.cc)*0.5))})]}), + pick:(o,c)=>{if(c===1){o.ok=1;pieSpatEnd(o);return tr('pie_spat.home_r1');}o.until=S.day+PIE_HOME_DAYS;return tr('pie_spat.home_r0',{a:pieCcN(o.cc),d:dateStr(o.until)});}, + day:(o,d)=>{if(o.st==='on'&&!o.ok&&pieDishesIn(o.cc)){o.ok=1;pieSpatEnd(o);pieMood(pieInCc(o.cc),5);toast(tr('pie_spat.home_won',{a:pieCcN(o.cc)}),'good');}}, + end:o=>{if(o.st!=='on'||o.ok)return;const f=pieLicPrice(o.cc);pieCharge(f);pieMood(pieInCc(o.cc),-10);toast(tr('pie_spat.home_fined',{a:pieCcN(o.cc),cost:fmt$(f)}),'bad');}}, + jam:{n:2,def:1,can:()=>pieDishCc().filter(cc=>pieNb(cc)), + start:(o,cc)=>{o.cc=cc;o.cc2=pieNb(cc);o.until=S.day+rint(5,6);o.ask=o.until-1;compute();}, + cost:(o,c)=>c===0?piePrice(PIE_JAM_ANT)*(pieDishesIn(o.cc)+pieDishesIn(o.cc2)):0, + txt:o=>({t:tr('pie_spat.jam_t'),b:tr('pie_spat.jam_b',{a:pieCcN(o.cc),b:pieCcN(o.cc2),p:pct(PIE_JAM),d:dateStr(o.until)}),p:tr('pie_spat.jam_p'), + c:[tr('pie_spat.jam_c0',{cost:fmt$(piePrice(PIE_JAM_ANT)*(pieDishesIn(o.cc)+pieDishesIn(o.cc2))),p:pct(PIE_JAM_FILTER)}),tr('pie_spat.jam_c1',{p:pct(PIE_JAM)})]}), + pick:(o,c)=>{compute();return c===0?tr('pie_spat.jam_r0',{p:pct(PIE_JAM_FILTER)}):tr('pie_spat.jam_r1',{d:dateStr(o.until)});},end:()=>compute()}, + kill:{n:1,def:0,can:()=>pieDishCc().filter(pieFree),start:(o,cc)=>{o.cc=cc;}, + txt:o=>({t:tr('pie_spat.kill_t'),b:tr('pie_spat.kill_b',{a:pieCcN(o.cc)}),p:tr('pie_spat.kill_p'), + c:[tr('pie_spat.kill_c0',{a:pieCcN(o.cc),n:PIE_KILL_MOOD}),tr('pie_spat.kill_c1',{n:PIE_KILL_DAYS})]}), + pick:(o,c)=>{if(c===0){pieSpatEnd(o);const n=pieMood(pieInCc(o.cc),-PIE_KILL_MOOD);return tr('pie_spat.kill_r0',{n});} + o.until=S.day+PIE_KILL_DAYS;pieHold(o,o.cc,'sus');compute();return tr('pie_spat.kill_r1',{a:pieCcN(o.cc),d:dateStr(o.until)});}}, + lic:{n:1,def:1,can:()=>pieDishCc().filter(pieFree),start:(o,cc)=>{o.cc=cc;o.n=rint(90,91);}, + cost:(o,c)=>c===0?Math.round(pieLicPrice(o.cc)*0.25):0, + txt:o=>({t:tr('pie_spat.lic_t'),b:tr('pie_spat.lic_b',{a:pieCcN(o.cc)}),p:tr('pie_spat.lic_p',{a:pieCcN(o.cc)}), + c:[tr('pie_spat.lic_c0',{cost:fmt$(Math.round(pieLicPrice(o.cc)*0.25)),n:PIE_LOBBY_DAYS}),tr('pie_spat.lic_c1',{n:o.n})]}), + pick:(o,c)=>{o.until=S.day+(c===0?PIE_LOBBY_DAYS:o.n);pieHold(o,o.cc,'refused');compute();return tr('pie_spat.lic_r',{a:pieCcN(o.cc),d:dateStr(o.until)});}}, + pad:{n:1,def:1,can:()=>piePopCc().filter(cc=>CITIES.some(c=>c.cc===cc&&pieCoast(c.id))&&!S.pie.pads.some(p=>CITY[p.city].cc===cc)),start:(o,cc)=>{o.cc=cc;}, + txt:o=>({t:tr('pie_spat.pad_t'),b:tr('pie_spat.pad_b',{a:pieCcN(o.cc),n:PIE_PAD_DISHES}),p:tr('pie_spat.pad_p'), + c:[tr('pie_spat.pad_c0',{n:PIE_PAD_DISHES,a:pieCcN(o.cc),d:PIE_PAD_DAYS}),tr('pie_spat.pad_c1')]}), + pick:(o,c)=>{if(c!==0){pieSpatEnd(o);return tr('pie_spat.pad_r1');}o.until=S.day+PIE_PAD_DAYS;return tr('pie_spat.pad_r0',{n:PIE_PAD_DISHES,a:pieCcN(o.cc),d:dateStr(o.until)});}, + day:(o,d)=>{if(o.st!=='on'||o.ok||o.fail)return; + if(pieDishesIn(o.cc)>=PIE_PAD_DISHES){o.ok=1;pieSpatEnd(o);const P=S.pie,c=Object.keys(S.pops).filter(x=>CITY[x].cc===o.cc&&pieCoast(x)&&!P.pads.some(p=>p.city===x)).sort()[0]; + if(c&&P.pads.length=o.until-1){o.fail=1;o.until=d+PIE_AIR_SUS;pieHold(o,o.cc,'sus');compute();toast(tr('pie_spat.pad_failed',{a:pieCcN(o.cc),d:dateStr(o.until)}),'bad');}}}, +}; +const PIE_SPAT_KEYS=Object.keys(PIE_SPAT_DEF); +// Sanitize: only what the spat needs, countries that exist, days in range. +function pieSpatFix(id,o,s){const D=PIE_SPAT_DEF[id],A=pieCcAll(),day=s.day,cc=v=>typeof v==='string'&&own(A,v); + const v={st:o.st==='on'?'on':'ask',ask:int(o.ask,0,day+PIE_SPAT_ASK,day),until:int(o.until,0,day+720,day),c:int(o.c,-1,1,-1)}; + if(D.n>=1){if(!cc(o.cc))return null;v.cc=o.cc;}if(D.n>=2){if(!cc(o.cc2)||o.cc2===o.cc)return null;v.cc2=o.cc2;} + if(o.hold&&typeof o.hold==='object'){v.hold={};for(const k of Object.keys(o.hold))if(cc(k))v.hold[k]=int(o.hold[k],0,PIE_LIC_DAYS*10,0);} + if(o.n!==undefined)v.n=int(o.n,0,1e6,0);if(o.ok)v.ok=1;if(o.fail)v.fail=1; + if(id==='grab'){v.m=clamp(num(o.m,0.3),0,0.3);v.left=int(o.left,0,PIE_GRAB_N,0);} + return v;} +// The day: an unanswered spat decides itself on its deadline. +function pieSpatTick(id,o,d){const D=PIE_SPAT_DEF[id];if(o.st==='ask'&&d>=o.ask){pieSpatChoose(id,D.def,true);return;}if(D.day)D.day(o,d);} +for(const id of PIE_SPAT_KEYS)PIE_SPATS[id]={fix:(o,s)=>pieSpatFix(id,o,s),day:(o,d)=>pieSpatTick(id,o,d),end:o=>{const D=PIE_SPAT_DEF[id];if(D.end)D.end(o);pieRelease(o);}}; +// Starts one (id forces which, for tests, the astronomers and the Ex-Im Pie Bank; cc which country); true when it did. +function pieSpatStart(id,cc){const P=S.pie;if(!P||!P.co)return false; + if(!id){const ok=PIE_SPAT_KEYS.filter(k=>k!=='astro'&&!P.spat[k]&&PIE_SPAT_DEF[k].can().length);if(!ok.length)return false;id=pick(ok);} + const D=PIE_SPAT_DEF[id];if(!D||P.spat[id])return false;const cs=D.can();if(!cs.length)return false; + if(cc&&!cs.includes(cc))return false;const o={st:'ask',ask:S.day+PIE_SPAT_ASK,c:-1};D.start(o,cc||pick(cs));if(!o.until)o.until=o.ask+1;P.spat[id]=o; + S.stats.incidents++;S.stats.pieSpat=(S.stats.pieSpat||0)+1;pieFounder(N_('pie.fp_spat')); + const t=D.txt(o);toast(`🌍 ${t.t}
${t.b}`,'bad',[{l:tr('pie_spat.decide'),act:'pieSpatOpen',args:{id}}]);sfx('alert');return true;} +// The answer: what it costs (sandbox keeps count), what happens, and the press office's line. +function pieSpatChoose(id,c,auto){const P=S.pie,o=P&&P.spat[id],D=PIE_SPAT_DEF[id];if(!o||!D||o.st!=='ask')return false; + const cost=D.cost&&c>=0?D.cost(o,c):0;if(cost>0&&!pieSpend(cost))return false; + o.st='on';o.c=c;const r=D.pick(o,c);S.stats.survived++; + toast(`🌍 ${D.txt(o).t}
${auto?tr('pie_spat.auto')+' ':''}${r}
${D.txt(o).p}`,auto?'bad':'',[]);return true;} +// The NOC card and Pie Control list the questions waiting for an answer. +function pieSpatCard(){const P=S&&S.pie;if(!P)return '';const ks=PIE_SPAT_KEYS.filter(k=>P.spat[k]&&P.spat[k].st==='ask');if(!ks.length)return ''; + return `
${ks.map(k=>`
🌍 ${PIE_SPAT_DEF[k].txt(P.spat[k]).t}${btn(tr('pie_spat.decide'),'pieSpatOpen',{id:k},'pink sm')}
`).join('')}
`;} +function pieSpatSheet(id){const o=S&&S.pie&&S.pie.spat[id],D=PIE_SPAT_DEF[id];if(!o||!D)return;const t=D.txt(o); + let h=`
🌍 ${tr('pie_spat.eyebrow')}

${t.t}

`; + h+=`

${t.b}

${t.p}

`; + if(o.st==='ask')h+=`

${tr('pie_spat.decide_by',{d:dateStr(o.ask)})}

${t.c.map((l,c)=>{const v=D.cost?D.cost(o,c):0;return btn(l,'pieSpatPick',{id,c},c?'ghost':'pink',v>0&&!pieSand()&&S.cash`; + else h+=`

${tr('pie_spat.decided')}

`; + openModal(h,'pie-spat');} +// A land grab bills the next few launches (counted when they are booked, which is when the quote is paid). +function pieGrabUse(q){const o=S.pie&&S.pie.spat.grab;if(!o||o.st!=='on'||!(o.left>0))return;o.left--;if(!o.left)pieSpatEnd(o);} +function pieSpatDayAll(d){if(!pieChaos())return;const P=S.pie;if(Object.keys(P.spat).length>=PIE_SPAT_MAX)return;if(Math.random(){UI.tick=true;try{return g.next(v);}finally{UI.tick=false;}}; +// The intern's fiber test ({dark}, 95-standing-orders.js) is asked the same way, and answers true or false. +const dayAsk=y=>!!y&&(!!y.trial||!!y.dark); +const dayAnswer=y=>y.dark?opsDarkTrial(y):offerTrial(y.trial,y.hx); +// The same trial overtaken by an action (a customer gone shifts S.biz, so hx no longer points at the right ones): +// its checks, the customer and who is happy, made again on the game as it is now. +const dayAgain=y=>{if(y.dark)return opsDarkAgain(y);const o=y.o;if(!o||!S.offers.includes(o))return null;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;}; +function dayGo(g,step=dayStep){let v;for(let s=step(g);!s.done;s=step(g,v)){v=undefined;const y=s.value;if(y===DAY_REST)continue;if(dayAsk(y))v=dayAnswer(y);else compute();}} +function dayTick(){dayGo(dayRun());} +// dayPre(): the world's morning all at once; dayPreRun() the same with a place or two to let a frame through. +function dayPre(){const g=dayPreRun();for(;;){const s=g.next();if(s.done)return s.value;}} +function* dayPreRun(){ + if(!S||S.lost||!rule('clock'))return false; // no clock (puzzles): no days, no bills, nothing fires + S.day++; + const d=S.day; + // A charter never picked reads as the classic one once its days are over, as a reload reads it (specSanitize). + if(S.chartSet===false&&d-S.day0>CHARTER_DAYS)S.chartSet=true; + ddosForget(d);dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d); + yield DAY_REST; + if(!S.phpDone&&d-S.day0>45&&Math.random()<1/400)elephant(); + if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved); + {const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('day_tick.you_are_no_longer_tier_1',{why:t1Why()}),'bad');S.t1Now=t1;} + if(S.grace&&S.grace.until===d){toast(tr('day_tick.the_courtesy_route_has_ended_new'),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);} + lateDay(d); + if(R)ddosTrack(ddosAll(S,false).filter(a=>a.until>=d)); + ddosExpire(); + ddosTick(); + // What the Great Firewall drops is not your outage: it alone kept Anchors Away's 99.5% out of reach (playtest). + if(R&&R.demand>0)S.stats.clean=(R.served+(R.gfwLost||0))/R.demand>=0.995?(S.stats.clean||0)+1:0; + if(S.scn&&S.scn.id==='redsea')S.stats.asiaRun=asiaG()>=RS_G?(S.stats.asiaRun||0)+1:0; + if(S.ev.php===d)toast(tr('day_tick.the_internet_is_back_half_of'),'good'); + for(const k in S.peers){const [id,c]=k.split('@'),sn=snub(id,c);if(!sn)continue;delete S.peers[k];S.stats.depeered=(S.stats.depeered||0)+1; + {const v={net:esc(NET[id].name),ix:esc(ixName(c)),city:esc(CITY[ixCity(c)].name),why:esc(sn.why)};toast(ixNamesCity(c)?tr('day_tick.net_de_peered_you_at_ix',v):tr('day_tick.net_de_peered_you_at_ix_caef',v),'bad');}} + if(S.cnLic&&S.cnLic.state==='pending'&&d>=S.cnLic.ready){S.cnLic.state='ok';toast(tr('day_tick.license_granted_your_joint_venture'),'goal');sfx('coin');} + // cable ships: home again, sent to waiting cuts (50-cable-ships.js) + shipDay(); + // resolve incidents + for(const i of S.inc.slice())if(i.until<=d){const o=incOpen(i),l=o&&o.a==='link'&&S.links.find(x=>x.id===o.v),where=l?CITY[l.a].name+'–'+CITY[l.b].name:o&&o.a==='city'?CITY[o.v].name:'';clearInc(i); + toast(where?tr('day_tick.resolved_what_where_is_back_to',{what:incTitle(i.type),where:esc(where)}):tr('day_tick.resolved_what',{what:incTitle(i.type)}),'good',[],o);} + yield DAY_REST; + // eyeball growth / churn uses last computed service + for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c)*((R.bbF&&R.bbF[c])??1),P=eyeP(c),d0=p.bb.d; + if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);} + else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04)); + if(p.bb.v6||p.bb.v6e)ip6Grow(p.bb,d0);} + wispGrow(); + return d;} +function* dayPost(d){ + yield* ddosNewsRun();ddosTrack(); + for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();} + S.cash+=(R.revMo-R.costMo)/monLen(d); + S.stats.peak=Math.max(S.stats.peak,R.served);volDay(); + S.hist=S.hist||[];S.hist.push({d,dem:+R.demand.toFixed(2),srv:+R.served.toFixed(2),c:+(R.egT.c||0).toFixed(2),p:+(R.egT.p||0).toFixed(2),ix:+(R.egT.ix||0).toFixed(2),t:+(R.egT.t||0).toFixed(2),l2:+(R.egT.l2||0).toFixed(2),rev:Math.round(R.revMo),cost:Math.round(R.costMo),cash:Math.round(S.cash),inc:S.inc.length});if(S.hist.length>180)S.hist.shift(); + {const top=custLevel();if(top>(S.lvl||1)){for(let lv=(S.lvl||1)+1;lv<=top;lv++){track('level_'+lv);toast(tr('day_tick.customer_level_lv_name_new_customers',{lv,name:LEVELS[lv-1].n,unlock:LEVELS[lv-1].unlock})+`
${esc(LEVELS[lv-1].q)}`,'goal');}S.lvl=top;sfx('coin');}} + wispDay(d); + for(const l of S.links){if(l.kind!=='df')continue; + if(l.ready===d){delete l.lay;toast(`${l.own?tr('day_tick.your_fiber_is_finished_a_b',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('day_tick.dark_fiber_handed_over_a_b',{a:CITY[l.a].name,b:CITY[l.b].name})}
${(l.ch||[]).length?tr('day_tick.channels_are_lighting_up_now'):tr('day_tick.it_is_dark_add_optics_to')}`,'goal',[{l:tr('common.open'),act:'selLink',args:{id:l.id}}]);sfx('coin');} + if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+leadDays(extra));toast(tr('day_tick.construction_delay_n_days_why_a',{n:leadDays(extra),why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('day_tick.archaeologists_found_a_roman'),tr('day_tick.a_protected_hamster_species_lives'),tr('day_tick.the_railway_changed_its_mind_about'),tr('day_tick.the_drilling_crew_hit_a_granite'),tr('day_tick.a_town_council_wants_a_public'),tr('day_tick.somebody_else_s_gas_main_was'),tr('day_tick.the_permit_office_lost_your_permit')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}} + // DDoS protection SLA: a protected customer under attack who goes down, or is blackholed, is paid out (once per attack). + for(const a of ddosAll()){ + for(const b of S.biz)if(b.type==='scrub'&&b.id===a.tgt&&!(a.sla||[]).includes(b.id)&&(a.bh||ddosSf(a)<0.85)){ + (a.sla||(a.sla=[])).push(b.id);b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; + toast(tr('day_tick.sla_breach_name_the_attack_on',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} + // businesses mood + const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));let nb=0;TERR={S,gen:RW.gen,m:null};try{for(const b of S.biz.slice()){if(++nb%256===0)yield DAY_REST;if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b),lcX=lcBreach(b,d); + if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2); + else if(S.day-(b.since||0)<15){} + else{const dm=frr*(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0)+lcX);b.mood-=BIZ_T[b.type].orbit?Math.min(dm,PIE_PATIENCE):dm; + // An orbit customer served in full but promised more (the shark's full sky) grumbles, and never cancels over it. + if(BIZ_T[b.type].orbit&&sf>=0.95&&reachOk)b.mood=Math.max(b.mood,Math.min(b.pm,PIE_GRUMBLE)); + if(b.mood<=0){S.biz=S.biz.filter(x=>x!==b);toast(tr('day_tick.name_cancelled_too_many_outages_and',{name:esc(b.name),city:CITY[b.city].name}),'bad');sfx('err');} + else if(b.mood<30&&!b.warned){b.warned=b.warn60=true;const why=bizWhy(b)[0],paused=pref('pauseFurious')&&autoPause(); + toast(tr('day_tick.name_is_furious_fix_service_in',{name:esc(b.name),city:CITY[b.city].name})+(why?`
${esc(why)}`:'')+(paused?`
${tr('common.game_paused')}`:''),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');} + else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('day_tick.name_is_getting_unhappy_happiness_p',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?`
${esc(why)}`:''),'',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);}} + if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}}finally{TERR=null;} + yield DAY_REST; + // contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js) + clDay(d); + // the sales desk: meetings booked, golf played (38-sales-desk.js) + salesDay(d);yield* slRenRun(d); + yield DAY_REST; + // own IX members join + for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.lengthn.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg))); + if(cands.length){cands.sort((a,b)=>(a.pol==='open'?0:1)-(b.pol==='open'?0:1)||b.share-a.share);const n=Math.random()<.6?cands[0]:pick(cands);m.members.push(n.id);toast(tr('day_tick.net_joined_ix_another_member_paying',{net:esc(n.name),ix:esc(m.name),fee:fmt$(MYIX_FEE)}),'good');sfx('coin');} + m.next=d+8+Math.floor(Math.random()*10);}} + loanTick(d); + if(rule('money')==='infinite'&&S.cash<1e8)S.cash=1e9; + // offers + S.offers=S.offers.filter(o=>o.exp>d); + cmDay(d); + if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)*salesSpawn()){const n0=S.offers.length;spawnOffer();mktPrice(n0);salesShape(n0);} + yield DAY_REST; + // failures & events + // Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never. + let dirty=false;const cm=chaosMul(); + // A visiting chaos monkey does the breaking instead (its snips replace these while it is here). + yield* mkTickRun(d); + if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;yield* failureRun();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} + // Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year). + if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='sat'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;yield* eventRun();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} + if(dirty)yield; + // the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them + yield* slAutoRun(d); + if(opsHired())yield DAY_REST; + yield* opsRun(d); + if(S.pie){pieDay(d);pieTier();} + // payday floaters + if(cal(d).d===1){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-arpuOf(c));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');} + checkGoals(); + scnTick(d); + confTick(d); + specDay(d); + ip4Day(d); + // money trouble + if(S.cash<0){S.neg++;if(S.neg===1)toast(tr('day_tick.you_are_in_the_red_cancel'),'bad');} + else S.neg=0; + if(S.cash<-100000){if(rule('broke')==='rescue')rescueLoan();else{S.lost=true;track('bankrupt');showLose();return;}} + {const c=cal(d);if(c.m===0&&c.d===1&&[2,3,5].includes(c.y))track('game_year_'+c.y,true);} + if(d%10===0)save(); +} +function spawnOffer(){ + const mine=spMine(Object.keys(S.pops).filter(bizCity)),lv=lvl(); + const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(netAge()>60)types.push('scrub'); + if(lv>=2)types.push('isp','stream','edu','host','hft','bulk','event','event');if(mine.length>=3&&lv>=2)types.push('sdwan','sdwan'); + // A broker's callers are mostly carriers who want capacity on its glass (#300). + const bk=broker(),dfR=S.links.some(l=>l.kind==='df'&&l.ready<=S.day),dfO=S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day); + if(dfR)types.push('wwave','wwave');if(dfO)types.push('dfpair');if(bk){if(dfR)types.push('wwave','wwave','wwave','wwave');if(dfO)types.push('dfpair','dfpair','dfpair');}if(lv>=3)types.push('gpu','gpu','onramp','onramp');if(lv>=4)types.push('ai','ai','hyper','hyper'); + if(lv>=3&&MEGA.some(m=>mine.includes(m.c)))types.push('ingest');if(lv>=4&&MEGA.some(m=>mine.includes(m.c)))types.push('aiwan','aiwan','mtrain');if((lv>=4||bk)&&dfO)types.push('pairs'); + if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=LC_LV&&mine.length>=2)types.push('lowlat','lowlat');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); + const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor'); + // Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. + const dense=mine.filter(c=>(CITY_PDB[c]||[])[2]>=2000);if(lv>=2&&dense.length)types.push('isp'); + const fabC=mine.filter(c=>FABS.some(f=>f.cities.includes(c)));if(lv>=2&&fabC.length){types.push('fabip','fabip');if(mine.length>=2)types.push('fabl2');} + // What your network can already serve calls too, at a lower weight and the smallest size (#187). + const sp=spots(),spT=[...new Set(sp.map(s=>s.t))],bq=charter()==='boutique';for(const x of spT){types.push(x);if(x==='hft'&&bq)types.push(x,x);}if(bq&&lv>=2)types.push('hft','hft'); + types.push(...coreProducts(mine)); + const t=pick(types),T=BIZ_T[t]; + if(T.lv>lv&&spT.includes(t)){spawnSpot(t,pick(sp.filter(s=>s.t===t)));return;} + if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;} + if(T.nni){const city=pick(fabC),prov=pick(FABS.filter(f=>f.cities.includes(city))).id,bw=pick(T.opts),others=mine.filter(c=>c!==city),city2=T.l2&&others.length?pick(others):null;if(T.l2&&!city2)return; + const base=pick(BIZ_N.filter(n=>!S.usedNames.includes(n)).concat(BIZ_N)).replace(/ (Inc\.|Co\.|Ltd)$/,'');const name=tr('day_tick.name_via_fab',{name:base,fab:FAB[prov].name});useName(base); + const rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate; + S.offers.push({id:uid(),city,city2,prov,name,type:t,bw,rate,reqs:['nni'],exp:S.day+40});return;} + let city=(Math.random()<0.65&&mine.length)?pick(mine):pick(OFFC.concat(cnOk()?['pek','sha']:[])),city2=null; + if(T.l2){city=pick(mine);const pool=(Math.random()<(T.lv>=3?0.8:0.6)?mine:OFFC).filter(c=>c!==city);city2=pick(pool.length?pool:OFFC.filter(c=>c!==city));} + let bw=T.lv>=2?pick(T.opts):pick(T.opts.slice(0,mine.length>=4?4:3)); + const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n)); + let name=list.length?pick(list):(T.names?pick(T.names):'Startup #'+Math.floor(Math.random()*999)); + useName(name); + if(t==='provedor')city=pick(br); + if(t==='isp'&&dense.length&&Math.random()<0.5)city=pick(dense); + if(t==='hft'){const fin=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'],mf=mine.filter(c=>fin.includes(c));city=mf.length?pick(mf):pick(mine);city2=pick(fin.filter(c=>c!==city));} + let rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km*(T.lat?latPay():1)):T.rate; + if(CITY[city].au&&!T.l2&&!T.fiber&&!T.event){rate=Math.round(rate*AU_ARPU);bw=Math.min(bw,pick(T.opts.slice(0,2)));} + if(T.div&&!reqCan('diverse',{city,city2}))return; + const reqs=T.div?['diverse']:T.lat?['lat']:[];if((t==='hyper'||t==='ai'||t==='gpu')&&Math.random()<0.4)reqs.push('metro');const pool=Object.keys(REQS).filter(k=>!reqs.includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,{city,city2})); + if(Math.random()<(T.lv>=3?0.65:0.3))reqs.push(pick(pool)); + if(T.lv>=3&&Math.random()<0.35){const more=pool.filter(k=>!reqs.includes(k));if(more.length)reqs.push(pick(more));} + const r2=Math.round(rate*(1+reqs.reduce((a,k)=>a+REQS[k].bonus,0))); + // A latency ceiling must be one something you can build meets (#273), as diverse paths must be possible. + const latMax=T.lat?latMaxOf(city,city2):null;if(T.lat&&!(Math.min(latFloor(city,city2),bestLat(city,city2))<=latMax))return; + S.offers.push({id:uid(),city,city2,name,type:t,bw,rate:r2,reqs,latMax,exp:S.day+40}); +} diff --git a/src/game/88-days/15-day-pace.js b/src/game/88-days/15-day-pace.js new file mode 100644 index 0000000..df8c524 --- /dev/null +++ b/src/game/88-days/15-day-pace.js @@ -0,0 +1,15 @@ +/* ---------- the pace of days, as measured ---------- + How fast days really come with the route worker, for Settings › Diagnostic info: the speed asked, the speed held + (from the starts of the last 12 days), how long a day takes from its start to its end, and the slowest of them. + Measured only: a clock that started days on a steady beat was tried, and on big networks it cost a sixth of the + speed without making the days any more regular (their spread comes from the long days themselves, a second routing + for the intern's jobs or a failure, which no beat can hide). */ +const PACE={s:null,sp:0,st:[],d:[],t0:0}; +// A day starts (runClock(), 99-loop.js) / has ended (rwDayDone(), 28-route-worker.js). A new speed or another game: +// the measure starts again. +function paceStart(now){const P=PACE;if(P.s!==S||P.sp!==UI.speed){P.s=S;P.sp=UI.speed;P.st.length=0;P.d.length=0;} + P.st.push(now);if(P.st.length>13)P.st.shift();P.t0=now;} +function paceEnd(now){const P=PACE;if(!P.t0)return;P.d.push(now-P.t0);if(P.d.length>12)P.d.shift();P.t0=0;} +function diagPace(){const P=PACE;if(!S||!UI.speed)return 'days: paused';if(P.s!==S||P.sp!==UI.speed||P.st.length<3)return `days: x${UI.speed} asked · measuring`; + const gap=(P.st[P.st.length-1]-P.st[0])/(P.st.length-1),d=P.d.length?P.d.reduce((a,x)=>a+x,0)/P.d.length:0; + return `days: x${UI.speed} asked · x${(DAY_MS/gap).toFixed(1)} held (one every ${Math.round(gap)} ms)`+(d?` · a day takes ${Math.round(d)} ms, slowest ${Math.round(Math.max(...P.d))}`:'');} diff --git a/src/game/88-days/15-traffic-volume.js b/src/game/88-days/15-traffic-volume.js new file mode 100644 index 0000000..e0ae306 --- /dev/null +++ b/src/game/88-days/15-traffic-volume.js @@ -0,0 +1,12 @@ +/* ---------- Traffic carried: the network's odometer ---------- + S.vol counts the petabytes the network has carried in this game: every day adds a day of what it served. R.served + is in Gbps, so a day of 1 Gbps is 86,400 gigabits, 10.8 terabytes, 0.0108 PB. Badges ride on it (20-badges.js), + from the first petabyte to a zettabyte, the whole internet's traffic in a year around 2016. */ +const PB_DAY=86400/8/1e6; +function volDay(){S.vol=(S.vol||0)+(R.served>0?R.served*PB_DAY:0);} +// A volume of traffic, from the petabytes it is stored in: TB, PB, EB, ZB. +const fmtVol=pb=>pb>=1e6?(pb/1e6).toFixed(pb>=1e7?1:2)+' ZB':pb>=1000?(pb/1000).toFixed(pb>=1e4?1:2)+' EB':pb>=1?pb.toFixed(pb>=10?0:1)+' PB':(pb*1000).toFixed(pb>=0.01?0:1)+' TB'; +// Saves: a number of petabytes. A save from before the odometer starts from the days its history still holds (the +// last 180), so an old network gets most of the credit it earned. +function volFix(s){if(typeof s.vol==='number'&&Number.isFinite(s.vol)&&s.vol>=0)return; + s.vol=(Array.isArray(s.hist)?s.hist:[]).reduce((a,h)=>a+(h&&typeof h.srv==='number'&&h.srv>0&&Number.isFinite(h.srv)?h.srv:0),0)*PB_DAY;} diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js new file mode 100644 index 0000000..66dc330 --- /dev/null +++ b/src/game/88-days/20-badges.js @@ -0,0 +1,130 @@ +/* Badges: achievements with rarities. Earned per game, and also remembered across games on this + device in a hall of fame, so there is always something grand to work towards. */ +const RARITY={c:{n:tr('common.common'),col:'#16A866'},r:{n:tr('common.rare'),col:'#3A7BEA'},e:{n:tr('common.epic'),col:'#9D4EDD'},l:{n:tr('common.legendary'),col:'#FF8A3D'}}; +const st=()=>S.stats||{}; +// Round Cape Horn: a wave on the old ring, or your own cable whose surveyed path passes south of Tierra del Fuego (#272). +const hornLink=l=>(l.cable==='sam1'&&[l.a,l.b].includes('bue')&&[l.a,l.b].includes('scl'))||(l.kind==='df'&&l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.some(p=>p[1]<-55&&p[0]>-75&&p[0]<-60)); +const BADGES=[ + {id:'hello',i:'👋',t:tr('common.hello_neighbour'),d:tr('badges.bring_up_your_first_peering_session'),r:'c',ok:()=>R.sessions>=1}, + // Keeps its old id so badges already earned (in saves and the hall of fame) carry over. + {id:'backhoe',i:'🐒',t:tr('badges.met_the_chaos_monkey'),d:tr('badges.get_a_visit_from_the_chaos_monkey'),r:'c',ok:()=>(st().mkMet||0)>=1}, + {id:'debt',i:'🏦',t:tr('badges.in_debt_we_trust'),d:tr('badges.take_out_a_loan'),r:'c',ok:()=>(st().loans||0)>=1||(S.loans||[]).length>0}, + {id:'twins',i:'👯',t:tr('common.twins'),d:tr('badges.run_two_routers_in_one_pop'),r:'c',ok:()=>Object.values(S.pops).some(p=>(p.routers||1)>=2)}, + {id:'shark',i:'🦈',t:tr('common.shark_week'),d:tr('badges.get_a_subsea_cable_bitten_by'),r:'r',ok:()=>(st().sharks||0)>=1}, + {id:'ixc',i:'🔀',t:tr('common.ix_collector'),d:tr('badges.have_ports_on_10_internet_exchanges'),r:'r',ok:()=>Object.keys(S.ixp).length>=10}, + {id:'haggle',i:'🤝',t:tr('badges.never_paid_list_price'),d:tr('badges.haggle_a_de_kicks_quote_down'),r:'r',ok:()=>!!st().haggleWin}, + {id:'unsub',i:'📭',t:tr('common.unsubscribed'),d:tr('badges.opt_out_of_3_auto_enrolled'),r:'r',ok:()=>(st().optouts||0)>=3}, + {id:'read',i:'💔',t:tr('badges.left_on_read'),d:tr('badges.get_de_peered_by_a_big'),r:'r',ok:()=>(st().depeered||0)>=1}, + {id:'couch',i:'🛋️',t:tr('badges.peering_from_the_couch'),d:tr('badges.peer_at_an_ix_remotely'),r:'r',ok:()=>Object.keys(S.ixp).some(c=>isRemote(c)&&ixSessions(c).size>0)}, + {id:'sender',i:'🇰🇷',t:tr('common.sender_pays'),d:tr('badges.paid_pnis_with_all_three_korean'),r:'e',ok:()=>['ktt','skb','lgu'].every(n=>S.pni.some(p=>p.net===n&&pniOn(p)))}, + {id:'oink',i:'🐖',t:tr('common.pig_whisperer'),d:tr('badges.run_a_slow_booting_packetoinker'),r:'r',ok:()=>Object.keys(S.pops).some(c=>/Oinker/.test(RG[S.pops[c].rgen||0].chip)&&slowBoot(c))}, + {id:'gap',i:'🌴',t:tr('common.mind_the_gap'),d:tr('badges.link_panama_city_and_bogota'),r:'r',ok:()=>S.links.some(l=>[l.a,l.b].includes('pan')&&[l.a,l.b].includes('bog'))}, + {id:'andes',i:'🏔️',t:tr('badges.over_the_mountains'),d:tr('badges.build_fiber_across_the_andes'),r:'r',ok:()=>S.links.some(l=>!l.sub&&andesPair(l.a,l.b))}, + {id:'duo',i:'🏜️',t:tr('common.duopoly_customer'),d:tr('badges.buy_a_wave_inside_the_uae'),r:'r',ok:()=>S.links.some(l=>uaePair(l.a,l.b))}, + {id:'shed',i:'🔌',t:tr('common.stage_six'),d:tr('badges.ride_out_load_shedding_on_your'),r:'r',ok:()=>(st().shed||0)>=1}, + {id:'metro3',i:'🏢',t:tr('badges.two_buildings_three_cities'),d:tr('badges.have_a_second_site_in_3'),r:'r',ok:()=>Object.values(S.pops).filter(p=>p.site2).length>=3}, + {id:'penguin',i:'🐧',t:tr('common.lonely_penguin'),d:tr('badges.light_a_wave_on_the_humboldt'),r:'e',ok:()=>S.links.some(l=>l.cable==='humb')}, + {id:'horn',i:'⛵',t:tr('badges.the_long_way_round'),d:tr('badges.run_a_link_round_cape_horn'),r:'e',ok:()=>S.links.some(hornLink)}, + {id:'six',i:'🌍',t:tr('common.six_continents'),d:tr('badges.pops_in_every_region_on_the'),r:'e',ok:()=>regionsCount()>=6}, + {id:'giants',i:'🏭',t:tr('badges.friend_of_giants'),d:tr('badges.hold_deals_at_3_different_ai'),r:'e',ok:()=>new Set(S.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].mega).flatMap(b=>bCities(b))).size>=3}, + {id:'landlord',i:'🧵',t:tr('common.trench_landlord'),d:tr('badges.lease_hundreds_of_fiber_pairs_to'),r:'e',ok:()=>S.biz.some(b=>b.type==='pairs')}, + {id:'t1',i:'👑',t:tr('common.tier_1'),d:tr('badges.go_transit_free'),r:'e',ok:()=>!!S.won}, + {id:'sol',i:'⚡',t:tr('specialist.speed_of_light'),d:tr('specialist.win_as_a_low_latency_boutique'),r:'e',ok:()=>!!S.solWon}, + {id:'baron',i:'🌊',t:tr('broker.glass_baron'),d:tr('broker.win_as_a_cable_broker'),r:'e',ok:()=>!!S.baronWon}, + {id:'seat',i:'🚢',t:tr('specialist.part_owner_of_the_sea'),d:tr('specialist.take_a_seat_on_a_consortium'),r:'r',ok:()=>S.links.some(l=>l.seat)}, + {id:'bait',i:'🎣',t:tr('common.shark_bait'),d:tr('badges.get_bitten_by_sharks_3_times'),r:'l',ok:()=>(st().sharks||0)>=3}, + {id:'nines',i:'💎',t:tr('common.five_nines'),d:tr('badges.serve_99_5_of_demand_every'),r:'l',ok:()=>(st().clean||0)>=365}, + {id:'fifty',i:'🗺️',t:tr('badges.everywhere_at_once'),d:tr('badges.have_pops_in_50_cities'),r:'l',ok:()=>Object.keys(S.pops).length>=50}, + {id:'unicorn',i:'🦄',t:tr('common.unicorn'),d:tr('badges.hold_a_billion_dollars_in_cash'),r:'l',ok:()=>S.cash>=1e9}, + {id:'clean',i:'🧼',t:tr('badges.debt_free_tier_1'),d:tr('badges.win_without_ever_taking_a_loan'),r:'l',ok:()=>!!S.won&&!(st().loans||0)&&!(S.loans||[]).length}, + {id:'speed',i:'⚡',t:tr('common.speedrun'),d:tr('badges.reach_tier_1_within_three_years'),r:'l',ok:()=>!!S.won&&netAge()<=1095}, + {id:'te',i:'🧭',t:tr('common.traffic_whisperer'),d:tr('badges.have_auto_te_move_100_gbps'),r:'r',ok:()=>(st().teMax||0)>=100}, + {id:'street',i:'🚧',t:tr('common.same_street'),d:tr('badges.lose_a_metro_ring_to_one'),r:'r',ok:()=>(st().by||{}).ring>=1}, + {id:'anchor',i:'⚓',t:tr('common.anchors_aweigh'),d:tr('badges.have_a_cable_cut_by_a'),r:'r',ok:()=>!!(st().f||{}).anchor}, + {id:'retained',i:'🎁',t:tr('badges.customer_success_story'),d:tr('badges.take_a_de_kicks_retention_offer'),r:'r',ok:()=>!!st().retained}, + {id:'brrr',i:'🇧🇷',t:tr('common.samba_peering'),d:tr('badges.ports_on_ix_brrr_in_sao'),r:'e',ok:()=>['sao','rio','for'].every(c=>S.ixp[c]!==undefined)}, + {id:'bingo',i:'🎰',t:tr('badges.de_kicks_bingo'),d:tr('badges.ports_at_all_six_de_kicks'),r:'e',ok:()=>DK_CITIES.filter(c=>CITY[c]&&CITY[c].ix).every(c=>S.ixp[c]!==undefined)}, + {id:'fire',i:'🌋',t:tr('badges.ring_of_fire'),d:tr('badges.pops_all_the_way_round_the'),r:'e',ok:()=>['lax','tok','tpe','mnl','jkt','syd','akl','scl'].every(c=>S.pops[c])}, + {id:'curtain',i:'🎭',t:tr('badges.east_side_story'),d:tr('badges.pops_in_warsaw_prague_vienna'),r:'e',ok:()=>['waw','prg','vie','bud','buh','sof','beg','tll'].every(c=>S.pops[c])}, + {id:'islands',i:'🏝️',t:tr('common.island_hopper'),d:tr('badges.pops_in_reykjavik_dublin_london'),r:'e',ok:()=>['rek','dub','lon','cbo','tpe','mnl','tok','akl'].every(c=>S.pops[c])}, + {id:'wall',i:'🧱',t:tr('badges.through_the_wall'),d:tr('badges.run_a_licensed_pop_in_mainland'),r:'e',ok:()=>cnOk()&&Object.keys(S.pops).some(cnCity)}, + {id:'beaver',i:'🦫',t:tr('common.dam_it'),d:tr('badges.have_your_fiber_chewed_through_by'),r:'e',ok:()=>!!(st().f||{}).beaver}, + {id:'croc',i:'🐊',t:tr('common.snap_judgement'),d:tr('badges.have_your_fiber_bitten_by_a'),r:'l',ok:()=>!!(st().f||{}).croc}, + {id:'unbreak',i:'🛡️',t:tr('common.unbreakable'),d:tr('badges.survive_100_incidents_without'),r:'l',ok:()=>(st().survived||0)>=100}, + {id:'lv13',i:'🌐',t:tr('badges.is_this_the_internet'),d:tr('badges.reach_customer_level_13'),r:'l',ok:()=>(S.lvl||1)>=13}, + {id:'gigawatt',i:'⚛️',t:tr('common.gigawatt_landlord'),d:tr('badges.hold_an_ai_wan_a_training'),r:'l',ok:()=>['aiwan','mtrain','ingest','pairs'].every(t=>S.biz.some(b=>b.type===t))}, + {id:'blitz',i:'🚀',t:tr('common.blitz'),d:tr('badges.reach_tier_1_within_two_years'),r:'l',ok:()=>!!S.won&&netAge()<=730}, + {id:'tera',i:'📶',t:tr('badges.terabit_club'),d:tr('badges.serve_1_tbps'),r:'c',ok:()=>R.served>=1000}, + {id:'tera10',i:'🚄',t:tr('badges.ten_terabits'),d:tr('badges.serve_10_tbps'),r:'r',ok:()=>R.served>=10000}, + {id:'peta',i:'🌌',t:tr('common.hundred_terabits'),d:tr('badges.serve_100_tbps'),r:'e',ok:()=>R.served>=100000}, + {id:'petabit',i:'🪐',t:tr('badges.a_petabit_a_second'),d:tr('badges.serve_1_pbps_a_thousand_terabits'),r:'l',ok:()=>R.served>=1e6}, + // Traffic carried in total (15-traffic-volume.js): the odometer, in petabytes. + {id:'vol_pb',i:'💾',t:tr('badges.vol_pb'),d:tr('badges.vol_pb_d'),r:'c',ok:()=>(S.vol||0)>=1}, + {id:'vol_100pb',i:'🗄️',t:tr('badges.vol_100pb'),d:tr('badges.vol_100pb_d'),r:'r',ok:()=>(S.vol||0)>=100}, + {id:'vol_eb',i:'🚂',t:tr('badges.vol_eb'),d:tr('badges.vol_eb_d'),r:'e',ok:()=>(S.vol||0)>=1000}, + {id:'vol_zb',i:'🌠',t:tr('badges.vol_zb'),d:tr('badges.vol_zb_d'),r:'l',ok:()=>(S.vol||0)>=1e6}, + {id:'llama',i:'🦙',t:tr('common.llama_drama'),d:tr('badges.lose_fiber_to_a_llama_herd'),r:'l',secret:true,ok:()=>!!(st().f||{}).llama}, + {id:'hallway',i:'🎤',t:tr('common.hallway_track'),d:tr('badges.attend_a_conference'),r:'r',ok:()=>(st().confs||0)>=1}, + {id:'beer',i:'🍺',t:tr('badges.peering_over_beer'),d:tr('badges.set_up_a_pni_while_the'),r:'e',ok:()=>!!st().beerPni}, + {id:'circuit',i:'✈️',t:tr('common.conference_circuit'),d:tr('badges.attend_six_conferences_in_one_game'),r:'l',ok:()=>(st().confs||0)>=6}, + {id:'kiddie',i:'💻',t:tr('common.script_kiddie'),d:tr('badges.deploy_a_routescript_that_cuts_your'),r:'r',ok:()=>!!st().kiddie}, + {id:'fat',i:'🫠',t:tr('common.fat_finger'),d:tr('badges.deploy_a_routescript_that_takes_down'),r:'r',ok:()=>!!st().fat}, + {id:'scen1',i:'🎯',t:tr('common.scenario_solver'),d:tr('badges.complete_any_scenario'),r:'r',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')}, + {id:'weekly',i:'📅',t:tr('common.weekly_regular'),d:tr('badges.finish_a_weekly_challenge'),r:'r',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id==='weekly')}, + {id:'scen3',i:'🏅',t:tr('common.scenario_specialist'),d:tr('badges.complete_three_different_scenarios'),r:'e',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')&&Object.keys(scnHof()).filter(k=>k!=='weekly').length>=3}, + {id:'scenall',i:'🏆',t:tr('common.scenario_grandmaster'),d:tr('badges.complete_every_scenario'),r:'l',ok:()=>!!(S.scn&&S.scn.done&&S.scn.id!=='weekly')&&SCN.every(x=>scnHof()[x.id])}, + {id:'elephant',i:'🐘',t:tr('badges.i_survived_the_elephant'),d:tr('badges.live_through_the_day_half_the'),r:'l',secret:true,ok:()=>!!S.phpDone&&!(S.ev.php>S.day)}, + {id:'vigil',i:'⚖️',t:tr('common.vigilante'),d:tr('badges.fire_the_hackback_3000tm_and_flatten'),r:'e',secret:true,ok:()=>(st().vigilante||0)>=1}, + {id:'nullroute',i:'💥',t:tr('common.splash_damage'),d:tr('badges.blackhole_one_of_your_own_cities'),r:'r',ok:()=>(st().rtbh||0)>=1}, + {id:'toaster',i:'🍞',t:tr('common.toaster_wrangler'),d:tr('badges.weather_a_ddos_with_your_defences'),r:'c',ok:()=>(st().ddosHeld||0)>=1}, + {id:'cleanpipe',i:'🚿',t:tr('common.clean_pipes'),d:tr('badges.turn_on_a_transit_clean_pipe'),r:'r',ok:()=>S.transit.some(t=>t.clean)}, + {id:'lamb',i:'🐐',t:tr('common.sacrificial_lamb'),d:tr('badges.run_a_sacrificial_pni_choke_point'),r:'r',ok:()=>S.pni.some(p=>p.sacrif)}, + {id:'monkey',i:'🛡️',t:tr('badges.monkey_proof'),d:tr('badges.outlast_a_chaos_monkey_visit'),r:'e',ok:()=>(st().mkSurv||0)>=1}, + {id:'flood',i:'🌊',t:tr('badges.held_the_flood'),d:tr('badges.weather_a_multi_terabit_ddos'),r:'e',ok:()=>(st().ddosMonster||0)>=1}, + {id:'skynot',i:'🤖',t:tr('common.skynot_smiles'),d:tr('badges.land_a_hackback_3000tm_that_actually'),r:'e',secret:true,ok:()=>(st().hackWin||0)>=1}, + {id:'label',i:'🏷️',t:tr('core.label_switcher'),d:tr('core.run_an_mpls_backbone'),r:'c',ok:()=>coreOn()&&S.core.run>=1}, + {id:'bleed',i:'🩸',t:tr('core.bleeding_edge'),d:tr('core.run_an_srv6_backbone'),r:'r',ok:()=>coreOn()&&S.core.run>=4}, + {id:'mono',i:'🏪',t:tr('core.single_vendor_shop'),d:tr('core.run_sr_mpls_or_srv6_on'),r:'e',ok:()=>coreOn()&&S.core.run>=3&&Object.keys(S.pops).length>=8&&!coreOut().length&&coreVendors().size===1}, + {id:'zoo',i:'🦓',t:tr('core.vendor_zoo'),d:tr('core.run_an_mpls_backbone_with_4'),r:'r',ok:()=>coreOn()&&S.core.run>=1&&coreVendors().size>=4}, + {id:'billion',i:'🔥',t:tr('pie.b_billion'),d:tr('pie.b_billion_d'),r:'e',ok:()=>!!S.pie&&S.pie.book.spent>=1e9}, + {id:'baked',i:'🥧',t:tr('pie.b_baked'),d:tr('pie.b_baked_d'),r:'l',ok:()=>!!S.pie&&Object.keys(CRUSTS).some(id=>pieCov(id)>=1)}, + {id:'tour',i:'🎙️',t:tr('pie.b_tour'),d:tr('pie.b_tour_d'),r:'r',ok:()=>!!(st().pieTour)}, + {id:'zero',i:'🕳️',t:tr('badges.zero_peers_given'),d:tr('badges.reach_tier_2_with_every_single'),r:'l',secret:true,ok:()=>isTier2()&&!Object.keys(S.peers).length&&!S.pni.length}, +]; +/* Badge variants by ruleset (2.0): On-call earns the standard badge, Change Freeze a frosted one and BGP at 3 a.m. a + fiery one; Sandbox and the puzzles earn none (puzzles have stars). Earning a badge again under a harder preset + upgrades its look, here and in the hall of fame. S.ach[id] stays the day it was earned; S.achP[id] is its variant. */ +const BVAR={freeze:{k:'freeze',lv:1,i:'🧊',n:N_('badges.variant_freeze_dried'),col:'#5BC0EB'},oncall:{k:'oncall',lv:2,i:'⭐',n:N_('badges.variant_on_call'),col:'#FFD23F'},bgp:{k:'bgp',lv:3,i:'🔥',n:N_('badges.variant_forged_at_3_a_m'),col:'#FF5A1F'}}; +const BVAR_IDS=['freeze','oncall','bgp'],bvar=k=>own(BVAR,k)?BVAR[k]:BVAR.oncall; +// The preset this save plays under ('oncall' for every save from before rulesets), and the variant it earns (null: none). +const rulePre=()=>(typeof rulePreset==='function'?rulePreset():(S&&S.rules&&S.rules.preset))||'oncall'; +// Best Effort earns the gentlest variant, Freeze-dried. +function badgeVar(){if(!S||S.mode==='sandbox')return null;const p=rulePre();return p==='sandbox'||p==='puzzle'?null:p==='soft'?'freeze':own(BVAR,p)?p:'oncall';} +// The hall of fame is this device's localStorage, so it is checked like a save: unknown variants count as standard. +function hof(){let h;try{h=JSON.parse(localStorage.getItem('sot-badges')||'{}');}catch(e){h=null;}if(!h||typeof h!=='object'||Array.isArray(h))return {}; + for(const k of Object.keys(h)){const x=h[k];if(!x||typeof x!=='object'){delete h[k];continue;}const vs=x.vs&&typeof x.vs==='object'&&!Array.isArray(x.vs)?x.vs:{}; + x.vs={};for(const v of BVAR_IDS)if(typeof vs[v]==='string')x.vs[v]=vs[v];if(!Object.keys(x.vs).length)x.vs.oncall=typeof x.d==='string'?x.d:''; + x.v=BVAR_IDS.filter(v=>x.vs[v]!==undefined).pop();} + return h;} +function checkBadges(){S.ach=S.ach||{};S.achP=S.achP||{};const v=badgeVar();if(!v)return;let h=null;const V=BVAR[v]; + for(const b of BADGES){const had=S.ach[b.id]!==undefined;if(had&&bvar(S.achP[b.id]).lv>=V.lv)continue;let ok=false;try{ok=b.ok();}catch(e){} + if(!ok)continue;if(!had)S.ach[b.id]=S.day;S.achP[b.id]=v;const R0=RARITY[b.r]; + // "Upgraded" is about this device's collection: the hall of fame already held the badge, only in a lower variant. + if(!h)h=hof();const today=new Date().toISOString().slice(0,10),up=!!h[b.id]&&bvar(h[b.id].v).lv${b.i} ${up?tr('badges.badge_upgraded_name',{name:esc(b.t)}):tr('badges.badge_unlocked_name',{name:esc(b.t)})}
${R0.n}${v==='oncall'?'':` · ${V.i} ${tr(V.n)}`} · ${esc(b.d)}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');track('badge_'+b.id+(v==='oncall'?'':'_'+v));} + if(h)try{localStorage.setItem('sot-badges',JSON.stringify(h));}catch(e){}} +// How many badges this device has ever earned in each variant: the collection. +function badgeShelf(h){const o={freeze:0,oncall:0,bgp:0};for(const b of BADGES){const x=h[b.id];if(x)for(const v of BVAR_IDS)if(x.vs[v]!==undefined)o[v]++;}return o;} +function badgeGrid(){const h=hof(),got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined).length,sh=badgeShelf(h),V=badgeVar(); + return `

${tr('common.badges')} ${tr('badges.got_total_this_game_ever_ever',{got,total:BADGES.length,ever:Object.keys(h).filter(k=>BADGES.some(b=>b.id===k)).length})}

+
${BVAR_IDS.map(v=>`${BVAR[v].i} ${esc(tr(BVAR[v].n))} ${sh[v]}/${BADGES.length}`).join('')}
${V&&V!=='oncall'?`

${V==='bgp'?tr('badges.this_game_earns_fiery_badges'):tr('badges.this_game_earns_frosted_badges')}

`:''} +
${BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!h[b.id],R0=RARITY[b.r],hide=b.secret&&!on&&!ever,vk=on?bvar(S.achP&&S.achP[b.id]).k:ever?h[b.id].v:'',vn=vk&&vk!=='oncall'?' · '+BVAR[vk].i+' '+tr(BVAR[vk].n):''; + return `
${hide?'❔':b.i}${esc(hide?'???':b.t)}${R0.n}${ever&&!on?' · '+tr('common.earned_before'):''}${vk&&vk!=='oncall'?`${BVAR[vk].i} ${esc(tr(BVAR[vk].n))}`:''}${hide?'':`${esc(b.d)}`}
`;}).join('')}
`;} +function checkGoals(){checkBadges(); + for(const g of goals()){if(S.done[g.id]!==undefined)continue;let ok=false;try{ok=g.ok();}catch(e){} + if(ok){S.done[g.id]=S.day;if(g.r&&S.mode!=='sandbox'){S.cash+=g.r;} + toast(`${tr('badges.goal_complete_name',{name:esc(g.t)})}${g.r?`
${tr('badges.reward_amt',{amt:fmt$(g.r)})}`:''}`,'goal',[],{a:'tab',v:'goals'});sfx('coin'); + // Glass Baron is the broker's win; S.won stays Tier 1, which a broker can still become. + track('goal_'+g.id);if(g.baron){if(!S.baronWon){S.baronWon=S.day||1;track('win_baron');checkBadges();showBaronWin();}}else if(g.win&&!S.won){S.won=true;track('win_tier1');pieUnlock();checkBadges();showWin();}}} +} + diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js new file mode 100644 index 0000000..a38dabb --- /dev/null +++ b/src/game/90-actions/10-interface.js @@ -0,0 +1,65 @@ +/* ================= ACTIONS ================= */ +function spend(c){if(S.cash{const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return;linkCheckModal(l);}, + speed:({v})=>{v=+v;if(pzOn()||UI.clockLocked)return;if(![0,0.5,1,2,4,8].includes(v)||(S&&!rule('clock')&&v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();}, + help:()=>showHelp(), + dash:()=>{if(!S||pzOn())return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();}, + dashClose:()=>{$('dash').hidden=true;}, + dashTab:({k})=>{if(!DTABS.includes(k))return;UI.dtab=k;renderDash();const d=$('dash');if(d)d.scrollTop=0;}, + dashSort:({k})=>{if(!['name','asn','type','traffic','cost','lost'].includes(k))return;if(UI.dashSort===k)UI.dashDir=-(UI.dashDir||-1);else{UI.dashSort=k;UI.dashDir=k==='name'||k==='type'||k==='asn'?1:-1;}renderDash();}, + bank:()=>{if(!S||pzOn())return;UI.confirm=null;$('dash').hidden=true;const b=$('bankBox');b.hidden=false;UI._bh=null;renderBank();}, + bankClose:()=>{UI.confirm=null;$('bankBox').hidden=true;}, + takeLoan:({id})=>{const o=S.loanOffers.find(x=>x.id===id);if(!o)return;S.stats.loans=(S.stats.loans||0)+1;const B=BANKS[o.bank];let got=o.amount,note=''; + if(B.crypto){const f=0.55+Math.random()*0.8;got=Math.round(o.amount*f);note=' '+(f>=1?tr('interface.tubecoin_moved_up_p_on_the',{p:Math.round(Math.abs(f-1)*100)}):tr('interface.tubecoin_moved_down_p_on_the',{p:Math.round(Math.abs(f-1)*100)}));} + S.cash+=got;S.loanOffers=S.loanOffers.filter(x=>x!==o); + S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,got,bal:o.model==='transit'?o.owe:o.amount,apr:o.apr||0,apr0:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,model:o.model,cut:o.cut,covs:o.covs,base:{sub:S.links.filter(seaLink).length}}); + track('loan_taken');toast(`${tr('interface.amt_from_bank_has_landed',{amt:fmt$(got),bank:esc(B.name)})}
${B.equity?tr('interface.they_now_own_p_of_your',{p:pct(o.share)}):loanSummary(o)}${note}`,'good');sfx('coin');after();renderBank();}, + callBank:({amount})=>{if(!callOffer(amount))return;track('loan_called');sfx('click');renderBank();renderHUD();save();}, + declineLoan:({id})=>{S.loanOffers=S.loanOffers.filter(x=>x.id!==id);sfx('click');renderBank();renderHUD();save();}, + repayLoan:({id})=>{const l=S.loans.find(x=>x.id===id);if(!l)return;const B=BANKS[l.bank];const cost=repayCost(l,B); + if(UI.confirm!==id){UI.confirm=id;renderBank();return;}UI.confirm=null;if(!spend(cost)){renderBank();return;}S.loans=S.loans.filter(x=>x!==l);track('loan_repaid'); + toast(B.equity?tr('interface.you_bought_out_bank_they_flew',{bank:esc(B.name)}):tr('interface.loan_from_bank_repaid_early',{bank:esc(B.name)}),'good');after();renderBank();}, + leaseSwap:({a,b,src})=>{if(!S.pops[a]||!S.pops[b]||a===b)return;$('dash').hidden=true;UI.lmode='df';UI.dfSrc=['lease','build','cable'].includes(src)?src:isSub(a,b)?'cable':'build';UI.dfSys=glassLvl()>=3?'roadm':'lite';openLinkModal(a,b);}, + dashLink:({id})=>{$('dash').hidden=true;selectLink(id);focusLink(id);}, + mapSet:({v})=>{if(!['auto','2d'].includes(v))return;mapGl(v==='auto');refreshSettings();}, + themeSet:({v})=>{if(!themePick(v))return;refreshSettings();}, + animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();}, + soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();}, + langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save(true);location.reload();}, + mute:()=>{UI.muted=!UI.muted;try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();}, + closePanel:()=>{UI.sel=null;UI.confirm=null;renderPanel();renderLeft();}, + closeModal:()=>closeModal(), + tab:({t})=>{UI.tab=t;UI.confirm=null;renderPanel();}, + leftTab:({t})=>{UI.left=t;UI.leftOpen=true;renderLeft();}, + netFocus:({id})=>{if(!NET[id])return;$('dash').hidden=true;UI.netFocus=id;UI.nf='all';UI.left='nets';UI.leftOpen=true;UI.sel=null;renderPanel();renderLeft();const b=$('leftBody');if(b)b.scrollTop=0;}, + netFilter:({f})=>{UI.nf=f==='out'?'out':'all';listReset('nets');UI.netFocus=null;$('dash').hidden=true;UI.left='nets';UI.leftOpen=true;UI.sel=null;renderPanel();renderLeft();const b=$('leftBody');if(b)b.scrollTop=0;}, + meetGo:({city})=>{if(!isCity(city))return;$('dash').hidden=true;ACT.focusCity({city});if(S.pops[city]){UI.tab='peer';renderPanel();}}, + toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();}, + phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;if($('modal').classList.contains('link-check'))closeModal();haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();}, + phonePlay:()=>{if(playPause())haptic(10);}, + phoneSpeed:()=>{if(pzOn()||UI.clockLocked)return;if(S&&!rule('clock'))return;haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();}, + install:()=>{if(installEvt){installEvt.prompt();installEvt.userChoice.finally(()=>{installEvt=null;});return;} + openModal(pitchHtml(false));}, + pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();}, + logOpen:({id})=>{const e=(S.log||[]).find(x=>x.id===id),o=e&&e.o;if(!o)return;$('dash').hidden=true;closeModal(); + if(o.a==='city'&&isCity(o.v)){ACT.focusCity({city:o.v});return;} + if(o.a==='link'){if(S.links.some(l=>l.id===o.v)){ACT.selLink({id:o.v});return;}toast(tr('interface.that_link_is_gone_it_was'),'');return;} + if(o.a==='cust'){if(S.biz.some(b=>b.id===o.v)){ACT.custGo({id:o.v});return;}toast(tr('interface.that_customer_is_gone_the_contract'),'');return;} + if(o.a==='ip4'&&ip4On()){ACT.ip4Open();return;}if(o.a==='bank'||o.a==='ip4'){ACT.bank({});return;}if(o.a==='ops'){ACT.opsOpen();return;}if(o.a==='tab'&&LOG_TABS.includes(o.v))ACT.leftTab({t:o.v});}, + logAll:()=>{UI.logAll=!UI.logAll;renderLeft();}, + findOpen:()=>findOpen(), + findGo:({city})=>{if(!isCity(city))return;closeModal();$('dash').hidden=true;ACT.focusCity({city});}, + // A link from one of your POPs to a city you type instead of dragging to (#343): the same window the drag opens. + findLink:({city})=>{if(!isCity(city)||!S.pops[city]||pzOn())return;findOpen(city);}, + linkTo:({a,b})=>{if(!isCity(a)||!isCity(b)||a===b||pzOn()||!linkFromOk(a)||!linkToOk(b))return;$('dash').hidden=true;sfx('click');openLinkModal(a,b);}, + focusCity:({city})=>{selectCity(city);const C=CITY[city];cam.x=C.x;cam.y=C.y;cam.z=Math.max(cam.z,1.2);if(innerWidth<760)UI.leftOpen=false;renderLeft();}, + popStep:({d})=>{const L=popOrder(),n=L.length;if(!n)return;const i=UI.sel&&UI.sel.type==='city'?L.indexOf(UI.sel.id):-1;$('dash').hidden=true;ACT.focusCity({city:L[i<0?(d>0?0:n-1):(i+(d>0?1:n-1))%n]});}, + // The offer stays marked in its city's Offers here until something else is selected, so two offers in one city each get a press. + offerStep:()=>{const L=offerOrder(),n=L.length;if(!n){toast(tr('hud_and_panels.no_open_offers_right_now_businesses'));return;} + const i=L.findIndex(o=>o.id===UI.offerAt),o=L[(i+1)%n];$('dash').hidden=true;ACT.focusCity({city:o.city});UI.offerAt=o.id;if(S.pops[o.city])UI.tab='cust';renderPanel(); + const r=document.querySelector('#panelBody .row.on');if(r&&r.scrollIntoView)r.scrollIntoView({block:'nearest'});}, + zoomStep:({d})=>zoomAt(CW/2,CH/2,d>0?1.25:0.8), + keys:()=>showKeys(), + selLink:({id})=>{selectLink(id);focusLink(id);}, +}; diff --git a/src/game/90-actions/20-pops-transit-ix.js b/src/game/90-actions/20-pops-transit-ix.js new file mode 100644 index 0000000..9e4337c --- /dev/null +++ b/src/game/90-actions/20-pops-transit-ix.js @@ -0,0 +1,27 @@ +Object.assign(ACT,{ + buildPop:({city})=>{if(S.pops[city]||!CITY[city])return;if(!cityOn(city)){toast(popOffWhy(city),'bad');sfx('err');return;}const flipNote=CITY[city]&&CITY[city].au;if(cnCity(city)&&!cnOk()){toast(tr('pops_transit_ix.you_need_a_license_first_foreign'),'bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(city);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');if(flipNote)toast(pick([tr('pops_transit_ix.router_installed_in_city_upside_down',{city:CITY[city].name}),tr('pops_transit_ix.router_installed_in_city_the_vendor',{city:CITY[city].name})]),'good',[],{a:'city',v:city});UI.tab='cust';after();}, + launchBB:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:bbStart(city)};floater(C.x,C.y-30,tr('common.eyeballs_online'),'#16A866');after();}, + ad:({city})=>{const p=S.pops[city];if(!p||!p.bb)return;if(!spend(8000))return;p.boost=S.day+30;floater(CITY[city].x,CITY[city].y-30,tr('common.ad_campaign'),'#FF8A3D');after();}, + // A new port has every field sanitize() gives one, so live S is what a reload makes of it. + buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast(tr('pops_transit_ix.no_transit_in_this_scenario_peering'),'bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!sellsAt(NET[net],city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else{const pr=premOnlyAt(NET[net],city);S.transit.push({id:uid(),city,net,tier,down:0,...(pr?{premium:true}:{}),lacp:null,site:'a',n:1,clean:false,...(pr?{}:{premium:false})});}toast(tr('pops_transit_ix.net_transit_is_live_in_city',{net:esc(NET[net].name),city:CITY[city].name}),'good');after();}, + lagT:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const t=S.transit.find(x=>x.id===id);if(!t)return;const n=(t.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0){if(!portOk(t.city,t.tier)||!portGate(t.city,PORT_SLOT(t.tier)))return;if(!spend(PORT[t.tier].setup))return;}t.n=n;if(n<2&&t.site==='ab')t.site='a';toast(+d>0?tr('pops_transit_ix.lag_member_added_net_in_city',{net:esc(NET[t.net].name),city:CITY[t.city].name,lag:lagName(t.tier,n)}):tr('pops_transit_ix.lag_member_removed'),'good');after();}, + lagP:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const p=S.pni.find(x=>x.id===id);if(!p)return;const n=(p.n||1)+(+d);if(n<1||n>PNI_LAG_MAX)return;if(d>0&&n>pniLagMax(p.city)){toast(tr('pops_transit_ix.this_pni_already_bundles_n_ports',{n:n-1,more:PNI_LAG_RT,max:PNI_LAG_MAX}),'bad');sfx('err');return;}if(d>0&&(!pniOn(p)||p.up||msfNope(p.net,p.city)))return;if(+d>0&&(!portGate(p.city,PORT_SLOT(p.tier))||!spend(1500+PORT[p.tier].setup/2)))return; + // A LAG member is an augment: the big networks take months for that too. + if(d>0){const lead=pniLead(p.net);p.up={tier:p.tier,n,ready:S.day+lead,g1:!!p.g1};if(!lead)pniUpDone(p);toast(lead?tr('pops_transit_ix.augment_ordered_with_net_eta',{net:esc(NET[p.net].name),eta:pniWhen(lead)}):tr('pops_transit_ix.augment_with_net_is_up',{net:esc(NET[p.net].name),port:p.n+'×'+pniPN(p)}),'good');after();return;}p.n=n;if(n<2&&p.site==='ab')p.site='a';sfx('build');after();}, + lagIx:({city,d})=>{d=+d;if(d!==1&&d!==-1)return;if(!isIx(city)||S.ixp[city]===undefined||S.myIx[city]||!S.pops[ixCity(city)])return;S.ixn=S.ixn||{};const n=(S.ixn[city]||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0&&(!portGate(ixCity(city),PORT_SLOT(S.ixp[city]))||!spend(ixPortMo(city,S.ixp[city]))))return;S.ixn[city]=n;if(n<2&&S.ixSite&&S.ixSite[city]==='ab')S.ixSite[city]='a';sfx('build');after();}, + cancelTransit:({id,ok})=>{if(!ok&&UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.transit=S.transit.filter(t=>t.id!==id);UI.confirm=null;after();}, + buyIx:({city,tier,signed})=>{tier=+tier;if(!PORT[tier]||!ixName(city)||(!S.pops[ixCity(city)]&&(!remoteCities().includes(ixCity(city))||tier>1))||(S.ixp[city]!==undefined&&tier<=S.ixp[city]))return;if(S.pops[ixCity(city)]&&!portOk(ixCity(city),tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}{const h0=S.ixp[city]!==undefined;if(!S.myIx[city]&&!portGate(ixCity(city),h0?(PORT_SLOT(tier)-PORT_SLOT(S.ixp[city]))*((S.ixn||{})[city]||1):PORT_SLOT(tier)))return;} + if(isDk(city)&&S.ixp[city]===undefined&&!signed){const dk=dkState();if(dk.stall>S.day){toast(tr('pops_transit_ix.de_kicks_sales_is_still_aligning',{n:dk.stall-S.day}),'bad');sfx('err');return;}dk.lastQ=dk.lastQ||{};const lq=dk.lastQ[city];dk.q={city,tier,m:lq&&lq.until>S.day?lq.m:dkQuoteMult(),h:lq&&lq.until>S.day?lq.h:0};dk.lastQ[city]={m:dk.q.m,h:dk.q.h,until:S.day+90};dkQuoteModal();return;}const had=S.ixp[city]!==undefined;if(!spend(ixPortMo(city,tier)*(had?((S.ixn||{})[city]||1):1)))return;S.ixp[city]=tier;if(!had)toast(S.pops[ixCity(city)]?tr('pops_transit_ix.port_up_at_ix_now_request',{ix:esc(ixName(city))}):tr('pops_transit_ix.remote_port_up_at_ix_it',{ix:esc(ixName(city))}),'good',[],{a:'city',v:ixCity(city)});after();}, + cancelIx:({city,sure,ok})=>{if(!ok&&UI.confirm!=='ix'+city){UI.confirm='ix'+city;renderPanel();return;} + if(isDk(city)&&!sure){const dk=dkState();if(!dk.retUsed[city]){openModal(`
${tr('pops_transit_ix.de_kicks_group_customer_success')}

${tr('pops_transit_ix.wait_before_you_go')}

${tr('pops_transit_ix.we_value_our_partnership_too_much')}

${tr('common.retention_offer')}${tr('pops_transit_ix.40_off_for_6_months')}

${tr('pops_transit_ix.after_that_the_normal_price_returns')}

${btn(tr('pops_transit_ix.stay_take_the_discount'),'dkStay',{city},'pink')}${btn(tr('common.leave_anyway'),'cancelIx',{city,sure:1},'ghost')}
`);return;}} + closeModal();if(S.dk){if(S.dk.m[city]){S.dk.lastQ=S.dk.lastQ||{};S.dk.lastQ[city]={m:S.dk.m[city],h:3,until:S.day+365};}delete S.dk.m[city];delete S.dk.add[city];delete S.dk.ret[city];}delete S.ixp[city];delete S.rs[city];if(S.ixn)delete S.ixn[city];for(const k in S.peers)if(k.endsWith('@'+city))delete S.peers[k];UI.confirm=null;after();}, + rs:({city})=>{if(!isIx(city)||S.ixp[city]===undefined)return;S.rs[city]=!S.rs[city];if(S.rs[city])toast(tr('pops_transit_ix.route_server_session_up_you_now'),'good');sfx('build');after();}, + dkAccept:()=>{const dk=dkState(),q=dk.q;if(!q)return;dk.m[q.city]=q.m;dk.q=null;closeModal();ACT.buyIx({city:q.city,tier:q.tier,signed:true});if(S.ixp[q.city]===undefined)delete dk.m[q.city];else toast(tr('pops_transit_ix.signed_with_de_kicks_welcome_to'),'good');}, + dkHaggle:()=>{const dk=dkState(),q=dk.q;if(!q||q.h>=3)return;q.h++;const r=Math.random(); + if(r<0.45){S.stats.haggleWin=1;q.m=+(q.m*(0.75+Math.random()*0.15)).toFixed(2);dkQuoteModal();toast(tr('pops_transit_ix.just_this_once_your_account_manager'),'good');} + else if(r<0.75){q.m=+(q.m*1.1).toFixed(2);dkQuoteModal();toast(tr('pops_transit_ix.after_consulting_with_management_the'),'bad');} + else{dk.stall=S.day+5+Math.floor(Math.random()*6);dk.q=null;closeModal();toast(tr('pops_transit_ix.haggling_paused_why',{why:esc(pick(DK_STALL))}),'bad');}}, + dkWalk:()=>{const dk=dkState(),q=dk.q;if(q){dk.lastQ=dk.lastQ||{};dk.lastQ[q.city]={m:q.m,h:q.h,until:S.day+90};if(q.h>0)dk.stall=Math.max(dk.stall||0,S.day+3);}dk.q=null;closeModal();toast(tr('pops_transit_ix.de_kicks_will_circle_back_expect'),'');}, + dkOptOut:({city,n})=>{const dk=dkState(),k='dk'+city+n;if(UI.confirm!==k){UI.confirm=k;renderPanel();return;}dk.add[city]=(dk.add[city]||[]).filter(x=>x.n!==n);UI.confirm=null;S.stats.optouts=(S.stats.optouts||0)+1;toast(tr('pops_transit_ix.opted_out_of_name_it_took',{name:esc(n)}),'good');after();}, + dkStay:({city})=>{if(!isDk(city))return;S.stats.retained=1;const dk=dkState();dk.ret[city]=S.day+180;dk.retUsed[city]=true;UI.confirm=null;closeModal();toast(tr('pops_transit_ix.40_off_ix_for_6_months',{ix:esc(ixName(city))}),'good');after();}, +}); diff --git a/src/game/90-actions/21-ix-downgrade.js b/src/game/90-actions/21-ix-downgrade.js new file mode 100644 index 0000000..efb9f79 --- /dev/null +++ b/src/game/90-actions/21-ix-downgrade.js @@ -0,0 +1,10 @@ +/* Step a port down one size: exchange ports, transit ports and PNIs. Upgrading was possible, downsizing meant leaving and rejoining. + A PNI stops at the smallest size the network sells (Tier 1s and closed CDNs: no 10G). */ +Object.assign(ACT,{ + downIx:({city})=>{const had=S.ixp[city];if(had===undefined||S.myIx[city]||!(had>0))return; + S.ixp[city]=had-1;toast(tr('ix_downgrade.port_downgraded_at_ix',{port:PORT[had-1].n,ix:esc(ixName(city))}),'good');sfx('click');after();}, + downT:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t||!(t.tier>0))return;t.tier--; + toast(tr('ix_downgrade.transit_downgraded',{net:esc(NET[t.net].name),city:CITY[t.city].name,port:lagName(t.tier,t.n)}),'good');sfx('click');after();}, + downP:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||!pniOn(p)||p.up||p.g1||!(p.tier>pniMin(p.net)))return;p.tier--; + toast(tr('ix_downgrade.pni_downgraded',{net:esc(NET[p.net].name),city:CITY[p.city].name,port:pniPN(p)}),'good');sfx('click');after();}, +}); diff --git a/src/game/90-actions/30-route-script-and-tools.js b/src/game/90-actions/30-route-script-and-tools.js new file mode 100644 index 0000000..518b8c1 --- /dev/null +++ b/src/game/90-actions/30-route-script-and-tools.js @@ -0,0 +1,30 @@ +Object.assign(ACT,{ + teEdit:()=>{if(!S.te)return;UI.teDraft=undefined;teModal();}, + teClose:()=>{const t=$('teSrc');if(t)UI.teDraft=t.value;closeModal();}, + teOpt:()=>{UI.teDraft=teOptimize();teModal();}, + teExample:()=>{UI.teDraft=TE_EXAMPLE;teModal();}, + teSlop:()=>{const t0=performance.now(),a=aiSlop(Math.random()<0.02),secs=Math.max(0.1,(performance.now()-t0)/1000);UI.teDraft=UI.slop=a.src;teModal(`

🤖 ${esc(a.ai)} ${tr('route_script_and_tools.thought_for_s_seconds',{s:secs.toFixed(1)})}
${tr(a.say)}

`);sfx('build');}, + teHelp:()=>{const t=$('teSrc');if(t)UI.teDraft=t.value;teHelpModal();}, + teBack:()=>teModal(), + teRecipe:({id})=>{const r=TE_RECIPES.find(x=>x.id===id);if(!r)return;UI.teDraft=r.src().join('\n');teModal(`

${tr('route_script_and_tools.loaded_name_check_it_then_deploy',{name:tr(r.n)})}

`);}, + teClear:()=>{S.te.script='';UI.teDraft=undefined;TE_CACHE={src:null,p:null};after();teModal(`

${tr('route_script_and_tools.script_removed_plain_auto_te_is')}

`);}, + // The script as an argument (a server runs these without the editor), else the editor's text. + teCheck:({script}={})=>{const t=$('teSrc');const src=typeof script==='string'?script:t?t.value:'';UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`
${esc(p.errors.join('\n'))}
`);return;}const r=teTrial(src);teModal(`
${esc(trn('route_script_and_tools.n_rule_ok',p.n)+'\n'+tr('route_script_and_tools.served_a_b',{a:fmtG(r.before.served),b:fmtG(r.after.served)})+'\n'+tr('route_script_and_tools.transit_a_mo_b_mo',{a:fmt$(r.before.tc),b:fmt$(r.after.tc)})+'\n'+tr('route_script_and_tools.spilled_g_onto_alternate_paths',{g:fmtG(r.after.moved)})+(r.after.bh?'\n'+tr('route_script_and_tools.blackholed_g',{g:fmtG(r.after.bh)}):''))}
`);}, + teDeploy:({script}={})=>{const t=$('teSrc');const src=(typeof script==='string'?script:t?t.value:'').slice(0,4000);UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`
${esc(tr('common.commit_failed')+'\n'+p.errors.join('\n'))}
`);sfx('err');return;}const r=teTrial(src);S.te.script=src;S.te.on=true;TE_CACHE={src:null,p:null};UI.teDraft=undefined;after(); + const drop=r.before.served>1?1-r.after.served/r.before.served:0,saved=r.before.tc>0?1-r.after.tc/r.before.tc:0; + if(drop>0.1&&UI.slop===src){if(drop>0.3)S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_the',{p:pct(drop)}),'bad');sfx('alert');} + else if(drop>0.3){S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_you',{p:pct(drop)}),'bad');sfx('alert');} + else{if(saved>0.1&&drop<0.01)S.stats.kiddie=1;toast(`${tr('common.commit_complete')}
${saved>0.01?trn('route_script_and_tools.n_rule_live_transit_bill_down',p.n,{p:pct(saved)}):trn('route_script_and_tools.n_rule_live',p.n)}`,'good');sfx('build');}closeModal();UI.slop=undefined;checkGoals();}, + buyTE:()=>{if(S.te)return;if(lvl()<3){toast(tr('route_script_and_tools.auto_te_unlocks_at_customer_level'),'bad');sfx('err');return;}if(!coreTE()){toast(tr('core.auto_te_needs_an_rsvp_te_or'),'bad');sfx('err');return;}if(!spend(TE_COST))return;S.te={on:true,day:S.day,script:''};toast(tr('route_script_and_tools.auto_te_is_live_the_controller'),'good');after();}, + teToggle:()=>{if(!S.te)return;S.te.on=!S.te.on;after();}, + trace:({city})=>traceModal(city), + traceRun:()=>{const f=$('trFrom'),t=$('trTo');traceModal(f&&f.value,t&&t.value);}, + traceMode:({m})=>{if(!TR_MODES.includes(m))return;const f=$('trFrom'),t=$('trTo');sfx('click');traceModal(f&&f.value,t&&t.value,m);}, + traceCopy:()=>{try{navigator.clipboard.writeText(UI.trText||'');toast(tr('route_script_and_tools.copied_paste_it_into_your_favourite'),'good');}catch(e){}}, + share:()=>shareModal(), + shareDl:()=>shareFile(f=>{if(!f)return;const a=document.createElement('a');a.href=URL.createObjectURL(f);a.download=f.name;document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);track('share_download');}), + shareGo:()=>shareFile(f=>{const d={title:'Series of Tubes',text:tr('route_script_and_tools.name_as_asn_tier_peak_peak',{name:S.name,asn:S.asn,tier:tierLabel(),peak:fmtG(S.stats.peak||0)}),url:'https://seriesoftub.es/'};try{if(f&&navigator.canShare&&navigator.canShare({files:[f]}))d.files=[f];navigator.share(d).then(()=>track('share_done')).catch(()=>{});}catch(e){}}), + confGo:({key})=>{S.confReg=S.confReg||{};if(S.confReg[key])return;const cf=upcomingConfs(75).find(x=>x.key===key);if(!cf||cf.day<=S.day||(cf.cap&&glassLvl(){S.confReg=S.confReg||{};const was=S.confReg[key];if(was==='sp')return;const cf=upcomingConfs(75).find(x=>x.key===key);if(!cf||cf.day<=S.day||!confSp(cf))return;if(!spend(CONF_SP-(was?CONF_COST:0)))return;S.confReg[key]='sp';toast(tr('conferences.you_are_sponsoring_conf_your_logo',{conf:esc(cf.n),region:esc(REG[CITY[cf.c].reg])}),'good');sfx('coin');after();}, + tutSkip:()=>{S.tut=null;try{localStorage.setItem('sot-tut','1');}catch(e){}renderCoach();}, +}); diff --git a/src/game/90-actions/40-sites-peering-caches.js b/src/game/90-actions/40-sites-peering-caches.js new file mode 100644 index 0000000..1bb7836 --- /dev/null +++ b/src/game/90-actions/40-sites-peering-caches.js @@ -0,0 +1,38 @@ +Object.assign(ACT,{ + addSite:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||p.site2)return;if(!spend(SITE2_COST))return;p.site2=true;p.site2Day=S.day;toast(tr('sites_peering_caches.second_site_live_in_city_b',{city:CITY[city].name,b:esc(siteName(city,'b')),a:esc(siteName(city,'a'))}),'good');sfx('build');after();}, + rmSite:({city})=>{const p=S.pops[city];if(!p||!p.site2)return;if(UI.confirm!=='site'+city){UI.confirm='site'+city;renderPanel();return;}UI.confirm=null;p.site2=0;p.sdown=null;p.ringcut=0;for(const t of S.transit)if(t.city===city)t.site='a';for(const x of S.pni)if(x.city===city)x.site='a';for(const x of S.caches)if(x.city===city)x.site='a';if(S.ixSite)for(const x of ixIdsIn(city))delete S.ixSite[x];after();}, + siteSet:({k,id,s})=>{if(!['a','b','ab'].includes(s))return; + const o=k==='t'?S.transit.find(x=>x.id===id):k==='p'?S.pni.find(x=>x.id===id):null;if(k!=='ix'&&!o)return;if(k==='ix'&&(!isIx(id)||S.ixp[id]===undefined||!S.pops[ixCity(id)]))return; + if(k==='ix'&&S.myIx[id]){S.ixSite=S.ixSite||{};S.ixSite[id]=s;after();return;} + const n=()=>k==='ix'?((S.ixn||{})[id]||1):(o.n||1); + if(k==='p'&&o.up)delete o.up.site; + if(s==='ab'&&n()<2){const before=n();if(k==='t')ACT.lagT({id,d:1});else if(k==='p')ACT.lagP({id,d:1});else ACT.lagIx({city:id,d:1}); + // A PNI's second member is an augment that lands months later (#219): it remembers to split the LAG when it does. + if(k==='p'&&o.up&&o.up.n>=2&&n()<2){o.up.site='ab';after();return;} + if(n()<2||n()===before)return;toast(tr('sites_peering_caches.second_lag_member_added_one_member'),'good');} + if(k==='ix'){S.ixSite=S.ixSite||{};S.ixSite[id]=s;}else o.site=s;after();}, + peer:({city,net})=>{if(!isIx(city)||!isNet(net)||S.ixp[city]===undefined||!ixMembers(city).includes(net))return;const r=peerOk(net,'ix',city);if(!r.ok){toast(tr('sites_peering_caches.net_declined_why',{net:esc(NET[net].name),why:esc(r.why)}),'bad');sfx('err');return;}S.peers[net+'@'+city]=true; + toast(`${tr('sites_peering_caches.net_accepted',{net:esc(NET[net].name)})}
${NET[net].pol==='selective'?tr('sites_peering_caches.they_checked_your_pearingdb_page_and'):tr('sites_peering_caches.bgp_session_established')}`,'good');sfx('build');after();}, + unpeer:({city,net})=>{delete S.peers[net+'@'+city];after();}, + peerAll:({city})=>{if(!isIx(city)||S.ixp[city]===undefined)return;const set=ixSessions(city);let n=0;for(const id of ixMembers(city))if(!set.has(id)&&peerOk(id,'ix',city).ok){S.peers[id+'@'+city]=true;n++;}if(!n)return;toast(trn('sites_peering_caches.n_new_session_at_ix_small',n,{ix:esc(ixName(city))}),'good',[],{a:'city',v:ixCity(city)});sfx('build');after();}, + tailTog:()=>{UI.tailOpen=!UI.tailOpen;renderLeft();}, + pni:({city,net,tier})=>{const q=pniQuote(city,net,tier);if(!q)return;if(q.why){toast(q.why,'bad');sfx('err');after();return;}if(!spend(q.cost))return;const lead=pniPlace(q); + toast(lead?tr('sites_peering_caches.pni_with_net_ordered_eta_a',{net:esc(NET[net].name),eta:pniWhen(lead),dc:esc(siteName(city,'a'))}):tr('sites_peering_caches.pni_with_net_is_up_already',{net:esc(NET[net].name),dc:esc(siteName(city,'a'))}),'good');after();}, + pniAllOpen:({net})=>{pniAllModal(net);}, + pniAllSize:({v})=>{if(!UI.pniAll)return;pniAllModal(UI.pniAll.net,+v);$('modalCard').querySelector('[data-chg="pniAllSize"]')?.focus();}, + // q: the total the sheet showed. The batch is planned again now; a different total (the prices are fixed, so another + // plan), or nothing left to order, is shown again, not bought. + pniAll:({net,tier,q})=>{const b=pniBatch(net,tier);if(!b)return;if(q!==undefined&&(+q!==b.cost||!b.orders.length)){pniAllModal(net,tier,tr('utilities.quote_changed'));sfx('err');return;}if(!b.orders.length)return;if(!spend(b.cost))return; + for(const q of b.orders)pniPlace(q);UI.pniAll=null;closeModal(); + toast(trn('pni_all.n_orders_with_net',b.orders.length,{net:esc(net===null?tr('common.all_networks'):NET[net].name),kept:b.kept,blocked:b.blocked.length}),'good');after();}, + pniChase:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||(pniOn(p)&&!p.up))return;const r=Math.random(); + if(r<0.15){if(p.up)p.up.ready=Math.max(S.day+1,p.up.ready-30);else p.ready=Math.max(S.day+1,p.ready-30);toast(tr('sites_peering_caches.your_account_manager_found_the_order'),'good');} + else toast(pick([tr('sites_peering_caches.it_is_with_the_provisioning_team'),tr('sites_peering_caches.we_are_waiting_on_the_colo'),tr('sites_peering_caches.your_ticket_was_merged_into_another'),tr('sites_peering_caches.could_you_resend_the_loa_you'),tr('sites_peering_caches.your_account_manager_is_on_paternity')]));after();}, + peerPol:({p})=>{if(!PPOL.includes(p))return;S.ppol=p;after();}, + cancelPni:({id,ok})=>{if(!ok&&UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.pni=S.pni.filter(p=>p.id!==id);UI.confirm=null;after();}, + cache:({city,net})=>{const n=NET[net];if(!n||!n.cache||!S.pops[city])return;if((R.demTo[net]||0)x.city===city&&x.net===net),nb=hv.filter(x=>x.site==='b').length,site=S.pops[city].site2&&nb{S.caches=S.caches.filter(c=>c.id!==id);after();}, + // Move one of a CDN's boxes to the other building (#69), so a dark building only takes out part of the cache. + cacheSite:({city,net,s})=>{if(s!=='a'&&s!=='b'||!S.pops[city]||!S.pops[city].site2)return;const x=S.caches.find(c=>c.city===city&&c.net===net&&(c.site==='b'?'b':'a')!==s);if(!x)return;x.site=s;sfx('click');after();}, +}); diff --git a/src/game/90-actions/45-pni-list.js b/src/game/90-actions/45-pni-list.js new file mode 100644 index 0000000..93c3abb --- /dev/null +++ b/src/game/90-actions/45-pni-list.js @@ -0,0 +1,6 @@ +// The PNI list's filter, sort and folded groups (#175, #172): view state only, never saved. +Object.assign(ACT,{ + pniFilter:({f})=>{UI.pniF=['all','t','worth','pni'].includes(f)?f:'all';listReset('pni');renderPanel();}, + pniGrp:({g,o})=>{if(!PNI_GRP.includes(g))return;UI.pniOpen=UI.pniOpen||{};UI.pniOpen[g]=!!o;renderPanel();}, + pniSort:()=>{UI.pniSort=UI.pniSort==='az'?'worth':'az';renderPanel();}, +}); diff --git a/src/game/90-actions/46-net-filter.js b/src/game/90-actions/46-net-filter.js new file mode 100644 index 0000000..83e3ceb --- /dev/null +++ b/src/game/90-actions/46-net-filter.js @@ -0,0 +1,6 @@ +// Find a network at a POP (#199): view state only. +Object.assign(ACT,{ + netFind:({q})=>{UI.netQ=String(q??'').slice(0,40);listReset('pni');renderPanel();}, + netOnly:()=>{UI.netOnly=!UI.netOnly;listReset('pni');renderPanel();}, + netClear:()=>{UI.netQ='';UI.netOnly=false;listReset('pni');renderPanel();}, +}); diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js new file mode 100644 index 0000000..2ee68fa --- /dev/null +++ b/src/game/90-actions/50-customers.js @@ -0,0 +1,31 @@ +Object.assign(ACT,{ + // List spare capacity with a capacity broker (#203): w waves and p spare pairs, sold as the route's market wants. + listFiber:({id,w,p})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||l.ready>S.day)return;w=Math.max(0,Math.min(freeCh(l)-((l.list&&l.list.w)||0),w|0));p=l.own?Math.max(0,Math.min((pairFree(l)?1:0)-((l.list&&l.list.p)||0),p|0)):0; + if(!w&&!p){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;}const L=l.list||(l.list={w:0,p:0});L.w+=w;L.p+=p;if(w)L.hw=(L.hw||0)+w;if(p)L.hp=(L.hp||0)+p; + toast(tr('broker.listed',{a:CITY[l.a].name,b:CITY[l.b].name}),'good');sfx('click');after();}, + unlistFiber:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||!l.list)return;delete l.list;sfx('click');after();}, + accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!ip4Fits(o)){const n=ip4Need(o),u=ip4Use(),k=ip4Pools(u),v={name:esc(o.name),p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,u.free))};toast(k===1?tr('ip4.no_space_v6',v):k?tr('ip4.no_space_both',v):tr('ip4.no_space',v),'bad',[{l:tr('ip4.section'),act:'ip4Open'}]);sfx('err');return;}const customer=auto?autoOffer(o):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} + if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l)=o.start){toast(tr('customers.too_late_the_event_has_already'),'bad');return;} + // A carrier renting more alien waves on a fiber it already rents grows its contract, like a real order for extra waves, + // instead of a new customer for every few waves (a big fiber business otherwise fills the save with tiny contracts). + const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name); + if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots); + floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;} + S.offers=S.offers.filter(x=>x!==o);if(o.mk&&clOn(customer))customer.mk=o.mk;if(o.by)customer.by=o.by;S.biz.push(clSign(customer)); + // The shark's commission: one month of what the deal pays, on signing. + if(o.by==='shark'){const c=Math.round(bizMo(customer));if(c>0){S.cash-=c;toast(tr('sales.commission',{name:esc(o.name),cost:fmt$(c)}),'');}} + floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();}, + decline:({id})=>{if(salesOverride(S.offers.find(x=>x.id===id))){after();return;}S.offers=S.offers.filter(x=>x.id!==id);after();}, + dropBiz:({id})=>{const b0=S.biz.find(x=>x.id===id);if(!b0)return;if(BIZ_T[b0.type].event&&S.day>=b0.start){toast(tr('customers.the_event_is_already_running_the'),'bad');sfx('err');return;}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();}, +}); +/* The renewal haggle (#178, 75-customer-lifecycle.js): match their price, meet halfway (they take it about two times + in three), or let them go. */ +function clHagOf(id){const b=S.biz.find(x=>x.id===id);return b&&b.hag?b:null;} +Object.assign(ACT,{ + renewMatch:({id})=>{const b=clHagOf(id);if(!b)return;clRenew(b,b.hag.rate);clNote('ren');toast(tr('lifecycle.matched',{name:esc(b.name)}),'good');sfx('coin');after();}, + renewMeet:({id})=>{const b=clHagOf(id);if(!b)return;const mid=clMid(b); + if(clR(b,'meet'){const b=clHagOf(id);if(!b)return;clGone(b,'cheap');toast(tr('lifecycle.let_go',{name:esc(b.name)}),'');after();}, +}); diff --git a/src/game/90-actions/51-customer-fix.js b/src/game/90-actions/51-customer-fix.js new file mode 100644 index 0000000..e02f23d --- /dev/null +++ b/src/game/90-actions/51-customer-fix.js @@ -0,0 +1,11 @@ +Object.assign(ACT,{ + // Buy what the offer asks for, then sign (#241). cost: the price the button showed; a quote that moved more than a + // day's hardware drift (quoteNear) buys nothing. + acceptFix:({id,cost})=>{const o=S.offers.find(x=>x.id===id),q=reqFix(o);if(!o||!q||!reqFixCanSign(o))return; + if(!quoteNear(+cost,q.cost)){toast(tr('utilities.quote_changed'),'bad');sfx('err');after();return;} + if(S.cash{for(const x of q.items){if(x.k==='gen')ACT.addGen({city:x.city});else if(x.k==='metro')ACT.addSite({city:x.city});else ACT.addRouter({city:x.city});}}); + toast(esc(tr('req_fix.bought',{list:q.items.map(x=>tr(REQ_FIX_L[x.k],{city:CITY[x.city].name})).join(', '),cost:fmt$(q.cost)})),'good'); + ACT.accept({id});}, +}); diff --git a/src/game/90-actions/52-sales.js b/src/game/90-actions/52-sales.js new file mode 100644 index 0000000..027cbd3 --- /dev/null +++ b/src/game/90-actions/52-sales.js @@ -0,0 +1,16 @@ +// The sales desk (38-sales-desk.js): hiring one salesperson, letting them go, and asking the board for a VP of Sales +// when the CEO has taken over. +Object.assign(ACT,{ + salesOpen:()=>{if(S)salesModal();}, + salesHire:({id})=>{if(!S||!own(SALES,id)||slP()||!salesCanHire()||!rule('clock'))return;const P=SALES[id];if(P.mo&&!spend(P.mo))return; + S.sales=Object.assign(S.sales||{},{p:id,hired:S.day,vp:null,golf:null,say:null});UI.confirm=null; + toast(id==='ceo'?tr('sales.ceo_took_over',{name:esc(slCap())}):tr('sales.hired',{name:esc(slCap())}),'good');sfx('coin');after();salesModal();}, + salesFire:()=>{const p=slP();if(!p||p==='ceo')return;if(UI.confirm!=='salesFire'){UI.confirm='salesFire';salesModal();return;}UI.confirm=null;const nm=slCap();S.sales.p=null; + toast(tr('sales.fired',{name:esc(nm)}),'');after();salesModal();}, + // The CEO cannot be fired. A board meeting (and its catering) can get you a VP of Sales, who takes over a month later. + // Signing for you (39-sales-auto.js): on or off, and the minimum under which offers are declined. + salesAuto:()=>{if(!slP())return;const A=S.slAuto||(S.slAuto=slAutoNew());A.on=!A.on;sfx('click');after();salesModal();}, + salesRen:()=>{if(!slP())return;const A=S.slAuto||(S.slAuto=slAutoNew());if(A.ren)delete A.ren;else A.ren=true;sfx('click');after();salesModal();}, + salesMin:()=>{if(!slP())return;const A=S.slAuto||(S.slAuto=slAutoNew());A.min=opsCycle(SL_MINS,A.min);sfx('click');after();salesModal();}, + salesVp:()=>{if(slP()!=='ceo'||S.sales.vp)return;if(!spend(SALES_VP))return;S.sales.vp=S.day+SALES_VP_DAYS;toast(tr('sales.vp_asked',{n:SALES_VP_DAYS}),'');after();salesModal();}, +}); diff --git a/src/game/90-actions/53-customer-paths.js b/src/game/90-actions/53-customer-paths.js new file mode 100644 index 0000000..8f723e7 --- /dev/null +++ b/src/game/90-actions/53-customer-paths.js @@ -0,0 +1,15 @@ +Object.assign(ACT,{ + pathOpen:({id})=>{const b=S.biz.find(x=>x.id===id);if(b&&pathKind(b))pathModal(b);}, + pathMove:({id,link})=>{const b=S.biz.find(x=>x.id===id),l=b&&pathKind(b)==='fiber'&&fiberTargets(b).find(t=>t.l.id===link&&!t.no);if(!l)return; + // A carrier already renting waves of that kind (and size) on that fiber: one contract, as when it orders more there. + const wv=b.type==='wwave'||b.type==='mwave',what=(x,n)=>b.type==='wwave'?wwWhat(l.l,n):cmWhat(l.l,cmWP(x.g),n); + const more=wv&&S.biz.find(x=>x!==b&&x.type===b.type&&x.link===link&&x.name===b.name&&x.g===b.g); + if(more){more.slots=(more.slots||0)+(b.slots||0);more.rate+=b.rate;more.since=Math.min(more.since??0,b.since??0);more.mood=Math.min(more.mood??100,b.mood??100);more.what=what(more,more.slots);S.biz=S.biz.filter(x=>x!==b);} + else{b.link=link;if(wv)b.what=what(b,b.slots||1);} + CM_V++; // managed waves come off their fiber's capacity (mwG()), which caches by fiber + closeModal();toast(tr('customer_paths.name_moved_to_fiber',{name:esc(b.name),fiber:fibLab(l.l)}),'good');sfx('build');after();}, + pathPin:({id,via})=>{const b=S.biz.find(x=>x.id===id);if(!b||pathKind(b)!=='circuit'||typeof via!=='string')return;const p=via.split(','); + if(p.length<2||p[0]!==b.city||p[p.length-1]!==b.city2||new Set(p).size!==p.length||!pathHops(pathEdges(),p))return; + b.pin=p;closeModal();toast(tr('customer_paths.name_now_rides_path',{name:esc(b.name),path:esc(pathStr(p))}),'good');sfx('build');after();}, + pathAuto:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b||!b.pin)return;delete b.pin;closeModal();toast(tr('customer_paths.name_follows_routing_again',{name:esc(b.name)}),'good');sfx('click');after();}, +}); diff --git a/src/game/90-actions/53-market.js b/src/game/90-actions/53-market.js new file mode 100644 index 0000000..a362177 --- /dev/null +++ b/src/game/90-actions/53-market.js @@ -0,0 +1,15 @@ +// The capacity market (37-fiber-market.js): its tab, and the settings the broker sells by. +Object.assign(ACT,{ + marketOpen:()=>{if(!S||pzOn())return;UI.dtab='market';$('dash').hidden=false;renderDash();}, + mktHold:({v})=>{if(!CM_HOLD.includes(v))return;S.cm.hold=v;cmRelist();sfx('click');after();}, + // Switching a product off takes what the broker listed of it off the market (what you listed by hand stays); what it + // already sold stays sold. + mktCfg:({p,k,v})=>{const c=CM_P.includes(p)&&S.cm.p[p];if(!c)return; + if(k==='on'){c.on=!!v;if(!c.on)for(const l of S.links)if(l.list&&l.list[CM_L[p]])l.list[CM_L[p]]=cmHand(l,CM_L[p]);} + else if(k==='min'&&CM_MIN[p].includes(v))c.min=v;else if(k==='floor'&&CM_FLOOR.includes(v))c.floor=v;else return; + cmRelist();sfx('click');after();}, + // A route the broker leaves alone keeps nothing listed by the thresholds, only what you listed by hand. + mktRoute:({k})=>{const r=typeof k==='string'&&cmRoutes().get(k);if(!r)return;if(S.cm.off[k]){delete S.cm.off[k];}else{S.cm.off[k]=1; + for(const l of r.ls)if(l.list)for(const p of CM_P)if(S.cm.p[p].on)l.list[CM_L[p]]=cmHand(l,CM_L[p]);} + cmRelist();sfx('click');after();}, +}); diff --git a/src/game/90-actions/54-address-space.js b/src/game/90-actions/54-address-space.js new file mode 100644 index 0000000..feb196d --- /dev/null +++ b/src/game/90-actions/54-address-space.js @@ -0,0 +1,32 @@ +/* Address space (#150, 33-address-space.js): buy, lease in, lease out, sell, hand back, and the CGNAT and NAT64 ratios. + Every block change keeps room for the customers already signed, with every dual-stack home behind CGNAT. */ +const ip4Re=()=>{after();renderBank();}; +function ip4Can(){if(ip4On())return true;toast(tr('ip4.off'),'bad');sfx('err');return false;} +const ip4Blk=id=>S.ip4.b.find(b=>b.id===id); +function ip4Busy(){toast(ip4InUse(),'bad');sfx('err');} +// No more blocks than a save keeps (IP4_BLK): a new one is refused with the way out. +function ip4Room(){if(!ip4Full())return true;toast(tr('ip4.too_many',{n:IP4_BLK}),'bad');sfx('err');return false;} +Object.assign(ACT,{ + ip4Open:()=>{if(!S||pzOn()||!ip4On())return;if(!$('modal').hidden)closeModal();ACT.bank();const g=$('bankIp4');if(g&&g.scrollIntoView)g.scrollIntoView({block:'start'});}, + // The size the market rows quote (a dropdown: v is the prefix length). + ip4Pick:({v})=>{const len=Number(v);if(ip4LenOk(len))UI.ip4Len=len;renderBank();}, + ip4Buy:({len})=>{if(!ip4Can())return;len=Number(len);if(!ip4LenOk(len)||!ip4Room())return;const c=ip4Cost(len);if(!spend(c))return; + S.ip4.b.push({id:uid(),len,k:'buy',d:S.day});toast(tr('ip4.bought',{p:'/'+len,n:ip4N(ip4Sz(len)),price:fmt$(c)}),'good');sfx('coin');ip4Re();}, + ip4Lease:({len})=>{if(!ip4Can())return;len=Number(len);if(!ip4LenOk(len)||!ip4Room())return;const mo=ip4InMo(len); + S.ip4.b.push({id:uid(),len,k:'in',d:S.day,mo});toast(tr('ip4.leased_in',{p:'/'+len,n:ip4N(ip4Sz(len)),price:fmt$(mo)}),'good');sfx('click');ip4Re();}, + ip4Sell:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k==='in'||b.out)return; + if(ip4Held(b)){toast(tr('ip4.held',{date:dateStr(b.d+IP4_HOLD)}),'bad');sfx('err');return;}if(!ip4Spare(b)){ip4Busy();return;} + if(UI.confirm!==id){UI.confirm=id;renderBank();return;}UI.confirm=null;const v=ip4Value(b.len);S.ip4.b=S.ip4.b.filter(x=>x!==b);S.cash+=v; + toast(tr('ip4.sold',{p:'/'+b.len,price:fmt$(v)}),'good');sfx('coin');ip4Re();}, + ip4Out:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k==='in'||b.out)return;if(!ip4Spare(b)){ip4Busy();return;} + b.out=true;b.mo=ip4OutMo(b.len);toast(tr('ip4.leased_out',{p:'/'+b.len,price:fmt$(b.mo)}),'good');sfx('coin');ip4Re();}, + ip4Back:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||!b.out)return;delete b.out;delete b.mo;sfx('click');ip4Re();}, + ip4Return:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k!=='in')return;if(!ip4Spare(b)){ip4Busy();return;} + S.ip4.b=S.ip4.b.filter(x=>x!==b);sfx('click');ip4Re();}, + // Fewer homes per address needs more addresses: refused when the customers already signed would not fit. + ip4Nat:({v})=>{if(!ip4Can())return;const r=Number(v);if(!IP4_NAT.includes(r)||r===S.ip4.nat)return;const u=ip4Use(); + if(r{if(!ip4Can())return;const r=Number(v);if(!IP4_N64.includes(r)||r===S.ip4.n64)return;const u=ip4Use(); + if(r{if(!ip4Can())return;const why=ip6Why(city);if(why){toast(why,'bad');sfx('err');return;}const p=ip6Pop(city); + if(S.cash{if(!ip4Can())return;const p=ip6Pop(city);if(!p||!p.bb||!p.bb.v6e)return;delete p.bb.v6e;sfx('click'); + toast(tr('ip6.stopped',{city:esc(CITY[city].name),p:pct(p.bb.v6||0)}),'');after();}, +}); diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js new file mode 100644 index 0000000..3c87c8e --- /dev/null +++ b/src/game/90-actions/60-links.js @@ -0,0 +1,59 @@ +Object.assign(ACT,{ + upLink:({id,tier})=>{tier=+tier;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='wave'||!LT[tier]||tier<=l.tier)return;{const w=subWaveWhy(tier,l.km,l.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}{const so=soldOut(l.a,l.b,tier,l.cable);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}if(!waveOk(l.a,l.b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;}const nm=Math.round(waveMo(l.km,l.sub,tier)*(l.mult||1));if(!spend(nm))return;l.mo=nm;l.tier=tier;after();}, + decomOpen:({city})=>{UI.decom=new Set(city&&S.pops[city]?[city]:[]);decomModal();}, + decomToggle:({city})=>{if(!own(S.pops,city))return;UI.decom=UI.decom||new Set();if(UI.decom.has(city))UI.decom.delete(city);else UI.decom.add(city);decomModal();}, + decomGo:()=>{const sel=[...(UI.decom||[])].filter(c=>own(S.pops,c));if(!sel.length||sel.length>=Object.keys(S.pops).length)return;closeModal();UI.decom=null;UI.sel=null;decommission(sel);sfx('alert');after();}, + rmLink:({id})=>{{const n=xpOver(id).length;if(n){toast(trn('express.fiber_busy',n),'bad');sfx('err');UI.confirm=null;renderPanel();return;}}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}{const l=S.links.find(x=>x.id===id),back=cabBack(l);if(back>0){S.cash+=back;toast(tr('links.name_is_called_off_the_cable',{name:esc(l.cname||tr('common.your_cable')),price:fmt$(back)}),'good');} + const n=chBack(l?[l]:[]);if(n)toast(trn('links.n_optic_back_on_the_spares_shelf',n),'good');}const l0=S.links.find(x=>x.id===id),sib=l0?pairLinks(l0.a,l0.b).filter(x=>x!==l0&&x.kind!=='vxc'):[];S.links=S.links.filter(l=>l.id!==id);prunePairMet(); + // One of several parallel links (#119): the panel moves on to the next one between the same cities, so a row of them + // can be handed back without opening the panel again each time. + UI.sel=sib.length?{type:'link',id:sib[0].id}:null;UI.confirm=null;after();}, + // The chaos monkey takes a banana and goes home early (no bonus). + mkBanana:()=>{if(!mkOn())return;if(!spend(mkBananaCost()))return;S.stats.bananas=(S.stats.bananas||0)+1;mkLeave('banana');track('monkey_banana');after();}, + fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))return; + // At sea, paying means a private charter: another ship sails, it does not appear (50-cable-ships.js). + if(shipSea(i)){if(shipRush(i)){const s=SHIP[i.ship];toast(tr('cable_ships.ship_chartered',{ship:esc(s.n),home:esc(CITY[s.home].name),n:Math.max(1,i.until-S.day)}),'good');sfx('coin');after();}return;}if(i.slow&&i.rushed)return;if(!spend(i.cost))return; + if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();}, + myIxUp:({city})=>{const m=own(S.myIx,city)&&S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();}, + foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name; + S.myIx[city]={name:nm,members:[],next:S.day+4,fab:0};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();}, + buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); + if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return; + if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;} + const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;} + {const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b)); + if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} + const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);satBeside(a,b);closeModal(); + if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';} + floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');after();}, + // A new fabric port, or every member of one upgraded to a faster speed (#140): as fast as the router takes. + buyNni:({city,prov,tier})=>{tier=+tier;if(!NNI[tier]||!isCity(city)||!own(FAB,prov)||!FAB[prov].cities.includes(city)||!S.pops[city])return;const ex=nniPort(city,prov),n=ex?(ex.n||1):1;if(ex&&tier<=ex.tier)return; + if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:NNI[tier].n}),'bad');sfx('err');return;} + if(!portGate(city,(PORT_SLOT(tier)-(ex?PORT_SLOT(ex.tier):0))*n)||!spend(NNI[tier].mo*n))return;if(ex)ex.tier=tier;else S.nni.push({id:uid(),city,prov,tier});toast(tr('links.fab_port_is_up_in_city',{fab:esc(FAB[prov].name),city:CITY[city].name}),'good');after();}, + // A fabric port bundles into a LAG like transit and PNIs (#140): a member at the same speed, on a router port of its own. + lagNni:({city,prov,d})=>{d=+d;if(d!==1&&d!==-1)return;const pt=nniPort(city,prov);if(!pt||!NNI[pt.tier])return;const n=(pt.n||1)+d;if(n<1||n>LAG_MAX)return; + if(d>0){if(!portOk(city,pt.tier)){toast(tr('actions.your_router_can_t_take_a',{port:NNI[pt.tier].n}),'bad');sfx('err');return;}if(!portGate(city,PORT_SLOT(pt.tier))||!spend(NNI[pt.tier].mo))return;} + else if(nniUsed(city,prov)>lagCap(NNI[pt.tier].g,n)+1e-9){toast(tr('links.too_many_circuits_for_a_smaller'),'bad');sfx('err');return;} + if(n>1)pt.n=n;else delete pt.n;sfx('build');after();}, + rmNni:({city,prov})=>{if(nniUsed(city,prov)>0){toast(tr('links.cancel_the_circuits_on_this_port'),'bad');sfx('err');return;}S.nni=S.nni.filter(x=>!(x.city===city&&x.prov===prov));after();}, + openVxc:(a)=>openVxcModal(a), + buyVxc:({a,b,prov,t})=>{t=+t;if(!CITY[a]||!CITY[b]||noTalk(a,b))return;const g=VXC[t].g,pa=nniPort(a,prov);if(!pa||nniUsed(a,prov)+g>nniCap(pa)+1e-9){toast(tr('links.not_enough_room_on_your_fabric'),'bad');sfx('err');return;} + if(S.pops[b]){const pb=nniPort(b,prov);if(!pb||nniUsed(b,prov)+g>nniCap(pb)+1e-9){toast(tr('links.not_enough_room_on_your_fab',{fab:esc(FAB[prov].name),city:CITY[b].name}),'bad');sfx('err');return;}} + const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});satBeside(a,b);closeModal(); + toast(tr('links.circuit_up_in_59_seconds_vxc',{vxc:VXC[t].n,fab:esc(FAB[prov].name),a:CITY[a].name,b:CITY[b].name})+(S.pops[b]?'':' '+tr('links.now_grab_an_ix_port_there')),'good');if(!S.pops[b])selectCity(b);after();}, + upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='vxc'||!VXC[t]||t<=l.vt)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>nniCap(pt)+1e-9){toast(tr('links.fabric_port_in_city_is_full',{city:CITY[c].name}),'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();}, + cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);prunePairMet();const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();}, + setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();}, + setMetric:({id,v})=>{if(v!=='custom'&&!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;const m=S.pairMet||(S.pairMet={}),k=edgeKey(l); + // Switching to custom starts from the current preset's factor, so nothing moves until the player edits it. + if(v==='custom'){if(!pairCm(k))m[k]={k:'f',v:MET[pairMet(k)].f};}else if(v==='normal')delete m[k];else m[k]=v;metBlur();sfx('click');after();}, + metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l)return;const key=edgeKey(l),c=pairCm(key);if(!c||c.k===k)return; + // The cost stays what it was on this link, written the other way. + const w=pairW(key,l.km);S.pairMet[key]={k,v:clampM(k,k==='w'?w:w/(l.km+60))};metBlur();sfx('click');after();}, + // v: the typed value as an argument (a server runs this without the field), else the field's. + metricSet:({id,v})=>{const l=S.links.find(x=>x.id===id),t=$('metIn'),txt=v!==undefined?v:t?t.value:undefined;if(!l||txt===undefined)return;const key=edgeKey(l),c=pairCm(key);if(!c)return;const x=parseFloat(String(txt).replace(',','.'));if(!Number.isFinite(x)){sfx('err');return;} + if(t)t.blur();S.pairMet[key]={k:c.k,v:clampM(c.k,x)};sfx('click');after();}, + setCarry:({id,on})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;if(on)t.carry=true;else delete t.carry;sfx('click');after();}, + setStandby:({id,on})=>{const l=S.links.find(x=>x.id===id);if(!l)return;if(on)l.standby=true;else delete l.standby;sfx('click');after();}, + goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();}, +}); diff --git a/src/game/90-actions/70-dashboard-lists.js b/src/game/90-actions/70-dashboard-lists.js new file mode 100644 index 0000000..da73f96 --- /dev/null +++ b/src/game/90-actions/70-dashboard-lists.js @@ -0,0 +1,20 @@ +Object.assign(ACT,{ + custGo:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b)return;$('dash').hidden=true;ACT.focusCity({city:b.city});UI.tab='cust';renderPanel();}, + listMore:({k})=>{if(k!=='conn'&&k!=='cust'&&k!=='nets'&&k!=='pni'&&k!=='pops')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;if(k==='nets'){renderLeft();return;}if(k==='pni'){renderPanel();return;}renderDash();}, + custF:({v})=>{UI.kf=UI.kf||{};UI.kf.f=v==='sad'?'sad':'';listReset('cust');renderDash();}, + custCity:({v})=>{UI.kf=UI.kf||{};UI.kf.city=isCity(v)?v:'';listReset('cust');renderDash();}, + custSort:({k})=>{if(!['mood','mo','name','city'].includes(k))return;listReset('cust');if(UI.custSort===k)UI.custDir=-(UI.custDir||1);else{UI.custSort=k;UI.custDir=k==='mo'?-1:1;}renderDash();}, + custOpen:({sad}={})=>{if(!S)return;UI.kf=sad?{f:'sad'}:{};listReset('cust');UI.dtab='cust';const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;}, + popGo:({city})=>{if(!isCity(city)||!cityOn(city))return;$('dash').hidden=true;ACT.focusCity({city});}, + popsReg:({v})=>{UI.popF=UI.popF||{};UI.popF.reg=own(REG,v)?v:'';listReset('pops');renderDash();}, + popsSort:({k})=>{if(!['eye','cost','name'].includes(k))return;listReset('pops');const sk=UI.popSort||'eye',d0=k==='eye'?-1:1;UI.popDir=sk===k?-(UI.popDir||d0):d0;UI.popSort=k;renderDash();}, + goConn:({city,k})=>{if(!isCity(city)||!own(CONN_K,k))return;$('dash').hidden=true;ACT.goEgress({city,k});}, + connF:({f,v})=>{const F=UI.cf=UI.cf||{};listReset('conn');if(f==='all'){UI.cf={};}else if(f==='k'){F.k=own(CONN_K,v)?v:'';}renderDash();}, + connCity:({v})=>{UI.cf=UI.cf||{};listReset('conn');UI.cf.city=isCity(v)?v:'';renderDash();}, + connNet:({v})=>{UI.cf=UI.cf||{};listReset('conn');UI.cf.net=NET[v]?v:'';renderDash();}, + connSort:({k})=>{if(!['k','city','name','use','mo'].includes(k))return;listReset('conn');if(UI.connSort===k)UI.connDir=-(UI.connDir||1);else{UI.connSort=k;UI.connDir=k==='use'||k==='mo'?-1:1;}renderDash();}, + connFor:({net})=>{if(!NET[net])return;UI.cf={net};ACT.connOpen();}, + connCancel:({k,id})=>{const r=conns().find(x=>x.k===k&&x.id===id);if(!r||r.mine)return;const key='cc:'+k+':'+id;if(UI.confirm!==key){UI.confirm=key;renderDash();return;}UI.confirm=null; + if(k==='t')ACT.cancelTransit({id,ok:1});else if(k==='p')ACT.cancelPni({id,ok:1});else if(k==='ix')ACT.cancelIx({city:id,ok:1});else if(k==='c')ACT.rmCache({id});else{const [city,prov]=id.split('|');ACT.rmNni({city,prov});}renderDash();}, + connOpen:()=>{if(!S)return;UI.dtab='conn';listReset('conn');const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;}, +}); diff --git a/src/game/90-actions/80-security-and-china.js b/src/game/90-actions/80-security-and-china.js new file mode 100644 index 0000000..92488ee --- /dev/null +++ b/src/game/90-actions/80-security-and-china.js @@ -0,0 +1,25 @@ +Object.assign(ACT,{ + applyCn:()=>{if(S.cnLic.state!=='none')return;if(!spend(CN_LIC))return;S.cnLic={state:'pending',ready:S.day+leadDays(45)};toast(tr('security_and_china.application_filed_your_local_partner'),'goal');after();}, + togglePrem:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t||!premCity(NET[t.net],t.city)||premOnlyAt(NET[t.net],t.city))return;t.premium=!t.premium;sfx('click');after();}, + buildScrub:({city,tier})=>{if(!S.pops[city]||S.scrubs.some(x=>x.city===city))return;const T=SCRUB_TIERS[tier||0];if(!T)return;if((lvl()||1){const x=S.scrubs.find(q=>q.city===city);tier=+tier;if(!x||!SCRUB_TIERS[tier]||tier<=(x.tier||0))return;const T=SCRUB_TIERS[tier];if((lvl()||1){if(!hasScrub())return;S.scrubMode=S.scrubMode==='ondemand'?'always':'ondemand';sfx('click');after();}, + rmScrub:({city})=>{if(!S.scrubs.some(x=>x.city===city))return;if(UI.confirm!=='scrub:'+city){UI.confirm='scrub:'+city;renderAll();return;}S.scrubs=S.scrubs.filter(x=>x.city!==city);if(!hasScrub())S.scrubMode='always';UI.confirm=null;after();}, + cleanPipe:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.clean=!t.clean;toast(t.clean?tr('security_and_china.clean_pipe_add_on_enabled_on',{net:NET[t.net].name,mo:fmt$(cleanMo(t))}):tr('security_and_china.clean_pipe_add_on_removed_from',{net:NET[t.net].name}),t.clean?'good':'');after();}, + sacrif:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;p.sacrif=!p.sacrif;toast(p.sacrif?tr('security_and_china.net_pni_is_now_a_sacrificial',{net:NET[p.net].name}):tr('security_and_china.net_pni_is_back_to_normal',{net:NET[p.net].name}),p.sacrif?'good':'');after();}, + // RTBH blackholes the target upstream: your ports and everyone else are saved, the target is dark until you withdraw it. + rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}if(a.bh)return;a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a); + const T=ddosTaught(),first=!T.rtbh;T.rtbh=1;toast(tr('ddos.rtbh_on',{who:esc(ddosWho(a))})+(first?'
'+tr('ddos.learn_rtbh')+'':''),'bad');sfx('alert');after();}, + unrtbh:({id}={})=>{const a=ddosFind(id);if(!a||!a.bh)return;a.bh=false;toast(tr('ddos.rtbh_off',{who:esc(ddosWho(a))}),'');after();}, + // On-demand scrubbing, when it does not engage by itself: start the diversion now. + ddosEngage:({id}={})=>{const a=ddosFind(id);if(!a||!hasScrub()||a.eng!==undefined)return;a.eng=S.day;toast(tr('ddos.engaged'),'good');sfx('click');after();}, + ddosAuto:({k}={})=>{if(!['rtbh','scrub'].includes(k))return;const A=S.ddosAuto||(S.ddosAuto={rtbh:false,scrub:true});A[k]=k==='scrub'?A.scrub===false:!A.rtbh;sfx('click');after();}, + // Sandbox only: try the tools on a flood of your own. + ddosTest:()=>{if(S.mode!=='sandbox'||!Object.keys(S.pops).length)return;ddosAttack(true);after();}, + hackback:({id}={})=>{const a=ddosFind(id);if(!a||a.until<=S.day){toast(tr('security_and_china.nothing_to_hack_back_right_now'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1; + if(Math.random()<0.35){a.until=S.day;a.bh=false;S.stats.hackWin=(S.stats.hackWin||0)+1;toast(tr('security_and_china.hackback_3000tm_strikes_back_skynot',{city:CITY[a.city].name}),'goal');sfx('coin');} + else{const fine=15000+Math.floor(Math.random()*35000);S.cash-=fine;S.stats.vigilante=(S.stats.vigilante||0)+1; + toast(tr('security_and_china.hackback_3000tm_hit_the_wrong_target',{who:pick([tr('security_and_china.skynot_ai_flattened_a_grandma_s'),tr('security_and_china.you_counter_flooded_a_smart_fridge'),tr('security_and_china.the_botnet_was_already_someone_else')]),fine:fmt$(fine)}),'bad');sfx('err');} + after();}, + cnPrem:({v})=>{UI.cnPrem=!!+v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, +}); diff --git a/src/game/90-actions/85-pop-tiers.js b/src/game/90-actions/85-pop-tiers.js new file mode 100644 index 0000000..c467cb6 --- /dev/null +++ b/src/game/90-actions/85-pop-tiers.js @@ -0,0 +1,17 @@ +// POP standards (#315): save one, bring a POP up to one, bring every POP of a kind up to it. +Object.assign(ACT,{ + ptSave:({city,k})=>{const p=own(S.pops,city)&&S.pops[city];if(!ptOn()||!p||!POP_TIERS.includes(k))return;const T=ptO();T.def[k]={g:p.rgen||0,rt:p.routers||1};T.at[city]=k; + toast(esc(tr('pop_tiers.saved',{kind:ptName(k),desc:`${T.def[k].rt} × ${RG[T.def[k].g].n}`})),'good');sfx('click');after();}, + // cost: the price on the button, within a day's hardware drift (quoteNear); a plan that changed under it buys nothing. + // A POP that already meets it is only marked (cost 0). + ptApply:({city,k,cost})=>{if(!ptOn()||!own(S.pops,city)||!POP_TIERS.includes(k)||!ptO().def[k])return;const q=ptPlan(city,k); + if(!quoteNear(+cost,q?q.cost:0)){toast(tr('utilities.quote_changed'),'bad');sfx('err');after();return;} + if(q&&q.why){toast(esc(q.why),'bad');sfx('err');return;}if(q&&S.cash{if(!ptOn()||!POP_TIERS.includes(k))return;const A=ptAll(k);if(!A.todo.length)return; + if(!quoteNear(+cost,A.cost)){utilitiesModal(city,tr('utilities.quote_changed'));return;} + if(S.cash{if(!S.core||S.mode==='puzzle'||S.pz||S.ar||S.scn)return;const n=S.core.lv+1;if(n>4)return; + if(lvl(){if(!coreOn()||S.core.lab||S.core.lv<1)return;if(!spend(CORE_LAB))return; + S.core.lab=true;toast(tr('core.interop_lab_open_vendors_now'),'good');sfx('coin');after();}, + routingOpen:()=>{if(S&&!pzOn())routingModal();}, + coreSet:({v})=>{if(!S.core)return;v=+v;if(!(v>=0&&v<=S.core.lv)||(v===S.core.run&&!S.core.legacy))return;S.core.run=v;delete S.core.legacy;sfx('click');after();}, + via:({v})=>{UI.via=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, + setRoute:({id,m})=>{if(!own(RT,m))return;const b=S.biz.find(x=>x.id===id);if(b){b.route=m;delete b.pin;sfx('click');after();}}, + route:({r})=>{UI.route=r;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, + addParallel:({id})=>{const l=S.links.find(x=>x.id===id);if(l)openLinkModal(l.a,l.b);}, + // This POP's build becomes the standard's POP part: its model, routers, second building and generator. + popStdSet:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||pzOn())return;S.popStd=bstdPut({...bstd(),g:p.rgen||0,rt:p.routers||1,site2:!!p.site2,gen:!!p.gen}); + toast(tr('pop_std.new_pops_now_start_with_list',{list:esc(bstdPopParts(bstd()).join(', '))}),'good');sfx('click');after();if(bstdShown())bstdModal();}, + popStdClear:()=>{S.popStd=null;sfx('click');after();if(bstdShown())bstdModal();}, + addRouter:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;if(!spend(routerCost(p.rgen||0,p.routers||1)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');after();}, + models:()=>{UI.models=!UI.models;renderPanel();}, + rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;{const m=Math.min(PNI_LAG_MAX,PNI_LAG_RT*(p.routers-1)),big=S.pni.find(x=>x.city===city&&Math.max(x.n||1,(x.up&&x.up.n)||1)>m);if(big){toast(tr('routing_and_routers.a_pni_here_bundles_n_ports',{net:esc(NET[big.net].name),n:Math.max(big.n||1,(big.up&&big.up.n)||1),m}),'bad');sfx('err');return;}}if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;}p.routers--;{const back=tradeIn(p.rgen||0,1);if(back>0){S.cash+=back;toast(tr('routing_and_routers.sold_a_model_on_ebuy_price',{model:esc(RG[p.rgen||0].n),price:fmt$(back)}),'good');}}after();}, + upRouter:({city,g})=>{const p=own(S.pops,city)&&S.pops[city];if(!p)return;g=g===undefined?mainRG(RG[p.rgen||0].cls+1):+g;if(!RG[g]||g===(p.rgen||0))return;{const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;}}if(!techOk('rg',g,RG[g].lvl)){toast(tr('routing_and_routers.model_unlocks_at_customer_level_lv',{model:esc(RG[g].n),lv:RG[g].lvl}),'bad');sfx('err');return;} + const rt=p.routers||1,old=p.rgen||0;if(p.rupDay===S.day){toast(tr('routing_and_routers.the_new_routers_in_city_are',{city:CITY[city].name}),'bad');sfx('err');return;}const back=tradeIn(old,rt);if(!spend(swapCost(city,g)))return;p.rgen=g;p.rupDay=S.day;if(back>0)toast(tr('routing_and_routers.sold_the_old_model_on_ebuy',{model:esc(RG[old].n),price:fmt$(back)}),'good'); + if(rt===1&&popIdle(city))toast(tr('routing_and_routers.new_router_in_city_swapped_before',{city:CITY[city].name}),'good'); + else if(rt===1){const sl=slowBoot(city),dd=sl?3:1;p.down=Math.max(p.down||0,S.day+dd);addInc({type:'maint',ref:city,until:S.day+dd,msg:sl?tr('routing_and_routers.swapping_the_only_router_in_city',{city:CITY[city].name,model:RG[g].n,how:pick(SLOW_BOOT),n:dd}):tr('routing_and_routers.swapping_the_only_router_in_city_d5b5',{city:CITY[city].name,model:RG[g].n}),cost:0});toast(`${tr('routing_and_routers.maintenance_window_in_city',{city:CITY[city].name})}
${sl?tr('routing_and_routers.one_router_and_this_one_takes',{n:dd}):tr('routing_and_routers.one_router_means_downtime_during_the')}`,'bad');} + else toast(tr('routing_and_routers.rolling_upgrade_in_city_n_model',{city:CITY[city].name,n:rt,model:esc(RG[g].n)}),'good'); + floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');after();}, +}); diff --git a/src/game/90-actions/86-specialist.js b/src/game/90-actions/86-specialist.js new file mode 100644 index 0000000..1bb641e --- /dev/null +++ b/src/game/90-actions/86-specialist.js @@ -0,0 +1,14 @@ +Object.assign(ACT,{ + demoAsk:({k,id})=>{const it=demoItem(k,id);if(!it||!demoCan(it.lvl)||demoAt(k,id)!==null)return;S.demo=S.demo||{};const at=S.day+leadDays(DEMO_DAYS);S.demo[k+':'+id]=at; + toast(tr('specialist.the_vendor_ships_a_demo_name',{name:esc(it.n),n:at-S.day,p:Math.round((DEMO_MUL-1)*100)}),'good');after();}, + seatBuy:({n})=>{const o=S.seatOff;n=+n;if(!o||o.exp<=S.day||!SEAT_N.includes(n))return;const miss=[o.a,o.b].filter(c=>!S.pops[c]),cost=seatCost(o.km,n)+miss.reduce((x,c)=>x+popCost(c),0);if(!spend(cost))return; + for(const c of miss){S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(c);} + const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n),regen:0});satBeside(o.a,o.b); + S.seatOff=null;S.stats.seats=(S.stats.seats||0)+1;UI.sel={type:'link',id}; + toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();}, + seatNo:()=>{S.seatOff=null;after();}, + charter:({k})=>{if(!own(CHARTERS,k)||S.chartSet||S.scn||S.mode!=='normal')return;S.charter=k;S.chartSet=true;if($('modal').className==='charter')closeModal(); + toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();} + // A new multiplayer session's code to share waited for the charter (95-modals/48-multiplayer.js). + if(UI.mpLater)mpStartTell();after();}, +}); diff --git a/src/game/90-actions/87-express.js b/src/game/90-actions/87-express.js new file mode 100644 index 0000000..2ab83e9 --- /dev/null +++ b/src/game/90-actions/87-express.js @@ -0,0 +1,22 @@ +// Express lightpaths (#58, 65-express.js): light a wave from a to b over a chain of your ROADM fibers, or one more +// channel on it; giving one up is rmLink, like any link. Every check is made here: tools and the NOC window send raw args. +Object.assign(ACT,{ + // The link window on its Express tab, from a fiber's panel or the tab itself. via: the path a fiber's panel offered, + // listed first even when shorter ones exist (the window checks it with xpParse). + xpOpen:({a,b,via})=>{if(!isCity(a)||!isCity(b)||a===b||!S.pops[a])return;UI.lmode='xp';UI.xpPath=typeof via==='string'?via.slice(0,400):null;openLinkModal(a,b);}, + // via: the fibers' ids in order from a, comma-separated. The same path again adds a channel to the express already there. + xpBuild:({a,b,via,o})=>{const sp=xpParse(a,b,via);if(!sp||!OPT[o]){toast(tr('express.no_such_path'),'bad');sfx('err');return;} + const ids=sp.map(s=>s.id),old=xpFind(a,b,ids),why=xpWhy(a,b,sp,o);if(why){toast(tr('express.cannot',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + if(old&&(old.ch=old.ch||[]).length>=XP_CH)return;if(!portGate(a,chPorts(o,a))||!portGate(b,chPorts(o,b)))return;const spare=spareN(o)>0;if(!spend(xpCost(sp,o,!old)))return;if(spare)S.spares[o]--; + let l=old;if(l)l.ch.push(o);else{l={id:uid(),a,b,kind:'xp',via:ids,ch:[o],km:Math.round(sp.reduce((x,s)=>x+s.km,0)),mo:0,cut:0,day:S.day};S.links.push(l);} + closeModal();UI.sel={type:'link',id:l.id};UI.confirm=null; + toast(old?tr('express.one_more',{optic:OPT[o].n,a:CITY[l.a].name,b:CITY[l.b].name,n:l.ch.length}):tr('express.lit',{optic:OPT[o].n,a:CITY[a].name,b:CITY[b].name,via:esc(xpVia(l))}),'good');sfx('build');after();}, + // One channel more (d:1) or less (d:-1) on an express; an unplugged optic goes on the spares shelf. The last one stays: + // giving the express up is the link's own button. + xpCh:({id,o,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='xp'||!OPT[o]||(d!==1&&d!==-1))return;l.ch=l.ch||[];const mid=[(CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20]; + if(d<0){const i=l.ch.lastIndexOf(o);if(i<0)return;if(l.ch.length<2){toast(tr('express.last_channel'),'bad');sfx('err');return;} + l.ch.splice(i,1);S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;floater(mid[0],mid[1],tr('fiber_and_hardware.optic_to_spares',{optic:OPT[o].n}),'#7B61FF');after();return;} + const sp=xpSpans(l);if(!sp||l.ch.length>=XP_CH)return;const why=xpWhy(l.a,l.b,sp,o);if(why){toast(tr('express.cannot',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + if(!portGate(l.a,chPorts(o,l.a))||!portGate(l.b,chPorts(o,l.b)))return;const spare=spareN(o)>0;if(!spend(xpCost(sp,o,false)))return;if(spare)S.spares[o]--; + l.ch.push(o);floater(mid[0],mid[1],`+${OPT[o].n}`,'#FF4F9A');after();}, +}); diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js new file mode 100644 index 0000000..b8b493b --- /dev/null +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -0,0 +1,42 @@ +Object.assign(ACT,{ + dfMode:({m})=>{UI.lmode=m;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, + seaPackage:({k})=>{const p=UI.pending;if(!own(SUB_UPGRADES,k)||!p)return;const km=seaQuote(p.a,p.b,own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard').km,up=seaUps(km); + if(!up[k]&&!subHelps(km,k,up[subOther(k)]))return;UI.seaterminal=up.terminal;UI.seaengineering=up.engineering;UI['sea'+k]=!up[k];openLinkModal(p.a,p.b);}, + subUpgrade:({id,k})=>{const l=S.links.find(l=>l.id===id);if(!l||l.kind!=='df'||!l.own||!l.sub||l.seat||!own(SUB_UPGRADES,k)||glassLvl()<4||l['sub'+k]!==undefined||!subHelps(l.km,k,l['sub'+subOther(k)]!==undefined))return;if(!spend(subUpgradeCost(l,k)))return;l.paid=(l.paid>0?l.paid:ownCabCost(l.km))+subUpgradeCost(l,k);l['sub'+k]=Math.max(S.day,l.ready||0)+leadDays(SUB_UPGRADES[k].days);after();}, + seaDesign:({v})=>{if(!own(SEA_DESIGNS,v))return;UI.seaDesign=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, + ownCab:()=>{UI.lmode='df';UI.dfSrc='cable';UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, + dfSrc:({v})=>{UI.dfSrc=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, + dfSys:({v})=>{UI.dfSys=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, + orderCable:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a)||!linkToOk(b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return; + if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} + const used=new Set(S.links.map(l=>l.cname).filter(Boolean)),cname=OWNCAB_NAMES.find(n=>!used.has(n))||`${pick(OWNCAB_NAMES)} ${used.size+1}`,id=uid(),ship=layName({id}),days=q.days; + S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1,regen:0});satBeside(a,b); + const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false; + S.stats.ownCab=(S.stats.ownCab||0)+1;UI.dfSrc='lease';closeModal();UI.sel={type:'link',id}; + toast(tr('fiber_and_hardware.the_ship_sets_sail_name_your',{ship,name:cname,km:km.toLocaleString(),a:CITY[a].name,b:CITY[b].name,n:days}),'goal');sfx('build');after();}, + orderDf:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(!dfAllowed(a,b)||!linkFromOk(a)||!linkToOk(b))return;const sc=isSub(a,b)?subDfCable(a,b):null,km=sc?sc.km:kmBetween(a,b); + const own=UI.dfSrc==='build'&&!sc,sys=DF_SYS[UI.dfSys]&&techOk('sys',UI.dfSys,DF_SYS[UI.dfSys].lvl)?UI.dfSys:'lite';if(glassLvl()<2)return; + const up=(own?digCost(km):0)+sysCost(sys)+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return; + if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} + const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),id=uid(); + const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false,regen:0}; + S.links.push(l);satBeside(a,b);closeModal();UI.sel={type:'link',id}; + toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();}, + regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||(l.sub&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return; + if(d<0&&((l.ch||[]).some(o=>!optMode(o,Object.assign({},l,{regen:n})))||xpRegenBad(l,n))){toast(tr('fiber_and_hardware.those_optics_need_the_regen_site'),'bad');sfx('err');return;} + if(d>0&&!spend(regenAddCost(l)))return;l.regen=n;toast(d>0?tr('fiber_and_hardware.regen_site_n_is_up_optical',{n,a:CITY[l.a].name,b:CITY[l.b].name,km:spanKm(l).toLocaleString()}):tr('fiber_and_hardware.regen_site_removed'),'good');sfx('build');after();}, + addCh:({id,o})=>{const l=S.links.find(x=>x.id===id),O=OPT[o];if(!l||!O||l.kind!=='df')return;const why=chWhy(l,o);if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:O.n,why:esc(why)}),'bad');sfx('err');return;}if(!portGate(l.a,chPorts(o,l.a))||!portGate(l.b,chPorts(o,l.b)))return;const sp=spareN(o)>0;if(!spend(chCost(l,o)))return;if(sp)S.spares[o]--;(l.ch=l.ch||[]).push(o);floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,`+${O.n}`,'#FF4F9A');after();}, + rmCh:({id,o})=>{const l=S.links.find(x=>x.id===id);if(!l||!OPT[o]||l.kind==='xp')return;const i=(l.ch||[]).lastIndexOf(o);if(i<0)return;l.ch.splice(i,1);S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('fiber_and_hardware.optic_to_spares',{optic:OPT[o].n}),'#7B61FF');after();}, + hwLock:()=>{if(hwLock())return;const c=hwLockCost();if(!spend(c))return;S.hw=S.hw||{};S.hw.lock={until:S.day+HW_LOCK_DAYS,mul:hwTrend(S.day)};toast(tr('fiber_and_hardware.prices_locked_until_date_your_vendor',{date:dateStr(S.hw.lock.until)}),'good');after();}, + buySpare:({o})=>{if(!OPT[o]||!techOk('opt',o,OPT[o].lvl)||spareN(o)>=64)return;if(!spend(optCost(o)))return;S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;sfx('build');after();}, + sellSpare:({o})=>{if(!OPT[o]||spareN(o)<1)return;S.spares[o]--;const v=spareValue(o);S.cash+=v;toast(tr('fiber_and_hardware.sold_a_spare_optic_on_ebuy',{optic:OPT[o].n,price:fmt$(v),p:pct(SPARE_RESALE)}),'good');sfx('coin');after();}, + addPair:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||!isRdm(l.sys)||l.ready>S.day)return;const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return;if((l.ch||[]).length+soldSlots(l)+xpSlots(l){const l=S.links.find(x=>x.id===id),to=l&&sysNext(l);if(!to||!techOk('sys',to,DF_SYS[to].lvl))return;if(!spend(sysUpCost(l)))return;l.sys=to;if(l.ready<=S.day){l.eqDown=S.day+1;toast(tr('fiber_and_hardware.line_system_swap_all_channels_are'),'bad');}after();}, + spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();}, + // Your own subsea cable: book a second lay ship before laying starts; it lays from the other end (50-cable-ships.js). + seaRush:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l)return;const k=prepSteps(l);if(!k)return;const n=all?k:1;if(!spend(n*prepCost(l)))return;const ready=Math.max(prepFloor(l),l.ready-PREP_STEP*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('cable_ships.the_factory_runs_a_night_shift',saved,{n:saved}),'good');sfx('build');after();}, + layShip:({id})=>{const l=S.links.find(x=>x.id===id);const q=l&&layQuote(l);if(!q||!spend(q.cost))return;l.ship2=1;setCableReady(l,l.ready-q.save); + toast(trn('cable_ships.second_lay_ship_booked',q.save,{ship:esc(layName(l,1)),n:q.save}),'good');sfx('coin');after();}, + crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.sub||!crewSteps(l))return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(crewFloor(l),l.ready-30*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('fiber_and_hardware.more_crews_on_site_construction_is',saved,{n:saved}),'good');after();}, + addGen:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,tr('common.generator'),'#FF8A3D');after();}, +}); diff --git a/src/game/90-actions/87-teleports.js b/src/game/90-actions/87-teleports.js new file mode 100644 index 0000000..8d6a947 --- /dev/null +++ b/src/game/90-actions/87-teleports.js @@ -0,0 +1,39 @@ +// Teleports and satellite capacity (#83): build the gateway, rent circuits on its birds, resize them. Cancel is rmLink. +// A Starblink gateway on a teleport sells LEO circuits from there (teleLeo, teleLeoRm). Island zones' circuits start at +// their city's teleport too (87-wisp-zones.js). +Object.assign(ACT,{ + teleBuild:({city})=>{const p=S.pops[city];if(!p||teleOf(city))return; + const why=teleWhy(city);if(why){toast(why,'bad');sfx('err');return;} + if(!spend(TPORT_COST))return;p.tele=1;toast(tr('satellites.teleport_up_in_city',{city:CITY[city].name}),'good');after();}, + teleTrk:({city})=>{const p=S.pops[city];if(!p||teleOf(city)!==1)return; + const why=trkWhy(city);if(why){toast(why,'bad');sfx('err');return;} + if(!spend(TRK_COST))return;p.tele=2;toast(tr('satellites.tracking_antennas_up',{city:CITY[city].name}),'good');after();}, + // Closing a teleport asks twice, and never while circuits still start there (an island zone's too). + teleRm:({city})=>{const p=S.pops[city];if(!p||!teleOf(city))return;const n=S.links.filter(l=>l.kind==='sat'&&l.a===city).length+wispSats(city).length; + if(n){toast(trn('satellites.cancel_n_circuits_first',n),'bad');sfx('err');return;} + if(UI.confirm!=='tele:'+city){UI.confirm='tele:'+city;renderPanel();return;} + delete p.tele;delete p.leo;UI.confirm=null;toast(tr('satellites.teleport_closed',{city:CITY[city].name}));after();}, + teleLeo:({city})=>{if(!own(S.pops,city)||leoGw(city))return;const why=leoGwWhy(city);if(why){toast(why,'bad');sfx('err');return;} + if(!spend(LEO_GW_COST))return;S.pops[city].leo=1;toast(tr('satellites.leo_gateway_up',{prov:SAT_PROV.sbk.n,city:CITY[city].name,km:SAT_ORB.leo.km.toLocaleString()}),'good');after();}, + // Closing the gateway asks twice, and never while LEO circuits still start there. + teleLeoRm:({city})=>{if(!leoGw(city))return;const n=S.links.filter(l=>l.a===city&&leoLink(l)).length+wispSats(city,'leo').length; + if(n){toast(trn('satellites.cancel_n_circuits_first',n),'bad');sfx('err');return;} + if(UI.confirm!=='leo:'+city){UI.confirm='leo:'+city;renderPanel();return;} + delete S.pops[city].leo;UI.confirm=null;toast(tr('satellites.leo_gateway_closed',{city:CITY[city].name}));after();}, + satOpen:({a,b})=>satModal(a,b), + // Rent a circuit from teleport a to b: the first month up front, like a wave; a POP at b comes with it if there is none. + // Next to a link you already have between the two, it goes on standby: the backup that carries only when the cable is down. + buySat:({a,b,bird,g})=>{g=+g;const why=satWhy(a,b,bird,g);if(why){toast(why,'bad');sfx('err');return;} + if(!portGate(a,1)||!portGate(b,1))return;const mo=satMo(bird,g),pop=!S.pops[b];if(!spend(mo+(pop?popCost(b):0)))return; + if(pop){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} + // One satellite a pair: LEO puts the GEO and MEO circuits there on standby, and one ordered beside LEO waits on standby. + const lo=SATS[bird].orb==='leo',sb=pairLinks(a,b).some(l=>l.kind!=='sat'||!lo&&!l.standby&&leoLink(l));if(lo&&!sb)satBeside(a,b); + const n=leadDays(SAT_ORB[SATS[bird].orb].days),id=uid(); + S.links.push({id,a,b,kind:'sat',bird,g,km:satKm(bird,a,b),sub:true,mo,cut:0,day:S.day,ready:S.day+n,...(sb?{standby:true}:{})}); + closeModal();UI.sel={type:'link',id}; + toast(trn('satellites.circuit_ordered',n,{cap:fmtCap(g),bird:esc(SATS[bird].n),a:CITY[a].name,b:CITY[b].name})+(sb?' '+tr('satellites.on_standby_beside_your_link'):''),'good');after();}, + // Bigger or smaller on the same bird: a bigger one pays its new month up front, as a wave upgrade does. + satSize:({id,g})=>{g=+g;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='sat'||g===l.g||!SAT_ORB[SATS[l.bird].orb].g.includes(g))return; + if(g>l.g&&leoLink(l)){const w=leoGrowWhy(l);if(w){toast(w,'bad');sfx('err');return;}} + const mo=satMo(l.bird,g);if(g>l.g&&!spend(mo))return;l.g=g;l.mo=mo;sfx('click');after();}, +}); diff --git a/src/game/90-actions/87-wisp-zones.js b/src/game/90-actions/87-wisp-zones.js new file mode 100644 index 0000000..0173521 --- /dev/null +++ b/src/game/90-actions/87-wisp-zones.js @@ -0,0 +1,30 @@ +// Island Wi-Fi (#83): satellite capacity for a zone from its city's teleport, a spur cable, closing either (rules: +// 60-features/46-wisp-zones.js). The first order of a zone brings the island kit too. Every act names the zone (z) only; +// its city is the zone's own. +Object.assign(ACT,{ + // A circuit for the zone. With one running, one on another bird is a move: the old one carries until the new one is up. + wispSat:({z,bird,g})=>{if(!own(WISP,z))return;g=+g;const why=wispSatWhy(z,bird,g);if(why){toast(why,'bad');sfx('err');return;} + const c=WISP[z].c,Z=wispZ(z),mo=wispSatMo(bird,g);if(!spend(mo+(Z?0:wispKit(z))))return; + const n=leadDays(SAT_ORB[SATS[bird].orb].days),o={bird,g,mo,day:S.day,ready:S.day+n},mv=!!(Z&&Z.sat),v={cap:fmtCap(g),bird:esc(SATS[bird].n),zone:esc(WISP[z].n)}; + if(!Z){const p=S.pops[c];(p.wisp||(p.wisp={}))[z]={day:S.day,d:wispStart(z),sat:o};}else if(mv)Z.nxt=o;else Z.sat=o; + toast(mv?trn('wisp.moving',n,v):trn('wisp.ordered',n,v),'good');after();}, + // Bigger or smaller on the same bird: a bigger one pays its new month up front, as satSize does. + wispSatSize:({z,g})=>{if(!own(WISP,z))return;g=+g;const Z=wispZ(z),o=Z&&Z.sat;if(!o||g===o.g||!SAT_ORB[wispOrb(o)].g.includes(g))return; + if(g>o.g&&wispOrb(o)==='leo'){const w=leoGrowWhy({a:WISP[z].c});if(w){toast(w,'bad');sfx('err');return;}} + const mo=wispSatMo(o.bird,g);if(g>o.g&&!spend(mo))return;o.g=g;o.mo=mo;sfx('click');after();}, + // Cancelling asks twice; a move being commissioned goes with it. + wispSatRm:({z})=>{if(!own(WISP,z))return;const Z=wispZ(z);if(!Z||!Z.sat&&!Z.nxt)return; + if(UI.confirm!=='wsat:'+z){UI.confirm='wsat:'+z;renderPanel();return;}delete Z.sat;delete Z.nxt;UI.confirm=null;after();}, + // A spur cable from the city: the price of the day, and the island kit when the zone starts with it. + wispSpur:({z})=>{if(!own(WISP,z))return;const why=wispSpurWhy(z);if(why){toast(why,'bad');sfx('err');return;} + const c=WISP[z].c,Z=wispZ(z);if(!spend(wispSpurCost(z)+(Z?0:wispKit(z))))return;const n=wispSpurDays(z),sp={day:S.day,ready:S.day+n}; + if(Z)Z.sp=sp;else{const p=S.pops[c];(p.wisp||(p.wisp={}))[z]={day:S.day,d:wispStart(z),sp};} + toast(trn('wisp.spur_ordered',n,{zone:esc(WISP[z].n)}),'good');sfx('build');after();}, + // Closing a zone asks twice: its circuits, spur, homes and any cut go with it. + wispRm:({z})=>{if(!own(WISP,z))return;const Z=wispZ(z);if(!Z)return; + if(UI.confirm!=='wz:'+z){UI.confirm='wz:'+z;renderPanel();return;}const p=S.pops[WISP[z].c];delete p.wisp[z];if(!Object.keys(p.wisp).length)delete p.wisp; + S.inc=S.inc.filter(i=>!(i.type==='wspur'&&i.z===z));UI.confirm=null;if(UI.wz===z)UI.wz=null;toast(tr('wisp.closed',{zone:esc(WISP[z].n)}));after();}, + // A zone in its city's Customers tab (a view): the same button again on the open zone folds it. + wispOpen:({z})=>{if(!own(WISP,z))return;const c=WISP[z].c,here=!!UI.sel&&UI.sel.type==='city'&&UI.sel.id===c; + const same=here&&UI.tab==='cust'&&UI.wz===z;UI.tab='cust';UI.wz=same?null:z;if(here){UI.confirm=null;renderPanel();}else selectCity(c);}, +}); diff --git a/src/game/90-actions/88-build-standard.js b/src/game/90-actions/88-build-standard.js new file mode 100644 index 0000000..3948306 --- /dev/null +++ b/src/game/90-actions/88-build-standard.js @@ -0,0 +1,24 @@ +// The build standard sheet (93-ui/59-build-standard.js): pick a target, or bring everything up to the standard in one go. +// The plan a sheet showed, as a short key: its jobs, in any order (the plan sorts POPs by today's load). +function bstdPlanKey(J){const s=J.map(j=>j.grp+' '+j.k+' '+j.ch+' '+j.w).sort().join('\n');let h=0x811c9dc5; + for(let i=0;i>>0).toString(36);} +const bstdSum=J=>Math.round(J.reduce((a,j)=>a+j.cost,0)); +Object.assign(ACT,{ + bstdOpen:()=>{if(S&&!pzOn())bstdModal();}, + // v: a position in the list the sheet shows; without v, the next value (the MCP tools step through a list). + bstdSet:({k,v})=>{if(!S||pzOn()||!own(BSTDK,k))return;const D=bstd(),x=opsPick(bstdOpts(k),D[k],v);if(x===undefined||!bstdOk(BSTDK[k],x))return; + D[k]=x;S.popStd=bstdPut(D);sfx('click');after();opsRedraw('bstdSet',{k},bstdModal);}, + // The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One + // recompute at the end, and one toast: what got done, and what still waits. + // quote: the plan the sheet showed (bstdPlanKey), q: its total. Another plan, a total that moved more than a day's drift + // (quoteNear), or nothing left to do is shown again, not built. + bstdApply:({quote,q}={})=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false); + if((quote!==undefined||q!==undefined)&&(!J.length||(quote!==undefined&&String(quote)!==bstdPlanKey(J))||(q!==undefined&&!quoteNear(+q,bstdSum(J))))){bstdModal(tr('utilities.quote_changed'));sfx('err');return;} + if(!J.length)return;const c0=S.cash;let n=0,later=0; + // An IPv6-only swap pays as its routers go in: what the swaps under way still owe (one this click started too) stays + // in hand, so every job, a swap or not, needs its price on top of that. The toast counts a swap whole, as the quote did. + opsQuiet(()=>{const did=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash-ip6Owed()>=c;},j=>!!j.go());n=did.length;for(const j of did)if(j.later)later+=j.cost;}); + after();const z=bstdQuote(false),left=z.pops+z.ports+z.links; + toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash+later)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err'); + if(bstdShown())bstdModal();}, +}); diff --git a/src/game/90-actions/88-ops.js b/src/game/90-actions/88-ops.js new file mode 100644 index 0000000..e30678a --- /dev/null +++ b/src/game/90-actions/88-ops.js @@ -0,0 +1,32 @@ +// Standing orders: hiring the intern, the switches and dials, and a new POP from the template. +const opsCycle=(a,v)=>a[(a.indexOf(v)+1)%a.length]; +// A pick from a list (v: its position, as the sheet's dropdown sends it), or without v the next value (the MCP tools step). +const opsPick=(a,cur,v)=>{if(v===undefined)return opsCycle(a,cur);const i=Number(v);return Number.isInteger(i)&&i>=0&&i(bstdShown()?bstdModal:opsModal)(); +const opsRedraw=(act,args,draw=opsSheet)=>{draw();const j=JSON.stringify(args);for(const el of $('modalCard').querySelectorAll(`[data-chg="${act}"]`))if(el.dataset.args===j){el.focus();break;}}; +Object.assign(ACT,{ + opsOpen:()=>{if(S)opsModal();}, + opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO(),m=monthIdx(S.day);O.intern=id;O.hired=S.day;O.wk=null; + // A new hire starts on a fresh month's budget, whatever the last one spent. + if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} + O.log.unshift({d:S.day,i:id,r:[]});toast(esc(tr('ops.hired',{name:opsName(true)})),'good',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);after();opsModal();}, + opsFire:()=>{if(!opsHired())return;if(UI.confirm!=='opsFire'){UI.confirm='opsFire';opsModal();return;}UI.confirm=null;const nm=opsName();S.ops.intern=null; + toast(esc(tr('ops.fired',{name:nm})),'');after();opsModal();}, + opsToggle:({k})=>{if(!opsHired()||!own(OPSK,k))return;S.ops.on[k]=!S.ops.on[k];sfx('click');after();opsSheet();}, + opsParam:({k,p,v})=>{if(!opsHired()||!own(OPSK,k)||!own(OPSK[k].p,p))return;const P=OPSK[k].p[p],x=opsPick(opsOpts(k,p),opsP(k,p),v);if(x===undefined||!(P.ok?P.ok(x):P.v.includes(x)))return; + (S.ops.p[k]||(S.ops.p[k]={}))[p]=x;sfx('click');after();opsRedraw('opsParam',{k,p});}, + opsCap:({k,v})=>{if(!opsHired()||!own(OPSK,k)||!OPSK[k].cap)return;const x=opsPick(opsCaps(k),opsCap(k),v);if(x===undefined)return;S.ops.cap[k]=x;sfx('click');after();opsRedraw('opsCap',{k});}, + opsFloor:({v})=>{if(!opsHired())return;const x=opsPick(OPS_FLOORS,S.ops.floor,v);if(x===undefined)return;S.ops.floor=x;sfx('click');after();opsRedraw('opsFloor',{});}, + opsCity:({v})=>{if(!S||!S.pops[v])return;UI.opsCity=v;opsModal();}, + opsPop:({k,city})=>{if(!opsHired()||!OPS_POP.includes(k)||!S.pops[city])return;const sk=S.ops.skip,a=sk[city]||[];sk[city]=a.includes(k)?a.filter(x=>x!==k):[...a,k];if(!sk[city].length)delete sk[city]; + UI.opsCity=city;sfx('click');after();opsModal();}, + opsTpl:({k})=>{if(!opsHired()||!OPS_TPL.includes(k))return;S.ops.tpl[k]=!S.ops.tpl[k];sfx('click');after();opsModal();}, + // One tap, a whole POP: the same clicks in the same order, all or nothing on the price. + opsNewPop:({city})=>{if(!opsHired())return;const q=opsTplQuote(city);if(!q)return;if(S.cash{ACT.buildPop({city});if(!S.pops[city])return;if(S.ops.tpl.bb)ACT.launchBB({city});if(q.net)ACT.buyTransit({city,net:q.net,tier:0});if(q.ix)ACT.buyIx({city:q.ix,tier:0}); + if(q.kit){const k=utilityKit(city);if(k&&k.cost&&S.cash>=k.cost)ACT.utilityKit({city,cost:k.cost});}}); + if(!S.pops[city])return;UI.tab='links';floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');sfx('build'); + toast(esc(tr('ops.tpl_done',{name:opsName(),city:CITY[city].name,list:q.parts.join(', ')||tr('ops.tpl_just_pop')})),'good',[],{a:'city',v:city});after();}, +}); diff --git a/src/game/90-actions/88-optic-counts.js b/src/game/90-actions/88-optic-counts.js new file mode 100644 index 0000000..8a4db1c --- /dev/null +++ b/src/game/90-actions/88-optic-counts.js @@ -0,0 +1,27 @@ +// Quote the whole change before spending: shelf optics still need regen cards. +function opticCountCost(l,o,n){ + const add=Math.max(0,n-(l.ch||[]).filter(k=>k===o).length),sp=Math.min(add,spareN(o)),r=REGEN_CH*(l.regen|0),c=optCost(o); + return sp*Math.round(c*r)+(add-sp)*Math.round(c*(1+r)); +} +Object.assign(ACT,{ + setChCount:({id,o,n})=>{ + const l=S.links.find(x=>x.id===id); + if(!l||l.kind!=='df'||!own(OPT,o)||!Number.isSafeInteger(n)||n<0||n>chMax(l))return; + const old=(l.ch||[]).filter(k=>k===o).length,d=n-old; + if(!d)return; + if(d>0){ + const why=chWhy(l,o); + if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + const free=chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l); + if(d>free){toast(tr('optic_counts.only_n_channels_free',{n:free}),'bad');sfx('err');return;} + if(!portGate(l.a,d*chPorts(o,l.a))||!portGate(l.b,d*chPorts(o,l.b))||!spend(opticCountCost(l,o,n)))return; + const sp=Math.min(d,spareN(o));if(sp)S.spares[o]-=sp; + (l.ch=l.ch||[]).push(...Array(d).fill(o)); + }else{ + let left=-d;l.ch=l.ch.filter(k=>k!==o||left--<=0); + S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)-d; + } + if(UI.opticCounts)delete UI.opticCounts[JSON.stringify([id,o])]; + after(); + }, +}); diff --git a/src/game/90-actions/88-utilities.js b/src/game/90-actions/88-utilities.js new file mode 100644 index 0000000..fadef88 --- /dev/null +++ b/src/game/90-actions/88-utilities.js @@ -0,0 +1,29 @@ +Object.assign(ACT,{ + utilities:({city}={})=>{if(S)utilitiesModal(city);}, + utilityPick:()=>{if(S&&$('utilityCity'))utilitiesModal($('utilityCity').value);}, + utilityRouteServers:({city}={})=>{if(!S)return;const ids=utilityRouteServers();for(const ix of ids)S.rs[ix]=true; + if(ids.length){sfx('build');after();}utilitiesModal(city,tr('utilities.route_servers_joined',{n:ids.length}));}, + utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||(!q.cost&&!q.moves.length))return; + // Prices can change while a modal is open. Refresh the quote before spending more (a day's drift is fine: quoteNear). + if(!quoteNear(+cost,q.cost)){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} + if(q.cost&&!spend(q.cost))return;const p=S.pops[city]; + if(q.gen)p.gen=true;if(q.site){p.site2=true;p.site2Day=S.day;}if(q.router)p.routers=2; + const moves=new Map(q.moves.map(m=>[m.id,m.site]));for(const c of S.caches)if(moves.has(c.id))c.site=moves.get(c.id); + after();const msg=tr('utilities.kit_applied',{city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + // Every POP's kit in one go (#317), all or nothing on the quoted price (within a day's drift), one redraw at the end. + utilityKitAll:({cost,city})=>{const q=utilityKitAll();if(!q||!q.cities.length)return; + if(!quoteNear(+cost,q.cost)){utilitiesModal(city,tr('utilities.quote_changed'));return;} + if(S.cash{for(const c of q.cities){const k=utilityKit(c);if(!k||S.cash{if(!opsHired())return;S.ops.tpl.kit=!S.ops.tpl.kit;sfx('click');after();utilitiesModal(city);}, + utilityCaches:({city,quote,modal})=>{const q=utilityCaches(city);if(!q||!q.add.length)return; + if(q.key!==quote){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} + if(!portGate(city,q.ports))return; + for(const c of q.add)S.caches.push({id:uid(),city,net:c.net,site:c.site,...(c.g?{g:c.g}:{})}); + sfx('build');after();const msg=tr('utilities.caches_requested',{n:q.add.length,city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + utilityPeers:({city}={})=>{if(!S)return;const rows=utilityPeers();let n=0; + for(const row of rows)for(const id of row.requests){S.peers[id+'@'+row.ix]=true;n++;} + if(n){sfx('build');after();}utilitiesModal(city,tr('utilities.peers_requested',{n}));}, +}); diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js new file mode 100644 index 0000000..d7b4c3f --- /dev/null +++ b/src/game/90-actions/89-game-and-settings.js @@ -0,0 +1,44 @@ +Object.assign(ACT,{ + randomName:()=>{const input=$('nmIn');if(input)input.value=UI.nm=randomNetworkName(input.value);}, + start:()=>{if(UI.asnTxt&&!asnOk(+UI.asnTxt)){toast(tr('title.asn_not_usable'),'bad');const i=$('asnIn');if(i){i.classList.add('bad');i.focus();}return;}const nm=(($('nmIn')&&$('nmIn').value)||randomNetworkName()).slice(0,24),sb=UI.mode==='sandbox'; + beginGame(nm,homeOk(UI.startCity)?UI.startCity:'fra',sb?{mode:'sandbox',rules:{chaos:own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'}}:{mode:'normal',preset:NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall'});}, + // Title-screen doors and their options toggle in place, so the name being typed and the city stay as they are. + modeSet:({m})=>{if(m!=='sandbox'&&m!=='normal')return;UI.mode=m;document.querySelectorAll('.door').forEach(b=>b.classList.toggle('on',b.dataset.door===m));const n=$('doorNormal'),x=$('doorSandbox');if(n)n.hidden=m!=='normal';if(x)x.hidden=m!=='sandbox';}, + presetSet:({p})=>{if(!NORMAL_PRESETS.includes(p))return;UI.preset=p;ACT.modeSet({m:'normal'});document.querySelectorAll('.preset').forEach(b=>{b.classList.toggle('on',b.dataset.preset===p);b.setAttribute('aria-pressed',b.dataset.preset===p);});const w=$('presetWhat');if(w)w.innerHTML=presetWhat(p);}, + chaosSet:({c})=>{if(!own(CHAOS,c))return;UI.sbChaos=c;ACT.modeSet({m:'sandbox'});document.querySelectorAll('.chs').forEach(b=>b.classList.toggle('on',b.dataset.chaos===c));}, + // Puzzles live in their own module; until it ships, the door says so. + puzzleDoor:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||randomNetworkName()).slice(0,24);if(typeof ACT.puzzleMenu==='function')ACT.puzzleMenu();else toast(tr('title.puzzles_are_coming_soon'),'goal');}, + scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();}, + startScn:({id})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});}, + // The published weekly scenario when it came, else the in-browser one. + wsShare:()=>{if(!S||!S.scn||!S.scn.wk||!S.scn.done)return;const t=wsShareText(),copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'); + if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}track('wkscn_share');}, + startWeekly:()=>{const nm=UI.nm||(S&&S.name)||randomNetworkName();if(wsBegin(wsDef(),nm))return;const o=wsLoad();o.go[pzWeekKey(new Date())]=1;wsStore(o);const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, + pickStart:({city})=>{if(!homeOk(city))return;UI.startCity=city;const s=$('homeSel');if(s)s.value=city;const w=$('homeWhat');if(w)w.innerHTML=homeWhat();}, + pickHome:({v})=>{if(v)ACT.pickStart({city:v});else ACT.pickStart({city:'fra'});}, + // Delete this window's network and go back to the title (the other networks stay). + newgame:()=>{if(pzOn())pzLeave();const id=UI.slot;if(id){slotDrop(id);slotFree(id);}gameClear();showTitle();}, + keepPlaying:()=>{closeModal();}, + exportSave:()=>exportSave(), + importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,.txt,application/json,text/plain';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();}, + importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S; + // An import is a new network next to the others: the one playing here is saved and kept. + try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');if(MP_API)mpResume();}, + menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`
AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}

${esc(S.name)}

+ ${saveFailing()?`

${saveFailMsg()}

`:`

${tr('game_and_settings.your_game_saves_itself_every_few')}

`} + + + +
`);}, + settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, + settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();}, + prefSet:({v})=>{const [k,b]=String(v).split(':');if(!own(PREF_DEF,k))return;setPref(k,b==='1');sfx('click');refreshSettings();}, + vpSet:({v})=>{diagOn(v==='on');refreshSettings();}, + resetAsk:()=>openModal(`

${tr('game_and_settings.start_a_new_network')}

${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(S?S.name:tr('common.your_network'))})}

${btn(tr('game_and_settings.delete_and_start_over'),'newgame',{},'red big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`), + whatsNewShow:()=>whatsNew(true,true), + updateNow:()=>{save(true);location.reload();}, + updateLater:()=>{$('update').hidden=true;UI.updLater=Date.now();}, + helpClose:()=>{if(UI.started)closeModal();else showTitle();}, +}); diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js new file mode 100644 index 0000000..4138396 --- /dev/null +++ b/src/game/90-actions/90-action-helpers.js @@ -0,0 +1,65 @@ +// Overland routes already dug between two cities, in the order they were built (#77). The first is the +// main route; every other one was a diverse route and keeps that price when you add waves to it. +function landTrenches(a,b){const out=[];for(const l of pairLinks(a,b)){if(l.kind==='vxc'||l.kind==='xp'||l.cable||l.sub)continue;const k=l.trench||l.id;let t=out.find(x=>x.k===k);if(!t)out.push(t={k,n:0,caps:[]});t.n++;t.caps.push(capName(l));}return out;} +// Which route a new wave joins: null = a new diverse route. 'same' is the old two-way choice (the main route). +function routeJoin(a,b){const ts=landTrenches(a,b),r=UI.route||'';if(r==='same')return ts[0]||null;if(r.startsWith('t:'))return ts.find(t=>t.k===r.slice(2))||null;return null;} +function pairLinks(a,b){return S.links.filter(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));} +// A city pair's metric goes with its last link, so a new link between the same cities starts on normal. +function prunePairMet(){const m=S.pairMet;if(!m)return;const k=new Set(S.links.map(edgeKey));for(const x of Object.keys(m))if(!k.has(x))delete m[x];} +// Short, busy subsea routes (London–Amsterdam, London–Paris) sell dark fiber pairs too. +function subDfCable(a,b){return cablesOk(a,b).filter(c=>CAB[c.cid].df).sort((x,y)=>x.km-y.km)[0]||null;} +function dfAllowed(a,b){if(noTalk(a,b))return false;if(isSub(a,b))return !!subDfCable(a,b);return cnCity(a)===cnCity(b)&&!uaePair(a,b)&&!landX(a,b);} +// A link starts at one of your POPs. The map only drags one from a POP, but a typed order (the agent API) names both ends. +function linkFromWhy(a){return S.pops[a]?'':tr('action_helpers.you_have_no_pop_in_city',{city:CITY[a].name});} +function linkFromOk(a){const w=linkFromWhy(a);if(w){toast(w,'bad');sfx('err');}return !w;} +// ...and ends at a city you could build a POP in (#203): a typed order can name one the map does not show. +function linkToOk(b){if(S.pops[b]||cityOn(b))return true;toast(popOffWhy(b),'bad');sfx('err');return false;} +// A retired small city (off: true) takes no new POP; the nearest open city in its country stands in for it. +function popOffWhy(c){const C=CITY[c],near=CITIES.filter(o=>!o.off&&o.cc===C.cc).sort((x,y)=>kmBetween(c,x.id)-kmBetween(c,y.id))[0]; + return tr('action_helpers.city_is_off_the_map_small',{city:C.name,near:near?near.name:''});} +// Why a city takes no exchange of your own. The reasons a POP would not fix come first. +function foundIxWhy(c){const C=CITY[c];if(C.cn)return tr('link_panels.running_an_exchange_in_mainland'); + if(S.myIx[c])return tr('action_helpers.you_already_run_ix_in_city',{ix:esc(S.myIx[c].name),city:C.name}); + if(C.ix)return tr('action_helpers.city_already_has_an_exchange_ix',{city:C.name,ix:esc(C.ix)}); + return S.pops[c]?'':tr('action_helpers.you_have_no_pop_in_city_build',{city:C.name});} +/* Optics you unplug go on a spares shelf instead of in the bin (#45): the next channel of that type uses a spare + for free (only the regen sites' transponders are new), or you sell it on eBuy for part of the price. */ +const SPARE_RESALE=0.4,spareN=o=>(S&&S.spares&&S.spares[o])|0,spareValue=o=>Math.round(optCost(o)*SPARE_RESALE); +// A fiber given up (a cancelled IRU, a cable called off, a decommissioned POP) keeps its optics: they go on the shelf too (#229). +const chBack=links=>{let n=0;for(const l of links)for(const o of (l&&l.ch)||[])if(OPT[o]){S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;n++;}return n;}; +function chCost(l,o){const r=REGEN_CH*(l.regen|0);return Math.round(optCost(o)*(spareN(o)>0?r:1+r));} +// One more regen site on fiber l: the hut, and a regen card for every channel in its glass, the expresses riding it too. +function regenAddCost(l){let o=(l.ch||[]).reduce((a,c)=>a+optCost(c),0);for(const x of xpOver(l.id))for(const c of x.ch||[])o+=optCost(c);return REGEN_COST+Math.round(o*REGEN_CH);} +function optCost(o){return Math.round(OPT[o].cost*techMul(OPT[o].lvl)*hwMul('opt')*(S&&S.ev&&S.ev.tariff>S.day?1.4:1));} +// Line systems upgrade in place: Rainbow → ROADMaster → C+L. Every lit pair gets the new gear. +const sysNext=l=>l.sys==='lite'?'roadm':l.sys==='roadm'?'cl':null,sysUpCost=l=>{const t=sysNext(l);return t?sysCost(t)*(t==='cl'&&l.own?Math.max(1,l.pairs|0):1):0;}; +function pairBtn(l){if(!l.own||!isRdm(l.sys)||l.ready>S.day)return '';const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return `${tr('action_helpers.n_fiber_pairs_lit_the_trench',{n})}`; + const full=(l.ch||[]).length+soldSlots(l)+xpSlots(l)>=chMax(l),c=pairCost(l);return btn(l.sub?tr('action_helpers.light_fiber_pair_n_price',{n:n+1,price:fmt$(c)}):tr('action_helpers.light_fiber_pair_n_price_mo',{n:n+1,price:fmt$(c),mo:fmt$(ampCount(l.km)*AMP_MO)}),'addPair',{id:l.id},full?'pink sm':'ghost sm',!full||S.cash(OPT[x].sys!=='roadm'||isRdm(l.sys))&&optMode(x,withSubUps(l))).map(x=>OPT[x].n);if(alt.length)return tr('action_helpers.upgrades_cannot_stretch_this_optic',{...v,optics:alt.join(', ')});} + return tr('action_helpers.this_channel_reaches_max_km_on',v);}return tr('action_helpers.too_far_even_at_its_slowest',{span:spanKm(l).toLocaleString(),max:mx.toLocaleString()});} + if((l.ch||[]).length+soldSlots(l)+xpSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)}); + for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&RG[p.rgen||0].clsinnerWidth>760&&innerWidth<=1200; +function selectLink(id){UI.sel={type:'link',id};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;$('panel').classList.remove('full');renderPanel();renderLeft();} +// Frame the whole drawn line (cables bend far from the straight one) in the part of the map the panel leaves free: +// above a phone's bottom sheet, left of the side panel. Long links zoom out to fit; short ones zoom in like a city. +// A puzzle keeps its own framing beside the puzzle card (pzCam). +function focusLink(id){if(pzOn())return;const l=S.links.find(x=>x.id===id);if(!l||!CITY[l.a]||!CITY[l.b])return;const pts=linkGeom(l).pts; + let x0=Infinity,x1=-Infinity,y0=Infinity,y1=-Infinity;for(const [x,y] of pts){if(xx1)x1=x;if(yy1)y1=y;} + const P=$('panel'),r=P&&!P.hidden&&P.getBoundingClientRect();let fl=0,fr=CW,ft=70,fb=CH; + if(r&&r.width>0){if(r.width>CW*0.6)fb=Math.min(fb,r.top);else fr=Math.min(fr,r.left);} + // Phones leave a thin strip above the sheet: a fixed margin would eat most of it. + const m=(a,b)=>Math.max(40,b-a-Math.min(100,(b-a)*0.3)),fw=m(fl,fr),fh=m(ft,fb),z=clamp(Math.min(fw/Math.max(1,x1-x0),fh/Math.max(1,y1-y0),Math.max(cam.z,1.2)),ZMIN,ZMAX); + cam.z=z;cam.x=(x0+x1)/2-((fl+fr)/2-CW/2)/z;cam.y=(y0+y1)/2-((ft+fb)/2-CH/2)/z;wrapCam();} +function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;UI.offerAt=null;if(isTablet()||isPhone())UI.leftOpen=false;const P=$('panel');if(P)P.classList.remove('full');if(!S.pops[c])UI.tab='cust';renderPanel();} + diff --git a/src/game/90-actions/91-slots.js b/src/game/90-actions/91-slots.js new file mode 100644 index 0000000..17aab37 --- /dev/null +++ b/src/game/90-actions/91-slots.js @@ -0,0 +1,35 @@ +Object.assign(ACT,{ + // Continue a network from the list (or the newest one). + cont:({id}={})=>{if(!slotOkId(id)){const t=slotTop(slotIdx(true));if(!t)return;id=t.id;} + if(id===UI.slot&&S&&!pzOn()){UI.started=true;closeModal();renderAll();return;} + slotOpen(id,false,()=>track('game_continue',true));}, + // Back to the title with this network kept and saved. + toTitle:()=>{if(pzOn()){pzLeave();}slotLeave();gameClear();showTitle();}, + slotBack:()=>{if(S&&UI.started)closeModal();else showTitle();}, + // A damaged save, opened once more: if it loads, it is no longer damaged; if not, it is marked again. + slotRetry:({id})=>{const l=slotIdx(),e=l.find(x=>x.id===id);if(!e)return;e.broken=false;slotIdxPut(l);closeModal();ACT.cont({id});}, + slotMenu:({id})=>{const h=slotMenuHtml(id);if(h)openModal(h);}, + slotExport:({id})=>exportSlot(id), + slotDel:({id,back})=>{const e=slotIdx().find(x=>x.id===id);if(!e)return; + openModal(`

${tr('slots.delete_name',{name:esc(e.name||tr('common.unnamed_network'))})}

${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(e.name||tr('common.unnamed_network'))})}

${slotBusy(id)?`

${tr('slots.it_is_open_in_another_window')}

`:''}
${btn(tr('slots.delete_forever'),'slotDelGo',{id,back},'red big')}${btn(tr('slots.keep_it'),back==='space'?'slotSpace':'slotBack',{},'ghost big')}
`);}, + slotDelGo:({id,back})=>{if(!slotIdx().some(e=>e.id===id))return; + if(id===UI.slot){ACT.newgame();return;} + slotDrop(id);try{BC&&BC.postMessage({t:'gone',id});}catch(e){}sfx('click'); + if(back==='space')openModal(slotSpaceHtml());else showTitle();}, + slotSpace:()=>openModal(slotSpaceHtml()), + // The other window cannot be brought forward from here; it says hello when the player gets there. + slotSwitch:({id})=>{try{BC&&BC.postMessage({t:'focus',id});}catch(e){}const e=slotIdx().find(x=>x.id===id);showTitle();toast(tr('slots.name_is_waiting_in_your_other',{name:esc(e&&e.name||'')}),'goal');}, + // Ask the other window to save and step aside, then open it here. Without an answer (it is frozen, or the browser has + // no BroadcastChannel) it is taken anyway after a moment: the other window stops writing the moment it notices. + slotTake:({id})=>{if(!slotOkId(id))return;const w=SLOT.wait={id,go:()=>{if(SLOT.wait!==w)return;SLOT.wait=null;clearTimeout(w.t);slotOpen(id,true);}}; + w.t=setTimeout(w.go,BC?1500:0);try{if(BC)BC.postMessage({t:'take',id});}catch(e){w.go();}}, + rename:()=>{if(!S||!UI.started||pzOn())return;openModal(`

${tr('slots.rename_your_network')}

${btn(tr('slots.rename'),'renameGo',{},'pink big')}${btn(tr('common.cancel'),'menu',{},'ghost big')}
`);}, + // name: the new name as an argument (a server runs this without the sheet), else the sheet's field. + renameGo:({name}={})=>{const el=$('rnIn'),raw=typeof name==='string'?name:el?el.value:null;if(!S||raw===null||pzOn())return;const v=raw.replace(/\s+/g,' ').trim().slice(0,24);if(!v)return;S.name=v;closeModal();after();toast(tr('slots.renamed_to_name',{name:esc(v)}),'good');}, +}); +// No game on screen: the map stays empty behind the title. +function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();} +// Back from the title (or a puzzle) into a loaded network. +function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1); + if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} + closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');if(MP_API)mpResume();} diff --git a/src/game/90-actions/92-multiplayer.js b/src/game/90-actions/92-multiplayer.js new file mode 100644 index 0000000..5515551 --- /dev/null +++ b/src/game/90-actions/92-multiplayer.js @@ -0,0 +1,34 @@ +// Multiplayer (60-features/89-multiplayer.js, 95-modals/48-multiplayer.js). Every one does nothing unless the build +// stamped MP_API; the title-screen ones are in the click delegate's no-game list (96-map/95-clicks.js). +Object.assign(ACT,{ + mpDoor:()=>{if(!MP_API)return;const i=$('nmIn');UI.nm=((i&&i.value)||UI.nm||randomNetworkName()).slice(0,24);openModal(mpStartHtml()); + const n=$('mpName');if(n)n.addEventListener('input',e=>{UI.nm=e.target.value;}); + const c=$('mpCode');if(c)c.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpJoin({});}});}, + mpBack:()=>{const n=$('mpName');if(n)UI.nm=n.value.slice(0,24);showTitle();}, + mpStart:()=>{if(!MP_API||UI.mpBusy)return;const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra',preset=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',t=$('mpTitle'); + mpBusy(true);mpReq('POST','/sessions',{net:{name:nm,home},preset,title:(t&&t.value||'').slice(0,40),avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,false);},e=>{mpBusy(false);mpErr(e);});}, + mpJoin:()=>{if(!MP_API||UI.mpBusy)return;const i=$('mpCode'),code=mpNorm(i?i.value:'');if(!code){toast(tr('mp.err_code'),'bad');if(i)i.focus();return;} + const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra'; + mpBusy(true);mpReq('POST','/sessions/'+code+'/join',{net:{name:nm,home},avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,true);},e=>{mpBusy(false);mpErr(e);});}, + mpOpen:()=>{if(!mpIs())return;openModal(mpPanelHtml(),'mp');const s=$('mpSay');if(s)s.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpChat({});}}); + // About to move to another device: the server gets what this one has first, so the link opens it as it is now. + const d=document.querySelector('#mpPanel details.mpmove');if(d)d.addEventListener('toggle',()=>{if(d.open)mpSyncNow();});mpPoll();}, + mpShare:()=>{if(!mpIs())return;mpSend(tr('mp.share_line',{code:mpShow(S.mp.code),url:location.origin+location.pathname}));}, + // The link carries the secret: it goes to the clipboard, or is selected for copying by hand, never into a toast. + mpCopyLink:()=>{if(!mpIs())return;const l=mpLink(S.mp);if(!l)return;mpSyncNow();const sel=()=>{const i=$('mpLink');if(i){i.focus();i.select();}}; + try{navigator.clipboard.writeText(l).then(()=>toast(tr('mp.link_copied'),'good'),sel);}catch(e){sel();}}, + mpChat:()=>{if(!mpIs()||MP.gone)return;const i=$('mpSay'),t=(i?i.value:'').trim().slice(0,200);if(!t)return;const m=S.mp; + mpReq('POST',mpPath(m,'/feed'),{text:t},{auth:m}).then(j=>{if(i)i.value='';mpOk(j);},e=>{if(e&&e.status===429)toast(tr('mp.slow_down'),'bad');else mpFail(e);});}, + mpLeaveAsk:()=>{if(!mpIs())return;openModal(`

${tr('mp.leave_q',{code:mpShow(S.mp.code)})}

${tr('mp.leave_d',{name:esc(S.name)})}

${btn(tr('mp.leave'),'mpLeave',{},'red big')}${btn(tr('common.keep_playing'),'mpOpen',{},'ghost big')}
`);}, + // Leaving keeps the network, as a game of its own; the session forgets it (and a session that forgot it already too). + mpLeave:()=>{if(!mpIs())return;const m=S.mp,out=()=>{if(!S||S.mp!==m)return;S.mp=null;mpTokSet(m.code,m.pid,null);mpReset(); + closeModal();renderAll();save(true);toast(tr('mp.left',{name:esc(S.name)}),'good');}; + mpReq('DELETE',mpPath(m,'/me'),undefined,{auth:m}).then(out,e=>{if(e&&(e.status===401||e.status===404))out();else toast(tr('mp.server_away'),'bad');});}, + // Only a save at least as new as the one the server said it has (after a conflict), or newer than this one, is loaded: + // "Load the newer save" never takes the player back to an older one. + mpNewer:()=>{if(!mpIs())return;const m=S.mp,min=(m.seq||0)+(MP.stale?0:1); + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{if(!S||S.mp!==m)return;const sq=int(j&&j.seq,0,1e15,0);if(sq>=min){mpAdopt(j,m);return;} + m.seq=Math.max(m.seq||0,sq);MP.stale=false;toast(tr('mp.no_newer',{name:esc(S.name)}),'good');mpPanelUpdate();},mpFail);}, + // Overwrite the server's save with this one: with a number past the server's, at the next save (never half a day). + mpKeep:()=>{if(!mpIs())return;S.mp.seq=Math.max(S.mp.seq||0,MP.staleSeq||0);Object.assign(MP,{stale:false,force:true,wait:0});save(true);mpPanelUpdate();}, +}); diff --git a/src/game/90-actions/92-transfer.js b/src/game/90-actions/92-transfer.js new file mode 100644 index 0000000..fea6a19 --- /dev/null +++ b/src/game/90-actions/92-transfer.js @@ -0,0 +1,14 @@ +// Moving a network to another device (#263): the save file through the share sheet, or a link to paste. +Object.assign(ACT,{ + xfer:({id}={})=>{const sid=slotOkId(id)?id:UI.slot;if(!sid||!slotIdx().some(e=>e.id===sid))return; + xferPack(sid).then(x=>{UI.xfer=x;openModal(xferHtml());track('xfer_open');},()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));}, + // Straight from the tap: a share sheet only opens on a user's gesture. + xferShare:()=>{const x=UI.xfer;if(!x||!x.file)return; + try{navigator.share({files:[x.file],title:'Series of Tubes'}).then(()=>track('xfer_share'),e=>{if(e&&e.name!=='AbortError')exportSlot(x.id);});}catch(e){exportSlot(x.id);}}, + xferLink:()=>{const x=UI.xfer;if(!x||!x.link)return;const no=()=>toast(tr('transfer.could_not_copy_the_link_here'),'bad'); + if(x.mp&&x.id===UI.slot)mpSyncNow(); + try{navigator.clipboard.writeText(x.link).then(()=>toast(x.mp?tr('mp.link_copied'):tr('transfer.link_copied_paste_it_on_your'),'good'),no);}catch(e){no();}}, + xferFile:()=>{const x=UI.xfer;if(x)exportSlot(x.id);}, + xferRecv:()=>openModal(xferRecvHtml()), + xferPaste:()=>{const el=$('xferIn');if(el)xferTake(el.value.trim());}, +}); diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js new file mode 100644 index 0000000..560d802 --- /dev/null +++ b/src/game/90-actions/95-puzzles.js @@ -0,0 +1,67 @@ +// Can a wave of this size be lit between a and b here? Router ports and models as in the main game; a city without a +// POP yet will get a Rusty Router. +function pzWaveWhy(a,b,tier,r){if(r&&subWaveWhy(tier,r.km,r.sub))return tr('common.too_far_for_this_cable');if(!S.ar&&!waveOk(a,b,tier))return tr('puzzles.needs_what',{what:waveNeed(tier)});return '';} +const pzPortsFree=c=>!S.pops[c]||portsUsed(c)+1<=portsMax(c)+1e-9; +Object.assign(ACT,{ + // The chaos monkey acts out the N-1 check, or is told to get on with it. + pzMonkey:()=>{if(pzOn()&&pzEval().goal)pzMonkey();}, + pzMkSkip:()=>{if(pzOn())pzMkSkip();}, + // The puzzle list. The ruleset's title-screen door calls this. + puzzleMenu:()=>{if(S&&UI.started&&!pzOn())UI.nm=S.name;pzMenu();}, + pzStart:({id})=>{const d=pzDef(id);if(!d||!pzPackOpen(d.pack))return;pzBegin(d);}, + pzWeekly:()=>{if(pzWkLoading())return;pzBegin(pzWkDef());}, + pzFinish:()=>{if(!pzOn())return;if(S.ar){arResults(false);return;}const e=pzEval();if(e.stars)pzResults(e,e.stars);}, + pzRetry:()=>{if(!pzOn())return;if(S.ar){arBegin(arRun());return;}pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, + pzLeave:()=>{if(pzOn())pzLeave();}, + // The sheet's next-fix line: bring the city, or the link a cut hurts most, into view (the zoom stays). + // Phones split a puzzle's city and link cards into tabs (97-puzzles-phone.js); the tab shown is kept per kind of card. + pzTab:({k,t})=>{if(!pzOn()||!['city','link'].includes(k)||typeof t!=='string')return;UI.pzTab={...(UI.pzTab||{}),[k]:t};renderPanel();}, + // A flow chip on a phone: that city's card, with the city on screen. + pzCity:({c})=>{if(!pzOn()||!isCity(c)||!pzKind(c))return;ACT.pzLook({c});selectCity(c);renderTabbar();}, + pzLook:({c,u})=>{if(!pzOn())return;let x,y;if(c&&isCity(c)){x=CITY[c].x;y=CITY[c].y;}else{const l=u&&S.links.find(q=>pzUnit(q)===u);if(!l)return;const A=CITY[l.a],B=CITY[l.b];x=A.x+wrapDx(A.x,B.x)/2;y=(A.y+B.y)/2;} + const sh=isPhone()&&CW<=CH?($('pzBox').offsetHeight||0):0;cam.x=x;cam.y=y+sh/2/cam.z;wrapCam();haptic(8);}, + pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via','off'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop(city);sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();}, + pzRmPop:({city})=>{if(!pzOn()||!S.pops[city]||(S.ar&&city===S.ar.hq))return;pzSnap();if(S.ar)arSink([city],S.links.filter(l=>l.a===city||l.b===city));delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, + pzLinkTo:({a,b})=>{if(!pzOn()||!S.pops[a]||a===b)return;pzLinkModal(a,b);}, + pzVia:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzVia=v;pzLinkModal(p.a,p.b,true);}, + pzDiv:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzDiv=!!+v;pzLinkModal(p.a,p.b,true);}, + pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!(S.ar?AR_TIERS:PZ_TIERS).includes(tier))return;const {a,b}=p,kb=pzKind(b);if(!S.pops[a]||!['goal','via','off'].includes(kb))return; + const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub))return; + const why=pzWaveWhy(a,b,tier,r);if(why){toast(esc(why),'bad');sfx('err');return;} + if(!S.ar&&(!portGate(a,1)||(S.pops[b]&&!portGate(b,1))))return; + // Overland: the same trench as a link already on the pair (the one picked from, or the first), or a diverse route + // of its own. Every trench but the first runs the long way round and costs 40% more. + const lands=pzOn()&&!r.sub?S.links.filter(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):[],t0=lands.length?pzUnit(lands[0]):null; + const same=UI.pzDiv===false&&lands.length?(lands.find(l=>pzUnit(l)===UI.pzTrench)||lands[0]):null,trench=same?pzUnit(same):null,div=!!t0&&trench!==t0; + pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop(b);const id=uid(),f=r.f*(div?DIVERSE:1); + S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:trench||id,cut:0,day:0,br:S.ar?S.ar.bi:0}); + closeModal();sfx('build');haptic(12);floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,S.ar?tr('architect.tube_laid'):tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');UI.sel=null;pzAfter();}, + // Another link next to this one: the picker opens on the same pair, on the same route, in the same trench or a diverse one. + pzAddPar:({id,div})=>{const l=pzOn()&&S.links.find(x=>x.id===id);if(!l)return;UI.pzVia=l.cable||'land';UI.pzDiv=!!+div;UI.pzTrench=l.cable?null:pzUnit(l); + // A diverse tube takes the cheapest other route at this tube's size, as a new tube does, not the first one listed (#282). + if(+div&&l.cable){const o=pzRoutes(l.a,l.b).filter(x=>x.via!==l.cable&&!(S.pz.noSub&&x.sub)).sort((x,y)=>pzLinkCost(x,l.tier,true)-pzLinkCost(y,l.tier,true))[0];if(o)UI.pzVia=o.via;} + pzLinkModal(l.a,l.b,true);}, + pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!(S.ar?AR_TIERS:PZ_TIERS).includes(tier)||l.tier===tier)return;const why=pzWaveWhy(l.a,l.b,tier,{km:l.km,sub:l.sub});if(why){toast(esc(why),'bad');sfx('err');return;} + pzSnap();if(S.ar){if(arAge(l){if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();if(S.ar)arSink([],S.links.filter(l=>l.id===id));S.links=S.links.filter(l=>l.id!==id);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, + // Routers: one more of the same model, one fewer, or every router in the POP swapped for another model. + pzRtAdd:({city})=>{const p=pzOn()&&!S.ar&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;pzSnap();p.routers=(p.routers||1)+1;sfx('build');floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');pzAfter();}, + pzRtRm:({city})=>{const p=pzOn()&&!S.ar&&S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;} + pzSnap();p.routers--;sfx('click');pzAfter();}, + pzRtModel:({city,g})=>{g=+g;const p=pzOn()&&!S.ar&&S.pops[city];if(!p||!PZ_RG.includes(g)||g===(p.rgen||0))return;const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;} + pzSnap();p.rgen=g;sfx('build');floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');pzAfter();}, + // A circuit follows the metrics (the IGP's shortest path) or takes the lowest-latency path, as customers can in the main game. + pzRoute:({i,m})=>{const b=pzOn()&&S.biz.find(x=>x.id===pzFlowId(+i));if(!b||!['normal','fast'].includes(m)||b.route===m)return;pzSnap();b.route=m;sfx('click');pzAfter();}, + pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;if(S.ar)arStop(true);const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};if(S.ar){S.ar.sunk=o.k||0;arDemand();}(o.r||[]).forEach((m,i)=>{if(S.biz[i])S.biz[i].route=m;});sfx('click');pzAfter();}, + pzReset:()=>{if(!pzOn())return;if(!$('modal').hidden)closeModal();pzSnap();if(S.ar){arReset();sfx('click');pzAfter();return;}S.pops={};S.links=[];S.pairMet={};for(const b of S.biz)b.route='normal';UI.sel=null;sfx('click');pzAfter();}, + pzShare:()=>{if(!pzOn())return;const t=S.ar?arShareText(arStars(arSpend()),arSpend()):pzShareText(pzEval()); + const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'),copy=()=>{try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}; + if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}copy();track('puzzle_share');}, +}); +// A puzzle is its own S: a leftover main-game button (an old toast, a stale panel, a shortcut) must not build, buy or +// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. The main game's +// routing controls (metric, standby, the redundancy check) work in a puzzle too, and their changes can be undone. +// This file is the last of the actions, so every one is here to wrap. +const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','themeSet','updateLater','updateNow','vpSet','whatsNewShow']); +const PZ_UNDO=new Set(['metricMode','metricSet','setMetric','setStandby']); +for(const k of Object.keys(ACT)){const f=ACT[k];if(PZ_UNDO.has(k))ACT[k]=a=>{if(pzOn())pzSnap();return f(a);};else if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k))ACT[k]=a=>pzOn()?undefined:f(a);} diff --git a/src/game/90-actions/96-architect.js b/src/game/90-actions/96-architect.js new file mode 100644 index 0000000..f74e15e --- /dev/null +++ b/src/game/90-actions/96-architect.js @@ -0,0 +1,8 @@ +// Architect runs (prototype). Named pz* like the puzzle actions, so a puzzle lets them through. +Object.assign(ACT,{ + pzArStart:({id})=>{const r=arRunDef(id);if(r)arBegin(r);}, + pzArGo:()=>{if(arOn())arShowStart();}, + pzArSkip:()=>{if(arOn())arShowSkip();}, + pzArNext:()=>{if(arOn())arNext();}, + pzArAll:()=>{if(!arOn())return;UI.arAll=!UI.arAll;if(!UI.arAll&&UI.sel&&UI.sel.type==='city'&&!arKind(UI.sel.id))UI.sel=null;sfx('click');renderAll();}, +}); diff --git a/src/game/90-actions/97-pie.js b/src/game/90-actions/97-pie.js new file mode 100644 index 0000000..33a69e0 --- /dev/null +++ b/src/game/90-actions/97-pie.js @@ -0,0 +1,41 @@ +// Pie in the Sky (60-features/99-pie-in-the-sky.js): every action checks pieCanBuild() for anything new. +const pieRe=()=>{after();if(!$('modal').hidden&&$('modal').className==='pie')pieModal();if(!$('bankBox').hidden)renderBank();}; +const pieNo=why=>{toast(why,'bad');sfx('err');pieRe();}; +Object.assign(ACT,{ + pieOpen:()=>{if(!S||pzOn()||!pieOn())return;UI.confirm=null;pieModal();}, + pieFound:()=>{const P=pieGet();if(!P||P.co)return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));if(!pieSpend(piePrice(PIE_CO)))return pieRe(); + P.co={name:PIE_NAMES[0]};P.born=Math.min(P.born,S.day);pieFounder(N_('pie.fp_found'));piePromise();track('pie_found');toast(tr('pie.t_found',{co:esc(pieCoName())}),'goal');pieRe();}, + pieFactory:()=>{const P=pieGet();if(!P||!P.co||P.fac)return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));if(!pieSpend(piePrice(PIE_FAC)))return pieRe(); + P.fac=true;toast(tr('pie.t_factory',{n:PIE_FAC_MONTH}),'good');pieRe();}, + piePad:({city})=>{const P=pieGet();if(!P||!P.co||!isCity(city))return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1')); + if(!S.pops[city]||!pieCoast(city))return pieNo(tr('pie.why_pad_city'));if(P.pads.some(p=>p.city===city)||P.pads.length>=PIE_PAD_MAX)return; + if(!pieSpend(piePrice(PIE_PAD)))return pieRe();P.pads.push({city,next:S.day,boosters:[]});toast(tr('pie.t_pad',{city:CITY[city].name,p:pct(pieEq(city))}),'good');pieRe();}, + pieRd:({k})=>{const P=pieGet();if(!P||!P.co||!own(PIE_RD,k)||P.rd[k])return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));if(!pieSpend(piePrice(PIE_RD[k].cost)))return pieRe(); + P.rd[k]=true;toast(tr('pie.t_rd',{rd:tr(PIE_RD[k].n)}),'good');if(k==='heavy')piePromise();pieRe();}, + pieLaunch:({rk,cr})=>{const P=pieGet();if(!P)return;const o={ins:!!UI.pieIns,las:!!UI.pieLas},q=pieQuote(rk,cr,o);if(!q.ok)return pieNo(q.why);if(!pieSpend(q.cost))return pieRe(); + const pad=P.pads.find(p=>p.city===q.pad);pad.next=q.day+leadDays(ROCKETS[rk].gap);if(rk==='again'&&!pad.boosters.length)pad.boosters.push({id:uid(),flights:0}); + P.stock=Math.max(0,P.stock-q.n);P.crusts[cr].queued+=q.n;P.q.push({id:uid(),rk,cr,pad:q.pad,n:q.n,day:q.day,cost:q.ins?q.insured:0,ins:q.ins,las:o.las&&!q.test,test:q.test});pieGrabUse(q); + {const v={n:q.n,crust:tr(CRUSTS[cr].n),city:CITY[q.pad].name,d:dateStr(q.day)};toast(q.test?tr('pie.t_queued_test',v):tr('pie.t_queued',v),'good');}pieRe();}, + pieIns:()=>{UI.pieIns=!UI.pieIns;sfx('click');pieModal();}, + pieLas:()=>{UI.pieLas=!UI.pieLas;sfx('click');pieModal();}, + pieDish:({city})=>{const P=pieGet();if(!P||!P.co||!isCity(city))return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));if(!S.pops[city])return pieNo(tr('pie.why_dish_city')); + if(P.dishes.some(x=>x.city===city)||P.dishes.length>=PIE_DISH_MAX)return;if(!pieSpend(piePrice(PIE_DISH+PIE_ANT)))return pieRe(); + P.dishes.push({id:uid(),city,ant:1,down:0});if(P.dishes.length===1)pieFounder(N_('pie.fp_dish'));toast(tr('pie.t_dish',{city:CITY[city].name}),'good');pieRe();}, + pieAnt:({id})=>{const P=pieGet();const x=P&&P.dishes.find(d=>d.id===id);if(!x||x.ant>=PIE_ANT_MAX)return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));if(!pieSpend(piePrice(PIE_ANT)))return pieRe();x.ant++;pieRe();}, + // Landing rights: bought for a year, renewed for another from whenever they run out. + pieLic:({cc})=>{const P=pieGet();if(!P||!P.co||typeof cc!=='string'||!CITIES.some(c=>c.cc===cc))return;const l=P.lic[cc];if(l&&l.state!=='ok'&&l.until>S.day)return pieNo(tr('pie.why_lic_refused')); + if(!pieSpend(pieLicPrice(cc)))return pieRe();P.lic[cc]={state:'ok',until:Math.max(S.day,l&&l.state==='ok'?l.until:0)+PIE_LIC_DAYS};toast(tr('pie.t_lic',{n:pieLicCountry(cc)}),'good');pieRe();}, + pieSafe:()=>{const P=pieGet();if(!P||!P.co)return;P.safe=!P.safe;sfx('click');pieRe();}, + pieName:()=>{const P=pieGet();if(!P||!P.co)return;const i=PIE_NAMES.indexOf(P.co.name);P.co.name=PIE_NAMES[(i+1)%PIE_NAMES.length];pieFounder(N_('pie.fp_rename'));pieRe();}, + // name: the new name as an argument (a server runs this without the field), else the field's. + pieRename:({name}={})=>{const P=pieGet(),el=$('pieNm'),raw=typeof name==='string'?name:el?el.value:null;if(!P||!P.co||raw===null)return;const v=raw.replace(/\s+/g,' ').trim().slice(0,40);if(!v)return;P.co.name=v;pieFounder(N_('pie.fp_rename'));pieRe();}, + // Government money (60-features/99-pie-subsidies.js): its section in the bank, a bid, the Ex-Im loan. It was Pie Control's Gov tab; the name stays for old toasts. + pieGovOpen:()=>{if(!S||pzOn()||!pieOn())return;if(!$('modal').hidden)closeModal();ACT.bank();const g=$('bankGov');if(g&&g.scrollIntoView)g.scrollIntoView({block:'start'});}, + pieBid:({id,f})=>{const P=pieGet();f=+f;const a=P&&P.gov.auc.find(x=>x.id===id);if(!a||!PIE_RDF_BIDS.includes(f))return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1')); + a.bid=f;toast(tr('pie_gov.t_bid',{city:esc(CITY[a.city].name),mo:fmt$(Math.round(a.ask*f)),d:dateStr(a.close)}),'good');sfx('click');pieRe();}, + pieExim:()=>{const P=pieGet();if(!P||!P.co)return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));if(!pieEximTake())return pieRe(); + const l=pieEximLoan();toast(`${tr('interface.amt_from_bank_has_landed',{amt:fmt$(l.amount),bank:esc(BANKS.exim.name)})}
${loanSummary(l)}`,'good');sfx('coin');pieRe();}, + pieTab:({t})=>{if(t==='gov')return ACT.pieGovOpen();if(!PIE_TABS.includes(t)&&t!=='book'&&t!=='founder')return;UI.pieTab=pieTabOf(t);pieModal();}, + pieHi:({id})=>{if(typeof id!=='string')return;sfx('click');pieHiSet(id);}, + pieCity:({v})=>{if(!S||!S.pops[v])return;UI.pieCity=v;pieModal();}, +}); diff --git a/src/game/90-actions/98-pie-globe.js b/src/game/90-actions/98-pie-globe.js new file mode 100644 index 0000000..281bd31 --- /dev/null +++ b/src/game/90-actions/98-pie-globe.js @@ -0,0 +1,4 @@ +// The Pie Control globe's day/night switch (96-map/89-pie-globe.js). Display only: nothing in the save changes. +Object.assign(ACT,{ + pieGlobeNight:()=>{pieGlobeNight(!PG.night);}, +}); diff --git a/src/game/90-actions/98-pie-spats.js b/src/game/90-actions/98-pie-spats.js new file mode 100644 index 0000000..298da7f --- /dev/null +++ b/src/game/90-actions/98-pie-spats.js @@ -0,0 +1,7 @@ +// Pie in the Sky: answering a geopolitical spat (85-incidents/65-pie-spats.js). Answers work while Tier 1 is lost too: +// diplomacy is not building. +Object.assign(ACT,{ + pieSpatOpen:({id})=>{if(!S||!S.pie||typeof id!=='string'||!own(PIE_SPAT_DEF,id)||!S.pie.spat[id])return;pieSpatSheet(id);}, + pieSpatPick:({id,c})=>{const P=S&&S.pie;c=+c;if(!P||typeof id!=='string'||!own(PIE_SPAT_DEF,id)||!(c===0||c===1))return; + if(!pieSpatChoose(id,c,false)){if(P.spat[id])pieSpatSheet(id);return;}closeModal();after();}, +}); diff --git a/src/game/91-save.js b/src/game/91-save.js new file mode 100644 index 0000000..b3b2983 --- /dev/null +++ b/src/game/91-save.js @@ -0,0 +1,100 @@ +/* ================= SAVE ================= */ +/* A network too big for the browser's storage fails to save every time, and turning it into text takes a + moment on huge saves, every 5 seconds and after every click. After a failure the autosave waits before trying + again (1 minute, then 2, 4, at most 5); leaving the page, exporting or another game (a new S) still try at once. */ +/* A puzzle is never saved: only its stars are, under their own key (sot-puzzles). While one runs, the network it set + aside (UI.pzKeep) is the one saved, to its own slot, so closing the tab mid-puzzle loses nothing. */ +function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot; + // Half a day (its routing still in the worker) is never saved: the day's end saves instead. + if(RW.job&&st===S){UI.saveDue=true;UI.lastSave=performance.now();return;} + if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return; + // A locked clock's speed is not the player's: the one they left the game at stays saved. + if(st===S){if(!UI.clockLocked)S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st; + if(!force&&failed&&performance.now()-f.at0)return; + /* A big network that moved on since its last save cannot be the same text: the route worker packs it, turns it into + text and compresses it (rwSave()); the page only copies the game over and writes what comes back. Not a network in a + multiplayer session: its text is made here (mpSave()), so the server gets the very save this slot holds. */ + if(!force&&!failed&&st===S&&!(MP_API&&S.mp)&&SLOT.day[id]!==undefined&&SLOT.day[id]!==st.day&&((SLOT.txt[id]||'').length>=GZ_BG||SLOT.big[id])&&gzOk()){ + const seq=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,p=rwSave(st,seq); + if(p){SLOT.top[id]=seq;let tier=null;try{tier=tierLabel();}catch(e){}gzSave({id,s:st,txt:null,seq,day:st.day,meta:slotMeta(st,tier),p});return;}} + // A network in a multiplayer session: the server keeps a copy too (60-features/89-multiplayer.js). + const txt=MP_API&&st===S&&S.mp?mpSave(st):JSON.stringify(packSave(st)); + // The very text the slot already holds (a paused game, nothing changed): writing a big network to storage costs more + // than turning it into text, every 5 seconds, for nothing. Unless a write is still on its way, or the page is closing. + if(!force&&!failed&&SLOT.txt[id]===txt&&(SLOT.top[id]||0)===(SLOT.sq[id]||0))return; + let tier=null;if(st===S)try{tier=tierLabel();}catch(e){} + const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,day:st.day,meta:slotMeta(st,tier)}; + if(gzOk()&&(txt.length>=GZ_MIN||!force&&txt.length>=GZ_BG&&rwOn()))gzSave(j);else slotPut(j,slotStamp(txt,seq));} +function saveErr(e,s){const f=UI.saveFail,again=f&&f.s===s;UI.saveFail={s,at:performance.now(),wait:again?Math.min(300000,f.wait*2):60000,full:saveFull(e)}; + // Say so once per game (#176): a save that silently fails loses everything since the last one that worked. + if(!again&&(s===S||s===UI.pzKeep))toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}},...(UI.saveFail.full&&slotOthers().length?[{l:tr('slots.free_up_space'),act:'slotSpace',args:{}}]:[])]);} +/* Saves of huge networks are gzipped by the browser (#176): about ten times smaller, so they fit in its storage. + Compressing runs in the background, one at a time, and the newest save of each network wins; one that a newer save + of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. + From GZ_BG up, the autosave is compressed too when the route worker does it: writing that much plain text held the + page longer than everything else in a save (a save as the page closes stays plain below GZ_MIN: at once). */ +const GZ='gz:',GZ_MIN=1e6,GZ_BG=2e5,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function'; +async function gzPipe(bytes,stream){const w=stream.writable.getWriter(),no=()=>{};w.write(bytes).catch(no);w.close().catch(no);// a bad stream is reported by read() below + const r=stream.readable.getReader(),parts=[];let n=0; + for(;;){const {done,value}=await r.read();if(done)break;parts.push(value);n+=value.length;} + const out=new Uint8Array(n);let o=0;for(const p of parts){out.set(p,o);o+=p.length;}return out;} +const b64=u=>{let s='';for(let i=0;i{const s=atob(t),u=new Uint8Array(s.length);for(let i=0;ib64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip'))); +const gzip=async txt=>GZ+await (rwGzip(txt)||gzB64(txt)); +const gunzip=async raw=>new TextDecoder().decode(await gzPipe(unb64(raw.slice(GZ.length)),new DecompressionStream('gzip'))); +// Jobs carry their slot, not the game object: a save still compressing lands in its own network whatever S is by then. +function gzSave(j){if(UI.gzBusy){SLOT.gzQ.set(j.id,j);return;}UI.gzBusy=true; + (j.p?j.p.then(r=>{j.txt=r.txt;return r.data;}):gzip(slotStamp(j.txt,j.seq))).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);}) + .catch(e=>{console.error('[tubes] compressing the save failed',e);}) + .finally(()=>{UI.gzBusy=false;const n=SLOT.gzQ.values().next().value;if(n){SLOT.gzQ.delete(n.id);gzSave(n);}else slotIdle();});} +/* Big networks are mostly customers, and most of a customer record was defaults (#176): no second city, no + requirements, the normal route, no warnings yet. The save leaves defaults out and sanitize() puts them back, so + the game after loading is the same; older versions read a missing field as its default too. An alien wave's + description is rebuilt from its fiber. */ +const BIZ_DEF={city2:null,latMax:null,route:'normal',sites:null,slots:0,warned:false,warn60:false}; +function packBiz(b){const o={};for(const k in b){const v=b[k];if(v===undefined||BIZ_DEF[k]===v||(k==='reqs'&&Array.isArray(v)&&!v.length)||(k==='pm'&&v===b.mood)||(k==='what'&&b.type==='wwave'&&b.link))continue;o[k]=v;}return o;} +function unpackBiz(b,links){for(const k in BIZ_DEF)if(!(k in b))b[k]=BIZ_DEF[k];if(!('pm' in b)&&b.mood!==undefined)b.pm=b.mood;if(!Array.isArray(b.reqs))b.reqs=[]; + if(b.type==='wwave'&&b.what===undefined){const l=links.get(b.link);b.what=l?wwWhat(l,b.slots||1):'';}return b;} +// sv (the slot's save stamp) is added when the text is written, never carried in the game. +const packSave=s=>({...s,sv:undefined,biz:s.biz.map(packBiz)}); +// Out of room (quota) or not allowed to store at all (private window, blocked site data): different advice. +const saveFull=e=>!!e&&(e.name==='QuotaExceededError'||e.name==='NS_ERROR_DOM_QUOTA_REACHED'||e.code===22||e.code===1014); +const saveFailing=()=>!!(UI.saveFail&&UI.saveFail.s===S); +const saveFailMsg=()=>UI.saveFail&&UI.saveFail.full?tr('save.your_network_is_too_big_to'):tr('save.this_browser_is_not_letting_the'); +// Save whenever the player might be leaving: tab hidden, page closing or reloading. +addEventListener('pagehide',()=>save(true)); +document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden')save(true);else checkUpdate();}); +/* Export / import: move a network to another device or keep a backup. The file is the same + object the autosave writes, wrapped with a little metadata. */ +function saveFileName(nm){const d=new Date().toISOString().slice(0,10),n=String(nm||'network').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'network';return `series-of-tubes-${n}-${d}.json`;} +function saveDl(txt,nm){const blob=new Blob([txt],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=saveFileName(nm);document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000); + toast(tr('save.save_exported_file_is_in_your',{file:esc(saveFileName(nm))}),'good');} +function exportSave(){if(!S||S.mode==='puzzle')return;save(true);saveDl(JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S:packSave(S)},null,1),S.name);} +// Any network on this device, straight from storage: the file wraps the saved text as it is, without loading it. +function exportSlot(id){const e=slotIdx().find(x=>x.id===id),raw=slotRaw(id);if(!e||raw==null)return; + if(id===UI.slot&&S&&!pzOn()){exportSave();return;} + (raw.startsWith(GZ)?gunzip(raw):Promise.resolve(raw)).then(t=>saveDl(`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},"exported":"${new Date().toISOString()}","S":${t}}`,e.name),()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));} +function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_is_not_valid_json')};let j;try{j=JSON.parse(txt);}catch(e){return {err:tr('save.that_file_is_not_valid_json')};} + const s=j&&j.app==='series-of-tubes'&&j.S?j.S:j; + if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links))return {err:tr('save.that_does_not_look_like_a')}; + if(s.lost)return {err:tr('save.that_network_went_bankrupt_it_cannot')}; + for(const c of Object.keys(s.pops))if(!isCity(c))return {err:tr('save.that_save_has_a_pop_in',{city:esc(String(c).slice(0,12))})}; + return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network'))};} +function importFile(file){if(!file)return;if(file.size>64e6){toast(tr('save.that_file_is_too_big_to'),'bad');return;} + const rd=new FileReader();rd.onload=()=>{const r=parseSave(String(rd.result));if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;} + importAsk(r);}; + rd.readAsText(file);} +// A save from a file or a transfer link (#263), checked by parseSave(): what it is, and whether to load it. +function importAsk(r){UI.importing=r.s;openModal(`
${tr('common.import_a_save')}

${tr('save.load_name',{name:esc(r.name)})}

${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}

${tr('slots.it_joins_your_networks_on_this')}

${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}
`);} +// This window's network, read synchronously (a compressed one was unpacked before boot). UI.loadBad: there, but unreadable. +function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null; + try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){} + UI.loadBad=true;return null;} +// What a network says once when it is opened again: new networks on the map (the courtesy route), Australia's prices. +// Boot calls it; a server-run network hears it from the server instead (it changes S). +function bootNotes(){if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);} + if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}} diff --git a/src/game/91-slots.js b/src/game/91-slots.js new file mode 100644 index 0000000..f607bda --- /dev/null +++ b/src/game/91-slots.js @@ -0,0 +1,166 @@ +/* ================= SAVE SLOTS ================= + Several networks per browser, one per window. Each network (a slot) is its own key, sot-save-v1:, plain JSON or + gzipped exactly like the old single save. A small index (sot-slots) describes them for the title screen, so listing + them never reads a save. A write goes to the slot first and to the index after, so the index never points at a save + that is not there yet; each write carries a sequence number (in the save and in its index entry), and a window never + writes over a newer one that another window saved. Each tab keeps its slot in sessionStorage: a reload continues it. + Only one window plays a slot at a time: a Web Lock where the browser has them, else a heartbeat key, sot-open:. */ +const SLOT_K='sot-save-v1:',SLOT_IX='sot-slots',SLOT_OLD='sot-save-v1',SLOT_HB='sot-open:',SLOT_SS='sot-slot',SLOT_MAIN='main'; +// txt: the text of each slot's last save that landed, before its stamp. +const SLOT={sq:{},top:{},txt:{},day:{},big:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''}; +function slotRid(){try{const a=new Uint32Array(2);crypto.getRandomValues(a);return (a[0].toString(36)+a[1].toString(36)).slice(0,10);}catch(e){return (Date.now().toString(36)+(uidN++).toString(36)).slice(-10);}} +const WIN=slotRid();// this page load; a reload is a new window that takes its tab's slot back +const lsGet=k=>{try{return localStorage.getItem(k);}catch(e){return null;}}; +const lsDel=k=>{try{localStorage.removeItem(k);}catch(e){}}; +const ssGet=k=>{try{return sessionStorage.getItem(k);}catch(e){return null;}}; +const ssSet=(k,v)=>{try{if(v==null)sessionStorage.removeItem(k);else sessionStorage.setItem(k,v);}catch(e){}}; +const slotOkId=id=>typeof id==='string'&&/^[a-z0-9]{1,24}$/.test(id); +const slotRaw=id=>slotOkId(id)?lsGet(SLOT_K+id)??(id===SLOT_MAIN?lsGet(SLOT_OLD):null):null; +// ---------- the index: read like a save, never trusted ---------- +function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null; + return {id:e.id,name:String(e.name==null?'':e.name).slice(0,24),asn:int(e.asn,0,4294967294,0),mode:['normal','sandbox','scenario'].includes(e.mode)?e.mode:'normal', + preset:typeof e.preset==='string'&&own(PRESETS,e.preset)?e.preset:'oncall',scn:typeof e.scn==='string'?e.scn.slice(0,60):null,day:int(e.day,0,1e7,0), + tier:['Tier 1','Tier 2','Tier 3'].includes(e.tier)?e.tier:null,cash:num(e.cash,0),at:num(e.at,0),size:int(e.size,0,1e10,0),seq:int(e.seq,0,1e15,0),gz:!!e.gz, + // A save marked damaged (bv: the game version that could not load it) is tried again by the next version: the fault is + // usually in the game, and the save itself is fine once it is fixed. + ...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false}), + // A network in a multiplayer session: ., so a link from another device finds it again. + ...(typeof e.mp==='string'&&/^[0-9A-HJKMNP-TV-Z]{6}\.[a-z0-9]{8}$/.test(e.mp)?{mp:e.mp}:{})};} +// mp is always there (null outside a session), so a network that left its session loses its badge in the list. +const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier,mp:s.mp&&s.mp.code?s.mp.code+'.'+s.mp.pid:null}); +function slotKeys(){const out=[];try{for(let i=0;i({...e})); + if(raw!=null)try{const j=JSON.parse(raw);if(j&&Array.isArray(j.slots))list=j.slots.map(slotClean).filter(Boolean);}catch(e){} + const bad=raw!=null&&!list;if(!list)list=[];{const seen=new Set();list=list.filter(e=>!seen.has(e.id)&&seen.add(e.id));} + if(scan||bad){const ks=slotKeys(),keys=new Set(ks);let ch=bad;const n=list.length; + if(ks.old&&list.some(e=>e.id===SLOT_MAIN))keys.add(SLOT_MAIN); + list=list.filter(e=>keys.has(e.id));if(list.length!==n)ch=true; + for(const id of keys)if(!list.some(e=>e.id===id)){list.push(slotFromKey(id));ch=true;} + if(ch)slotIdxPut(list);if(list.some(e=>e.gz&&!e.name&&!e.broken))slotFix(list);} + else if(raw!=null&&list.length){SLOT.ixRaw=raw;SLOT.ixList=list.map(e=>({...e}));} + return list;} +function slotIdxPut(list){const t=JSON.stringify({v:1,slots:list});try{localStorage.setItem(SLOT_IX,t);SLOT.ixRaw=t;SLOT.ixList=list.map(e=>({...e}));return true;}catch(e){SLOT.ixRaw=null;return false;}} +function slotFix(list){for(const e of list)if(e.gz&&!e.name&&!e.broken&&!SLOT['fix'+e.id]){SLOT['fix'+e.id]=1;const raw=slotRaw(e.id); + gunzip(raw).then(t=>{const s=JSON.parse(t);return s&&s.v===1?slotMeta(s,null):null;},()=>null).then(m=>{const l=slotIdx(),x=l.find(y=>y.id===e.id);if(!x)return; + if(m){const c=slotClean({...x,...m});if(!c.mp)delete x.mp;Object.assign(x,c);}else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}} +const slotByAt=l=>l.slice().sort((a,b)=>b.at-a.at); +// ---------- one writer per slot ---------- +// The heartbeat: who has a slot open, refreshed every few seconds. A hidden tab's timers can be slowed to once a +// minute, so it counts for longer. Tabs remove theirs when they close; a crashed one goes stale. +function slotHb(id){try{const h=JSON.parse(lsGet(SLOT_HB+id));return h&&typeof h.w==='string'&&isFinite(h.t)?h:null;}catch(e){return null;}} +const slotBusy=id=>{const h=slotHb(id);return !!h&&h.w!==WIN&&Date.now()-h.t<(h.h?180000:20000);}; +function slotBeat(){const id=UI.slot;if(!id)return;const h=slotHb(id); + // Without Web Locks the heartbeat is the lock: a fresh one from another window means it took over. + if(h&&h.w!==WIN&&!SLOT.locks.has(id)&&Date.now()-h.t<20000){slotLost(id,'take');return;} + try{localStorage.setItem(SLOT_HB+id,JSON.stringify({w:WIN,t:Date.now(),h:document.visibilityState==='hidden'?1:0}));}catch(e){}} +function slotUnbeat(id){const h=slotHb(id);if(h&&h.w===WIN)lsDel(SLOT_HB+id);} +const LOCKS=()=>{try{const l=navigator.locks;return l&&typeof l.request==='function'?l:null;}catch(e){return null;}}; +// cb(true) when this window may play the slot, cb(false) when another window has it. steal takes it over. +function slotClaim(id,steal,cb,n=4){const once=v=>{try{cb(v);}catch(e){console.error('[tubes] opening a network failed',e);}}; + if(SLOT.locks.has(id)){slotBeatFor(id);once(true);return;} + const L=LOCKS(); + if(L){let got=false; + L.request('sot-slot:'+id,steal?{steal:true}:{ifAvailable:true},lock=>{if(!lock){if(n>0&&(SLOT.rel.has(id)||!slotBusy(id)))setTimeout(()=>slotClaim(id,steal,cb,n-1),120);else once(false);return;}got=true;SLOT.rel.delete(id); + return new Promise(r=>{SLOT.locks.set(id,r);slotBeatFor(id);once(true);});}) + .catch(()=>{SLOT.locks.delete(id);if(got)slotLost(id,'take');});// stolen: another window took over + return;} + if(!steal&&slotBusy(id)){once(false);return;} + slotBeatFor(id);once(true);} +function slotBeatFor(id){try{localStorage.setItem(SLOT_HB+id,JSON.stringify({w:WIN,t:Date.now(),h:0}));}catch(e){}} +function slotFree(id){if(UI.slot===id)return;slotUnbeat(id);const r=SLOT.locks.get(id);SLOT.locks.delete(id);if(r){SLOT.rel.add(id);r();}} +// Saves still compressing land before a slot is handed back. +function whenIdle(f){if(!UI.gzBusy&&!SLOT.gzQ.size)f();else SLOT.idle.push(f);} +function slotIdle(){if(UI.gzBusy||SLOT.gzQ.size)return;const l=SLOT.idle.splice(0);for(const f of l)try{f();}catch(e){console.error(e);}} +// ---------- writing ---------- +// The sequence number rides along in the save, appended to the text (no second stringify). +const slotStamp=(txt,seq)=>txt.slice(0,-1)+',"sv":{"seq":'+seq+',"at":'+Date.now()+'}}'; +// Throws when the browser refuses (quota): save() reports it. Returns false when it must not write. +function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false; + const list=slotIdx(),ent=list.find(e=>e.id===id); + if(ent&&ent.seq>(SLOT.sq[id]||0)){slotLost(id,'newer');return false;} + let k=SLOT_K+id; + try{localStorage.setItem(k,data);} + catch(e){// A migrated save the browser has no room to copy keeps living in the old key, as it always did. + if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;} + if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed + SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq);SLOT.txt[id]=j.txt;SLOT.day[id]=j.day; + const e=ent||{id};if(!ent)list.push(e);const c=slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false});if(!c.mp)delete e.mp;Object.assign(e,c); + slotIdxPut(list);return true;} +function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}} +// ---------- opening, leaving, losing ---------- +function slotIn(id,sv){const e=slotIdx().find(x=>x.id===id);UI.slot=id;ssSet(SLOT_SS,id);SLOT.no.delete(id);SLOT.top[id]=0;delete SLOT.txt[id]; + // The day the slot holds, and whether it is big (compressed, or long): the first save that moves on goes to the worker. + {const raw=slotRaw(id);SLOT.day[id]=S?S.day:undefined;SLOT.big[id]=!!raw&&(raw.startsWith(GZ)||raw.length>=GZ_BG);} + SLOT.sq[id]=Math.max(sv&&isFinite(sv.seq)?+sv.seq:0,e?e.seq:0);} +function slotNew(){const id=slotRid();UI.slot=id;ssSet(SLOT_SS,id);SLOT.sq[id]=0;SLOT.no.delete(id);slotClaim(id,true,()=>{});return id;} +// Leave this window's network (saved first); the slot is free for other windows once its last save has landed. +function slotLeave(){const id=UI.slot;if(!id)return;save(true);UI.slot=null;UI.pzKeep=null;ssSet(SLOT_SS,null);whenIdle(()=>slotFree(id));} +// Read a slot and play it. A save that cannot be read or loaded is marked damaged and kept, so it can still be exported. +function slotOpen(id,steal,done){if(!slotIdx(true).some(e=>e.id===id)){showTitle();toast(tr('slots.that_network_is_gone'),'bad');return;} + slotClaim(id,!!steal,ok=>{if(!ok){slotBusyModal(id);return;} + const go=t=>{let s=null;try{s=JSON.parse(t);}catch(e){} + if(!s||s.v!==1||s.lost){slotBroke(id);return;}const sv=s.sv;delete s.sv; + const prev=S;try{S=migrate(s);compute();}catch(e){console.error('[tubes] loading a network failed',e);S=prev;slotBroke(id);return;} + if(UI.slot&&UI.slot!==id){const nw=S;S=prev;slotLeave();S=nw;} + slotIn(id,sv);gameResume();if(done)done();}; + const raw=slotRaw(id);if(raw==null){slotFree(id);slotDrop(id);showTitle();toast(tr('slots.that_network_is_gone'),'bad');return;} + if(raw.startsWith(GZ)){if(raw===UI.gzRaw)go(UI.gzText);else gunzip(raw).then(go,()=>slotBroke(id));}else go(raw);});} +function slotBroke(id){const l=slotIdx(),e=l.find(x=>x.id===id);if(e){e.broken=true;e.bv=APP_VERSION;slotIdxPut(l);} + if(UI.slot===id){UI.slot=null;ssSet(SLOT_SS,null);}slotFree(id); + S=null;R=emptyR();UI.started=false;UI.sel=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();toast(tr('loop.your_saved_game_could_not_be'),'bad');} +function slotDrop(id){if(!slotOkId(id))return;SLOT.no.add(id);lsDel(SLOT_K+id);if(id===SLOT_MAIN)lsDel(SLOT_OLD);slotUnbeat(id); + const l=slotIdx();slotIdxPut(l.filter(e=>e.id!==id));if(UI.slot===id){UI.slot=null;ssSet(SLOT_SS,null);}} +/* Another window took this network over, or saved a newer version of it: this one stops writing and says so calmly. */ +function slotLost(id,why){if(UI.slot!==id)return;SLOT.no.add(id);UI.slot=null;ssSet(SLOT_SS,null);SLOT.gzQ.delete(id);if(why==='gone')slotUnbeat(id); + const r=SLOT.locks.get(id);SLOT.locks.delete(id);if(r)r(); + const s=pzOn()?UI.pzKeep:S,name=s?s.name:''; + if(pzOn()){UI.pzKeep=null;UI.pzFrom='title';toast(tr('slots.name_moved_to_another_window_toast',{name:esc(name)}),'bad');return;} + gameClear();if(why==='gone'){showTitle();toast(tr('slots.name_was_deleted_in_another_window',{name:esc(name)}),'bad');}else slotLostModal(id,name,why);} +// ---------- the legacy single save becomes the first slot ---------- +/* Read old, write new, read it back, then add it to the index. The old key stays as a fallback until the slot's next + save lands; if the browser has no room for a copy, the network keeps living in the old key (slotRaw reads it). */ +function slotMigrate(cb){const raw=lsGet(SLOT_OLD); + if(raw==null||slotIdx(true).some(e=>e.id===SLOT_MAIN)){cb();return;} + const done=s=>{if(s&&s.lost){cb();return;} + let ok=false;try{localStorage.setItem(SLOT_K+SLOT_MAIN,raw);ok=localStorage.getItem(SLOT_K+SLOT_MAIN)===raw;}catch(e){} + if(!ok)lsDel(SLOT_K+SLOT_MAIN); + const l=slotIdx();l.push(slotClean({id:SLOT_MAIN,...(s?slotMeta(s,null):{}),seq:0,at:Date.now(),size:raw.length,gz:raw.startsWith(GZ),broken:!s,bv:APP_VERSION}));slotIdxPut(l);if(!s)UI.bootBroken=true;cb();}; + if(!raw.startsWith(GZ)){let s=null;try{s=JSON.parse(raw);}catch(e){}done(s&&s.v===1?s:null);return;} + if(!gzOk()){done(null);return;} + gunzip(raw).then(t=>{UI.gzRaw=raw;UI.gzText=t;let s=null;try{s=JSON.parse(t);}catch(e){}done(s&&s.v===1?s:null);},()=>done(null));} +/* Before the game boots: migrate, then pick this tab's network. A reload continues the tab's own slot; a new tab with + exactly one network continues it as before; with more, the title screen lists them. A compressed save is unpacked + here, so loadSave() stays synchronous for everything else. */ +function slotBoot(go){slotMigrate(()=>{const list=slotIdx(true),mine=ssGet(SLOT_SS); + let id=list.some(e=>e.id===mine&&!e.broken)?mine:null;if(!id&&mine)ssSet(SLOT_SS,null); + const auto=!id&&list.length===1&&!list[0].broken&&!slotBusy(list[0].id)?list[0].id:null; + if(!id&&!auto){go();return;} + slotClaim(id||auto,false,ok=>{const w=id||auto; + if(!ok){if(id){ssSet(SLOT_SS,null);UI.bootBusy=id;}go();return;} + UI.slot=w;const raw=slotRaw(w); + if(raw&&raw.startsWith(GZ)&&raw!==UI.gzRaw){if(!gzOk()){go();return;}gunzip(raw).then(t=>{UI.gzRaw=raw;UI.gzText=t;go();},e=>{console.error('[tubes] unpacking the save failed',e);go();});} + else go();});});} +// ---------- other windows ---------- +const BC=(()=>{try{return typeof BroadcastChannel==='function'?new BroadcastChannel('sot-slots'):null;}catch(e){return null;}})(); +if(BC)BC.onmessage=({data:m})=>{if(!m||typeof m!=='object'||!slotOkId(m.id))return; + if(m.t==='focus'&&UI.slot===m.id){try{window.focus();}catch(e){}toast(tr('slots.here_it_is_name',{name:esc(S?S.name:'')}),'goal');} + // Asked to hand over: save what we have, wait for it to land, then step aside and say so. + if(m.t==='take'&&UI.slot===m.id){save(true);whenIdle(()=>{slotLost(m.id,'take');try{BC.postMessage({t:'gave',id:m.id});}catch(e){}});} + if(m.t==='gave'&&SLOT.wait&&SLOT.wait.id===m.id)SLOT.wait.go(); + if(m.t==='gone')slotLost(m.id,'gone');}; +addEventListener('storage',e=>{const k=e.key;if(!k)return;const id=UI.slot; + if(id&&k===SLOT_HB+id&&e.newValue){let h=null;try{h=JSON.parse(e.newValue);}catch(_){}if(h&&h.w!==WIN)slotLost(id,'take');} + else if(id&&k===SLOT_K+id&&e.newValue==null)slotLost(id,'gone');// deleted in another window: never written back + else if(id&&k===SLOT_IX){const x=slotIdx().find(y=>y.id===id);if(x&&x.seq>(SLOT.sq[id]||0))slotLost(id,'newer');} + if(k===SLOT_IX||k.startsWith(SLOT_HB))slotRefresh();}); +addEventListener('pagehide',()=>{if(UI.slot)slotUnbeat(UI.slot);}); +addEventListener('pageshow',e=>{if(e.persisted)slotBeat();}); +if(!window.__TUBES_TEST__)setInterval(slotBeat,5000); diff --git a/src/game/92-audio.js b/src/game/92-audio.js new file mode 100644 index 0000000..fd041d5 --- /dev/null +++ b/src/game/92-audio.js @@ -0,0 +1,14 @@ +/* ================= AUDIO ================= */ +let AC=null; +function audioInit(){if(AC)return;try{AC=new (window.AudioContext||window.webkitAudioContext)();}catch(e){}} +function tone(f,t0,dur,type='square',vol=.05){if(!AC)return;const o=AC.createOscillator(),g=AC.createGain();o.type=type;o.frequency.value=f;g.gain.setValueAtTime(vol,AC.currentTime+t0);g.gain.exponentialRampToValueAtTime(.0001,AC.currentTime+t0+dur);o.connect(g).connect(AC.destination);o.start(AC.currentTime+t0);o.stop(AC.currentTime+t0+dur+.02);} +function sfx(k){if(UI.muted||!AC)return;try{ + if(k==='coin'){tone(988,0,.08);tone(1319,.08,.18);} + else if(k==='build'){tone(523,0,.07,'triangle',.08);tone(784,.06,.12,'triangle',.08);} + else if(k==='err'){tone(180,0,.18,'sawtooth',.04);} + else if(k==='alert'){tone(880,0,.1,'square',.04);tone(660,.12,.1,'square',.04);tone(880,.24,.12,'square',.04);} + else if(k==='star'){tone(784,0,.09,'triangle',.07);tone(1175,.08,.2,'triangle',.07);} + else if(k==='fanfare'){tone(523,0,.12,'triangle',.07);tone(659,.12,.12,'triangle',.07);tone(784,.24,.12,'triangle',.07);tone(1047,.36,.35,'triangle',.08);} + else if(k==='click'){tone(660,0,.04,'triangle',.05);} +}catch(e){}} + diff --git a/src/game/93-ui/10-dom.js b/src/game/93-ui/10-dom.js new file mode 100644 index 0000000..d747df7 --- /dev/null +++ b/src/game/93-ui/10-dom.js @@ -0,0 +1,27 @@ +/* ================= DOM RENDER ================= */ +const $=id=>document.getElementById(id); +const btn=(label,act,args={},cls='',dis=false,title='')=>``; +const logo=n=>``; +const barCls=u=>u>=0.9?'bad':u>=0.65?'warn':''; +/* Panels are rebuilt from state every tick. Replacing a thousand rows makes the browser style and lay out every one + of them again, so patch what changed instead: same HTML, far less work. A button that now does something else, and + any form field that changed, is swapped out whole, so a tap that started on the old one still cannot fire it (#44). */ +const SWAP={INPUT:1,SELECT:1,TEXTAREA:1,OPTION:1}; +function morph(el,html){const t=document.createElement(el.tagName);t.innerHTML=html;morphKids(el,t);} +function sameNode(x,y){if(x.nodeType!==y.nodeType||x.nodeName!==y.nodeName)return false;if(x.nodeType!==1)return true; + if(SWAP[x.nodeName])return x.outerHTML===y.outerHTML; + return x.getAttribute('data-act')===y.getAttribute('data-act')&&x.getAttribute('data-args')===y.getAttribute('data-args');} +function morphKids(a,b){let x=a.firstChild,y=b.firstChild; + while(y){const ny=y.nextSibling; + if(!x)a.appendChild(y); + else if(!sameNode(x,y)){a.replaceChild(y,x);x=y;} + else if(x.nodeType===1){if(!SWAP[x.nodeName]){const ya=y.attributes,xa=x.attributes; + for(let i=0;i=0;i--)if(!y.hasAttribute(xa[i].name))x.removeAttribute(xa[i].name); + morphKids(x,y);}} + else if(x.nodeValue!==y.nodeValue)x.nodeValue=y.nodeValue; + x=x&&x.nextSibling;y=ny;} + while(x){const nx=x.nextSibling;a.removeChild(x);x=nx;}} +function renderAll(){if(isTablet()&&!UI.sel)UI.leftOpen=false;renderHUD();renderLeft();renderPanel();renderHint();renderMega();renderCoach();pzRender();routingRefresh();if(S)charterAsk();} +function renderMega(){const el=$('mega');if(!el)return;const on=!!(S&&S.ev&&S.ev.php>S.day);if(el.hidden===!on)return;el.hidden=!on;} + diff --git a/src/game/93-ui/15-theme.js b/src/game/93-ui/15-theme.js new file mode 100644 index 0000000..c081ce1 --- /dev/null +++ b/src/game/93-ui/15-theme.js @@ -0,0 +1,27 @@ +/* ---------- Light or dark (#80) ---------- + Settings › Theme: Auto follows the device's light or dark setting, or the player picks one. A choice per device + (localStorage sot-theme, like the animation and map settings), not part of the save. The page's reads it and + sets before the first paint, so a dark screen never flashes light; this keeps it in step when the + choice or the device's setting changes. The panels follow at once (CSS custom properties, 00-base.css); the map + keeps pictures painted in the old colours, so it paints them again, once (themeRepaint()). */ +const THEME_OPTS=['auto','light','dark'],THEME_BAR={light:'#57C4E5',dark:'#0E2A44'}; // the browser bar: --sea +const THEME={pref:'auto',dark:false,mq:null,on:null}; +function themeRead(){let v=null;try{v=localStorage.getItem('sot-theme');}catch(e){}return THEME_OPTS.includes(v)?v:'auto';} +const themeSys=()=>{try{return !!(THEME.mq&&THEME.mq.matches);}catch(e){return false;}}; +// The page's colours from the choice (and the device's setting, on Auto). A switch repaints the map's cached pictures. +function themeApply(repaint=true){const dark=THEME.pref==='dark'||(THEME.pref==='auto'&&themeSys()),was=THEME.dark,R0=document.documentElement; + THEME.dark=dark;R0.setAttribute('data-theme',dark?'dark':'light'); + for(const [n,v] of [['theme-color',THEME_BAR[dark?'dark':'light']],['color-scheme',dark?'dark':'light']]){const m=document.querySelector(`meta[name="${n}"]`);if(m)m.setAttribute('content',v);} + if(repaint&&was!==dark)themeRepaint();return dark;} +function themePick(v){if(!THEME_OPTS.includes(v))return false;THEME.pref=v;try{v==='auto'?localStorage.removeItem('sot-theme'):localStorage.setItem('sot-theme',v);}catch(e){}themeApply();return true;} +// Reads the choice and listens to the device's setting, which Auto follows as it changes (a phone at dusk). +function themeInit(){THEME.pref=themeRead();THEME.on=()=>{if(THEME.pref==='auto')themeApply();}; + try{THEME.mq=window.matchMedia?matchMedia('(prefers-color-scheme: dark)'):null;}catch(e){} + const q=THEME.mq;if(q){try{q.addEventListener?q.addEventListener('change',THEME.on):q.addListener(THEME.on);}catch(e){}} + THEME.dark=document.documentElement.getAttribute('data-theme')==='dark';return themeApply(false);} +/* What the map painted in the old colours: the land (the 2D picture, the card's coastlines), every sprite (labels, + cities), the Pie globe unless the player chose its day or night. All painted again on the next frame, not every frame. */ +function themeRepaint(){WL.key=null;FRAME.length=0;UI.drawnAt=0;spritesReset();glLandDrop(); + let g=null;try{g=localStorage.getItem('sot-globe');}catch(e){}if(!g){PG.night=THEME.dark;PG.g=null;PG.dirty=true;}} +// Picked in another tab: this one follows, and so does the NOC window on a second screen. +if(!RW_IN){themeInit();addEventListener('storage',e=>{if(e.key==='sot-theme'||e.key===null){THEME.pref=themeRead();themeApply();}});} diff --git a/src/game/93-ui/20-phone.js b/src/game/93-ui/20-phone.js new file mode 100644 index 0000000..c97abf3 --- /dev/null +++ b/src/game/93-ui/20-phone.js @@ -0,0 +1,24 @@ +/* ================= PHONE ================= */ +const isPhone=()=>innerWidth<=760||(innerHeight<=500&&matchMedia('(pointer:coarse)').matches); +const SPEEDS=[0.5,1,2,4,8]; +function renderTabbar(){const tb=$('tabbar');if(!tb||(pressing&&UI.ticking))return;if(!isPhone()||!S||!UI.started||pzOn()){tb.hidden=true;document.body.classList.toggle('sheet-open',pzOn()&&isPhone()&&!!UI.sel);return;}tb.hidden=false; + const open=UI.leftOpen&&!UI.sel,cur=UI.left||'goals',G=goals(),ndone=G.filter(g=>S.done[g.id]!==undefined).length; + const tab=(k,ic,l,cnt,red)=>``; + // A locked clock's two buttons come from whatever locked it (HOOKS.tabbar), in the same two slots, so the tabs stay put. + const h=(rule('clock')?UI.clockLocked&&HOOKS.tabbar?HOOKS.tabbar():``+ + ``:'')+ + (()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${G.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length?' ':'',true)+tab('nets','🌐',tr('common.networks'),''); + if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;} + document.body.classList.toggle('sheet-open',!!(UI.sel||UI.leftOpen));} +function haptic(ms){if(UI.muted)return;try{navigator.vibrate&&navigator.vibrate(ms||12);}catch(e){}} +// Bottom sheets: drag the handle up to expand, down to shrink or close; tap it to toggle. +(function(){let g=null; + document.addEventListener('pointerdown',e=>{const h=e.target.closest('[data-grab]');if(!h||!isPhone()||e.target.closest('button,select,input'))return;const el=h.parentElement;g={el,y:e.clientY,dy:0,id:e.pointerId,full:el.classList.contains('full')};try{h.setPointerCapture(e.pointerId);}catch(_){}el.style.transition='none';}); + document.addEventListener('pointermove',e=>{if(!g||e.pointerId!==g.id)return;g.dy=e.clientY-g.y;if(g.dy>0)g.el.style.transform=`translateY(${g.dy}px)`;}); + const end=e=>{if(!g||e.pointerId!==g.id)return;const {el,dy,full}=g;g=null;el.style.transition='';el.style.transform=''; + if(Math.abs(dy)<6){el.classList.toggle('full');return;} + if(dy<-40){el.classList.add('full');return;} + if(dy>40){if(full){el.classList.remove('full');return;}if(el.id==='panel')ACT.closePanel();else{UI.leftOpen=false;renderLeft();}}}; + document.addEventListener('pointerup',end);document.addEventListener('pointercancel',end);})(); +// Toasts can be tapped away on touch screens. +document.addEventListener('click',e=>{const t=e.target.closest('.toast');if(t&&!e.target.closest('[data-act]')&&isPhone())t.remove();}); diff --git a/src/game/93-ui/30-install.js b/src/game/93-ui/30-install.js new file mode 100644 index 0000000..17d0f33 --- /dev/null +++ b/src/game/93-ui/30-install.js @@ -0,0 +1,23 @@ +/* ================= INSTALL (PWA) ================= */ +let installEvt=null; +addEventListener('beforeinstallprompt',e=>{e.preventDefault();installEvt=e;}); +addEventListener('appinstalled',()=>{installEvt=null;track('pwa_installed',true);if(UI.pendGame){const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;beginGame(...p);}toast(tr('install.installed_open_series_of_tubes_from'),'good');}); +const isStandalone=()=>{try{return navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches);}catch(e){return false;}}; +const isIOS=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||(navigator.platform==='MacIntel'&&navigator.maxTouchPoints>1); +function installRow(){if(isStandalone())return ''; + return `
📲 ${tr('install.best_played_as_an_app')}
${tr('install.full_screen_works_offline_one_tap')}${isIOS()?' '+tr('install.install_it_before_you_start_a'):''}
${btn(tr('common.install'),'install',{},'pink sm')}
`;} +/* Phones get a real pitch before a new game: an installed app is full screen, works offline, and on iPhone + keeps its save away from Safari's clean-ups. Storage is separate on iOS, so installing first matters. */ +const SHARE_SVG=''; +const needPitch=()=>isPhone()&&!isStandalone(); +function installSteps(){ + if(isIOS())return `
  1. ${tr('install.tap_share_icon_in_the_browser',{icon:SHARE_SVG})}
  2. ${tr('install.tap_add_to_home_screen_you')}
  3. ${tr('install.open_series_of_tubes_from_your')}
`; + if(installEvt)return ''; + return `
  1. ${tr('install.open_your_browser_menu')}
  2. ${tr('install.tap_install_app_or_add_to')}
  3. ${tr('install.open_series_of_tubes_from_your_e03f')}
`;} +function pitchHtml(starting){const ios=isIOS(); + return `
${starting?`
${tr('install.before_you_start')}
`:''}

📲 ${tr('install.play_it_as_an_app')}

+

${tr('install.series_of_tubes_is_made_for')}

+
  • 🗺️ ${tr('common.full_screen')} ${tr('install.no_browser_bars_a_lot_more')}
  • 📶 ${tr('common.works_offline')} ${tr('install.build_your_backbone_on_the_train')}
  • ${ios?`
  • 💾 ${tr('install.your_save_stays_safe')} ${tr('install.safari_can_clear_the_data_of')}
  • ⚠️ ${tr('common.install_first')} ${tr('install.on_iphone_a_game_started_in')}
  • `:`
  • ⚡ ${tr('install.one_tap_away')} ${tr('install.it_opens_straight_into_your_network')}
  • `}
+ ${installSteps()} +
${installEvt?btn(tr('install.install_the_app'),'install',{},'pink big'):''}${starting?btn(tr('install.play_in_the_browser_anyway'),'pitchSkip',{},installEvt?'ghost':'ghost big'):btn(tr('common.got_it'),'closeModal',{},installEvt?'ghost':'pink')}
`;} +if('serviceWorker' in navigator&&location.protocol==='https:'&&!IS_DEV)addEventListener('load',()=>{navigator.serviceWorker.register('/sw.js').catch(()=>{});}); diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js new file mode 100644 index 0000000..92d1a16 --- /dev/null +++ b/src/game/93-ui/40-hud-and-panels.js @@ -0,0 +1,95 @@ +function fitHud(){const h=$('hud');if(!h)return;h.classList.remove('fit1','fit2','fit3');if(innerWidth<=760)return; + const row=()=>{let m=0;for(const c of h.children)if(c.offsetParent)m=Math.max(m,c.offsetHeight);return m;}; + for(const c of ['fit1','fit2','fit3']){if(h.offsetHeight<=row()*1.5)break;h.classList.add(c);}} +function renderHUD(){ + // No clock (puzzles): there is no time to speed up, so the speed buttons go. + // A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud). + {const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();} + $('muteBtn').style.opacity=UI.muted?.4:1; + if(MP_API)mpHud();// the session chip: also hidden again on the title screen and in a puzzle + if(!S)return; + if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;} + {const rt=ruleTag(),ha=$('hAsn');ha.title=rt?tr('rules.rules_are_locked_for_this_network',{rules:rt}):'';} + $('hName').textContent=S.name;$('hAsn').textContent='AS'+S.asn+(S.mode==='sandbox'||ruleTag()&&!S.scn?' · '+ruleTag():S.scn?' · '+(scnName())+(S.scn.done||S.scn.failed?'':` · ${tr('ui.n_d_left',{n:Math.max(0,S.scn.days-S.day)})}`):''); + $('hCash').textContent=fmt$(S.cash);$('hCash').style.color=S.cash<0?'var(--tx-red,var(--bad))':''; + const net=R.revMo-R.costMo;$('hRate').innerHTML=`${net>=0?'▲':'▼'} ${tr('common.price_mo',{price:fmt$(Math.abs(net))})}`; + $('hTraffic').textContent=`${fmtG(R.served)}`; + $('hTrafBar').style.width=(R.demand?R.served/R.demand*100:0)+'%'; + $('hTrafBar').style.background=R.demand&&R.served/R.demand<0.9?'var(--bad)':'var(--ok)'; + $('hReach').textContent=reachPct(R.reach);$('hReach').style.color=R.reach<0.99?'var(--tx-red,var(--bad))':'var(--eye)'; + $('hTier').textContent=tierLabel()+' · '+tr('hud_and_panels.lv_n',{n:S.lvl||1}); + {const P=scnProg(),hs=$('hScn');hs.hidden=!P;if(P){const sc=S.scn;$('hScnVal').textContent=sc.done?tr('common.done'):sc.failed?tr('common.time_s_up'):`${Math.round(P.f*100)}% · ${tr('ui.n_d_left',{n:Math.max(0,sc.days-S.day)})}`;}} + $('hDate').textContent=dateStr(S.day); + {const bo=(S.loanOffers||[]).length,hb=$('hBank');hb.hidden=!bo;hb.textContent=bo;} + {const st=custStats(),hc=$('hCust');hc.hidden=!st.n;if(st.n){$('hCustVal').innerHTML=`${st.avg>=80?'😀':st.avg>=60?'🙂':st.avg>=30?'😟':'😡'} ${Math.round(st.avg)}%${st.unhappy?` ${st.unhappy}`:''}`;hc.classList.toggle('hot',st.furious>0);}} + const n=S.inc.length;$('hNoc').classList.toggle('hot',n>0);{const b=$('hNocNew');if(b)b.hidden=true;}$('hNocVal').textContent=n?trn('hud_and_panels.n_incident',n):tr('common.all_quiet'); + if(!window.__TUBES_TEST__)fitHud(); + renderTabbar(); +} +function renderLeft(){checkLayer(); + // Tablets in landscape: both side panels don't fit next to the map, so the left one tucks away + // while a city or link is open and comes back with the toggle button. + const tab=isTablet(),L=$('left');L.classList.toggle('closed',tab?(!!UI.sel&&!UI.leftOpen):!UI.leftOpen);const tg=$('leftToggle');if(tg&&innerWidth>760)tg.hidden=!(tab&&L.classList.contains('closed')); + renderTabbar(); + if(!S||pzOn()){L.hidden=true;return;}L.hidden=false; + const G=goals(),ndone=G.filter(g=>S.done[g.id]!==undefined).length; + const tabs=[['goals',`${tr('common.goals')}${ndone}/${G.length}`],['deals',`${tr('common.deals')}${S.offers.length+clHags()?`${S.offers.length+clHags()}`:''}`],['noc',`NOC${S.inc.length?``:''}`],['nets',`${tr('common.networks')}`]]; + $('leftTabs').innerHTML=tabs.map(([k,l])=>``).join('')+(innerWidth<760?``:''); + let h=''; + if(UI.left==='goals'){ + h+=charterCard()+lateCard()+scnCard()+lvlCard()+t1Card(); + const cur=G.find(g=>S.done[g.id]===undefined); + h+=G.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `
${d?'✓':''}
${esc(g.t)}
${c||!d?`
${esc(g.d)}
`:''}${!d&&g.r?`
${tr('hud_and_panels.reward_cash',{cash:fmt$(g.r)})}
`:''}
`;}).join(''); + h+=badgeGrid(); + }else if(UI.left==='deals'){ + {const st=custStats();if(st.n)h+=`
${tr('common.your_customers')} ${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}
${st.unhappy?`
${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}
`:''}
${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}
`;} + h+=salesCard()+clDealsHtml()+confSection()+seatSection(); + {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}
${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}
`;} + if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; + for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); + h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${ip4Why(o)}${bRisk(o)}${reqList(o)}${reqFixHtml(o)} +
${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} + }else if(UI.left==='noc'){ + h+=`
${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${pieNocBtn()}${btn(`⚙️ ${tr('routing.routing_and_ddos')}${S.te&&!coreTE()?'':''}`,'routingOpen',{},'')}
`; + h+=`

${tr('hud_and_panels.your_network_operations_center_every')}

`; + h+=opsCard()+pieSpatCard()+mkCard()+ddosPanel(); + // Incidents come first, the ones you can fix with one click at the top (#63): no scrolling past hot ports to replace an optic. + for(const i of S.inc.filter(i=>i.type!=='ddos').sort((a,b)=>(b.cost?1:0)-(a.cost?1:0)||(b.impact||0)-(a.impact||0))){h+=`
${incTitle(i.type)}
${esc(i.msg)}
${shipSea(i)?'🚢 '+esc(shipStatus(i)):trn('hud_and_panels.auto_fix_in_n_day',i.until-S.day)}${i.impact?` · ${tr('hud_and_panels.g_lost',{g:fmtG(i.impact)})}`:''}
${i.cost?`
${btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash`:''}
`;} + h+=logSection();UI.logSeen=Date.now(); + if(S.grace&&S.grace.until>S.day&&R.graceNets)h+=`
${tr('common.courtesy_route')}${tr('hud_and_panels.n_networks_d_days_left',{n:R.graceNets,d:S.grace.until-S.day})}

${tr('hud_and_panels.reaches_networks_from_the_last')}

`; + const hot=S.links.filter(l=>!linkDown(l)&&capOf(l)>0&&(R.load[l.id]||0)/capOf(l)>=0.85).sort((a,b)=>(R.load[b.id]/capOf(b))-(R.load[a.id]/capOf(a))); + if(hot.length){h+=`

${tr('common.congested_links')}

${S.te&&S.te.on?'':'

'+tr('hud_and_panels.raise_a_full_link_s_metric')+'

'}`+hot.map(l=>`
${CITY[l.a].name} ⇄ ${CITY[l.b].name}
${capName(l)} · ${tr('hud_and_panels.p_full',{p:pct((R.load[l.id]||0)/capOf(l))})}
${btn(tr('common.inspect'),'selLink',{id:l.id},'pink sm')}
`).join('');} + h+=hwCard(); + const slow=Object.keys(S.pops).filter(latSlow).sort((a,b)=>R.latF[a]-R.latF[b]); + if(slow.length)h+=`

🐢 ${tr('common.slow_cities')}

${tr('hud_and_panels.their_users_go_out_through_transit')}

`+slow.map(c=>{const f=R.latFar[c];return `
${CITY[c].name} → ${CITY[f.to].name}
${tr('hud_and_panels.p_of_its_traffic_ms_ms',{p:pct(Math.min(1,f.share)),ms:Math.round(f.ms),sf:pct(R.latF[c])})}
${btn(tr('common.inspect'),'focusCity',{city:c},'ghost sm')}
`;}).join(''); + const hotR=hotPorts(); + if(hotR.length)h+=`

${tr('hud_and_panels.ports_caches_and_routers_running_hot')}

`+hotR.map(x=>`
${HOTL[x.k]}
${CITY[x.city].name} · ${esc(x.lab)}
${tr('hud_and_panels.p_full',{p:pct(Math.min(1,x.u))})}${x.u>=0.995?' · '+tr('hud_and_panels.dropping_or_overflowing'):''} · ${esc(x.tip)}
${btn(tr('common.inspect'),'focusCity',{city:x.city},'pink sm')}
`).join(''); + if(!S.inc.length&&!hot.length&&!hotR.length&&!slow.length)h+=`

${tr('hud_and_panels.all_systems_green_enjoy_it_while')}

`; + h+=`
${tr('hud_and_panels.incidents_so_far')}${S.stats.incidents}
${tr('hud_and_panels.survived_with_no_impact')}${S.stats.survived}
`; + }else{ + if(Object.keys(S.ixp).length||ppol()!=='open')h+=pdeskCard(); + h+=`

${tr('hud_and_panels.every_network_on_the_map_traffic')}

`; + {const nc=connsN();if(nc)h+=`
${btn(tr('hud_and_panels.all_connections_n',{n:nc}),'connOpen',{},'pink sm')}
`;} + const where=netWhereIdx(),tl=NETS.filter(n=>n.tail),tlOn=tl.filter(n=>where(n.id).some(x=>x[2]==='ix')).length; + const foc=UI.netFocus&&NET[UI.netFocus]?NET[UI.netFocus]:null,out=!foc&&UI.nf==='out',lostN=ntLost().length; + h+=`
${btn(tr('common.all_networks'),'netFilter',{f:'all'},!foc&&!out?'sm':'ghost sm')}${btn(tr('hud_and_panels.out_of_reach_without_transit_n',{n:lostN}),'netFilter',{f:'out'},out?'sm':'ghost sm')}
`; + if(out&&!lostN)h+=`

${tr('hud_and_panels.nothing_every_network_is_reachable')}

`; + // Shown 100 at a time like the dashboard lists: every country's own eyeballs made this list long (2.0). + const nl=(foc?[foc]:out?ntLost():NETS).filter(n=>!n.tail||UI.tailOpen||foc||out); + for(const n of nl.slice(0,listN('nets'))){ + h+=`
${logo(n)}
${esc(n.name)} AS${n.asn}
${TYPE_L[n.type]} ${n.pol} · ${tr('hud_and_panels.p_of_traffic',{p:(NSH[n.id]*100).toFixed(1)})}${n.price?` · ${tr('hud_and_panels.transit_price_gbps',{price:(n.price*S.priceMul).toFixed(2)})}`:''}
${pniChip(n.id,null)}
${esc(n.blurb)}
${netWhere(n,where)}${(foc||out)&&!R.nt[n.id]?`

${esc(offTransitHint(n.id))}

`:''}${(foc||out)&&coneVia(n.id)&&(R.cone[n.id]||!R.nt[n.id])?`

${R.cone[n.id]?tr('hud_and_panels.reached_through_the_customer_cone_of',{net:esc((NET[R.cone[n.id]]||coneVia(n.id)).name)}):tr('hud_and_panels.buys_transit_from_net_peer_with',{net:esc(coneVia(n.id).name)})}

`:''}${foc||out&&!R.nt[n.id]?meetLine(n,foc?24:4):''}
`;} + h+=listMore('nets',nl.length,n=>trn('hud_and_panels.n_more_networks',n)); + if(!foc&&!out)h+=`
${tr('hud_and_panels.the_long_tail')} ${tr('hud_and_panels.n_small_networks',{n:tl.length})}
${tr('hud_and_panels.p_of_traffic_between_them_scattered',{p:(tl.reduce((a,n)=>a+NSH[n.id],0)*100).toFixed(1),n:tlOn})}
${btn(UI.tailOpen?tr('common.hide'):tr('common.show'),'tailTog',{},'ghost sm')}
`; + } + if(h!==UI._lh){UI._lh=h;morph($('leftBody'),h);} +} +function renderPanel(){checkLayer(); + const P=$('panel'); + if(!S||!UI.sel){P.hidden=true;return;} + P.hidden=false; + // Don't wipe a half-typed custom metric on the daily re-render. + const fe=document.activeElement;if(fe&&fe.id==='metIn'&&UI.sel.type!=='city'&&fe.dataset.id===UI.sel.id)return; + const scrollEl=$('panelBody').querySelector('.scroll');const st=scrollEl?scrollEl.scrollTop:0; + const html=pzOn()?pzPanel(UI.sel):UI.sel.type==='city'?cityPanel(UI.sel.id):linkPanel(UI.sel.id);if(!html){P.hidden=true;return;}if(html===UI._ph&&!P.hidden&&$('panelBody').firstChild)return;UI._ph=html;morph($('panelBody'),html); + const ns=$('panelBody').querySelector('.scroll');if(ns)ns.scrollTop=st; +} diff --git a/src/game/93-ui/45-core-panel.js b/src/game/93-ui/45-core-panel.js new file mode 100644 index 0000000..de2a972 --- /dev/null +++ b/src/game/93-ui/45-core-panel.js @@ -0,0 +1,17 @@ +/* ---------- NOC: the backbone's technology ---------- */ +const CORE_WHAT=[N_('core.shortest_paths_only_every_router'),N_('core.labels_switch_traffic_that_only'),N_('core.tunnels_unlock_auto_te_and'),N_('core.segment_routing_te_detours_up'),N_('core.segment_routing_over_ipv6_the')]; +function corePanel(){if(!S.core||S.mode==='puzzle'||S.pz||S.ar||S.scn)return '';const C=S.core,run=C.run,lv=C.lv,n=lv+1; + let h=`

${tr('core.backbone')}

${tr('core.running')}${tr(CORE_LV[run])}
`; + h+=`

${tr(CORE_WHAT[run])}${run?' '+tr('core.uses_p_of_router_cpu',{p:pct(CORE_CPU[run])}):''}

`; + if(C.legacy)h+=`

${tr('core.your_auto_te_predates_backbones')}

`; + // Run any level already paid for: one step down is the safe way past vendor squabbles. + if(lv>0)h+=`
${CORE_LV.slice(0,lv+1).map((l,i)=>btn(tr(l),'coreSet',{v:i},i===run&&!C.legacy?'pink sm':'ghost sm')).join('')}
`; + if(n<=4){const lk=lvl()${btn(lk?tr('core.lv_at_customer_level_n',{lv:tr(CORE_LV[n]),n:CORE_REQ[n]}):tr('core.upgrade_to_lv_cost',{lv:tr(CORE_LV[n]),cost:fmt$(CORE_COST[n])}),'coreUp',{},'sm',lk||S.cash`; + h+=`

${tr(CORE_WHAT[n])}

`;} + const out=coreOut();if(out.length)h+=`

${trn('core.n_pop_outside_the_core_its',out.length,{list:out.slice(0,5).map(c=>CITY[c].name).join(', ')+(out.length>5?'…':''),lv:tr(CORE_LV[run])})}

`; + const v=coreOn()&&run>=1?coreVendors():null; + if(v&&v.size>1)h+=coreIopRisk()?`

${tr('core.n_vendors_at_the_top_of',{n:v.size,lv:tr(CORE_LV[run])})}

`:`

${tr('core.n_vendors_one_step_below_their',{n:v.size})}

`; + if(run>=2)h+=`

🛟 ${tr('core.fast_reroute_customers_lose_half')}

`; + if(coreOn()&&lv>=1)h+=C.lab?`

🧪 ${tr('core.interop_lab_cuts_interop_incidents',{p:pct(1-CORE_LAB_F)})}

` + :`
${btn(tr('core.build_an_interop_lab_cost',{cost:fmt$(CORE_LAB)}),'coreLab',{},'ghost sm',S.cash

${tr('core.test_vendors_against_each_other',{p:pct(1-CORE_LAB_F)})}

`; + return h;} diff --git a/src/game/93-ui/46-routing-modal.js b/src/game/93-ui/46-routing-modal.js new file mode 100644 index 0000000..98367ae --- /dev/null +++ b/src/game/93-ui/46-routing-modal.js @@ -0,0 +1,17 @@ +/* ---------- Routing & DDoS: one modal for the network-wide settings ---------- + The backbone, Auto-TE and DDoS automation used to sit at the bottom of the NOC tab, below every incident and + the log, where nobody found them. A button at the top of the NOC tab opens them here, with the traceroute. */ +// Auto-TE: paused, installed or for sale. +function tePanel(){ + return S.te&&!coreTE()?`
Auto-TE${tr('core.paused')}

${tr('core.auto_te_is_paused_it_needs')}

`:S.te?`
Auto-TE${S.te.on?tr('hud_and_panels.on_moving_g_onto_alternate_paths',{g:fmtG(R.teMoved||0)}):tr('common.off')}
${btn(S.te.on?tr('hud_and_panels.turn_auto_te_off'):tr('hud_and_panels.turn_auto_te_on'),'teToggle',{},'ghost sm')}${btn(S.te.script?tr('common.edit_routescript'):tr('hud_and_panels.write_a_routescript'),'teEdit',{},'pink sm')}
${S.te.script?`

RouteScript: ${teRules()?tr('hud_and_panels.n_rules_live',{n:teRules().n}):S.te.on?tr('hud_and_panels.has_errors_not_running'):tr('common.controller_off')}${R.teBlack?` · ${tr('hud_and_panels.blackholing_g',{g:fmtG(R.teBlack)})}`:''}

`:''}` + :`
Auto-TE${lvl()<3?tr('hud_and_panels.unlocks_at_customer_level_3'):tr('common.not_installed')}

${tr('hud_and_panels.traffic_takes_the_shortest_path_even')}

${coreTE()?'':`

${tr('core.auto_te_needs_an_rsvp_te_or')}

`}
${btn(tr('hud_and_panels.install_auto_te_cost_mo_mo',{cost:fmt$(TE_COST),mo:fmt$(TE_MO)}),'buyTE',{},'pink sm',lvl()<3||S.cash`;} +// What the modal holds, without its title (scripts/lib/fuzz-page.js reads its buttons too). +// Traceroute opens its own modal from here: it explains the routing these settings shape. +function routingBody(){return `
🔎 ${tr('common.traceroute')}
${tr('routing.trace_note')}
${btn(tr('routing.trace_run'),'trace',{},'sm')}
`+corePanel()+`

${tr('common.traffic_engineering')}

${tePanel()}` + +`

${tr('routing.ddos_defence')}

${ddosSettings()}`;} +function routingModal(){if(!S)return;const card=$('modalCard'),open=!$('modal').hidden&&card.querySelector('[data-routing]'),st=open?card.scrollTop:0; + let h=`
NOC

${tr('routing.routing_and_ddos')}

+

${tr('routing.how_traffic_crosses_your_backbone')}

`; + openModal(h+routingBody());if(open)card.scrollTop=st;} +// Actions taken in the modal re-render the game through after(); this keeps the open modal in step. +function routingRefresh(){if(S&&!$('modal').hidden&&$('modalCard').querySelector('[data-routing]'))routingModal();} diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js new file mode 100644 index 0000000..a9c8fd4 --- /dev/null +++ b/src/game/93-ui/50-city-panel.js @@ -0,0 +1,115 @@ +function cityPanel(c){ + const C=CITY[c],p=S.pops[c],ix=ixName(c),down=p&&p.down>S.day; + // Your POP's router model, as a picture left of the name (10-catalog/25-router-art.js). + const art=p?rgArt(p.rgen||0):''; + let h=`
${art?`${art}`:''}
${REG[C.reg]} · ${esc(siteName(c,'a'))}

${C.name}

+
${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}${grantFact(c)}${satFact(c)}${wispFact(c)}${latSlow(c)?`🐢 ${tr('city_panel.ms_ms_to_transit',{ms:Math.round(R.latFar[c].ms)})}`:''}${regionMult(c)>1?`${tr('city_panel.transit_x_pricier',{x:regionMult(c)})}`:''}${C.kr&&scnRule('sender')?`${tr('city_panel.sender_pays_fee_per_gbps',{fee:fmt$(KR_FEE)})}`:''}${colo(c)>1?`${tr('city_panel.few_data_centers_pops_x',{x:colo(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('city_panel.underserved_users_grow_60_faster')+'':''}${ix?`${tr('city_panel.ix_ix',{ix:esc(ix)})}`:''}${p?`${tr('common.your_pop')}`:''}${down?`DOWN`:''}
+
`; + if(!p){ + h+=`
${C.note?`

${esc(C.note)}

`:''} + ${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`

${tr('city_panel.open_a_pop_here')}

${tr('city_panel.a_pop_point_of_presence_is')}

+ ${C.ru?`

${tr('city_panel.includes_the_mandatory_government',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${(q=>btn(tr('city_panel.build_pop_cost_mo_mo',{cost:fmt$(popCost(c)+(q?q.cost:0)),mo:fmt$(popMo(c)+(q?q.mo:0))}),'buildPop',{city:c},'pink big',S.cash${q.site2||q.gen?tr('pop_std.includes_the_build_standard',{list:esc(bstdPopParts({g:q.g,rt:q.rt,site2:q.site2,gen:q.gen}).join(', ')),cost:fmt$(q.cost),mo:fmt$(q.mo)}):tr('pop_std.includes_the_standard_n_model',{n:q.rt,model:esc(RG[q.g].n),cost:fmt$(q.cost),mo:fmt$(q.mo)})}

`:''))(popStdQuote())} +

${tr('city_panel.or_drag_from_one_of_your')}

${opsTplHtml(c)}`}`; + h+=offersHere(c)+satNoPop(c)+wispNoPop(c); + const trs=NETS.filter(n=>sellsAt(n,c)); + const fh=FABS.filter(f=>f.cities.includes(c)); + if(ix&&fh.length){if(remoteCities().includes(c))h+=ixSection(c).replace('

'+tr('common.internet_exchange')+'

','

'+tr('city_panel.remote_peering_at_the_ix')+'

'); + else h+=`

${tr('common.remote_peering')}

${tr('city_panel.peer_at_ix_without_building_a',{ix:esc(ix),fabs:fh.map(f=>esc(f.name)).join(tr('common.or'))})}

${REMOTE_WARN}${btn(tr('city_panel.order_circuit_anyway'),'openVxc',{to:c},'ghost sm')}
`;} + h+=`

${tr('city_panel.who_s_here')}

${MEGA.filter(m=>m.c===c).length?`${tr('city_panel.ai_and_cloud_campuses_nearby_list',{list:MEGA.filter(m=>m.c===c).map(m=>`${esc(m.n)}`).join(', ')})}
`:''}${tr('city_panel.transit_sellers_list',{list:trs.map(n=>`${esc(n.name)}`).join(', ')||tr('common.none')})}
${tr('city_panel.fabrics_list',{list:fh.map(f=>`${esc(f.name)}`).join(', ')||tr('common.none')})}
${ix?ixIdsIn(c).map(x=>tr('city_panel.ix_members_on_ix_n',{ix:esc(ixName(x)),n:ixMembers(x).length})).join('
'):tr('city_panel.no_ix_here_yet_you_could')}
`; + return h; + } + const tabs=[['cust',tr('common.customers')],['up',tr('common.transit')],['peer',tr('common.peering')],['links',tr('common.infra')]]; + h+=`
`; + if(C.cn&&UI.tab==='cust')h+=chinaSection(c); + const sf=sfOf(R,c),dem=R.cityDem[c]||0; + if(down){const i=S.inc.filter(x=>x.ref===c&&POPDOWN.includes(x.type)).sort((a,b)=>b.until-a.until)[0];h+=`

${tr('city_panel.this_pop_is_down')}

${i?esc(i.msg):''} ${tr('city_panel.customers_here_get_nothing_until_it')}

${i&&i.cost?btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red'):''}
`;} + if(UI.tab==='cust'){ + {const nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||1;if(nl>=nc*0.95)h+=`

${tr('city_panel.router_maxed_out')}

${tr('city_panel.your_routers_here_are_forwarding',{load:fmtG(nl),cap:fmtG(nc)})}

${btn(tr('common.open_infra'),'tab',{t:'links'},'pink sm')}
`;} + h+=`

${tr('common.home_broadband')}

`; + if(!p.bb){const s=bbStart(c);h+=`

${tr('city_panel.sell_internet_to_homes_here_starts',{start:fmtG(s),max:fmtG(eyeP(c)),rate:fmt$(EYE_RATE*arpuOf(c))})}${C.au?` ${scnRule('levy')?tr('city_panel.it_runs_on_your_own_fibre',{pct:pct(AU_LEVY)}):tr('city_panel.the_nearly_broadband_network_keeps',{pct:pct(AU_WHOLESALE)})}`:''}${lateOn()&&lateLeft()?' '+trn('late.bb_pitch',lateLeft()):''}

${btn(tr('city_panel.launch_broadband_cost',{cost:fmt$(bbCost(c))}),'launchBB',{city:c},'pink big',S.cash${tr('common.eyeball_demand')}${tr('city_panel.a_of_b',{a:fmtG(eye),b:fmtG(eyeP(c))})}
+
${tr('city_panel.served_in_city',{city:C.name})}${pct(sf)}
+
${tr('common.revenue')}${tr('common.price_mo',{price:fmt$(eye*sf*EYE_RATE*arpuOf(c))})}
+
${tr('city_panel.network_wide_peering_ratio')}${pct(R.peerShare||0)}

${tr('city_panel.more_traffic_over_peering_pnis_and')}

+ ${sf<0.9?`

${tr('city_panel.customers_are_unhappy_and_leaving')}

`:''} +
${p.boost>S.day?`${tr('city_panel.ad_campaign_n_d_left',{n:p.boost-S.day})}`:btn(tr('city_panel.run_ad_campaign_8k_2_growth'),'ad',{city:c},'',S.cash<8000)}
${ip6Html(c)}`;} + h+=``+wispHtml(c)+`

${tr('common.business_customers')}

`; + const bz=S.biz.filter(b=>bCities(b).includes(c)); + if(!bz.length)h+=`

${tr('city_panel.no_businesses_yet_offers_pop_up')}

`; + for(const b of bz)h+=`
${esc(b.name)}
${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${clTermTxt(b)?' · '+clTermTxt(b):''}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('city_panel.fiber_is_down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('common.needs_a_scrubbing_center')+'':''}${S.day-(b.since||0)<15?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}${pathCtl(b)}
${tr('common.happiness_p',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.drop'),'dropBiz',{id:b.id},'ghost sm')}
`; + h+=`
`+offersHere(c); + }else if(UI.tab==='up'){ + h+=netFilterHtml()+portNote(c)+latNote(c); + h+=`

${tr('common.ip_transit')}

${tr('city_panel.pay_a_bigger_network_per_gbps')}

`; + const prov0=NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>a.price-b.price),prov=prov0.filter(n=>netKeep(n,S.transit.some(x=>x.city===c&&x.net===n.id))); + if(!prov0.length)h+=`

${tr('city_panel.nobody_sells_transit_here_haul_your')}

`;else if(!prov.length)h+=netNone(); + for(const n of prov){const t=S.transit.find(x=>x.city===c&&x.net===n.id);const pr=transitPerG(n,c,premOnlyAt(n,c)||!!(t&&premOn(t)))*S.priceMul; + h+=`
${logo(n)}
${esc(n.name)} ${TYPE_L[n.type]}
${tr('city_panel.price_per_gbps_month_billed_on',{price:pr.toFixed(2)})}
${premOnlyAt(n,c)&&!t?`
${tr('city_panel.only_the_cn_too_premium_crossing')}
`:''}`; + if(t){const u=R.useT[t.id]||0,cap=lagCap(PORT[t.tier].g,t.n),tdown=t.down>S.day; + h+=`
${lagName(t.tier,t.n)}${tdown?' · '+tr('common.outage')+'':''}${fmtG(u)}
${prefCtl('t',t.id,t.pref)}${carryCtl(t)}${siteCtl('t',t.id,c,t.site)}${premOnlyAt(n,c)?`

${tr('city_panel.only_the_cn_too_premium_crossing')}

`:premCity(n,c)?`
${btn(t.premium?tr('city_panel.cn_too_premium_on'):tr('city_panel.switch_to_cn_too_premium_x',{x:n.premium}),'togglePrem',{id:t.id},t.premium?'green sm':'sm')}
`:''}${(()=>{const top=transitTop([t.id],4);return top.length?`
${tr('city_panel.top_destinations_on_this_port')}
${top.map(([id,v])=>`
${esc(NET[id].name)} · ${fmtG(v)} · ${esc(offTransitHint(id,c))}
`).join('')}
`:'';})()}
${tr('city_panel.95th_pct_p95_commit_commit_bill',{p95:fmtG(R.p95[t.id]||0),commit:fmtG(cap*.2),bill:fmt$(Math.max(R.p95[t.id]||0,PORT[t.tier].g*(t.n||1)*.2)*pr+PORT[t.tier].tmo*(t.n||1))})}
+
${PORT.map((P2,i)=>i>t.tier&&portShown(i)?btn((t.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',{port:P2.n,cost:fmt$(P2.setup*(t.n||1)),mo:fmt$(P2.tmo*(t.n||1))}):tr('common.upgrade_port_cost_mo_mo',{port:P2.n,cost:fmt$(P2.setup*(t.n||1)),mo:fmt$(P2.tmo*(t.n||1))}),'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash0?btn(tr('link_panels.downgrade_port_price',{port:PORT[t.tier-1].n,price:portMo(PORT[t.tier-1].tmo*(t.n||1))}),'downT',{id:t.id},'ghost sm'):''}${(t.n||1)1?btn(tr('common.member'),'lagT',{id:t.id,d:-1},'ghost sm'):''}${btn(t.clean?tr('city_panel.clean_pipe_on'):tr('city_panel.clean_pipe_mo_mo_scrubs_ddos',{mo:fmt$(cleanMo(t))}),'cleanPipe',{id:t.id},t.clean?'green sm':'sm')}${btn(UI.confirm===t.id?tr('common.really_cancel'):tr('common.cancel'),'cancelTransit',{id:t.id},'ghost sm')}
`;} + else h+=`
${PORT.map((P2,i)=>portShown(i)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(P2.setup),mo:fmt$(P2.tmo)}),'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash`; + h+=`
`;} + h+=`
`; + }else if(UI.tab==='peer'){ + h+=netFilterHtml()+portNote(c); + h+=ixSection(c); + h+=`

${tr('city_panel.private_interconnects_pni')}

${tr('city_panel.a_dedicated_cross_connect_to_one',{dc:esc(siteName(c,'a'))})}

`; + h+=pniListHtml(c); + h+=`

${tr('common.embedded_caches')}

${tr('city_panel.cdns_put_free_cache_servers_inside')}

`; + for(const n of NETS.filter(n=>n.cache&&netKeep(n,S.caches.some(x=>x.city===c&&x.net===n.id)))){const have=S.caches.filter(x=>x.city===c&&x.net===n.id),dem=R.demTo[n.id]||0,ok=dem>=n.cache.min; + h+=`
${logo(n)}
${esc(n.cache.name)}
${tr('common.from_net',{net:esc(n.name)})} · ${have.length?`${trn('common.n_box',have.length)} · ${tr('city_panel.serving_v',{v:fmtG(have.reduce((a,x)=>a+(R.useCache[x.id]||0),0))})}`:tr('city_panel.100g_per_box')}
${!ok?`
${tr('city_panel.needs_min_gbps_of_traffic_to',{min:n.cache.min,net:esc(n.name),now:dem.toFixed(1)})}
`:''}
+ ${have.length?btn(tr('common.remove'),'rmCache',{id:(have.find(x=>x.site==='b')||have[0]).id},'ghost sm'):''}${btn(have.length?tr('common.box'):tr('common.request'),'cache',{city:c,net:n.id},'sm',!ok)}
${S.pops[c].site2&&have.length?(()=>{const nb=have.filter(x=>x.site==='b').length,na=have.length-nb;return `
${tr('city_panel.boxes_a_in_a_b_in',{a:na,b:nb})}${na?btn(tr('city_panel.move_one_to_b'),'cacheSite',{city:c,net:n.id,s:'b'},'ghost sm'):''}${nb?btn(tr('city_panel.move_one_to_a'),'cacheSite',{city:c,net:n.id,s:'a'},'ghost sm'):''}
`;})():''}`;} + h+=`
`; + }else{ + h+=utilityKitLine(c); + const ls=S.links.filter(l=>l.a===c||l.b===c); + const rt=p.routers||1,g=p.rgen||0,G=RG[g],nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||nodeCap(c),Ni=g===mainRG(G.cls)?mainRG(G.cls+1):-1,N=Ni>=0?RG[Ni]:null,pu=portsUsed(c),pm=portsMax(c); + h+=`

${tr('common.routers')}

${tr('city_panel.the_model_sets_your_fastest')}

+
${rt} × ${esc(G.n)}
${tr('city_panel.up_to_pn_interfaces_ports_ports',{pn:G.pn,ports:G.ports,cap:fmtG(G.cap)})} · ${esc(G.blurb)}
${coreMeta(g)}
${coreOn()&&coreRun()>0&&!inCore(c)?`
${tr('core.this_router_can_t_run_your',{lv:tr(CORE_LV[coreRun()])})}
`:''}
+
${tr('common.router_ports')}${tr('city_panel.used_max_in_use',{used:fmtPorts(pu),max:pm})}
${pu>=pm?`

${tr('city_panel.every_port_is_taken_add_a')}

`:''} +
${tr('common.forwarding_chip')}${esc(G.chip)}
${tr('common.boot_time')}${slowBoot(c)?`${tr('city_panel.n_min_a_slow_one',{n:bootMin(c)})}`:tr('city_panel.n_min',{n:bootMin(c)})}
${slowBoot(c)?`

${tr('city_panel.this_chassis_takes_forever_to_boot')}

`:''} + ${(()=>{const fc=G.fsN||0,u=(R.fsUse&&R.fsUse[c])?R.fsUse[c].used:0;return `
${tr('ddos.fs_rules')}${fc?tr('ddos.fs_used',{used:u,cap:fc}):tr('ddos.fs_no_tcam')}
${fc?`
`:''}`;})()} +
${tr('common.forwarding_load')}${fmtG(nl)} / ${fmtG(nc)}
+ ${nl>=nc*0.95?`

${tr('city_panel.maxed_out_traffic_here_is_being')}

`:''} +
${N?(!techOk('rg',Ni,N.lvl)?demoBtn('rg',Ni,N.lvl,tr('city_panel.model_level_lv',{model:esc(N.n),lv:N.lvl}),'pink'):btn(tr('city_panel.upgrade_to_model_cost_mo_mo',{model:esc(N.n),cost:fmt$(swapCost(c,Ni)),mo:fmt$(N.mo*rt)}),'upRouter',{city:c,g:Ni},'pink',S.cash=RCAGE?CAGE_MO:0))}),'addRouter',{city:c},'',S.cash1?btn(tr('common.remove_one'),'rmRouter',{city:c},'ghost sm'):''}
+ ${rt>=RCAGE&&rt${tr('city_panel.the_standard_cage_holds_n_routers',{n:RCAGE,mo:fmt$(CAGE_MO)})}

`:''}${rt>=RMAX?`

${tr('city_panel.this_pop_has_the_most_routers',{n:RMAX})}

`:''}${rt>RCAGE?`
${tr('city_panel.cage_extension')}${fmt$(cageMo(rt))}/mo
`:''} + ${popStdHtml(c)}${popTierHtml(c)} + ${UI.models?routerModels(c):''} + ${N||UI.models?`

${(p.rgen||0)>0?tr('city_panel.prices_include_p_back_for_the',{p:fmt$(tradeIn(p.rgen||0,rt))})+' ':''}${p.rupDay===S.day?tr('city_panel.new_routers_went_in_today_the')+' ':''}${rt>1?tr('city_panel.rolling_upgrade_one_router_at_a'):tr('city_panel.with_one_router_the_upgrade_needs')}

`:''} +

${rt>=2?tr('city_panel.a_crash_here_only_costs_one'):tr('city_panel.one_router_is_a_single_point')}

+

${tr('common.metro_diversity')}

${p.site2?(()=>{const up=s=>[...S.transit.filter(t=>t.city===c&&onSite(t.site,s)).map(t=>tr('common.net_transit',{net:NET[t.net].name})+(t.site==='ab'?' '+tr('common.split'):'')),...S.pni.filter(x=>x.city===c&&onSite(x.site,s)).map(x=>'PNI '+NET[x.net].name+(x.site==='ab'?' '+tr('common.split'):'')),...ixIdsIn(c).filter(x=>S.ixp[x]!==undefined&&onSite((S.ixSite||{})[x],s)).map(x=>(S.myIx[x]?tr('city_panel.ix_switch',{ix:ixName(x)}):tr('common.port_port',{port:ixName(x)}))+((S.ixSite||{})[x]==='ab'?' '+tr('common.split'):'')),...S.caches.filter(x=>x.city===c&&(x.site==='b'?'b':'a')===s).map(x=>NET[x.net].cache.name)]; + const row=s=>{const dn=siteDown(c,s),u=up(s);return `
${esc(siteName(c,s))}${dn?' DOWN':''}
${u.length?esc(u.join(', ')):tr('city_panel.nothing_plugged_in_here_yet')}
`;}; + return `

${tr('city_panel.two_buildings_joined_by_your_own')}

${row('a')}${row('b')}${up('b').length&&up('a').length?'':`

${tr('city_panel.everything_is_in_one_building_move')}

`}
${tr('city_panel.second_site_and_metro_ring')}${tr('common.price_mo',{price:fmt$(SITE2_MO)})}
${btn(UI.confirm==='site'+c?tr('city_panel.really_close_it'):tr('city_panel.close_site_b'),'rmSite',{city:c},'ghost sm')}
`;})() + :`

${tr('city_panel.right_now_city_is_one_building',{city:esc(CITY[c].name)})}

${btn(tr('city_panel.add_a_second_site_cost_mo',{cost:fmt$(SITE2_COST),mo:fmt$(SITE2_MO)}),'addSite',{city:c},'pink',S.cash`}
+

${tr('common.power')}

${tr('common.backup_generator')}${p.gen?tr('common.installed'):tr('common.none_304f')}
${p.gen?'

'+tr('city_panel.power_cuts_are_covered')+'

':`
${btn(tr('city_panel.install_generator_cost_mo_mo',{cost:fmt$(GEN_COST),mo:fmt$(GEN_MO)}),'addGen',{city:c},'',S.cash`}
`; + h+=`

${tr('city_panel.ddos_scrubbing_center')}

`; + {const here=S.scrubs.find(x=>x.city===c),others=S.scrubs.filter(x=>x.city!==c); + if(here){const T=SCRUB_TIERS[here.tier||0]; + h+=`

${tr('city_panel.pulls_floods_onto_its_own',{g:fmtG(T.g)})}

+
${tr('common.capacity')}${T.n} · ${fmtG(T.g)}
+
${tr('common.mode')}${S.scrubMode==='ondemand'?tr('city_panel.on_demand_half_the_first_day'):tr('common.always_on')} · ${fmt$(scrubMo1(here))}/mo
+
${btn(S.scrubMode==='ondemand'?tr('city_panel.switch_to_always_on'):tr('city_panel.switch_to_on_demand_cheaper'),'scrubMode',{},'sm')}${SCRUB_TIERS.map((X,i)=>i>(here.tier||0)?btn(tr('city_panel.upgrade_to_tier_cost',{tier:X.n,cost:fmt$(Math.round(X.cost*0.6))}),'scrubUp',{city:c,tier:i},'sm',(lvl()||1)`;} + else{h+=`

${others.length?tr('city_panel.floods_here_are_pulled_to',{city:CITY[others.slice().sort((a,b)=>kmBetween(c,a.city)-kmBetween(c,b.city))[0].city].name,km:Math.round(kmBetween(c,others.slice().sort((a,b)=>kmBetween(c,a.city)-kmBetween(c,b.city))[0].city)).toLocaleString()}):tr('city_panel.cleans_ddos_attacks_for_your_whole')}

${SCRUB_TIERS.map((X,i)=>btn(tr('city_panel.build_tier_cost_mo_mo',{tier:X.n,cost:fmt$(X.cost),mo:fmt$(X.mo)}),'buildScrub',{city:c,tier:i},i===0?'':'sm',(lvl()||1)`;}} + h+=`
`; + const fabs=FABS.filter(f=>f.cities.includes(c)); + if(fabs.length){h+=`

${tr('city_panel.interconnection_fabrics_nni')}

${tr('city_panel.buy_a_port_on_a_fabric')}

`; + for(const f of fabs){const pt=nniPort(c,f.id),used=nniUsed(c,f.id); + h+=`
${esc(f.name)}
${esc(f.blurb)}
`; + // Every speed the router takes, every member a LAG may have (#140), as for transit and PNIs. + if(pt){const n=pt.n||1,N=NNI[pt.tier],cap=nniCap(pt),up=(N2,i)=>{const a={port:N2.n,cost:fmt$(N2.mo*n),mo:fmt$(N2.mo*n)};return btn(n>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_price_mo',{port:N2.n,price:fmt$(N2.mo)}),'buyNni',{city:c,prov:f.id,tier:i},'sm',S.cash${lagName(pt.tier,n)} · ${portMo(N.mo*n)}${tr('city_panel.g_of_circuits',{g:fmtG(used)})} / ${fmtG(cap)}
${btn(tr('common.new_circuit'),'openVxc',{from:c,prov:f.id},'pink sm')}${NNI.map((N2,i)=>i>pt.tier&&portShown(i)?up(N2,i):'').join('')}${n1?btn(tr('common.member'),'lagNni',{city:c,prov:f.id,d:-1},'ghost sm'):''}${btn(tr('common.remove_port'),'rmNni',{city:c,prov:f.id},'ghost sm')}
`;} + else h+=`
${NNI.map((N,i)=>portShown(i)?btn(tr('city_panel.port_port_price_mo_197d',{port:N.n,price:fmt$(N.mo)}),'buyNni',{city:c,prov:f.id,tier:i},'sm',S.cash`; + h+=`
`;} + h+=`
`;} + h+=teleHtml(c); + h+=`

${tr('city_panel.fiber_from_city',{city:C.name})}

${tr('city_panel.drag_from_this_router_to_any')}

${btn(tr('city_panel.link_to_a_city'),'findLink',{city:c},'sm')}
`; + if(!ls.length)h+=`

${tr('common.no_links_yet')}

`; + for(const l of ls){const o=l.a===c?l.b:l.a,u=capOf(l)?(R.load[l.id]||0)/capOf(l):0,cut=linkDown(l); + h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='xp'?tr('express.city_via',{via:xpVia(l)}):l.kind==='sat'?tr('satellites.via_bird',{bird:esc(satName(l))})+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=`
`; + if(Object.keys(S.pops).length>1)h+=`

${tr('common.decommission')}

${tr('city_panel.shut_this_pop_down_its_links')}

${btn(tr('city_panel.decommission_city',{city:C.name}),'decomOpen',{city:c},'ghost sm')}${btn(tr('city_panel.decommission_several_pops'),'decomOpen',{},'ghost sm')}
`; + } + return h+`
`; +} diff --git a/src/game/93-ui/51-net-filter.js b/src/game/93-ui/51-net-filter.js new file mode 100644 index 0000000..69ba979 --- /dev/null +++ b/src/game/93-ui/51-net-filter.js @@ -0,0 +1,14 @@ +/* ---------- Find a network at a POP (#199) ---------- + The Transit and Peering tabs list every network that sells or peers there: dozens in a big city. One search box and a + "connected only" switch filter all of them (transit, exchange members, PNIs, caches). View state only, never saved; + it stays while you hop between POPs, and a Clear button says it is on. */ +const netQ=()=>(UI.netQ||'').trim().toLowerCase(); +const netFiltered=()=>!!netQ()||!!UI.netOnly; +// on: connected to that network in this list (a transit port, a session, a PNI, a cache box). A number finds an AS. +function netKeep(n,on){const q=netQ();if(q&&!n.name.toLowerCase().includes(q)&&!(n.asn&&String(n.asn).startsWith(q)))return false;return !UI.netOnly||!!on;} +function netFilterHtml(){return `
+
${btn(tr('net_filter.connected_only'),'netOnly',{},UI.netOnly?'green sm':'ghost sm')}${netFiltered()?btn(tr('net_filter.clear'),'netClear',{},'ghost sm'):''}
`;} +const netNone=()=>`

${tr('pni_list.nothing_matches')}

`; +// Typing redraws the panel. The morph swaps an input whose value changed, so the new box gets the focus and the caret back. +document.addEventListener('input',e=>{if(e.target.id!=='netQ'||!S)return;const at=e.target.selectionStart;ACT.netFind({q:e.target.value}); + const n=$('netQ');if(n&&n!==e.target){n.focus();try{n.setSelectionRange(at,at);}catch(err){}}}); diff --git a/src/game/93-ui/52-pni-list.js b/src/game/93-ui/52-pni-list.js new file mode 100644 index 0000000..ad79a5a --- /dev/null +++ b/src/game/93-ui/52-pni-list.js @@ -0,0 +1,31 @@ +/* ---------- The PNI list of a POP (#175, #172) ---------- + Every network here answers three questions: how you reach it today (one chip), whether a PNI here is worth it + (a value line from live routing) and whether you can get one (the order buttons, policy and lead time). Sorted by + monthly value, filtered, grouped by type; groups with nothing to do (no PNI there, nothing you could order that moves 1 Gbps) stay folded. */ +const PNI_GRP=['t1','t2','eye','cdn','paid'],pniGrpOf=n=>n.pol==='paid'?'paid':n.type; +const pniGrpL=k=>k==='paid'?tr('ops.p_paid'):TYPE_L[k]; +function pniValLine(n,c,v){ + if(v.g<1)return `
${tr('pni_list.little_to_gain_here',{g:fmtG(v.want)})}
`; + const via=[v.t>=0.05?tr('pni_list.via_transit',{g:fmtG(v.t)}):'',v.ix>=0.05?tr('pni_list.via_ix',{g:fmtG(v.ix)}):'',v.p>=0.05?tr('pni_list.via_haul',{g:fmtG(v.p)}):'',v.u>=0.05?tr('pni_list.via_drop',{g:fmtG(v.u)}):''].filter(Boolean).join(' · '); + const val=(v.val>0?'+':'')+tr('common.price_mo',{price:fmt$(Math.round(v.val))}); + return `
${tr('pni_list.n_here',{g:fmtG(v.want)})}: ${via} → ${tr('pni_list.with_port',{port:PORT[v.tier].n,val})}
`;} +function pniRow(c,n,pn,v,chk){let h=`
${logo(n)}
${esc(n.name)} ${n.pol}${v&&v.worth?` ⭐ ${tr('pni_list.worth_it')}`:''}
${pniChip(n.id,c)}
${v?pniValLine(n,c,v):''}`; + if(pn&&!pniOn(pn))h+=pniWait(pn,c); + else if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(pniG(pn),pn.n);h+=`
${(pn.n||1)>1?`${pn.n}×${pniPN(pn)} LAG`:pniPN(pn)} PNI${fmtG(u)}
${pn.up?`
${tr('city_panel.augment_on_order_port_about_n',{port:(pn.up.n>1?pn.up.n+'×':'')+(pn.up.g1?'1G':PORT[pn.up.tier].n),n:Math.max(0,pn.up.ready-S.day)})} ${btn(tr('common.chase_it'),'pniChase',{id:pn.id},'ghost sm')}
`:''}
${prefCtl('p',pn.id,pn.pref)}${siteCtl('p',pn.id,c,pn.up&&pn.up.site==='ab'?'ab':pn.site)}${(pn.n||1)>=pniLagMax(c)&&(pn.n||1)${tr('pni_list.lag_full_add_a_router',{n:pn.n||1,more:PNI_LAG_RT,max:PNI_LAG_MAX})}
`:''}
${PORT.map((P2,i)=>!pn.up&&!msfNope(n.id,c)&&(i>pn.tier||(pn.g1&&i===0))?btn((a=>(pn.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a))({port:P2.n,cost:fmt$((1500+P2.setup/2)*(pn.n||1)),mo:fmt$(P2.pni*(pn.n||1))}),'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)||S.cash<(1500+P2.setup/2)*(pn.n||1)):'').join('')}${!pn.up&&!pn.g1&&pn.tier>pniMin(n.id)&&!msfNope(n.id,c)?btn(tr('link_panels.downgrade_port_price',{port:PORT[pn.tier-1].n,price:portMo(PORT[pn.tier-1].pni*(pn.n||1))}),'downP',{id:pn.id},'ghost sm'):''}${(pn.n||1)1?btn(tr('common.member'),'lagP',{id:pn.id,d:-1},'ghost sm'):''}${NET[n.id].cn?btn(pn.sacrif?tr('common.sacrificial_choke'):tr('city_panel.make_sacrificial_contains_floods_1_2'),'sacrif',{id:pn.id},pn.sacrif?'green sm':'sm'):''}${btn(UI.confirm===pn.id?tr('common.really_remove'):tr('common.remove'),'cancelPni',{id:pn.id},'ghost sm')}
`;} + else{h+=chk.ok?`
${pniG1(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:'1G',cost:fmt$(PNI_G1_COST),mo:fmt$(Math.round(PORT[0].pni/2))}),'pni',{city:c,net:n.id,tier:-1},'sm',S.cashportShown(i)&&i>=pniMin(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(1500+P2.setup/2),mo:fmt$(P2.pni)}),'pni',{city:c,net:n.id,tier:i},'sm',S.cash<1500+P2.setup/2||!portOk(c,i)):'').join('')}
${pniEta(n.id)}${pniMin(n.id)?' · '+tr('city_panel.no_10g_net_starts_at_100g',{net:esc(n.name)}):pniG1(n.id)?' · '+tr('city_panel.sells_pnis_down_to_1g'):''}
${chk.fee?`
${tr('city_panel.paid_peering_price_mo_on_top',{price:fmt$(chk.fee)})}
`:''}`:`
${esc(chk.why)}
`;} + return h+`
`;} +function pniListHtml(c){const f=UI.pniF||'all',az=UI.pniSort==='az',open=UI.pniOpen||{}; + // The search (#199) first: a network it hides needs no value worked out. + const rows=NETS.filter(n=>n.pops.includes(c)).map(n=>[n,S.pni.find(x=>x.city===c&&x.net===n.id)||null]).filter(([n,pn])=>netKeep(n,pn)).map(([n,pn])=>{const chk=pn?null:peerOk(n.id,'pni',c),v=pn?null:pniVal(n.id,c);return {n,pn,v,chk,s:pniStat(n.id,c).k,go:!!pn||(chk.ok&&v.g>=1)};}); + const keep=r=>f==='all'||(f==='t'&&(r.s==='t'||r.s==='none'))||(f==='worth'&&r.v&&r.v.worth)||(f==='pni'&&(r.s==='here'||r.s==='else')); + const val=r=>r.v?r.v.val:-Infinity; + rows.sort((a,b)=>az?a.n.name.localeCompare(b.n.name):(b.v&&b.v.worth)-(a.v&&a.v.worth)||val(b)-val(a)||a.n.name.localeCompare(b.n.name)); + let h=`
${[['all',tr('pni_list.f_all')],['t',tr('pni_list.f_transit')],['worth',tr('pni_list.f_worth')],['pni',tr('pni_list.f_pni')]].map(([k,l])=>btn(l,'pniFilter',{f:k},f===k?'sm':'ghost sm')).join('')}${btn(az?tr('pni_list.sort_az'):tr('pni_list.sort_worth'),'pniSort',{},'ghost sm')}

${tr('pni_list.worth_rule')}

`; + const shown=rows.filter(keep);if(!shown.length)return h+`

${tr('pni_list.nothing_matches')}

`; + let left=listN('pni'),tot=0; + for(const g of PNI_GRP){const gr=shown.filter(r=>pniGrpOf(r.n)===g);if(!gr.length)continue; + const w=gr.filter(r=>r.v&&r.v.worth).length,act=w||gr.some(r=>r.go),isOpen=f!=='all'||netFiltered()||(open[g]??act); + h+=`
${btn(`${isOpen?'▾':'▸'} ${esc(pniGrpL(g))} ${trn('pni_list.n_networks_w_worth_it',gr.length,{w})}`,'pniGrp',{g,o:isOpen?0:1},'ghost sm')}
`; + if(!isOpen)continue;tot+=gr.length; + for(const r of gr){if(left--<=0)break;h+=pniRow(c,r.n,r.pn,r.v,r.chk);}} + return h+listMore('pni',tot,n=>trn('hud_and_panels.n_more_networks',n));} diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js new file mode 100644 index 0000000..9b56fda --- /dev/null +++ b/src/game/93-ui/55-utilities.js @@ -0,0 +1,38 @@ +function utilityKitHtml(city,modal=false){const q=utilityKit(city);if(!q)return '';const p=S.pops[city]; + const row=(label,have)=>`
${label}${have?tr('common.installed'):tr('common.none_304f')}
`; + return `

${tr('utilities.redundancy_kit')}

+ ${row(tr('common.backup_generator'),p.gen)}${row(tr('utilities.second_site'),p.site2)}${row(tr('utilities.two_routers'),(p.routers||1)>=2)} +

${tr('utilities.cache_moves',{n:q.moves.length})}

+ ${q.cost||q.moves.length?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.apply_kit'),'utilityKit',{city,cost:q.cost,modal},'pink',q.cost>0&&S.cash`:`

${tr('utilities.kit_balanced')}

`} +

${tr('utilities.redundancy_note')}

${utilityCachesHtml(city,modal)}`;} +// In the Infra tab (#192): one line and the button, since the generator, second site, routers and caches each have +// their own rows below; the full kit with its caches is in Utilities. +function utilityKitLine(city){const q=utilityKit(city);if(!q)return '';const todo=q.cost||q.moves.length; + return `

${tr('utilities.redundancy_kit')} · ${todo?tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})+(q.moves.length?' · '+tr('utilities.cache_moves',{n:q.moves.length}):''):tr('utilities.kit_balanced')}

+
${todo?btn(tr('utilities.apply_kit'),'utilityKit',{city,cost:q.cost},'pink sm',q.cost>0&&S.cash
`;} +function utilityCachesHtml(city,modal=false){const q=utilityCaches(city);if(!q)return ''; + return `

${tr('common.embedded_caches')}

${tr('utilities.cache_note')}

+

${tr('utilities.cache_quote',{n:q.add.length,mo:fmt$(q.mo)})}

+ ${q.free+1e-9${tr('utilities.cache_ports',{need:q.ports,free:fmtPorts(q.free)})}

`:''} +
${btn(tr('utilities.request_caches',{n:q.add.length}),'utilityCaches',{city,quote:q.key,modal},'pink',!q.add.length||q.free+1e-9
`;} +function utilitiesModal(city,message){if(!S)return;const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); + city=S.pops[city]?city:UI.sel&&UI.sel.type==='city'&&S.pops[UI.sel.id]?UI.sel.id:S.pops[S.home]?S.home:cities[0]; + const rows=utilityPeers(),n=rows.reduce((v,r)=>v+r.requests.length,0),rs=utilityRouteServers().length; + openModal(`

${tr('utilities.title')}

+ ${message?`

${esc(message)}

`:''} +

${tr('utilities.ix_peering')}

${tr('utilities.peering_note')}

+
${btn(tr('utilities.join_route_servers',{n:rs}),'utilityRouteServers',{city},'pink',!rs)}${btn(tr('utilities.request_all',{n}),'utilityPeers',{city},'',!n)}
+

${tr('utilities.route_server_note')}

+ ${ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

${btn(tr('common.peering_policy'),'leftTab',{t:'nets'},'ghost sm')}`:''} + ${rows.map(r=>`
${esc(ixName(r.ix))} · ${tr('utilities.peer_counts',{ready:r.requests.length,existing:r.existing,blocked:r.blocked.length})} + ${r.blocked.map(b=>`

${esc(NET[b.id].name)}: ${esc(b.why)}

`).join('')}
`).join('')}
+ ${utilityKitAllHtml(city)}${popTierAllHtml(city)} + ${cities.length?`
${btn(tr('utilities.view_pop'),'utilityPick',{},'sm')}
${utilityKitHtml(city,true)}`:''}`); +} +// The kit everywhere (#317), and where new POPs get it: the intern's template, which the intern clicks through. +function utilityKitAllHtml(city){const q=utilityKitAll();if(!q)return '';const tpl=opsHired()&&S.ops.tpl.kit; + return `

${tr('utilities.kit_everywhere')}

${tr('utilities.kit_everywhere_note')}

+ ${q.cities.length?`

${trn('utilities.kit_all_quote',q.cities.length,{cost:fmt$(q.cost),mo:fmt$(q.mo)})}${q.moves?' · '+tr('utilities.cache_moves',{n:q.moves}):''}

+
${btn(trn('utilities.kit_all_apply',q.cities.length,{cost:fmt$(q.cost)}),'utilityKitAll',{cost:q.cost,city},'pink',S.cash`:`

${tr('utilities.kit_all_done')}

`} +

${opsHired()?(tpl?tr('utilities.kit_new_pops_on',{name:opsName()}):tr('utilities.kit_new_pops_off',{name:opsName()})):tr('utilities.kit_new_pops_hire')}

+ ${opsHired()?`
${btn(tpl?tr('utilities.kit_new_pops_stop'):tr('utilities.kit_new_pops_start'),'utilityKitNew',{city},tpl?'ghost sm':'sm')}
`:''}
`;} diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js new file mode 100644 index 0000000..240ff20 --- /dev/null +++ b/src/game/93-ui/57-ops-panel.js @@ -0,0 +1,53 @@ +const OPS_TPL_L={bb:N_('ops.tpl_bb'),transit:N_('ops.tpl_transit'),ix:N_('ops.tpl_ix'),kit:N_('ops.tpl_kit')}; +// The Ops panel: the intern, their shift log, and the standing orders with their dials. A bottom sheet on phones. +function opsCard(){if(!S)return '';const last=opsHired()&&S.ops.log[0]; + return `
${opsHired()?`${INTERNS[S.ops.intern].i} ${esc(tr('ops.ops_name',{name:opsName(true)}))}`:`🧑‍💻 ${tr('ops.standing_orders')}`}
+
${opsHired()?esc(last?opsEntry(last):tr('ops.l_quiet',{name:opsName()})):opsCanHire()?tr('ops.hire_pitch_short'):tr('ops.locked',{lv:2})}
+
${btn(opsHired()?tr('ops.standing_orders'):tr('ops.hire_an_intern'),'opsOpen',{},opsHired()?'sm':'pink sm',!opsHired()&&!opsCanHire())}
`;} +const opsEntry=e=>(e.f!==undefined?opsFFLine(e)+' ':'')+(e.r.length||e.f===undefined?opsLine(e):''); +function opsVal(k,p,v=opsP(k,p)){const P=OPSK[k].p[p];return p==='prov'?(v==='cheap'?tr('ops.cheapest'):v==='have'?tr('ops.already_connected'):NET[v].name):P.f(v);} +// A setting as a list to pick from: the option values are positions in the list the action reads again. +const opsSel=(lab,act,args,vals,cur,name)=>``; +const opsCapName=(k,v)=>v?tr('common.price_mo',{price:(OPSK[k].mo?'+':'')+fmt$(v)}):tr('ops.no_cap'); +// The router model and the line system are the build standard's, chosen in its sheet only: in their place, what it says +// and the way there. "Keep as is" leaves each order to its own rule: the next model or line system up, when needed. +const OPS_BSTD={routers:{k:'g',l:N_('ops.p_model'),f:v=>v==='keep'?tr('ops.model_next'):RG[v].n},optup:{k:'sys',l:N_('ops.p_sys'),f:v=>v==='keep'?tr('ops.sys_next'):DF_SYS[v].n}}; +function opsFromStd(k){const x=OPS_BSTD[k];return x?`
${tr(x.l)}${esc(tr('ops.from_bstd',{x:x.f(bstd()[x.k])}))}${pzOn()?'':btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}
`:'';} +function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.ops.spent[k]||0,am=Math.round(S.ops.addMo[k]||0); + return `
${tr(d.t)}
${tr(d.d)}${k==='caches'?' '+tr('ops.caches_rent',{price:fmt$(CACHE_MO),big:fmt$(CACHE_BIG_MO)}):''}
+
+ ${k==='std'?`
${tr('bstd.now_line',{list:S.popStd?esc(bstdLine(bstd())):tr('pop_std.none')})}
${btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}
`:''} + ${on?`
${opsFromStd(k)}${Object.keys(d.p).map(p=>opsSel(tr(d.p[p].l),'opsParam',{k,p},opsOpts(k,p),opsP(k,p),v=>opsVal(k,p,v))).join('')} + ${d.cap?opsSel(d.mo?tr('ops.budget_running'):tr('ops.budget'),'opsCap',{k},opsCaps(k),cap,v=>opsCapName(k,v)):''}
+ ${sp||am?`
${tr('ops.spent_and_mo',{price:fmt$(sp),mo:opsMo$(am)})}
`:''} + ${k==='ix'&&ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

`:''}`:''}
`;} +function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr('ops.ops')}

${tr('ops.standing_orders')}

`; + if(!hired){h+=`

${tr('ops.hire_pitch_weekly')}

`; + if(!rule('clock'))h+=`

${tr('ops.no_clock')}

`;else if(!opsCanHire())h+=`

${tr('ops.locked',{lv:2})}

`; + else h+=Object.entries(INTERNS).map(([id,I])=>`
${tr(I.n)}
${tr(I.d)}
${tr(I.g)}
+ ${btn(tr('ops.hire_mo',{price:fmt$(INTERN_MO)}),'opsHire',{id},'pink sm',S.cash
`).join(''); + openModal(h+opsOnceHtml(),'ops');return;} + const O=S.ops,I=INTERNS[O.intern]; + h+=`
${tr(I.n)}
${tr('ops.salary',{price:fmt$(INTERN_MO),d:dateStr(O.hired)})}
${tr(I.g)}
+ ${btn(UI.confirm==='opsFire'?tr('ops.really_fire'):tr('ops.fire'),'opsFire',{},'ghost sm')}
+

${esc(opsMood())}

${opsReportHtml()} + ${O.log.length?`
${O.log.slice(0,6).map(e=>esc(tr('ops.day_d',{d:e.d})+': '+opsEntry(e))).join('\n')}
`:''} +
${opsSel(tr('ops.floor'),'opsFloor',{},OPS_FLOORS,O.floor,v=>v?fmt$(v):tr('ops.no_cap'))}
`; + h+=`

${tr('ops.how_it_works',{name:opsName()})}

`+OPS.map(opsOrderHtml).join(''); + // Per POP: switch single orders off where the player wants to decide by hand. + const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)),c=S.pops[UI.opsCity]?UI.opsCity:cities[0]; + if(c)h+=`

${tr('ops.per_pop')}

+
${OPS_POP.map(k=>{const here=opsHere(k,c);return ``;}).join('')}
+

${tr('ops.per_pop_note')}

`; + h+=`

${tr('ops.template')}

${tr('ops.template_note',{name:opsName()})}

${OPS_TPL.map(k=>``).join('')}
`; + h+=opsOnceHtml();openModal(h,'ops');} +// The shift report: last week in one paragraph, and this week so far. The daily lines below are the detail. +function opsReportHtml(){const O=S.ops,w=Math.floor(S.day/7),cur=O.wk&&O.wk.w===w&&opsWkAny(O.wk)?O.wk:null,rep=O.rep&&O.rep.w===w-1?O.rep:null;if(!cur&&!rep)return ''; + const row=(t,x)=>`
${t}
${esc(opsWeekLine(x))}
`; + return (rep?row(tr('ops.report_last'),rep):'')+(cur?row(tr('ops.report_now'),cur):'');} +// The big one-off batches (#181, #192) live here now, next to the orders that run them every week. +// The build standard too: its sheet works with or without an intern (targets, new POPs, everything up in one tap). +const opsOnceHtml=()=>`

${tr('ops.by_hand')}

${tr('ops.by_hand_note')}

${btn(tr('utilities.title'),'utilities',{},'sm')}${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'sm')}${pzOn()?'':btn(tr('bstd.title'),'bstdOpen',{},'sm')}
`; +// On a city without a POP: open it from the template in one tap. +function opsTplHtml(c){if(!opsHired())return '';const q=opsTplQuote(c);if(!q)return ''; + return `

${tr('ops.template')}

${esc(tr('ops.tpl_offer',{name:opsName(),list:[tr('ops.tpl_pop'),...q.parts].join(', ')}))}

${btn(tr('ops.tpl_open',{cost:fmt$(q.cost)}),'opsNewPop',{city:c},'pink',S.cash
`;} diff --git a/src/game/93-ui/58-sales-panel.js b/src/game/93-ui/58-sales-panel.js new file mode 100644 index 0000000..71e98ea --- /dev/null +++ b/src/game/93-ui/58-sales-panel.js @@ -0,0 +1,33 @@ +// The sales desk in Deals, and its sheet: the three kinds of salesperson, who is at the desk, and what they cost. +function salesCard(){if(!S||!rule('clock'))return '';const p=slP(),L=S.sales||{}; + return `
${p?`${SALES[p].i} ${esc(tr('sales.at_desk',{name:slCap()}))}`:`💼 ${tr('sales.desk')}`}
+
${p?(L.vp?tr('sales.vp_coming',{n:Math.max(0,L.vp-S.day)}):slCardLine()||tr(SALES[p].d)):salesCanHire()?tr('sales.pitch'):tr('sales.locked',{lv:SALES_LV})}
+
${btn(p?tr('sales.desk'):tr('sales.hire_sales'),'salesOpen',{},p?'sm':'pink sm',!p&&!salesCanHire())}
`;} +function salesModal(){if(!S)return;const p=slP(),L=S.sales||{}; + let h=`
${tr('common.deals')}

${tr('sales.desk')}

`; + h+=`

${tr('sales.intro')}

`; + if(!rule('clock'))h+=`

${tr('ops.no_clock')}

`;else if(!salesCanHire()&&!p)h+=`

${tr('sales.locked',{lv:SALES_LV})}

`; + h+=Object.entries(SALES).map(([id,P])=>{const here=p===id; + const act=here?(id==='ceo'?(L.vp?`${tr('sales.vp_coming',{n:Math.max(0,L.vp-S.day)})}`:btn(tr('sales.ask_vp',{cost:fmt$(SALES_VP)}),'salesVp',{},'ghost sm',S.cash
${tr(P.n)}
+
${tr(P.d)}
${pieOn()?`
🥧 ${tr(SL_SKY[id])}
`:''}${here&&id!=='ceo'?`
${tr('ops.salary',{price:fmt$(P.mo),d:dateStr(L.hired||0)})}
`:''}${act?`
${act}
`:''}
`;}).join(''); + if(p&&p!=='ceo')h+=`

${tr('sales.one_at_a_time')}

`; + h+=p?slAutoHtml(p):rule('clock')?`

${tr('sales.by_hand')}

`:''; + openModal(h,'ops');} +// What each of them does in orbit, shown once there is a rocket company to sell for (99-pie-sales.js). +const SL_SKY={eng:N_('sales.eng_sky'),shark:N_('sales.shark_sky'),ceo:N_('sales.ceo_sky')}; +const SL_AUTO={eng:N_('sales.auto_eng'),shark:N_('sales.auto_shark'),ceo:N_('sales.auto_ceo')}; +const SL_REN={eng:N_('sales.ren_eng'),shark:N_('sales.ren_shark'),ceo:N_('sales.ren_ceo')}; +// Signing for you (39-sales-auto.js): the switch, the minimum, and this week's and last week's tally. +function slAutoHtml(p){const A=S.slAuto||slAutoNew(),w=Math.floor(S.day/7),cur=A.wk&&A.wk.w===w&&slWkAny(A.wk)?A.wk:null,rep=A.rep&&A.rep.w===w-1?A.rep:null; + const row=(x,last)=>`
${esc(slWeekLine(x,last))}
`; + return `

${tr('sales.auto')}

${tr(SL_AUTO[p],{name:esc(slCap())})}

+
+ ${btn(`${tr('sales.decline_below')}: ${A.min?tr('common.price_mo',{price:fmt$(A.min)}):tr('sales.never')}`,'salesMin',{},'ghost sm')}
+ ${rep?row(rep,true):''}${cur?row(cur,false):''}
+

${tr('sales.ren')}

${tr(SL_REN[p],{name:esc(slCap())})}

+
`;} +// On the card in Deals: this week's tally, once there is one. +function slCardLine(){if(!slAutoOn())return '';const A=S.slAuto,x=A.wk&&A.wk.w===Math.floor(S.day/7)&&slWkAny(A.wk)?A.wk:null;return x?esc(slWeekLine(x,false)):'';} diff --git a/src/game/93-ui/59-build-standard.js b/src/game/93-ui/59-build-standard.js new file mode 100644 index 0000000..8d6e7d1 --- /dev/null +++ b/src/game/93-ui/59-build-standard.js @@ -0,0 +1,41 @@ +/* The build standard sheet: every target as a list (two to a row on a phone), grouped POP / ports and peering / fiber; + what is below the standard and what bringing it up costs, priced without changing anything; one tap to do it now; + and the intern's order that keeps it there. A bottom sheet on phones, like the Ops sheet it sits next to. */ +const BSTD_GRP=[['pop',N_('common.pops')],['port',N_('bstd.g_port')],['fiber',N_('bstd.g_fiber')]]; +// Every value a target can take, in the order its list shows them; the current one is always on the list. +function bstdOpts(k){const L=BSTDK[k].v(),cur=bstd()[k];if(!L.includes(cur))L.push(cur);return L;} +function bstdVal(k,v){if(v===BSTDK[k].d&&k!=='rt')return tr('bstd.keep'); + switch(k){case 'g':return RG[v].n+(rgOpen(v)?'':' '+tr('bstd.from_level',{lv:RG[v].lvl})); + case 'rt':return v>1?tr('bstd.at_least_n',{n:v}):tr('bstd.keep'); + case 'site2':case 'gen':return tr('bstd.at_every_pop'); + case 'v6':return tr('bstd.every_bb_city'); + case 'lag':return tr('bstd.at_least_n',{n:v}); + case 'split':return tr('bstd.both_buildings'); + case 'ix':return tr('bstd.every_exchange'); + case 'pni':return tr('bstd.in_n_cities',{n:v}); + case 'sys':return tr('bstd.or_better',{x:DF_SYS[v].n}); + case 'opt':return tr('bstd.fastest'); + case 'wv':return tr('bstd.or_better',{x:LT[v].n});} + return String(v);} +const bstdShown=()=>!!$('modal')&&!$('modal').hidden&&!!$('modalCard').querySelector('[data-sheet="bstd"]'); +// msg: why the sheet is shown again (the quote changed). +function bstdModal(msg){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hired=opsHired(),on=hired&&S.ops.on.std; + let h=`
${tr('ops.ops')}

${tr('bstd.title')}

+

${tr('bstd.tagline')}

${typeof msg==='string'&&msg?`

${esc(msg)}

`:''}`; + for(const [g,lab] of BSTD_GRP)h+=`

${tr(lab)}

${BSTD.filter(x=>x.grp===g&&bstdOn(x)).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}
+

${g==='pop'?tr('bstd.new_pops_note')+(bstdOn(BSTDK.v6)?' '+tr('bstd.v6_note'):'')+(Object.keys(S.pops).some(ptKind)?' '+tr('bstd.kinds_note'):''):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note_two')}

`; + // What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose + // line system has to wait is below it too, but not on the bill. + const n={pop:q.pops,port:q.ports,fiber:q.links},w=q.held.length; + h+=`

${tr('bstd.below')}

${q.n||w?BSTD_GRP.map(([g,lab])=>`
${tr(lab)}${n[g]}
`).join('') + +`
${tr('bstd.cost_now')}${fmt$(q.cost)}
${tr('bstd.cost_mo')}${tr('common.price_mo',{price:opsMo$(q.mo)})}
` + +(q.wait.length?`

${trn('bstd.held',q.wait.length)}

`:'')+(q.wv.length?`

${trn('bstd.held_wave',q.wv.length)}

`:'') + :`

${S.popStd?tr('bstd.all_up'):tr('bstd.none_set')}

`}
`; + // The intern keeps it there: the order's switch and budget, or a word on hiring one. + h+=`

${tr('ops.o_std')}

${hired?`
${esc(tr('bstd.intern_keeps',{name:opsName()}))}
${tr('ops.o_std_wave_d')}
+
+ ${on?`
${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}
`:''}
` + :`

${tr('bstd.hire_note')}

${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}
`}
`; + // The button carries the plan it shows and its total (bstdApply checks both again). + h+=`
${btn(q.n?tr('bstd.apply_now',{cost:fmt$(q.cost)}):w?tr('bstd.apply_wait'):tr('bstd.apply_nothing'),'bstdApply',{quote:bstdPlanKey(bstdPlan(false)),q:q.cost},'pink',!q.n)}
`; + openModal(h,'ops');} diff --git a/src/game/93-ui/60-decommission.js b/src/game/93-ui/60-decommission.js new file mode 100644 index 0000000..3490ab1 --- /dev/null +++ b/src/game/93-ui/60-decommission.js @@ -0,0 +1,23 @@ +/* Decommissioning POPs. Customers that touch a decommissioned city, or ride a removed link, are let go + with an early-termination penalty of three months of their contract. */ +const DECOM_MONTHS=3; +// An express riding a fiber that goes is decommissioned with it. +function decomImpact(cities){const set=new Set(cities),links=xpWith(S.links.filter(l=>set.has(l.a)||set.has(l.b))),lids=new Set(links.map(l=>l.id)); + const biz=S.biz.filter(b=>bCities(b).some(c=>set.has(c))||(b.link&&lids.has(b.link))); + const pen=b=>Math.max(2000,Math.round(b.fee?b.fee*0.5:b.bw*b.rate*DECOM_MONTHS)); + return {links,biz,pen,fee:biz.reduce((a,b)=>a+pen(b),0),eye:cities.reduce((a,c)=>a+(R.cityEye[c]||0),0)};} +function decomModal(){const sel=[...(UI.decom||[])],im=decomImpact(sel),all=Object.keys(S.pops),left=all.length-sel.length; + const rows=all.map(c=>``).join(''); + openModal(`

${tr('common.decommission_pops')}

+

${tr('decommission.pick_the_pops_to_shut_down')}

${rows} + ${sel.length?`
${tr('common.links_removed')}${im.links.length}
${tr('decommission.eyeballs_you_stop_serving')}${fmtG(im.eye)}
${trn('decommission.n_customer_let_go',im.biz.length)}${fmt$(im.fee)}
${im.biz.length?`

${im.biz.map(b=>esc(b.name)+' '+fmt$(im.pen(b))).join(' · ')}

`:''}${(z=>z.length?`

${tr('wisp.decom',{list:z.map(x=>esc(WISP[x].n)).join(', ')})}

`:'')(sel.flatMap(c=>wispAt(c).filter(wispZ)))}`:''} + ${left<1?`

${tr('decommission.keep_at_least_one_pop')}

`:''} +
${btn(sel.length?trn('decommission.decommission_n_pop_pay_fee',sel.length,{fee:fmt$(im.fee)}):tr('decommission.pick_a_pop'),'decomGo',{},'red',!sel.length||left<1)}${btn(tr('common.keep_them'),'closeModal',{},'ghost')}
`);} +function decommission(cities){const set=new Set(cities),im=decomImpact(cities),lids=new Set(im.links.map(l=>l.id)),bids=new Set(im.biz.map(b=>b.id)); + const back=chBack(im.links);S.links=S.links.filter(l=>!lids.has(l.id));prunePairMet();S.biz=S.biz.filter(b=>!bids.has(b.id));S.offers=S.offers.filter(o=>!bCities(o).some(c=>set.has(c))); + S.transit=S.transit.filter(t=>!set.has(t.city));S.pni=S.pni.filter(x=>!set.has(x.city));S.caches=S.caches.filter(x=>!set.has(x.city));S.nni=(S.nni||[]).filter(x=>!set.has(x.city)); + for(const c of cities){for(const x of ixIdsIn(c)){delete S.ixp[x];delete S.rs[x];if(S.ixn)delete S.ixn[x];if(S.ixSite)delete S.ixSite[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}delete S.myIx[c];S.scrubs=S.scrubs.filter(x=>x.city!==c);if(S.ops)delete S.ops.skip[c];if(S.popTiers)delete S.popTiers.at[c];delete S.pops[c];} + const rem=remoteCities();for(const x in S.ixp){const c=ixCity(x);if(!S.pops[c]&&!rem.includes(c)){delete S.ixp[x];delete S.rs[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}} + if(set.has(S.home))S.home=Object.keys(S.pops)[0]; + purgeInc();S.cash-=im.fee;S.stats.decom=(S.stats.decom||0)+cities.length; + toast(trn('decommission.n_pop_decommissioned_fee_in_early',cities.length,{fee:fmt$(im.fee),m:im.biz.length}),'bad');if(back)toast(trn('links.n_optic_back_on_the_spares_shelf',back),'good');} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js new file mode 100644 index 0000000..47db537 --- /dev/null +++ b/src/game/93-ui/70-link-panels.js @@ -0,0 +1,206 @@ +const portMo=v=>v?tr('common.price_mo',{price:fmt$(v)}):tr('common.free'); +function ixSection(c){const ids=ixIdsIn(c);if(ids.length<2)return ixBlock(c,false); + let h=`

${tr('common.internet_exchanges')}

${tr('link_panels.n_exchanges_compete_in_city_members',{n:ids.length,city:esc(CITY[c].name)})}

`; + for(const x of ids)h+=ixBlock(x,true);return h;} +function ixBlock(c,multi){const city=ixCity(c),C=CITY[city],ix=ixName(c),X=XIXM[c];let h=''; + h+=`

${multi?esc(ix)+(X?' '+tr('common.challenger')+'':' '+tr('common.incumbent')+''):tr('common.internet_exchange')}

`; + if(!ix&&C.cn){h+=`

${tr('link_panels.running_an_exchange_in_mainland')}

`;} + else if(!ix){h+=`

${tr('link_panels.there_s_no_ix_in_city',{city:C.name})}

${S.pops[city]?btn(tr('link_panels.found_your_own_ix_cost_mo',{cost:fmt$(MYIX_COST),mo:fmt$(MYIX_MO)}),'foundIx',{city:c},'pink',S.cash'+tr('link_panels.build_a_pop_here_first')+'

'}`;} + else if(S.ixp[c]===undefined){h+=`

${tr('link_panels.ix_is_a_shared_switch_one',{ix:esc(ix),list:(()=>{const m=ixMembers(c),big=m.filter(id=>!NET[id].tail),t=m.length-big.length;return (big.map(id=>esc(NET[id].name)).join(', ')||tr('common.nobody_yet'))+(t?trn('link_panels.plus_n_small_network',t):'');})()})}

${S.pops[city]?'':REMOTE_WARN}${X?`

${esc(X.blurb)} ${X.freeTo!==undefined?tr('link_panels.ports_up_to_port_are_free',{port:PORT[X.freeTo].n}):tr('link_panels.ports_at_p_of_the_usual',{p:Math.round(ixMul(c)*100)})}

`:''}${CITY[city].ixCheap?`

${tr('link_panels.run_by_a_nonprofit_public_prices')}

`:''}${isDk(c)?`

${tr('link_panels.run_by_de_kicks_group_no')}

`:''}
${PORT.map((P2,i)=>btn(isDk(c)?tr('link_panels.port_port_price_on_request',{port:P2.n}):tr('link_panels.port_port_price',{port:P2.n,price:portMo(ixPortMo(c,i))}),'buyIx',{city:c,tier:i},'',(!isDk(c)&&S.cash1))).join('')}
`;} + else{const mine=!!S.myIx[c],u=R.useIx[c]||0,cap=ixCap(c),set=ixSessions(c),xdown=S.ev.ixdown&&S.ev.ixdown[c]>S.day; + h+=`
${mine?tr('link_panels.your_own_fabric_name',{name:myFab(c).n}):lagName(S.ixp[c],(S.ixn||{})[c])}${xdown?' · FABRIC DOWN':''}${fmtG(u)}
${prefCtl('ix',c,S.ixPref&&S.ixPref[c])}${S.pops[city]?siteCtl('ix',c,city,(S.ixSite||{})[c]):''}`; + if(isDk(c)&&S.dk){const ad=S.dk.add[c]||[],rt=S.dk.ret[c];h+=`

${rt&&rt>S.day?tr('link_panels.de_kicks_personalised_pricing_p_of',{p:Math.round(dkMult(c)*100),n:rt-S.day}):tr('link_panels.de_kicks_personalised_pricing_p_of_3d4f',{p:Math.round(dkMult(c)*100)})}

`; + for(const x of ad)h+=`
${esc(x.n)}
${esc(x.blurb)} · ${tr('common.price_mo',{price:fmt$(x.mo)})}
${btn(UI.confirm==='dk'+c+x.n?tr('link_panels.lose_exclusive_benefits'):tr('common.opt_out'),'dkOptOut',{city:c,n:x.n},'ghost sm')}
`;} + if(isRemote(c))h+=`

${trn('link_panels.remote_port_via_a_reseller_1',ixMembers(c).filter(noRemote).length)}

`; + if(mine){const f=S.myIx[c].fab|0,N=MYIX_FAB[f+1];h+=`
${tr('link_panels.members_paying_you')}${tr('link_panels.n_of_up_to_max_price',{n:S.myIx[c].members.length,max:myFab(c).max,price:fmt$(S.myIx[c].members.length*MYIX_FEE)})}
${N?`
${btn(N.lvl>lvl()?tr('link_panels.name_fabric_level_lv',{name:N.n,lv:N.lvl}):tr('link_panels.upgrade_fabric_to_name_cost_mo',{name:N.n,cost:fmt$(N.cost),mo:fmt$(N.mo)}),'myIxUp',{city:c},'pink sm',N.lvl>lvl()||S.cash

${tr('link_panels.a_bigger_fabric_carries_more_traffic')}

`:'

'+tr('link_panels.biggest_fabric_money_can_buy')+'

'}`;} + else h+=`
${PORT.map((P2,i)=>i>S.ixp[c]&&portShown(i)?btn(tr('common.upgrade_port_price',{port:P2.n,price:portMo(ixPortMo(c,i)*((S.ixn||{})[c]||1))}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)):'').join('')}${S.pops[city]&&((S.ixn||{})[c]||1)1?btn(tr('common.member'),'lagIx',{city:c,d:-1},'ghost sm'):''}${S.ixp[c]>0?btn(tr('link_panels.downgrade_port_price',{port:PORT[S.ixp[c]-1].n,price:portMo(ixPortMo(c,S.ixp[c]-1)*((S.ixn||{})[c]||1))}),'downIx',{city:c},'ghost sm'):''}${btn(S.rs[c]?tr('link_panels.leave_route_server'):tr('link_panels.join_route_server'),'rs',{city:c},S.rs[c]?'ghost sm':'pink sm')}${S.rs[c]&&ppol()!=='open'?`${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}`:''}${btn(UI.confirm==='ix'+c?tr('common.really_leave'):tr('common.leave_ix'),'cancelIx',{city:c},'ghost sm')}
`; + h+=`
`; + {const elig=mine?[]:ixMembers(c).filter(id=>!set.has(id)&&peerOk(id,'ix',c).ok);if(elig.length>1)h+=`
${btn(tr('link_panels.request_all_n_willing_peers',{n:elig.length}),'peerAll',{city:c},'pink sm')}
`;} + {const ms=ixMembers(c),shown=ms.filter(id=>netKeep(NET[id],set.has(id)));if(ms.length&&!shown.length)h+=netNone();} + for(const id of ixMembers(c).filter(id=>netKeep(NET[id],set.has(id))).sort((a,b)=>NSH[b]-NSH[a])){const n=NET[id],on=set.has(id),viaRs=on&&!S.peers[id+'@'+c]&&!mine,chk=peerOk(id,'ix',c); + h+=`
${logo(n)}
${esc(n.name)}
${TYPE_L[n.type]} ${n.pol} · ${(NSH[id]*100).toFixed(NSH[id]<0.01?1:0)}%${n.tail?' '+tr('common.tiny')+'':''}
${!on&&!chk.ok?`
${esc(chk.why)}
`:''}
+ ${on?(viaRs||mine?`${mine?tr('common.member_fef5'):tr('common.via_rs')}`:btn(tr('common.peered_ce2f'),'unpeer',{city:c,net:id},'green sm',false,tr('link_panels.click_to_tear_down'))):btn(tr('common.request'),'peer',{city:c,net:id},'sm',!chk.ok)}
`;} + h+=`
`;} + h+=`
`;return h; +} +function borderSection(l){const w=borderShut(l);return w?`

${tr('link_panels.border_closed')}

${w==='gulf'?tr('link_panels.a_diplomatic_spat_has_closed_the')+' '+tr('link_panels.back_in_n_days',{n:S.ev.gulf-S.day}):tr('link_panels.russia_has_unplugged_itself_from_the')}

`:'';} +// Both ends of a link in its panel header open that city (#196), say to upgrade the router there for a bigger wave. +const lkEnds=l=>[l.a,l.b].map(c=>cityOn(c)?btn(esc(CITY[c].name),'popGo',{city:c},'clink'):esc(CITY[c].name)).join(' ⇄ '); +function vxcPanel(l){ + const load=R.load[l.id]||0,cap=VXC[l.vt].g,u=load/cap,down=linkDown(l),f=FAB[l.prov]; + let h=`
${tr('link_panels.virtual_circuit_name_km_km',{name:esc(f.name),km:l.km.toLocaleString()})}

${lkEnds(l)}

`; + h+=borderSection(l);if(down&&!borderShut(l))h+=`

${tr('common.fabric_outage')}

${tr('link_panels.name_is_down_nothing_you_can',{name:esc(f.name)})}

`; + h+=`

${tr('common.capacity')}

${tr('link_panels.name_circuit',{name:VXC[l.vt].n})}${fmtG(load)} / ${fmtG(cap)}
+
${tr('common.monthly')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${!S.pops[l.b]?`

${tr('link_panels.remote_peering_leg_into_ix',{ix:esc(CITY[l.b].ix)})}

`:''} +
${VXC.map((V,t)=>t>l.vt?btn(`${V.n} ${tr('common.price_mo',{price:fmt$(vxcMo(l.km,l.sub,t))})}`,'upVxc',{id:l.id,t},'sm'):'').join('')}
+ ${trafficSection(l)}${metricSection(l)} +
${btn(UI.confirm===l.id?tr('common.really_cancel'):tr('common.cancel_circuit'),'cancelVxc',{id:l.id},'ghost sm')}
`; + return h; +} +function prefCtl(kind,id,cur){cur=cur||'normal';return `
${tr('common.egress')}${Object.keys(PREF).map(v=>btn(PREF[v],'setPref',{kind,id,v},cur===v?'pink sm':'ghost sm')).join('')}
`;} +// Trial routing is isolated from the live save, counters and scenic-route memory. "Before" is the live routing, which +// after() keeps current, so a check costs one compute() on a big network, not two. +function linkTrial(id){const save=S,live=R,hot=UI.hotMap,cache=TE_CACHE; + try{const l0=save.links.find(x=>x.id===id);if(!l0||linkDown(l0))return null; + S=JSON.parse(JSON.stringify(save));const l=S.links.find(x=>x.id===id),before=live;l.cut=S.day+1;compute(); + const allowed=new Set(Object.keys(S.pops).filter(popUp).concat(remoteCities())),adj={}; + for(const x of S.links)if(!linkDown(x)&&allowed.has(x.a)&&allowed.has(x.b)){(adj[x.a]=adj[x.a]||[]).push(x.b);(adj[x.b]=adj[x.b]||[]).push(x.a);} + const seen=new Set([l.a]),q=[l.a];for(let i=0;i.01)losses.push({name:CITY[c].name,g});} + for(const b of S.biz)if(BIZ_T[b.type].l2){const g=Math.max(0,(before.l2[b.id]||0)-(R.l2[b.id]||0));if(g>.01)losses.push({name:b.name,g});} + const busy=S.links.filter(x=>x.id!==id&&!linkDown(x)&&capOf(x)>0&&(R.load[x.id]||0)/capOf(x)>=.995).map(x=>({name:CITY[x.a].name+' ⇄ '+CITY[x.b].name,g:R.load[x.id]||0,cap:capOf(x)})); + return {split:!seen.has(l.b),loss:losses.reduce((a,x)=>a+x.g,0),losses,busy,day:S.day}; + }finally{S=save;R=live;UI.hotMap=hot;TE_CACHE=cache;}} +function linkCheckModal(l){const t=linkTrial(l.id);if(!t)return; + const title=t.split?tr('link_panels.this_backhoe_wins'):t.loss>.01?tr('link_panels.connected_but_tight'):tr('link_panels.one_backhoe_is_not_enough'); + openModal(`

${tr('common.redundancy_check')}

${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)} · ${dateStr(t.day)}

${title}

${t.split?tr('link_panels.no_alternate_backbone_path_connects'):t.loss>.01?tr('link_panels.an_alternate_path_exists_but_current'):tr('link_panels.with_current_demand_and_routing_this')}

${tr('link_panels.additional_traffic_lost')}${fmtG(t.loss)}
${t.losses.length?`

${tr('common.service_affected')}

${t.losses.map(x=>`
${esc(x.name)}−${fmtG(x.g)}
`).join('')}`:''}${t.busy.length?`

${tr('link_panels.full_links_during_the_test')}

${t.busy.slice(0,6).map(x=>`
${esc(x.name)}${fmtG(x.g)} / ${fmtG(x.cap)}
`).join('')}`:''}

${tr('link_panels.snapshot_only_one_selected_link')}

${btn(tr('common.close'),'closeModal',{},'ghost')}
`,'link-check');} +function linkCheckControl(l){return `

${tr('common.redundancy_check')}

${tr('link_panels.what_happens_if_this_link_fails')}

${btn(tr('common.check_redundancy'),'linkCheck',{id:l.id},'ghost sm',linkDown(l))}
`;} +// At its own POP a carrier's port always takes that carrier's traffic (25-direct-egress.js). From POPs with no port of it, the +// traffic goes to the nearest transit port, or across your network to this one. Only worth asking when something else could take it. +function carryCtl(t){if(Object.keys(S.pops).length<2||!S.transit.some(x=>x.net!==t.net))return '';const n=esc(NET[t.net].name); + return `
${tr('link_panels.traffic_for_net',{net:n})}${btn(tr('link_panels.nearest_port'),'setCarry',{id:t.id,on:0},t.carry?'ghost sm':'pink sm')}${btn(tr('link_panels.carry_here'),'setCarry',{id:t.id,on:1},t.carry?'pink sm':'ghost sm')}
${t.carry?tr('link_panels.every_pop_carries_net_s_traffic',{net:n}):tr('link_panels.at_this_pop_net_s_traffic_always',{net:n})}
`;} +function trafficSection(l){ + const rec=R.ef[edgeKey(l)],n=pairLinks(l.a,l.b).length; + let h=linkCheckControl(l)+`

${tr('link_panels.what_s_on_this_link')}

`; + if(!rec){return h+`

${tr('link_panels.no_traffic_right_now')}

`;} + const tot=Object.values(rec.net).reduce((a,b)=>a+b,0)||1; + const nets=Object.entries(rec.net).sort((a,b)=>b[1]-a[1]); + const col=id=>id==='junk'?'#FF4D5E':id==='l2vpn'?'#7B61FF':id==='scrub'?'#22C47A':NET[id].col,nm=id=>id==='junk'?tr('common.ddos_junk'):id==='l2vpn'?tr('common.l2vpn_customers'):id==='scrub'?tr('common.scrubbed_traffic'):NET[id].name; + h+=`${n>1?`

${tr('link_panels.totals_for_all_n_links_between',{n})}

`:''}
${nets.map(([id,v])=>``).join('')}
`; + h+=`

${tr('common.content_from')}

`+nets.slice(0,6).map(([id,v])=>`
${esc(nm(id))}${fmtG(v)} · ${pct(v/tot)}
`).join(''); + const egs=Object.entries(rec.eg).sort((a,b)=>b[1]-a[1]); + h+=`

${tr('link_panels.enters_your_network_at')}

`+egs.slice(0,6).map(([k,v])=>{const d=R.egDesc[k];return `
${esc(d.lab)}
${CITY[d.city].name} · ${fmtG(v)} · ${pct(v/tot)}
${btn(tr('common.open'),'goEgress',{city:d.city,k:d.k},'ghost sm')}
`;}).join(''); + const dst=Object.entries(rec.dst).sort((a,b)=>b[1]-a[1]); + h+=`

${tr('link_panels.going_to_customers_in')}

`+dst.slice(0,6).map(([c,v])=>`
${CITY[c].name}${fmtG(v)} · ${pct(v/tot)}
`).join(''); + const u=tot/pairLinks(l.a,l.b).filter(x=>!linkDown(x)).reduce((a,x)=>a+capOf(x),0); + if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`

${tr('link_panels.biggest_feeder_egress_in_city_set',{egress:esc(d.lab),city:CITY[d.city].name})}

`;} + return h+``; +} +// Safari keeps the number field focused through a button tap, and renderPanel() skips a focused field: let go first (#131). +const metBlur=()=>{const t=$('metIn');if(t&&document.activeElement===t)t.blur();}; +function metricSection(l){const key=edgeKey(l),cur=pairMet(key),pl=pairLinks(l.a,l.b),sb=!!l.standby,base=l.km+60,sel=k=>cur===k?'pink sm':'ghost sm'; + let h=`

${tr('common.routing_metric')}

${tr('link_panels.your_routers_pick_the_lowest_cost_0160')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},sel(k))).join('')}${btn(tr('common.custom'),'setMetric',{id:l.id,v:'custom'},sel('custom'))}
`; + const cm=pairCm(key); + if(cm){const k=cm.k,[lo,hi]=MET_LIM[k],md=m=>k===m?'pink sm':'ghost sm'; + const pre=Object.keys(MET).map(m=>`${MET[m].l} ×${MET[m].f} = ${Math.round(base*MET[m].f)}`).join(', '); + h+=`

${tr('link_panels.a_link_s_cost_is_its')} ${tr('link_panels.presets_on_this_link_list',{list:pre})}

+
${btn(tr('common.multiplier'),'metricMode',{id:l.id,k:'f'},md('f'))}${btn(tr('common.cost'),'metricMode',{id:l.id,k:'w'},md('w'))}
+
${btn(tr('common.set'),'metricSet',{id:l.id},'pink sm')}
+

${k==='w'?tr('link_panels.cost_the_exact_number_whatever_the'):tr('link_panels.multiplier_scales_the_distance_cost')} ${tr('link_panels.cost_on_this_link_w_allowed',{w:Math.round(pairW(key,l.km)),lo:k==='w'?lo:'×'+lo,hi:k==='w'?hi:'×'+hi})}

`;} + // Standby only means something next to another link; a link left on standby alone can still be taken off it. + if(pl.length>1||sb){const busy=(R.load[l.id]||0)>1e-3,alone=!pl.some(x=>x!==l&&!x.standby&&!linkDown(x)); + const st=!sb?tr('link_panels.a_link_on_standby_carries_traffic'):!busy?tr('link_panels.on_standby_idle_while_the_other'):alone?tr('link_panels.on_standby_but_carrying_the_traffic'):tr('link_panels.on_standby_taking_the_overflow'); + h+=`

${tr('common.standby')}

${st}

${sb?btn(tr('link_panels.take_it_off_standby'),'setStandby',{id:l.id,on:0},'pink sm'):btn(tr('link_panels.put_this_link_on_standby'),'setStandby',{id:l.id,on:1},'ghost sm')}
`;} + return h+`
`;} +function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2; + let h=`

${tr('link_panels.behind_the_great_firewall')}

${tr('link_panels.mainland_china_plays_by_its_own',{list:CN_BLOCKED.slice(0,4).map(esc).join(', '),pct:pct(loss)})}

`; + if(st==='none')h+=`

${tr('link_panels.foreign_networks_need_a_local_joint')}

${btn(tr('link_panels.apply_for_a_license_price_mo_n_days',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO),n:leadDays(45)}),'applyCn',{},'pink',S.cash${tr('link_panels.license_paperwork_in_progress_n_days',{n:Math.max(0,S.cnLic.ready-S.day)})}

`; + else h+=`

${tr('link_panels.your_joint_venture_holds_an')}

`; + if(R.gfwCross>0.5)h+=`
${tr('link_panels.your_traffic_crossing_the_border')}${fmtG(R.gfwCross)}
${tr('link_panels.lost_on_the_way')}${fmtG(R.gfwLost)}
`; + return h+`
`;} +function subUpgradePanel(l){return `

${tr('common.submarine_transmission')}

${tr('common.better_terminals_and_optical_tuning')}

`+Object.entries(SUB_UPGRADES).map(([k,U])=>{ + const at=l['sub'+k],done=subUpgradeReady(l,k),cost=subUpgradeCost(l,k),preview={...l,['sub'+k]:S.day},use=at!==undefined||subHelps(l.km,k,l['sub'+subOther(k)]!==undefined); + const status=done?tr('common.installed'):at!==undefined?tr('link_panels.ready_in_n_days',{n:Math.max(0,at-S.day)}):tr('link_panels.price_n_days',{price:fmt$(cost),n:leadDays(U.days)}); + return `
${tr(U.n)}
${status}
${tr('common.up_to_g_per_channel',{g:fmtG(submarineRate(preview))})}
${use?'':`
${tr('reach_and_subsea.makes_no_difference_on_this_cable')}
`}
${at===undefined?btn(tr('common.install'),'subUpgrade',{id:l.id,k},'sm',!use||lvl()<4||S.cash`;}).join('');} +// The cable ship on a subsea cut (50-cable-ships.js), under the cut's story. +const shipNote=i=>{const t=i&&shipStatus(i);return t?`

🚢 ${esc(t)}

`:'';}; +// Building your own subsea cable: survey and factory first, then the lay ship at sea; a second one can be booked. +function layPanel(l){const d=S.day,st=layStart(l),q=layQuote(l),km=Math.round(layDone(l,d)*l.km),two=l.ship2?tr('cable_ships.ship_and_ship',{a:layName(l),b:layName(l,1)}):layName(l); + let h=d${tr('cable_ships.survey_permits_and_the_cable_factory')}${trn('cable_ships.laying_starts_in_n_days',st-d)}
` + :`
${tr('cable_ships.ships_lay_the_cable',{ships:esc(two)})}${tr('cable_ships.km_of_km',{km:km.toLocaleString(),of:Math.round(l.km).toLocaleString()})}
`; + const k=prepSteps(l),pc=prepCost(l),fast=Math.min(k*PREP_STEP,l.ready-prepFloor(l)); + if(k)h+=`
${btn(tr('cable_ships.hurry_the_permits_and_the',{n:Math.min(PREP_STEP,fast),price:fmt$(pc)}),'seaRush',{id:l.id},'sm',S.cash1?btn(tr('cable_ships.as_fast_as_money_goes',{n:fast,price:fmt$(k*pc)}),'seaRush',{id:l.id,all:1},'sm',S.cash`; + if(d${tr('cable_ships.money_only_goes_so_far',{n:prepMin(l)})}

`; + if(q)h+=`
${btn(tr('cable_ships.book_a_second_lay_ship',{price:fmt$(q.cost),n:q.save}),'layShip',{id:l.id},'sm',S.cash

${tr('link_panels.only_a_few_dozen_cable_ships')}

`; + else if(!l.ship2&&d${tr('link_panels.only_a_few_dozen_cable_ships')}

`; + return h;} +function dfPanel(l){ + const load=R.load[l.id]||0,cap=dfCap(l),u=cap?load/cap:0,bld=l.ready>S.day,A=CITY[l.a].name,B=CITY[l.b].name,inc=S.inc.find(i=>i.ref===l.id||i.ref===(l.trench||l.id)),amps=ampCount(l.km),sysD=DF_SYS[l.sys]; + let h=`
${tr('link_panels.dark_fiber_kind_km_km',{kind:l.own?tr('link_panels.your_own_build'):tr('common.leased_iru'),km:l.km.toLocaleString()})}

${lkEnds(l)}

`; + if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); + h+=`

${l.own?tr('common.under_construction'):tr('common.being_spliced')}

${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}${tr('common.n_days_left',{n:l.ready-S.day})}
${l.own&&l.sub?layPanel(l):l.own?`
${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash${!crewSteps(l)&&l.ready>S.day+1?`

${tr('link_panels.crews_can_halve_a_build_at_most')}

`:''}`:''}

${tr('link_panels.you_can_pre_install_optics_now')}

`;} + else if(inc&&linkDown(l))h+=`

${tr('common.dark_6bf5')}

${esc(inc.msg)}

${shipNote(inc)}${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; + h+=borderSection(l); + h+=`

${tr('common.capacity')}

${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${mwG(l)?` · ${tr('market.g_sold_as_managed',{g:fmtCap(mwG(l))})}`:''}${xpSlots(l)?` · ${trn('express.n_carry_expresses',xpSlots(l))}`:''}${fmtG(load)} / ${fmtG(cap)}
+ ${seatPanel(l)}${l.own&&l.sub?`
${tr('common.cable_design')}${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}
`:''} +
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${tr('link_panels.n_amp_huts',{n:amps})}${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}
${!bld&&!(l.ch||[]).length?`

${tr('link_panels.this_fiber_is_dark_add_optics')}

`:''}
`; + if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='mwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l); + h+=`

${tr('link_panels.selling_spare_capacity')}

${tr('link_panels.other_carriers_rent_what_you_do')}

+
${tr('common.free_channels')}${fc} / ${chMax(l)}
${sold.map(b=>`
${esc(b.name)}
${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}
${pathCtl(b)}
`).join('')} + ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(tr('common.accept'),'accept',{id:off.id},'pink sm')}
`:brListHtml(l,fc)}
`;} + h+=`

${tr('common.optics')}

${tr('link_panels.each_channel_is_a_pair_of')}

`; + if(l.own&&l.sub&&!l.seat)h+=subUpgradePanel(l); + for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k); + const md=optMode(k,l),cc=chCost(l,k),sp=spareN(k); + h+=`
${O.n} ${optModes(k,l).map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')}
${esc(O.blurb)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${sp?` · ${trn('link_panels.n_spare_on_the_shelf',sp)}`:''}${(np=>np>1?` · ${trn('link_panels.takes_n_router_ports_per_end',np)}`:'')(Math.max(chPorts(k,l.a),chPorts(k,l.b)))}
${md&&!md.full?`
⚠️ ${tr('link_panels.runs_at_g_per_channel_on',{g:fmtG(md.g)})} ${(!l.sub||l.seat)&®enNeed(k,l)>(l.regen|0)?trn('link_panels.n_regen_site_would_bring_it',regenNeed(k,l),{g:fmtG(O.g)}):''}
`:''}${why?`
${esc(why)}
`:''}${!techOk('opt',k,O.lvl)&&demoCan(O.lvl)?`
${demoBtn('opt',k,O.lvl,'','ghost sm')}
`:''}${opticCountControl(l,k,n)}
${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(sp?`+ ${cc?tr('link_panels.spare_price',{price:fmt$(cc)}):tr('common.spare')}`:`+ ${fmt$(cc)}`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash`;} + {const st=Object.keys(OPT).filter(k=>spareN(k)>0);h+=`

${tr('link_panels.unplugged_optics_go_on_the_spares')}

`; + {const used=[...new Set(l.ch||[])].filter(k=>OPT[k]&&OPT[k].lvl<=glassLvl());if(used.length)h+=`
${used.map(k=>btn(tr('link_panels.stock_a_spare_optic_price',{optic:OPT[k].n,price:fmt$(optCost(k))}),'buySpare',{o:k},'ghost sm',S.cash=64)).join('')}

${tr('link_panels.spares_bought_now_are_already_paid')}

`;}if(st.length)h+=`

${tr('common.spares_shelf')}

`+st.map(k=>`
${spareN(k)} × ${OPT[k].n}
${btn(tr('link_panels.sell_one_price',{price:fmt$(spareValue(k))}),'sellSpare',{o:k},'ghost sm')}
`).join('');} + const rg=l.regen|0,rgAdd=regenAddCost(l); + h+=`

${tr('common.line_system')}

${esc(sysD.n)}${tr('link_panels.n_amplifiers',{n:amps})}
+
${tr('common.regen_sites')}${rg?tr('link_panels.n_optical_spans_of_km_km',{n:rg,km:spanKm(l).toLocaleString()}):tr('common.none')}

${tr('link_panels.a_regen_site_turns_the_light',{price:fmt$(REGEN_MO)})}

${l.seat?`

${tr('broker.seat_regen_note')}

`:''}${l.sub&&l.own&&!l.seat?`

${tr('link_panels.no_regen_sites_in_the_middle')}

`:`
${rg`}

${esc(sysD.blurb)}

${(()=>{const t=sysNext(l);if(!t)return '';const T=DF_SYS[t],c=sysUpCost(l);return !techOk('sys',t,T.lvl)?demoBtn('sys',t,T.lvl,tr('link_panels.sys_level_n',{sys:T.n,n:T.lvl}),'sm'):btn(tr('link_panels.upgrade_to_sys_price',{sys:T.n,price:fmt$(c)}),'upSys',{id:l.id},'sm',S.cash

${tr('link_panels.spare_optics_and_amplifier_cards_on')}

`; + h+=xpDfSection(l); + {const sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc');h+=`

${tr('common.redundancy')}

${sib.length?tr('link_panels.other_links_between_these_cities'):tr('link_panels.this_is_the_only_link_between')}

${sib.map(x=>`
${esc(capName(x))} ${linkDown(x)?''+tr('common.cut')+'':''}${x.standby?' '+tr('common.standby')+'':''}
${(x.trench||x.id)===(l.trench||l.id)?tr('common.same_trench'):tr('common.diverse_route')}
${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join('')}
${btn(tr('link_panels.add_parallel_link'),'addParallel',{id:l.id},'pink sm')}
`;} + h+=`${trafficSection(l)}${metricSection(l)}
${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):(l.own?tr('link_panels.abandon_the_fiber'):tr('link_panels.cancel_the_iru')),'rmLink',{id:l.id},'ghost sm')}${cabBack(l)>0?`

${tr('link_panels.giving_it_up_now_returns_price',{price:fmt$(cabBack(l))})}

`:''}
`; + return h; +} +function offersHere(c){ + const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; + return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${spotWhy(o)}${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${ip4Why(o)}${bRisk(o)}${reqList(o)}${reqFixHtml(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; +} +function linkPanel(id){ + const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} + if(l.kind==='vxc')return vxcPanel(l); + if(l.kind==='sat')return satPanel(l); + if(l.kind==='df')return dfPanel(l); + if(l.kind==='xp')return xpPanel(l); + const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk); + let h=`
${l.cable?esc(CAB[l.cable].name):l.sub?tr('common.subsea_cable'):tr('common.terrestrial_fiber')} · ${l.km.toLocaleString()} km

${lkEnds(l)}

`; + if(cut)h+=`

${tr('common.cut_2e50')}

${inc?esc(inc.msg):''} ${inc&&shipSea(inc)?'':tr('link_panels.back_in_n_days',{n:l.cut-S.day})}

${shipNote(inc)}${inc&&inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; + h+=borderSection(l); + h+=`

${tr('common.capacity')}

${tr('link_panels.name_wave',{name:LT[l.tier].n})}${fmtG(load)} / ${fmtG(cap)}
+
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${l.cable?`
${tr('common.cable_system')}${esc(CAB[l.cable].name)}
`:''} +
${tr('common.wave_lease')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${u>=0.9?`

${tr('link_panels.congested_upgrade_it_or_add_a')}

`:''} +
${LT.map((T,i)=>{const d=Math.round(waveMo(l.km,l.sub,i)*(l.mult||1)),sw=subWaveWhy(i,l.km,l.sub),so=i>l.tier&&!sw&&soldOut(l.a,l.b,i,l.cable),ok=waveOk(l.a,l.b,i);return i>l.tier&&waveShown(i)?btn(`${T.n} ${sw?tr('common.too_far_for_this_cable'):so?tr('link_modal.sold_out_for_n_days',{n:Math.max(1,so.until-S.day)}):ok?tr('common.price_mo',{price:fmt$(d)}):tr('link_panels.needs_what',{what:esc(waveNeed(i))})}`,'upLink',{id:l.id,tier:i},'sm',S.cash${tr('common.km_km_of_cable_carries_at',{km:Math.round(l.km).toLocaleString(),g:fmtCap(subCarrier(l.km))})}${l.tier>subMaxTier(l.km)?' '+tr('link_panels.your_wave_was_sold_before_the'):''}

`:''}
+

${tr('common.redundancy')}

${mates.length?trn('link_panels.shares_a_trench_with_n_other',mates.length):sib.length?tr('link_panels.runs_on_its_own_route_a'):tr('link_panels.this_is_the_only_link_between')}

+ ${sib.map(x=>`
${tr('link_panels.name_parallel_link',{name:capName(x)})} ${x.cut>S.day?''+tr('common.cut')+'':''}
${(x.trench||x.id)===trk?tr('common.same_trench'):tr('common.diverse_route')}
${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join('')} +
${btn(tr('link_panels.add_parallel_link'),'addParallel',{id:l.id},'pink sm')}
+ ${trafficSection(l)}${metricSection(l)} +
${btn(UI.confirm===l.id?tr('common.really_decommission'):tr('common.decommission_link'),'rmLink',{id:l.id},'ghost sm')}
`; + return h; +} +const EGC={c:[tr('common.caches'),'#16A866'],p:[tr('common.pnis'),'#7B61FF'],ix:[tr('common.ix_peering_0631'),'#FFD23F'],t:[tr('common.transit'),'#FF8A3D'],l2:[tr('common.l2_circuits'),'#2F8CFF']}; +const CHBOX={W:600,H:180,L:50,B:20,T:8,R:8}; +function svgChart(rows,stackKeys,lines,fmtY,id){ + const {W,H,L,B,T,R:Rr}=CHBOX,off=(id&&UI.chartOff&&UI.chartOff[id])||{};stackKeys=stackKeys.filter(k=>!off[k]);lines=lines.filter(ln=>!off[ln.k]);if(rows.length<2)return `

${tr('link_panels.collecting_data_check_back_in_a')}

`; + let ymax=1;for(const r of rows){let s=0;for(const k of stackKeys)s+=r[k]||0;ymax=Math.max(ymax,s);for(const ln of lines)ymax=Math.max(ymax,r[ln.k]||0);}ymax*=1.1; + const x=i=>L+(W-L-Rr)*i/(rows.length-1),y=v=>T+(H-T-B)*(1-v/ymax);let g=''; + for(let j=0;j<=3;j++){const v=ymax*j/3,yy=y(v);g+=`${fmtY(v)}`;} + const base=rows.map(()=>0); + for(const k of stackKeys){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`;for(let i=1;i=0;i--)d+=`L${x(i)},${y(base[i])}`;g+=``;top.forEach((v,i)=>base[i]=v);} + for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=``;const last=rows[rows.length-1][ln.k]||0;g+=``;} + g+=`${dateStr(rows[0].d)}${dateStr(rows[rows.length-1].d)}`; + return `${g}`;} +// For a network you currently reach over transit: the cheapest way to move it to peering. +// Exchange members as sets, rebuilt once per routing pass: hints are asked for many networks at a time. +let IXMR=null,IXMC={};const ixHas=(x,id)=>{if(IXMR!==R){IXMR=R;IXMC={};}return (IXMC[x]||(IXMC[x]=new Set(ixMembers(x)))).has(id);}; +// Who brings a network along (#85): the nearest of its upstreams, then theirs; null if it sits in nobody's cone. +function coneVia(id){const a=ANC[id];if(!a||!a.length)return null;const t1=a.find(u=>NET[u].type==='t1');return NET[t1||a[0]];} +function offTransitHint(id,city){const n=NET[id];if(n.type==='t1'&&n.pol==='restrictive')return tr('link_panels.tier_1_only_a_pni_and'); + const ixc=Object.keys(S.pops).flatMap(ixIdsIn).filter(x=>ixHas(x,id)),here=city&&ixIdsIn(city).find(x=>ixHas(x,id))||null,pick1=here||ixc.find(x=>S.ixp[x]!==undefined)||ixc[0]; + if(n.pol==='open'){if(pick1)return here||ixNamesCity(pick1)?tr('link_panels.open_peer_join_the_route_server',{ix:ixName(pick1)}):tr('link_panels.open_peer_join_the_route_server_01a1',{ix:ixName(pick1),city:CITY[ixCity(pick1)].name});const x=nearestSpot(id);return x?tr('link_panels.open_peer_but_not_on_any',{city:CITY[x.c].name}):tr('link_panels.open_peer_but_not_on_any_bfbb');} + if(n.pol==='paid')return paidFree(n)?tr('link_panels.peers_with_you_for_free_over'):n.freeLv?tr('link_panels.paid_peering_only_a_pni_costs',{price:fmt$(n.paidFee),n:n.freeLv}):tr('link_panels.paid_peering_only_a_pni_costs_921d',{price:fmt$(n.paidFee)}); + const pniC=Object.keys(S.pops).filter(c=>n.pops.includes(c));const ixOk=pick1?peerOk(id,'ix',pick1):null,pOk=pniC.length?peerOk(id,'pni',pniC.includes(city)?city:pniC[0]):null; + if(pOk&&pOk.ok)return tr('link_panels.ready_for_a_pni_in_city',{city:CITY[pniC.includes(city)?city:pniC[0]].name}); + if(ixOk&&ixOk.ok)return tr('link_panels.will_peer_at_ix_request_a',{ix:ixName(pick1)}); + if(ixOk)return `${ixName(pick1)}: ${ixOk.why}`; + if(pniC.length)return tr('link_panels.pni_in_city_why',{city:CITY[pniC[0]].name,why:pOk.why});{const x=nearestSpot(id);return x?tr('link_panels.not_in_your_cities_yet_nearest',{city:CITY[x.c].name}):tr('link_panels.not_present_in_any_of_your');}} +function transitTop(ids,k=5){const m={};for(const id of ids)for(const [n,v] of Object.entries(R.tNet[id]||{}))m[n]=(m[n]||0)+v;return Object.entries(m).filter(([,v])=>v>0.01).sort((a,b)=>b[1]-a[1]).slice(0,k);} +// The broker: what is listed and how the route's market looks, or the buttons to list some (#203). +function brListHtml(l,fc){const L=l.list,free=cmRoomSpec(l),pf=l.own&&pairFree(l)&&!(L&&L.p),cut=Math.round((1-cmCut())*100),go=`
${btn(tr('market.open'),'marketOpen',{},'ghost sm')}
`; + const mk=`
${tr('broker.market',{a:CITY[l.a].name,b:CITY[l.b].name})}${trn('broker.n_waves',free)}
`; + if(L)return mk+`
${tr('broker.listed_title')}
${[L.w?trn('broker.n_waves_left',L.w):'',...CM_W.map(p=>L[CM_L[p]]?trn('market.n_g_left',L[CM_L[p]],{g:fmtCap(CM_G[p])}):''),L.p?trn('broker.n_pairs_left',L.p):''].filter(Boolean).join(' · ')} · ${tr('market.how',{n:cut})}
${btn(tr('broker.unlist'),'unlistFiber',{id:l.id},'ghost sm')}
`+ + (fc-L.w>=1?`
${btn(tr('broker.list_more',{n:Math.min(4,fc-L.w)}),'listFiber',{id:l.id,w:Math.min(4,fc-L.w)},'ghost sm')}${btn(tr('market.open'),'marketOpen',{},'ghost sm')}
`:go); + if(fc<1&&!pf)return mk+`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`+go; + const ns=[...new Set([1,4,Math.min(16,fc),fc])].filter(n=>n>=1&&n<=fc); + return mk+`

${tr('market.lead_fiber',{n:cut})}

${ns.map(n=>btn(n===fc&&n>1?tr('broker.list_all',{n}):trn('broker.list_n',n),'listFiber',{id:l.id,w:n},'sm')).join('')}${pf?btn(tr('broker.list_pair'),'listFiber',{id:l.id,p:1},'sm'):''}
`+(free<1?`

${tr('broker.no_market')}

`:'')+go;} diff --git a/src/game/93-ui/72-express.js b/src/game/93-ui/72-express.js new file mode 100644 index 0000000..2e800ff --- /dev/null +++ b/src/game/93-ui/72-express.js @@ -0,0 +1,48 @@ +/* Express lightpaths (#58): the panel of one, the section on a dark fiber's panel (what rides it, where it chains on) + and the Express tab of the link window (70-link-modal.js). The rules are in 80-simulation/65-express.js. */ +const xpSpanName=s=>`${CITY[s.a].name} ⇄ ${CITY[s.b].name}`; +// Why an express is dark today, fiber by fiber. +function xpDarkWhy(l){const sp=xpSpans(l);if(!sp)return [tr('express.dark_gone')];const d=S.day,out=[]; + for(const s of sp){const n=xpSpanName(s);if(linkCut(s))out.push(tr('express.dark_cut',{span:n}));else if(s.ready>d)out.push(trn('express.dark_building',s.ready-d,{span:n}));else if(s.eqDown>d)out.push(tr('express.dark_system',{span:n}));} + if(!out.length)out.push(tr('express.dark_reach'));return out;} +// One fiber of a path: whose it is, how long, the slots left for express channels. +const xpSpanMeta=s=>`${s.own?tr('common.own_dark_fiber'):tr('common.leased_iru')} · ${Math.round(s.km).toLocaleString()} km · ${tr('express.free_slots',{n:Math.max(0,xpFree(s)),max:chMax(s)})}`; +// An optic's settings over a run, as the fiber panel lists them. +const xpModes=(o,run)=>OPT[o].modes.map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')+` · ${xpOptG(o,run)?tr('express.runs_at',{g:fmtG(xpOptG(o,run))}):tr('express.out_of_reach')}`; +function xpPanel(l){const sp=xpSpans(l),load=R.load[l.id]||0,cap=capOf(l),u=cap?load/cap:0,down=linkDown(l),run=sp?xpRunKm(sp):0,ch=l.ch||[]; + let h=`
${tr('express.eyebrow',{km:Math.round(l.km).toLocaleString()})}

${lkEnds(l)}

`; + if(down)h+=`

${tr('common.dark_6bf5')}

${xpDarkWhy(l).map(t=>`

${t}

`).join('')}
`; + h+=`

${tr('common.capacity')}

${trn('express.n_channels',ch.length)}${fmtG(load)} / ${fmtG(cap)}
+ ${down?'':xpDim(l).map(s=>`

${tr('express.dim',{span:xpSpanName(s),p:pct(s.loss.f)})}

`).join('')}
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${tr('express.optical_run')}${run.toLocaleString()} km
+

${tr('express.passes',{via:esc(xpVia(l))})}

`; + if(sp)h+=`

${tr('express.its_fibers')}

${sp.map(s=>`
${xpSpanName(s)} ${linkCut(s)?''+tr('common.cut')+'':''}
${xpSpanMeta(s)}
${btn(tr('common.open'),'selLink',{id:s.id},'ghost sm')}
`).join('')}

${tr('express.slot_note')}

`; + if(sp){h+=`

${tr('common.optics')}

`; + for(const k of Object.keys(OPT)){const O=OPT[k],n=ch.filter(x=>x===k).length;if(!n&&!techOk('opt',k,O.lvl))continue;const why=xpWhy(l.a,l.b,sp,k),c=xpCost(sp,k,false),spn=spareN(k); + h+=`
${O.n}
${xpModes(k,run)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${spn?` · ${trn('link_panels.n_spare_on_the_shelf',spn)}`:''}
${why?`
${esc(why)}
`:''}
${n&&ch.length>1?btn('−','xpCh',{id:l.id,o:k,d:-1},'ghost sm'):''}${btn(`+ ${spn?tr('link_panels.spare_price',{price:fmt$(c)}):fmt$(c)}`,'xpCh',{id:l.id,o:k,d:1},'sm',!!why||S.cash`;} + h+=`

${tr('link_panels.unplugged_optics_go_on_the_spares')}

`;} + h+=`${trafficSection(l)}${metricSection(l)}
${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):tr('express.tear_down'),'rmLink',{id:l.id},'ghost sm')}

${tr('express.tear_down_note')}

`; + return h;} +// Where an express can go from this fiber: through either end and on over your other ROADM fibers. +function xpTargets(l){const out=[];for(const [x,y] of [[l.a,l.b],[l.b,l.a]])for(const p of xpPaths(x,null,l,6))if(xpRunKm(p.sp)<=xpReachMax())out.push({from:x,...p}); + return out.sort((p,q)=>p.km-q.km).slice(0,6);} +// On a dark fiber's panel: the expresses riding it, and where one could go from here. +function xpDfSection(l){if(l.sub)return '';const on=xpOver(l.id),rdm=isRdm(l.sys),tg=rdm?xpTargets(l):[]; + // Without a ROADMaster the hint is only worth showing where another fiber of yours meets this one. + const near=!rdm&&S.links.some(x=>x!==l&&x.kind==='df'&&!x.sub&&[x.a,x.b].some(c=>c===l.a||c===l.b)); + if(!on.length&&!tg.length&&!near)return ''; + let h=`

${tr('express.title')}

${tr('express.lead')}

`; + if(!rdm)h+=`

${tr('express.needs_roadm')}

`; + if(on.length)h+=`

${tr('express.riding_here')}

`+on.map(x=>`
${CITY[x.a].name} ⇄ ${CITY[x.b].name} ${linkDown(x)?''+tr('common.dark')+'':''}
${capName(x)} · ${trn('express.n_channels',(x.ch||[]).length)} · ${tr('express.city_via',{via:esc(xpVia(x))})}
${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join('')+`

${tr('express.riding_note')}

`; + if(tg.length)h+=`

${tr('express.express_to')}

`+tg.map(t=>{const cs=xpCities(t.from,t.sp);return `
${CITY[t.from].name} → ${CITY[t.to].name}
${tr('express.via_km',{via:cs.slice(1,-1).map(c=>CITY[c].name).join(', '),km:Math.round(t.km).toLocaleString()})}
${btn(tr('express.plan'),'xpOpen',{a:t.from,b:t.to,via:t.sp.map(s=>s.id).join(',')},'pink sm')}
`;}).join(''); + return h+`
`;} +// The link window's Express tab: the ways your fibers chain from a to b, shortest first, an optic per button. Optic +// names are long: they go above the reason, not in the narrow column a wave's '400G' fits in. +function xpModalBody(a,b,routes){let h=`

${tr('express.modal_lead',{a:CITY[a].name,b:CITY[b].name})}

`; + for(const r of routes){const sp=r.sp,ids=sp.map(s=>s.id),cs=xpCities(a,sp),run=xpRunKm(sp),old=xpFind(a,b,ids),lat=sp.reduce((x,s)=>x+linkLat(s),0); + h+=`

${tr('express.via_km',{via:cs.slice(1,-1).map(c=>CITY[c].name).join(', '),km:Math.round(r.km).toLocaleString()})}

+ ${sp.map(s=>`
${xpSpanName(s)} · ${xpSpanMeta(s)}
`).join('')} +
${tr('express.optical_run')}${run.toLocaleString()} km
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:lat.toFixed(1)})}
+ ${old?`

${trn('express.already',(old.ch||[]).length)}

`:''} +
${Object.keys(OPT).filter(k=>techOk('opt',k,OPT[k].lvl)).map(k=>{const O=OPT[k],why=xpWhy(a,b,sp,k),c=xpCost(sp,k,!old),g=xpOptG(k,run); + return ``;}).join('')}
`;} + return h+`

${tr('express.modal_note',{price:fmt$(XP_PASS)})}

`;} diff --git a/src/game/93-ui/72-teleport-panels.js b/src/game/93-ui/72-teleport-panels.js new file mode 100644 index 0000000..ce4ef6d --- /dev/null +++ b/src/game/93-ui/72-teleport-panels.js @@ -0,0 +1,93 @@ +// Teleports and satellite circuits on screen (#83): a POP's section, the order sheet, a circuit's panel. +const satLogo=P=>``; +// Round trip over bird id between a and b, in whole ms. +const satRtt=(id,a,b)=>Math.round(2*satLat({bird:id,km:satKm(id,a,b)})); +const satModalHead=(eye,title)=>`
🛰️ ${eye}

${title}

`; +// In a city's facts: its own users' traffic rides a satellite today (R.satU), and they count part of the service as bad (sfOf, R.latF). +// Over LEO alone they hardly notice, so the chip is a plain one. +const satFact=c=>R&&R.latF&&R.latF[c]<1&&R.satU&&R.satU[c]>1e-3?`🛰️ ${tr('satellites.users_ride_a_satellite')}`:''; +// The birds a dish at c sees, in words. +const satInView=c=>{const ids=teleSees(c);return ids.length?tr('satellites.in_view_list',{list:ids.map(id=>`${esc(SATS[id].n)} (${tr(SATS[id].sea)})`).join(', ')}):tr('satellites.no_bird_sees_this_city');}; +// In a POP's Infra tab: its teleport (build it, what it sees, its circuits), and the teleports that can reach it. +function teleHtml(c){if(pzOn())return '';const t=teleOf(c),from=satFrom(c),open=lvl()>=SAT_ORB.geo.lv;if(!t&&!open&&!from.length)return ''; + let h=`

🛰️ ${tr('satellites.satellites')}

`; + if(t){const out=S.links.filter(l=>l.kind==='sat'&&l.a===c),cf=UI.confirm==='tele:'+c,meo=teleSees(c).some(id=>SATS[id].orb==='meo'); + h+=`
${tr('satellites.teleport')}${t>1?tr('satellites.geo_dishes_and_meo_tracking'):tr('satellites.geo_dishes')} · ${tr('common.price_mo',{price:fmt$(TPORT_MO+(t>1?TRK_MO:0))})}
+
${satInView(c)}
`; + for(const l of out){const u=capOf(l)?(R.load[l.id]||0)/capOf(l):0; + h+=`
→ ${CITY[l.b].name}${l.standby?' '+tr('common.standby')+'':''}
${capName(l)} · ${esc(satName(l))}${l.ready>S.day?' · '+tr('city_panel.ready_in_n_d',{n:l.ready-S.day}):''} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=wispTeleRows(c); + h+=`
${btn(tr('satellites.rent_satellite_capacity'),'satOpen',{a:c},'pink sm')}${t===1&&lvl()>=SAT_ORB.meo.lv&&meo?btn(tr('satellites.add_tracking_antennas_cost_mo',{cost:fmt$(TRK_COST),mo:fmt$(TRK_MO)}),'teleTrk',{city:c},'sm',S.cash + ${t===1&&lvl()${tr('satellites.meo_comes_at_level',{lv:SAT_ORB.meo.lv})}

`:''}`; + h+=leoHtml(c);} + // Before the build: what its dishes would see and reach at your level, and no button to a teleport that reaches nothing. + else if(open){const why=teleWhy(c),n=why?0:satTargets(c).filter(x=>satBirds(c,x).some(id=>lvl()>=SAT_ORB[SATS[id].orb].lv)).length,nz=why||!wispOn()?0:wispAt(c).length; + h+=`

${tr('satellites.a_teleport_is_a_satellite_gateway')}

${satInView(c)}${why?'':' '+trn('satellites.n_places_in_reach',n)}
${nz?`
${tr('wisp.tele_reaches')} ${trn('wisp.n_zones',nz)}
`:''}${why&&teleSees(c).length?`
${esc(why)}
`:''} +
${btn(tr('satellites.build_a_teleport_cost_mo',{cost:fmt$(TPORT_COST),mo:fmt$(TPORT_MO)}),'teleBuild',{city:c},'sm',S.cash`;} + if(from.length)h+=satReach(c,from); + return h+`
`;} +/* A teleport's Starblink gateway: host it (level 5, under the shell, on your fiber), what it reaches, and once circuits + land there, the POP every island behind it leans on: its routers, the fiber out of the city and its transit ports (a + port on someone's cable is a way out too, satWired), as routing sees them. */ +function leoHtml(c){const O=SAT_ORB.leo;if(!satSees(LEO_BIRD,c))return ''; + if(lvl()${tr('satellites.leo_comes_at_level',{lv:O.lv})}

`; + if(!leoGw(c)){const why=leoGwWhy(c); + return `${why?`
${esc(why)}
`:''}
${btn(tr('satellites.host_leo_gateway_cost_mo',{cost:fmt$(LEO_GW_COST),mo:fmt$(LEO_GW_MO)}),'teleLeo',{city:c},'sm',!!why||S.cash`;} + // An island zone of this city over LEO lands here too (46-wisp-zones.js). + const out=S.links.filter(l=>l.a===c&&leoLink(l)),zl=wispSats(c,'leo'),n=satTargets(c).filter(x=>satPairOk(LEO_BIRD,c,x)).length,C=CITY[c].name; + let h=`
${tr('satellites.leo_gateway')}${esc(SAT_PROV.sbk.n)} · ${tr('common.price_mo',{price:fmt$(LEO_GW_MO)})}
${trn('satellites.n_in_leo_reach',n,{km:O.km.toLocaleString()})}
`; + if(!satWired(c))h+=`
${tr('satellites.leo_gateway_unwired',{city:C})}
`; + if(!out.length&&!zl.length)return h+`
${btn(UI.confirm==='leo:'+c?tr('satellites.really_close_it'):tr('satellites.close_the_leo_gateway'),'teleLeoRm',{city:c},'ghost sm')}
`; + const land=out.reduce((a,l)=>a+(R.load[l.id]||0),0)+zl.reduce((a,z)=>{const Z=wispZ(z),x=R.wisp&&R.wisp[z];return a+(x&&Z.sat&&wispOrb(Z.sat)==='leo'&&wispLink(z,Z)===Z.sat?x.car:0);},0),nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||nodeCap(c)||1,un=nl/nc, + ws=S.links.filter(l=>(l.a===c||l.b===c)&&wiredLink(l)&&!linkDown(l)&&!l.standby),wl=ws.reduce((a,l)=>a+(R.load[l.id]||0),0),wc=ws.reduce((a,l)=>a+capOf(l),0),uw=wc>0?wl/wc:0, + ts=S.transit.filter(t=>t.city===c&&!(t.down>S.day)),tl=ts.reduce((a,t)=>a+(R.useT[t.id]||0),0),tc=ts.reduce((a,t)=>a+lagCap(PORT[t.tier].g,t.n),0),ut=tc>0?tl/tc:0; + return h+`
${tr('satellites.leo_landing')}${fmtG(land)}
+
${tr('common.forwarding_load')}${fmtG(nl)} / ${fmtG(nc)}
+ ${wc>0||!tc?`
${tr('satellites.leo_backhaul',{city:C})}${fmtG(wl)} / ${fmtG(wc)}
${wc>0?`
`:''}`:''} + ${tc>0?`
${tr('satellites.leo_transit',{city:C})}${fmtG(tl)} / ${fmtG(tc)}
`:''} + ${un>=0.95||uw>=0.95||ut>=0.95?`

${tr('satellites.leo_bottleneck',{city:C})}

`:''}`;} +// Teleports that reach city c: a button each, to the order sheet. +const satReach=(c,from)=>`

${tr('satellites.reachable_from_your_teleports',{city:CITY[c].name})}

${from.slice(0,4).map(a=>btn(tr('fiber_modals.from_city',{city:CITY[a].name}),'satOpen',{a,b:c},'ghost sm')).join('')}
`; +// Whether a satellite can get to city c: a teleport of yours reaches it, or (once teleports are on sale) a bird you may +// rent from sees it. Never in a puzzle, as the rest of the satellites. +const satCan=c=>!pzOn()&&(satFrom(c).length>0||lvl()>=SAT_ORB.geo.lv&&satRemote(c)&&teleSees(c).some(id=>lvl()>=SAT_ORB[SATS[id].orb].lv)); +// Under the link window's "no subsea cable lands here" (#321): the teleports that reach c, a button each to the order +// sheet, or where to build one. +const satNoCable=c=>{const from=satFrom(c);return from.length?satReach(c,from):`

${tr('satellites.no_teleport_reaches_city',{city:CITY[c].name})}

`;}; +// A city without a POP of yours, that a teleport of yours reaches: a POP and a circuit in one go. +function satNoPop(c){if(pzOn()||S.pops[c])return '';const from=satFrom(c);if(!from.length)return ''; + return `

🛰️ ${tr('satellites.by_satellite')}

${tr('satellites.no_cable_needed_a_pop_here',{city:CITY[c].name})}

${satReach(c,from)}
`;} +// The order sheet: from teleport a to b. With one end missing it lists the choices first. +function satModal(a,b){a=isCity(a)?a:null;b=isCity(b)?b:null; + if(!a&&b){const fr=satFrom(b);if(fr.length===1)a=fr[0]; + else{openModal(satModalHead(tr('satellites.satellite_capacity'),tr('fiber_modals.to_city',{city:CITY[b].name}))+(fr.length?fr.map(x=>`
${CITY[x].name}
${tr('satellites.teleport')} · ${trn('satellites.n_birds_see_both',satBirds(x,b).length)}
${btn(tr('satellites.choose'),'satOpen',{a:x,b},'sm')}
`).join(''):`

${tr('satellites.no_teleport_reaches_city',{city:CITY[b].name})}

`));return;}} + if(!a||!teleOf(a))return; + if(!b){const ts=satTargets(a),mine=ts.filter(x=>S.pops[x]),more=ts.filter(x=>!S.pops[x]).slice(0,12); + const row=x=>`
${CITY[x].name}
${S.pops[x]?tr('common.your_pop'):tr('satellites.new_pop_cost',{cost:fmt$(newPopCost(x))})} · ${kmBetween(a,x).toLocaleString()} km · ${trn('satellites.n_birds_see_both',satBirds(a,x).length)}
${btn(tr('satellites.choose'),'satOpen',{a,b:x},'sm')}
`; + openModal(satModalHead(tr('satellites.satellite_capacity'),tr('fiber_modals.from_city',{city:CITY[a].name}))+`

${tr('satellites.who_a_satellite_serves')}

` + +(mine.length?`

${tr('satellites.your_pops_in_view')}

`+mine.map(row).join(''):'')+(more.length?`

${tr('satellites.more_islands_and_towns')}

`+more.map(row).join(''):'')+(ts.length?'':`

${tr('satellites.nothing_in_view_from_here')}

`));return;} + const pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).some(l=>l.kind!=='sat'),birds=satBirds(a,b); + const rows=birds.map(id=>{const B=SATS[id],O=SAT_ORB[B.orb],P=SAT_PROV[B.p],why=satWhy(a,b,id); + return `
${satLogo(P)}
${esc(B.n)} ${O.n}
${esc(P.n)} · ${tr(B.sea)} · ${tr('satellites.ms_round_trip',{ms:satRtt(id,a,b)})} · ${trn('satellites.up_in_n_days',leadDays(O.days))}
${esc(P.blurb)}
${why?`
${esc(why)}
`:''} +
${O.g.map(g=>btn(`${fmtCap(g)} ${tr('common.price_mo',{price:fmt$(satMo(id,g))})}`,'buySat',{a,b,bird:id,g},'sm',!!why||S.cash
`;}).join(''); + openModal(satModalHead(tr('satellites.satellite_capacity'),`${CITY[a].name} → ${CITY[b].name}`)+`

${tr('satellites.users_notice_geo_meo')}

` + +(birds.some(id=>SATS[id].orb==='leo')?`

${tr('satellites.users_notice_leo')}

`:'') + +(pop?`

${tr('satellites.no_pop_there_yet',{city:CITY[b].name,cost:fmt$(pop)})}

`:'')+(sib?`

${tr('satellites.it_waits_on_standby')}

`:'') + +(rows||`

${tr('satellites.no_bird_sees_both',{a:CITY[a].name,b:CITY[b].name})}

`));} +// A circuit's panel: what it carries, its latency and rent, a size up or down, standby and the metric, cancel. +function satPanel(l){const B=SATS[l.bird],O=SAT_ORB[B.orb],P=SAT_PROV[B.p],load=R.load[l.id]||0,cap=capOf(l),u=cap?load/cap:0,ms=satLat(l); + let h=`
🛰️ ${esc(B.n)} · ${O.n} · ${esc(P.n)}

${lkEnds(l)}

`; + // A closed border takes a circuit dark like any link between the two countries (linkCut): say so, as the others do (#329). + h+=borderSection(l); + if(l.ready>S.day){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); + h+=`

${tr('satellites.being_commissioned')}

${tr('satellites.pointing_dishes_and_testing')}${tr('common.n_days_left',{n:l.ready-S.day})}
`;} + h+=`

${tr('common.capacity')}

${capName(l)}${l.standby?' · '+tr('common.standby'):''}${fmtG(load)} / ${fmtG(cap)}
+ ${leoDown(l)?`

${trn('satellites.leo_safe_mode_n_days',S.ev.sky-S.day)}

`:''} +
${tr('common.latency')}${tr('satellites.ms_one_way_rtt',{ms:Math.round(ms),rtt:Math.round(2*ms)})}
+
${tr('satellites.radio_path')}${l.km.toLocaleString()} km
+
${tr('satellites.rent')}${tr('common.price_mo',{price:fmt$(l.mo)})}
+

${B.orb==='geo'?tr('satellites.geo_users_notice',{p:pct(O.loss)}):B.orb==='meo'?tr('satellites.meo_users_notice',{p:pct(O.loss)}):tr('satellites.leo_users_notice',{p:pct(O.loss),city:CITY[l.a].name})} ${esc(P.blurb)}

+
${O.g.filter(g=>g!==l.g).map(g=>btn(`${g>l.g?tr('satellites.grow_to',{cap:fmtCap(g)}):tr('satellites.shrink_to',{cap:fmtCap(g)})} ${tr('common.price_mo',{price:fmt$(satMo(l.bird,g))})}`,'satSize',{id:l.id,g},'sm',g>l.g&&S.cash
+ ${trafficSection(l)}${metricSection(l)} +
${btn(UI.confirm===l.id?tr('common.really_cancel'):tr('common.cancel_circuit'),'rmLink',{id:l.id},'ghost sm')}
`; + return h;} diff --git a/src/game/93-ui/73-wisp-panels.js b/src/game/93-ui/73-wisp-panels.js new file mode 100644 index 0000000..91f6b45 --- /dev/null +++ b/src/game/93-ui/73-wisp-panels.js @@ -0,0 +1,67 @@ +// Island Wi-Fi on screen (#83): a city's fact chip and teaser, the zones in its Customers tab, their rows at the teleport. +// Rows are laid out as the teleport section's (name, meta, a bar, small buttons that wrap), so they fit a phone at 360 px. +const wispFact=c=>{if(!wispOn())return '';const n=wispAt(c).length;return n?`🏝️ ${trn('wisp.n_zones',n)}`:'';}; +// A city without a POP of yours: what its islands are, and that a POP comes first. +function wispNoPop(c){if(!wispOn()||S.pops[c])return '';const zs=wispAt(c);if(!zs.length)return ''; + return `

🏝️ ${tr('wisp.section')}

${tr('wisp.no_pop',{list:zs.map(z=>`${esc(WISP[z].n)} (${tr('wisp.pool',{g:fmtG(wispPool(z))})})`).join(', ')})}

`;} +// A zone's status: what carries it today, or why nothing does. +function wispStatus(z,Z){if(!Z)return {t:tr('wisp.st_none'),k:'st'};if(wispLit(Z))return wispCut(z)?{t:tr('wisp.st_cut'),k:'restrictive'}:{t:tr('wisp.st_spur'),k:'open'}; + const o=Z.sat;if(o&&!(o.ready>S.day))return {t:SAT_ORB[wispOrb(o)].n,k:''};return o||Z.sp?{t:tr('wisp.st_soon'),k:'st'}:{t:tr('wisp.st_none'),k:'st'};} +// Days until the first of a zone's circuits or spur being commissioned comes up; 0 for none. +const wispSoon=Z=>[Z.sat,Z.nxt,Z.sp].reduce((m,o)=>o&&o.ready>S.day&&(!m||o.ready-S.day

🏝️ ${tr('wisp.section')}

${tr('wisp.lead',{rate:fmt$(wispRate(zs[0]))})}

${zs.map(wispRow).join('')}`;} +function wispRow(z){const W=WISP[z],Z=wispZ(z),r=R.wisp&&R.wisp[z],P=wispPool(z),st=wispStatus(z,Z),open=UI.wz===z,d=Z?Z.d:0,sf=r?r.sf:0,on=!!Z&&wispTake(Z)>0,n=Z&&!on?wispSoon(Z):0; + let h=`
${esc(W.n)} ${st.t}
${tr('wisp.pool',{g:fmtG(P)})}${on?' · '+tr('pie_gov.served',{p:pct(sf)}):n?' · '+tr('city_panel.ready_in_n_d',{n}):''}
${on?`
`:''}
${btn(open?tr('common.close'):tr('common.open'),'wispOpen',{z},'ghost sm')}
`; + return open?h+wispOpenHtml(z,Z,r):h;} +// The open zone: its homes and money (once something reaches them; until then, the day it will), its backhaul (the +// circuit, the birds to order on), the spur, closing it. A cut spur or a solar storm is an outage: that one shows in red. +function wispOpenHtml(z,Z,r){const K=Z?wispK(z,Z):0,k=Z?wispLink(z,Z):null;let h=''; + if(Z){const sf=r?r.sf:0,cl=sf<0.9?'var(--tx-red,var(--bad))':'var(--eye)',n=K>0?0:wispSoon(Z); + h+=K>0?`
${tr('wisp.homes_online')}${tr('city_panel.a_of_b',{a:fmtG(Z.d),b:fmtG(K)})}
+
${tr('wisp.served')}${pct(sf)}
+
${tr('common.revenue')}${tr('common.price_mo',{price:fmt$(r?r.d*r.sf*wispRate(z):0)})}
`:n?`

${trn('wisp.online_in_n_days',n)}

`:''; + h+=`
${tr('wisp.upkeep')}${tr('common.price_mo',{price:fmt$(wispUpMo(z)+(wispLit(Z)?wispSpurMo(z):0))})}
+ ${k&&r&&r.d>=k.g*0.98?`

${tr('wisp.full')}

`:''}`;} + h+=`

${tr('wisp.take',{geo:pct(SAT_ORB.geo.wisp),meo:pct(SAT_ORB.meo.wisp),leo:pct(SAT_ORB.leo.wisp)})}

${ip4On()?`

${tr('wisp.ipv6')}

`:''}`; + return `
${h}${wispBackhaul(z,Z,k)}${wispSpurHtml(z,Z)}${Z?`
${btn(UI.confirm==='wz:'+z?tr('satellites.really_close_it'):tr('wisp.close'),'wispRm',{z},'ghost sm')}
`:''}
`;} +// Backhaul: the circuit (and a move under way), then a row per bird that sees both the city and the islands. +function wispBackhaul(z,Z,k){const W=WISP[z],c=W.c,C=CITY[c].name,t=teleOf(c); + let h=`

${tr('wisp.backhaul')}

`; + if(satOnly(c))h+=`

${tr('wisp.double_hop',{city:C})}

`; + const o=Z&&Z.sat,run=(x,now)=>{const O=SAT_ORB[wispOrb(x)],P=SAT_PROV[SATS[x.bird].p],car=now&&k===x&&R.wisp&&R.wisp[z]?R.wisp[z].car:0,u=x.g?car/x.g:0,sb=now&&k&&k.sp; + return `
${satLogo(P)}
${esc(SATS[x.bird].n)} ${O.n}${sb?` ${tr('common.standby')}`:''}
${fmtCap(x.g)} · ${tr('satellites.ms_round_trip',{ms:Math.round(2*wispMs(z,x.bird))})} · ${tr('common.price_mo',{price:fmt$(x.mo)})}${x.ready>S.day?' · '+tr('city_panel.ready_in_n_d',{n:x.ready-S.day}):''}
+ ${now&&wispOrb(x)==='leo'&&leoStorm()?`

${trn('satellites.leo_safe_mode_n_days',S.ev.sky-S.day)}

`:''}${now?`
`:''}
`;}; + if(o){const G=SAT_ORB[wispOrb(o)].g;h+=run(o,true)+`
${G.filter(g=>g!==o.g).map(g=>btn(`${g>o.g?tr('satellites.grow_to',{cap:fmtCap(g)}):tr('satellites.shrink_to',{cap:fmtCap(g)})} ${tr('common.price_mo',{price:fmt$(wispSatMo(o.bird,g))})}`,'wispSatSize',{z,g},'sm',g>o.g&&S.cash`;} + if(Z&&Z.nxt)h+=run(Z.nxt,false); + if(!t){h+=`

${tr('wisp.no_teleport',{city:C})}

${btn(tr('satellites.build_a_teleport_cost_mo',{cost:fmt$(TPORT_COST),mo:fmt$(TPORT_MO)}),'teleBuild',{city:c},'sm',S.cash`;return h;} + if(Z&&Z.nxt)return h; + h+=o?`

${tr('wisp.move_note')}

`:Z?'':`

${tr('wisp.kit',{cost:fmt$(wispKit(z))})}

`; + const kit=Z?0:wispKit(z); + for(const id of wispBirds(z)){if(o&&o.bird===id)continue;const B=SATS[id],O=SAT_ORB[B.orb],P=SAT_PROV[B.p];if(lvl()${satLogo(P)}
${esc(B.n)} ${O.n}
${esc(P.n)} · ${tr('satellites.ms_round_trip',{ms:Math.round(2*wispMs(z,id))})} · ${trn('satellites.up_in_n_days',leadDays(O.days))}
${why?`
${esc(why)}
`:''} +
${up||O.g.map(g=>btn(`${fmtCap(g)} ${tr('common.price_mo',{price:fmt$(wispSatMo(id,g))})}`,'wispSat',{z,bird:id,g},'sm',!!why||S.cash
`;} + return h;} +// The spur: what it costs and takes, laying it, lit, or cut (with the incident's own rush button). +function wispSpurHtml(z,Z){const W=WISP[z],c=W.c;let h=`

${tr('wisp.spur')}

`; + if(!W.km)return h+`

${tr('wisp.spur_none')}

`; + const sp=Z&&Z.sp; + if(!sp){const why=wispSpurWhy(z),cost=wispSpurCost(z)+(Z?0:wispKit(z)); + return h+`

${tr('wisp.spur_lead',{km:W.km.toLocaleString(),city:CITY[c].name})}

${tr('common.price_mo',{price:fmt$(wispSpurMo(z))})} · ${trn('satellites.up_in_n_days',wispSpurDays(z))}
+ ${why?`
${esc(why)}
`:''}${lvl()${btn(tr('wisp.lay_spur',{cost:fmt$(cost)}),'wispSpur',{z},'pink sm',!!why||S.cash`}`;} + if(sp.ready>S.day){const tot=Math.max(1,sp.ready-sp.day),done=clamp((S.day-sp.day)/tot,0,1); + return h+`
${tr('wisp.spur_laying')}${tr('common.n_days_left',{n:sp.ready-S.day})}
`;} + const cut=wispCut(z);if(!cut)return h+`
${tr('wisp.spur_lit',{cap:fmtCap(WISP_SPUR_G)})}${W.km.toLocaleString()} km
`; + const i=S.inc.filter(x=>x.type==='wspur'&&x.z===z).sort((a,b)=>b.until-a.until)[0],up=!!Z.sat&&!(Z.sat.ready>S.day); + return h+`

${trn('wisp.spur_cut',cut-S.day)}

${i&&i.cost?`
${btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash`:''}${up?'':`

${tr('wisp.spur_trap')}

`}`;} +// In the teleport section: the zones' circuits from here, each opening its zone. +function wispTeleRows(c){const zs=wispSats(c);if(!zs.length)return ''; + return `
${tr('wisp.tele_reaches')}
`+zs.map(z=>{const Z=wispZ(z),o=Z.sat||Z.nxt,k=wispLink(z,Z),car=R.wisp&&R.wisp[z]&&k===Z.sat?R.wisp[z].car:0,u=Z.sat&&Z.sat.g?car/Z.sat.g:0; + return `
🏝️ ${esc(WISP[z].n)}${k&&k.sp&&Z.sat?' '+tr('common.standby')+'':''}
${fmtCap(o.g)} · ${esc(SATS[o.bird].n)}${o.ready>S.day?' · '+tr('city_panel.ready_in_n_d',{n:o.ready-S.day}):''} · ${tr('common.price_mo',{price:fmt$(o.mo)})}
${btn(tr('common.open'),'wispOpen',{z},'ghost sm')}
`;}).join('');} diff --git a/src/game/93-ui/75-optic-counts.js b/src/game/93-ui/75-optic-counts.js new file mode 100644 index 0000000..35fe1cf --- /dev/null +++ b/src/game/93-ui/75-optic-counts.js @@ -0,0 +1,20 @@ +function opticCountControl(l,o,n){ + const key=JSON.stringify([l.id,o]);let draft=UI.opticCounts&&UI.opticCounts[key]; + if(draft&&draft.base!==n){delete UI.opticCounts[key];draft=null;} + const v=draft?draft.n:n,value=draft?draft.value:n; + const price=Number.isSafeInteger(v)&&v>=0&&v<=chMax(l)?opticCountCost(l,o,v):0; + return `
`; +} +document.addEventListener('input',e=>{ + const f=e.target.closest('form.optic-count');if(!f||!S)return; + const l=S.links.find(x=>x.id===f.dataset.link),o=f.dataset.optic,n=f.elements.count.valueAsNumber; + if(!l||!own(OPT,o))return; + UI.opticCounts=UI.opticCounts||{};UI.opticCounts[JSON.stringify([l.id,o])]={base:(l.ch||[]).filter(k=>k===o).length,n,value:e.target.value}; + e.target.setAttribute('value',e.target.value); + f.querySelector('button').textContent=tr('optic_counts.apply_price',{price:fmt$(Number.isSafeInteger(n)&&n>=0&&n<=chMax(l)?opticCountCost(l,o,n):0)}); +}); +document.addEventListener('submit',e=>{ + const f=e.target.closest('form.optic-count');if(!f)return;e.preventDefault(); + if(!S||!f.reportValidity()||!$('modal').hidden)return; + ACT.setChCount({id:f.dataset.link,o:f.dataset.optic,n:f.elements.count.valueAsNumber}); +}); diff --git a/src/game/93-ui/80-find-city.js b/src/game/93-ui/80-find-city.js new file mode 100644 index 0000000..de0080f --- /dev/null +++ b/src/game/93-ui/80-find-city.js @@ -0,0 +1,34 @@ +/* ---------- Find a city (#218): a search box that jumps the map there ---------- + Matches the city's name, its country (in the player's language and in English) and its exchange and data center + names, so "Deutschland", "Germany" or "DE-CIX" all find Frankfurt. Press / anywhere, or the 🔍 chip in the HUD. */ +const FIND_N=8; +const fold=s=>String(s||'').normalize('NFD').replace(/[̀-ͯ]/g,'').toLowerCase().trim(); +// Country names, built once per page: they never change while playing. +let FIND_IX=null; +function findIndex(){if(FIND_IX)return FIND_IX;let dn=null,en=null;try{dn=new Intl.DisplayNames([LANG],{type:'region'});en=new Intl.DisplayNames(['en'],{type:'region'});}catch(e){} + const cn=(d,cc)=>{try{return d?d.of(cc)||'':'';}catch(e){return '';}}; + FIND_IX=Object.values(CITY).map(C=>{const land=cn(dn,C.cc)||C.cc||'';return {id:C.id,name:fold(C.name),land,ctry:fold(land+' '+cn(en,C.cc)+' '+(C.cc||'')),xtra:fold((C.ix||'')+' '+(C.dc||''))};});return FIND_IX;} +// Best matches first: the name starts with it, a word of the name does, the name has it, then country, then exchange or DC. +// With from (#343, a link from that POP), only cities a link could end in: not from itself, and only those the map shows. +function findCities(q,from){q=fold(q);const mine=c=>S&&S.pops&&S.pops[c]?0:1,ok=c=>!from||(c!==from&&cityOn(c)); + if(!q)return S&&S.pops?Object.keys(S.pops).filter(c=>isCity(c)&&ok(c)).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)).slice(0,FIND_N):[]; + const out=[];for(const e of findIndex()){const n=e.name;if(!ok(e.id))continue; + const s=n.startsWith(q)?0:n.split(/[\s\-.'()]+/).some(w=>w.startsWith(q))?1:n.includes(q)?2:e.ctry.includes(q)?3:e.xtra.includes(q)?4:-1; + if(s>=0)out.push([s,mine(e.id),-(CITY[e.id].P||0),e.id]);} + return out.sort((a,b)=>a[0]-b[0]||a[1]-b[1]||a[2]-b[2]).slice(0,FIND_N).map(r=>r[3]);} +function findRows(q,from){const ids=findCities(q,from),land=c=>(findIndex().find(e=>e.id===c)||{}).land||''; + if(!ids.length)return `

${q.trim()?tr('find.no_city_matches_q',{q:esc(q.trim())}):tr('find.type_a_city_a_country')}

`; + return ids.map((c,i)=>{const C=CITY[c],p=S&&S.pops&&S.pops[c]; + return ``;}).join('');} +/* The same box picks where a new link from one of your POPs goes (#343): on a crowded phone map, dragging from a POP + to a city far away is fiddly, so you type the other end and get the link window the drag would have opened. */ +function findOpen(from){if(!S||!UI.started)return;from=from&&S.pops[from]?from:null;UI.findFrom=from; + const title=from?tr('find.link_from_city',{city:CITY[from].name}):tr('find.find_a_city'); + openModal(`

${from?'🔗':'🔍'} ${esc(title)}

+
${findRows('',from)}
${from?`

${tr('find.pick_where_the_link_goes')}

`:isPhone()?'':`

${tr('find.press_slash_to_search_from')}

`}`,'find'); + const el=$('findIn');if(el)el.focus();} +document.addEventListener('input',e=>{if(e.target.id!=='findIn')return;const L=$('findList');if(L)L.innerHTML=findRows(e.target.value,UI.findFrom);}); +document.addEventListener('keydown',e=>{ + if(e.target.id==='findIn'){if(e.key==='Escape'){closeModal();return;}if(e.key==='Enter'){e.preventDefault();const f=UI.findFrom,c=findCities(e.target.value,f)[0];if(c){if(f)ACT.linkTo({a:f,b:c});else ACT.findGo({city:c});}}return;} + if(e.key!=='/'||e.ctrlKey||e.metaKey||e.altKey||(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]')))return; + if(!S||!UI.started||!$('modal').hidden)return;e.preventDefault();findOpen();}); diff --git a/src/game/93-ui/82-keys.js b/src/game/93-ui/82-keys.js new file mode 100644 index 0000000..94232af --- /dev/null +++ b/src/game/93-ui/82-keys.js @@ -0,0 +1,36 @@ +/* ---------- Keyboard shortcuts: arrows/WASD move, [ ] step through your POPs, $ through the offers, - = zoom, n (then a letter) the NOC, ? lists every key ---------- + Space, 0–4 and Escape live with the map's input (96-map/90-input.js), / with Find a city. */ +// Your POPs in the order Find a city lists them, so [ and ] walk the same list. +const popOrder=()=>S&&S.pops?Object.keys(S.pops).filter(isCity).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)):[]; +// Open offers in the Deals list's order, soonest to expire first, so $ walks the same list. +const offerOrder=()=>S&&S.offers?S.offers.filter(o=>isCity(o.city)).sort((a,b)=>a.exp-b.exp):[]; +// n opens the NOC dashboard, and a letter within KEY_LEAD ms of it picks a tab (n c: Connections). n never closes the +// dashboard, so n c switches tabs without it flashing shut; Escape closes it. +const DASH_KEYS={o:'overview',u:'cust',c:'conn',t:'traffic',r:'infra',l:'lease',m:'market'},KEY_LEAD=1000;let keyLead=0; +// Arrow keys and WASD move the map while held, at a steady speed on screen. Their own frame loop runs only while one is +// down, so the game loop does no extra work; letting go, a window opening or leaving the browser window stops it. +const PAN_KEYS={ArrowUp:[0,-1],w:[0,-1],ArrowDown:[0,1],s:[0,1],ArrowLeft:[-1,0],a:[-1,0],ArrowRight:[1,0],d:[1,0]},PAN_SPEED=700; +const panHeld=new Set();let panAt=null; +function panFrame(t){if(!panHeld.size||!$('modal').hidden||!$('dash').hidden){panHeld.clear();return;} + // A slow frame (a busy day, a background tab) moves at most 50 ms worth, not a jump across the map. + const dt=panAt==null?0:Math.min(0.05,(t-panAt)/1000);panAt=t;let dx=0,dy=0;for(const k of panHeld){dx+=PAN_KEYS[k][0];dy+=PAN_KEYS[k][1];} + cam.x+=dx*PAN_SPEED*dt/cam.z;cam.y+=dy*PAN_SPEED*dt/cam.z;wrapCam();requestAnimationFrame(panFrame);} +function showKeys(){const k=s=>`${s}`,TN={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),lease:tr('common.leased_lines'),market:tr('market.tab')}; + const tabs=Object.entries(DASH_KEYS).map(([l,t])=>`${k(l)} ${TN[t]}`).join(' '); + const rows=[[[...'←↑↓→'].map(k).join(' ')+'
'+[...'wasd'].map(k).join(' '),tr('keys.move_around_the_map')],[k(tr('keys.space')),tr('keys.pause_or_play')],[k('0')+' – '+k('4'),tr('keys.game_speed')],[k('/'),tr('find.find_a_city')],[k('[')+' '+k(']'),tr('keys.previous_or_next_of_your')],[k('$'),tr('keys.next_open_offer_soonest_to')],[k('-')+' '+k('='),tr('keys.zoom_the_map_out_or')],[k('n'),`${tr('keys.noc_dashboard_a_letter_right')}
${tabs}`],[k(tr('keys.esc')),tr('keys.close_a_window_or_deselect')],[k('?'),tr('keys.show_this_list')]]; + openModal(`

⌨️ ${tr('keys.keyboard_shortcuts')}

+
${rows.map(([a,b])=>`
${a}
${b}
`).join('')}
${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}
`,'keys');} +document.addEventListener('keydown',e=>{ + // Many layouts type [ and ] with Option or AltGr held, so Alt alone is fine; Ctrl or Cmd belongs to the browser. + if(e.key==='Shift'||e.metaKey||(e.ctrlKey&&!e.altKey)||(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]')))return; + const k=e.key.length===1?e.key.toLowerCase():e.key,step={'[':-1,']':1}[k],zoom={'-':-1,'_':-1,'=':1,'+':1}[k]; + const lead=Date.now()-keyLeadpanHeld.delete(e.key.length===1?e.key.toLowerCase():e.key)); +addEventListener('blur',()=>panHeld.clear()); diff --git a/src/game/93-ui/85-pie-control.js b/src/game/93-ui/85-pie-control.js new file mode 100644 index 0000000..3f65aa8 --- /dev/null +++ b/src/game/93-ui/85-pie-control.js @@ -0,0 +1,66 @@ +// Pie Control: a plain modal (a bottom sheet on phones) for the rocket company. Reached from the NOC tab (pieNocBtn()). +let PIE_CCN=null; +function pieLicCountry(cc){try{PIE_CCN=PIE_CCN&&PIE_CCN.l===LANG?PIE_CCN:{l:LANG,d:new Intl.DisplayNames([LANG],{type:'region'})};return PIE_CCN.d.of(cc)||cc;}catch(e){return cc;}} +// Pie Control sits in the NOC tab's top row once the rocket company is unlocked; a spat waiting for an answer keeps its own card lower down. +function pieNocBtn(){if(!pieOn())return '';return btn(`🥧 ${tr('pie.open_pie_control')}`,'pieOpen',{},'');} +const PIE_TABS=['traffic','co','fly','dish']; +// The tab UI.pieTab names, or the one that took its place: Gov moved to the bank, the Founder's feed into Company. +const pieTabOf=t=>PIE_TABS.includes(t)?t:t==='book'||t==='founder'?'co':'traffic'; +const PIE_FEED_TOP=3; +const pieTag=(t,on)=>`${t}`; +function pieModal(){if(!S||!pieOn())return;const P=S.pie||pieBlank(S.day),can=pieCanBuild(),T=UI.pieTab=pieTabOf(UI.pieTab); + let h=`
${tr('pie.pie_in_the_sky')}

${P.co?esc(pieCoName()):tr('pie.pie_control')}

`; + if(!can)h+=`

${tr('pie.why_not_t1')}

`; + if(pieSand())h+=`

${tr('pie.sandbox_note',{amt:fmt$(P.book.wouldHave)})}

`; + if(!P.co){h+=`

${tr('pie.found_pitch')}

${btn(tr('pie.found_price',{price:fmt$(piePrice(PIE_CO)),mo:fmt$(PIE_CO_MO)}),'pieFound',{},'pink',!can)}
`;openModal(h,'pie');return;} + const tab=(k,l)=>``; + h+=pieGlobeHtml()+pieSpatCard(); + h+=`
${tab('traffic',tr('pie_traffic.tab'))}${tab('co',tr('pie.tab_company'))}${tab('fly',tr('pie.tab_launch'))}${tab('dish',tr('pie.tab_dishes'))}
`; + const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)),c=S.pops[UI.pieCity]?UI.pieCity:cities[0]; + const sel=`
`; + if(T==='traffic')h+=pieTrafficHtml(); + else if(T==='co'){ + h+=`
${tr('pie.running_costs')}${tr('common.price_mo',{price:fmt$(pieMo())})}
`; + h+=`
${tr('pie.spent')}${fmt$(P.book.spent)}
${tr('pie.earned')}${fmt$(P.book.earned)}
`; + if(R&&R.pie)h+=`

${tr('pie.earned_mo',{amt:fmt$(R.pie.rev),n:R.pie.isl.length})}

`; + if(pieSand())h+=`
${tr('pie.would_have')}${fmt$(P.book.wouldHave)}
`; + h+=`
🏭 ${tr('pie.factory')}
${P.fac?tr('pie.factory_stock',{n:Math.floor(P.stock),m:PIE_FAC_MONTH}):tr('pie.factory_pitch',{m:PIE_FAC_MONTH,mo:fmt$(PIE_FAC_MO)})}
${P.fac?'':`
${btn(tr('pie.build_price',{price:fmt$(piePrice(PIE_FAC))}),'pieFactory',{},'pink sm',!can)}
`}
`; + h+=`
🧪 ${tr('pie.rd')}
${Object.keys(PIE_RD).map(k=>`
${tr(PIE_RD[k].n)}${P.rd[k]?`✓`:btn(fmt$(piePrice(PIE_RD[k].cost)),'pieRd',{k},'ghost sm',!can)}
`).join('')} + ${P.rd.heavy?`

${tr('pie.heavy_tests',{n:P.rd.heavyTests,max:PIE_HEAVY_TESTS})}

`:''}
`; + h+=`
🚀 ${tr('pie.pads')}
${P.pads.map(p=>`
${esc(CITY[p.city].name)} · −${pct(pieEq(p.city))}${p.next>S.day?tr('pie.pad_busy',{d:dateStr(p.next)}):tr('pie.pad_free')}${p.boosters.length?' · '+trn('pie.n_boosters',p.boosters.length):''}
`).join('')||`

${tr('pie.no_pads')}

`} + ${sel}
${btn(tr('pie.build_pad_price',{city:esc(CITY[c].name),price:fmt$(piePrice(PIE_PAD))}),'piePad',{city:c},'ghost sm',!can||!pieCoast(c)||P.pads.some(p=>p.city===c)||P.pads.length>=PIE_PAD_MAX)}
${pieCoast(c)?'':`

${tr('pie.why_pad_city')}

`}
`; + h+=`
🏷️ ${tr('pie.name')}
${btn(tr('pie.next_name'),'pieName',{},'ghost sm')}
+
${btn(tr('slots.rename'),'pieRename',{},'ghost sm')}
`; + h+=`
${btn(P.safe?tr('pie.safe_on'):tr('pie.safe_off'),'pieSafe',{},P.safe?'red sm':'ghost sm')}

${tr('pie.safe_note')}

`; + h+=pieFeedHtml(P.founder); + }else if(T==='fly'){ + let nudge=false; + h+=Object.keys(CRUSTS).map(id=>{const C=CRUSTS[id],cv=pieCov(id);return `
${tr(C.n)} ${pieTag(pieBaked(id)?tr('pie.baked'):tr('pie.half_baked'),pieBaked(id))}
+
${tr('pie.crust_line',{alt:C.alt,n:pieLive(id),full:C.full,q:P.crusts[id].queued,p:pct(cv)})}
+ ${(()=>{const f=pieLive(id)+P.crusts[id].queued>0&&pieLive(id)${t}

`; + if(!nudge&&f.pad&&f.days>PIE_PACE_SLOW&&P.pads.length${tr('pie.pace_pad',{city:esc(CITY[c].name),p:pct(pieEq(c))})}

${btn(tr('pie.build_pad_price',{city:esc(CITY[c].name),price:fmt$(piePrice(PIE_PAD))}),'piePad',{city:c},'ghost sm',!can)}
` + :`

${tr('pie.pace_pad_none')}

`;} + return x;})()} +
${Object.keys(ROCKETS).filter(pieRkOk).map(rk=>{const q=pieQuote(rk,id,{ins:!!UI.pieIns,las:!!UI.pieLas});return btn(`${tr(ROCKETS[rk].n)} ${q.ok?(q.test?tr('pie.test_flight')+' · ':'')+fmt$(q.cost):esc(q.why)}`,'pieLaunch',{rk,cr:id},'ghost sm',!q.ok);}).join('')}
`;}).join(''); + h+=`
${btn(UI.pieIns?tr('pie.ins_on_p',{p:pct(PIE_INS*pieInsMul())}):tr('pie.ins_off'),'pieIns',{},UI.pieIns?'green sm':'ghost sm')}${btn(UI.pieLas?tr('pie.las_on'):tr('pie.las_off'),'pieLas',{},UI.pieLas?'green sm':'ghost sm')}
`; + h+=`

${tr('pie.stock_line',{n:Math.floor(P.stock)})}

`; + if(P.q.length)h+=`

${tr('pie.queue')}

`+P.q.slice().sort((a,b)=>a.day-b.day).map(L=>`
${esc(tr(ROCKETS[L.rk].n))} → ${esc(tr(CRUSTS[L.cr].n))}${L.test?tr('pie.test_flight'):L.n} · ${esc(CITY[L.pad].name)} · ${dateStr(L.day)}
`).join(''); + }else if(T==='dish'){ + h+=`

${tr('pie.dish_note')}

`; + // A gentle hint while the sky is nearly empty: dishes cost money every month and earn nothing yet. Building stays open. + {const top=Math.max(...Object.keys(CRUSTS).map(pieCov));if(top${tr('pie.dish_wait',{min:pct(PIE_RAW),p:pct(top),mo:fmt$(PIE_DISH_MO),lo:pct(PIE_PATCHY_LO)})}

`;} + h+=P.dishes.map(x=>{const cc=CITY[x.city].cc,ok=pieLicOk(cc);return `
📡 ${esc(CITY[x.city].name)} · ${trn('pie.n_antennas',x.ant)}${ok?'':' · '+tr('pie.no_rights')}${btn(tr('pie.add_antenna',{price:fmt$(piePrice(PIE_ANT))}),'pieAnt',{id:x.id},'ghost sm',!can||x.ant>=PIE_ANT_MAX)}
`;}).join(''); + h+=sel+`
${btn(tr('pie.build_dish_price',{city:esc(CITY[c].name),price:fmt$(piePrice(PIE_DISH+PIE_ANT))}),'pieDish',{city:c},'ghost sm',!can||P.dishes.some(x=>x.city===c))}
`; + const ccs=[...new Set([...P.dishes.map(x=>CITY[x.city].cc),CITY[c].cc,...Object.keys(P.lic)])]; + h+=`

${tr('pie.landing_rights')}

`+ccs.map(cc=>{const l=P.lic[cc],ok=pieLicOk(cc); + return `
${esc(pieLicCountry(cc))}${ok?' · '+tr('pie.lic_until',{d:dateStr(l.until)}):l&&l.state!=='ok'&&l.until>S.day?' · '+tr('pie.lic_refused'):''}${btn((ok?tr('pie.renew'):tr('pie.buy'))+' '+fmt$(pieLicPrice(cc)),'pieLic',{cc},'ghost sm')}
`;}).join(''); + } + openModal(h,'pie');{const cv=document.querySelector('#modal .pgcv');if(cv)pieGlobeOpen(cv,pieGlobeData);}} +// The Founder's posts are flavour: the newest few at the bottom of the Company tab, the older ones folded away. +function pieFeedHtml(F){const post=p=>`
${esc(dateStr(p.d))}
${esc(pieFpText(p))}
`,top=F.posts.slice(0,PIE_FEED_TOP),more=F.posts.slice(PIE_FEED_TOP); + return `

${tr('pie.founder_feed')}

${tr('pie.promises')}${tr('pie.promises_line',{n:F.promises,b:F.broken})}
`+pieJitHtml(F) + +(top.length?top.map(post).join(''):`

${tr('pie.feed_empty')}

`) + +(more.length?`
${trn('pie.feed_older',more.length)}${more.map(post).join('')}
`:'')+'
';} diff --git a/src/game/93-ui/86-pie-traffic.js b/src/game/93-ui/86-pie-traffic.js new file mode 100644 index 0000000..a2a141d --- /dev/null +++ b/src/game/93-ui/86-pie-traffic.js @@ -0,0 +1,61 @@ +/* Pie Control's Traffic tab: what rides your satellites, how much, for whom, and why a sky or a dish is idle. Read from + the last compute (R.pie: flows, crust, dish from 35-pie-paths.js); the fiber comparison is worked out only here + (pieFiberMs, once per compute). The highlighted row (UI.pieHi) is display only and never saved. */ +const PIE_ROWS=40; +const pieIcon=t=>({pizza:'🏡',flywifi:'✈️',boat:'🚢',marsorb:'🔴',mars:'🔴',hft:'📈',bh:'🛰️'})[t]||'🔗'; +const pieCn=c=>c&&CITY[c]?esc(CITY[c].name):'?'; +const pieMs=v=>v<10?v.toFixed(1):String(Math.round(v)); +// Bar colour by use: green, amber from 60%, red from 90% (the globe's rings and the map badge use the same steps). +const pieLoadCls=u=>u>=0.9?'bad':u>=0.6?'warn':''; +const pieBar=(u,cls)=>`
`; +function pieDishWhy(d){const cc=CITY[d.city].cc,l=S.pie.lic[cc];return {nopop:tr('pie_traffic.d_nopop'),down:tr('pie_traffic.d_down'),lic:tr('pie_traffic.d_lic',{country:esc(pieLicCountry(cc))}), + ref:tr('pie_traffic.d_ref'),backhaul:tr('pie_traffic.d_backhaul'),spat:tr('pie_traffic.d_spat',{d:l?dateStr(l.until):''}),nocrust:tr('pie_traffic.d_nocrust'),isl:tr('pie_traffic.d_isl'),rain:tr('pie_traffic.d_rain'), + jam:tr('pie_traffic.d_jam'),nolas:tr('pie_traffic.d_nolas'),idle:tr('pie_traffic.d_idle')}[d.st]||'';} +function pieCrustWhy(c){return c.st==='half'?tr('pie_traffic.crust_half',{crust:tr(CRUSTS[c.id].n),p:pct(c.cov),min:pct(PIE_RAW)}):c.st==='part'?tr('pie_traffic.crust_part',{crust:tr(CRUSTS[c.id].n),p:pct(c.cov),c:pct(pieCarry(c.id)),min:pct(PIE_BAKED)}):c.st==='safe'?tr('pie_traffic.crust_safe'):c.st==='down'?tr('pie_traffic.crust_down'):'';} +// Why a cut-off POP gets no backhaul (R.pie.bh[].why from pieBhLand). +function pieBhWhy(w){return {nocrust:tr('pie_traffic.bh_nocrust'),noland:tr('pie_traffic.bh_noland'),nolas:tr('pie_traffic.bh_nolas',{km:PIE_BENT.toLocaleString()}),spat:tr('pie_traffic.bh_spat'),full:tr('pie_traffic.bh_full_none')}[w]||tr('pie_traffic.bh_noland');} +// The empty sky: every condition traffic needs, ticked or not, with a hint for the first thing to fix. +function pieChecks(Q){const P=S.pie,cr=Q.crust,best=cr.slice().sort((a,b)=>b.cov-a.cov)[0],ds=Q.dish,isl=ds.find(d=>d.st==='isl'),bh=Q.bh||[],no=bh.find(b=>!(b.cap>0)); + const sold=S.biz.some(b=>BIZ_T[b.type].orbit||(BIZ_T[b.type].lat&&b.route==='fast'&&b.city2&&pieKm(b.city,b.city2)>=PIE_MIN_KM)); + return [ + {k:'baked',ok:Q.hubs.length>0,l:tr('pie_traffic.ck_baked',{min:pct(PIE_RAW)}),h:!best?tr('pie_traffic.ck_baked_none'):pieCrustWhy(best)||tr('pie_traffic.ck_baked_none')}, + {k:'dish',ok:ds.some(d=>d.cap>0),l:tr('pie_traffic.ck_dish'),h:P.dishes.length?tr('pie_traffic.ck_dish_lic'):tr('pie_traffic.ck_dish_none')}, + {k:'backbone',ok:ds.some(d=>d.cap>0&&!Q.isl.includes(d.city)),l:tr('pie_traffic.ck_backbone'),h:Q.isl.length?tr('pie_traffic.ck_backbone_bh',{city:pieCn(isl?isl.city:Q.isl[0])}):tr('pie_traffic.ck_backbone_none')}, + ...(Q.isl.length?[{k:'backhaul',ok:bh.some(b=>b.cap>0)&&!no,l:tr('pie_traffic.ck_backhaul'),h:no?tr('pie_traffic.ck_backhaul_h',{city:pieCn(no.city),why:pieBhWhy(no.why)}):''}]:[]), + {k:'lasers',ok:cr.some(c=>c.las),l:tr('pie_traffic.ck_lasers'),h:tr('pie_traffic.ck_lasers_h')}, + {k:'customers',ok:sold,l:tr('pie_traffic.ck_customers'),h:tr('pie_traffic.ck_customers_h',{km:PIE_MIN_KM.toLocaleString()})}];} +function pieFlowRow(f,B){const b=B.get(f.id),hi=UI.pieHi===f.id,nm=b?esc(b.name):'?';let route,ms=''; + if(f.k==='t')route=f.dish?(f.dish===f.city?tr('pie_traffic.lands_here',{city:pieCn(f.city)}):tr('pie_traffic.lands_at',{city:pieCn(f.city),dish:pieCn(f.dish)})):tr('pie_traffic.no_landing',{city:pieCn(f.city)}); + else{route=tr('pie_traffic.route_ab',{a:pieCn(f.a),b:pieCn(f.b)})+(f.via.length>1?' · '+tr('pie_traffic.via_dishes',{up:pieCn(f.via[0]),down:pieCn(f.via[f.via.length-1])}):''); + if(f.ms!=null){const fm=pieFiberMs(f);ms=isFinite(fm)?tr('pie_traffic.orbit_vs_fiber',{o:pieMs(f.ms),f:pieMs(fm)}):tr('pie_traffic.orbit_no_fiber',{o:pieMs(f.ms)});}} + return ``;} +// A cut-off POP's backhaul: how full the pipe is, where it lands and what orbit adds, or why it has none. Tap: the globe shows it. +function pieBhRow(b){const id='bh:'+b.city,hi=UI.pieHi===id; + if(!(b.cap>0))return `
🛰️ ${tr('pie_traffic.bh_for',{city:pieCn(b.city)})}–

${pieBhWhy(b.why)}

`; + const u=b.g/b.cap; + return `
${pieBar(u,pieLoadCls(u))}${u>=0.9?`

${tr('pie_traffic.bh_full',{city:pieCn(b.city)})}

`:''}
`;} +function pieTrafficHtml(){const Q=R&&R.pie;if(!Q||!Q.flows)return `

${tr('pie_traffic.no_data')}

`; + const bh=Q.bh||[],bg=bh.reduce((a,b)=>a+b.g,0),fl=Q.flows.filter(f=>f.k!=='b'&&(f.g>0||f.k==='t')).sort((a,b)=>b.g-a.g),g=fl.reduce((a,f)=>a+f.g,0),n=fl.filter(f=>f.g>0).length,B=new Map(S.biz.map(b=>[b.id,b])); + let h=`

${trn('pie_traffic.headline',n,{g:fmtG(g),of:fmtG(pieMarket()),amt:fmt$(Q.rev)})}

`; + // Patchy-sky customers (99-pie-patchy.js): money, no traffic, so a line of its own. + if(Q.patchy&&Q.patchy.mo>0)h+=`
📶 ${tr('pie_traffic.patchy')}${tr('common.price_mo',{price:fmt$(Q.patchy.mo)})}
+

${esc(PIE_PATCHY_NAMES.slice(0,piePatchyN(Q.patchy.mo)).join(' · '))}

${tr('pie_traffic.patchy_hint',{lo:pct(PIE_PATCHY_LO),min:pct(PIE_RAW),max:pct(PIE_BAKED)})}

`; + if(!(g>0)&&!(bg>0))h+=`
${tr('pie_traffic.empty_title')}
    ${pieChecks(Q).map(c=>`
  • ${c.l}${c.ok?'':`${c.h}`}
  • `).join('')}
`; + h+=`

${tr('pie_traffic.crusts')}

`+(Q.crust.length?Q.crust.map(c=>{const why=pieCrustWhy(c); + return `
${tr(CRUSTS[c.id].n)} ${pieTag(c.st==='half'||c.st==='part'?tr('pie.half_baked'):tr('pie.baked'),c.st!=='half'&&c.st!=='part')}${c.cap>0?tr('pie_traffic.used_of',{u:fmtG(c.used),cap:fmtG(c.cap)}):pct(c.cov)}
+ ${c.cap>0?pieBar(c.used/c.cap,pieLoadCls(c.used/c.cap)):pieBar(c.cov/PIE_RAW,'warn')}${why?`

${why}

`:''}
`;}).join(''):`

${tr('pie_traffic.ck_baked_none')}

`); + if(bh.length)h+=`

${tr('pie_traffic.backhaul')}

${tr('pie_traffic.bh_hint')}

`+bh.slice().sort((a,b)=>b.g-a.g).map(pieBhRow).join(''); + if(fl.length){h+=`

${tr('pie_traffic.riding')}

${tr('pie_traffic.tap_hint')}

${fl.slice(0,PIE_ROWS).map(f=>pieFlowRow(f,B)).join('')}
`; + if(fl.length>PIE_ROWS)h+=`

${trn('pie_traffic.n_more',fl.length-PIE_ROWS)}

`;} + if(Q.dish.length)h+=`

${tr('pie_traffic.dishes')}

`+Q.dish.slice().sort((a,b)=>b.used-a.used).map(d=>{const why=d.st==='ok'?'':pieDishWhy(d); + return `
📡 ${pieCn(d.city)}${d.cap>0?pct(d.u):'–'}
${pieBar(d.u,pieLoadCls(d.u))} +

${d.bh>0?tr('pie_traffic.dish_line_bh',{t:fmtG(d.term),b:fmtG(d.bh),x:fmtG(d.transit),cap:fmtG(d.cap)}):tr('pie_traffic.dish_line',{t:fmtG(d.term),x:fmtG(d.transit),cap:fmtG(d.cap)})}${why?` · ${why}`:''}

`;}).join(''); + return h;} +// Tapping a row: mark it in place and point the globe at it, without rebuilding the panel (the scroll stays where it is). +function pieHiSet(id){UI.pieHi=UI.pieHi===id?null:id; + for(const r of document.querySelectorAll('#modal .pft-row')){const on=r.dataset.fid===UI.pieHi;r.classList.toggle('on',on);r.setAttribute('aria-pressed',String(on));} + if(PG.cv){PG.dAt=-1e9;PG.dirty=true;}} diff --git a/src/game/94-dashboard/10-progress.js b/src/game/94-dashboard/10-progress.js new file mode 100644 index 0000000..7a31dd2 --- /dev/null +++ b/src/game/94-dashboard/10-progress.js @@ -0,0 +1,31 @@ +/* ---------- scenario and level progress (#34) ---------- */ +// Red Sea Crisis (#113): traffic your links carry into and out of Asia, and how long it has stayed above the goal. +const RS_G=80,RS_DAYS=30,asiaG=()=>S.links.reduce((a,l)=>a+((CITY[l.a].reg==='AS')!==(CITY[l.b].reg==='AS')?(R.load[l.id]||0):0),0); +const pSrv=g=>({l:tr('common.traffic_served'),v:R.served,max:g,txt:`${fmtG(R.served)} / ${fmtG(g)}`}); +const pReach=()=>({l:tr('common.reach'),v:R.reach,max:0.99,txt:`${pct(R.reach)} / 99%`}); +const pChk=(l,ok)=>({l,v:ok?1:0,max:1,txt:ok?'✓':'—'}); +const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.5,txt:`${pct(R.reach)} / 50%`},pSrv(300)],redsea:()=>{const g=asiaG(),n=S.stats.asiaRun||0;return [pChk(tr('progress.a_path_from_marseille_to_singapore'),pathExists('mrs','sin')),{l:tr('progress.your_traffic_to_and_from_asia'),v:Math.min(g,RS_G),max:RS_G,txt:`${fmtG(g)} / ${fmtG(RS_G)}`},{l:tr('progress.days_in_a_row_at_g',{g:fmtG(RS_G)}),v:n,max:RS_DAYS,txt:`${n} / ${RS_DAYS}`}];},spat:()=>[pReach(),pSrv(150)], + carnaval:()=>[pChk(tr('progress.carnaval_delivered_in_full'),(S.stats.evFull||0)>=1)],ixbr:()=>{const n=brIxN();return [{l:tr('progress.ix_brrr_ports_on_your_backbone'),v:n,max:15,txt:`${n} / 15`},pChk(tr('progress.a_port_on_ix_brrr_manaus'),S.ixp.mao!==undefined),pSrv(200)];}, + c2c:()=>[pChk(tr('progress.a_path_from_cape_town_to'),pathExists('cpt','cai')),...['lag','nbo'].map(c=>pChk(tr('progress.city_on_your_network',{city:CITY[c].name}),pathExists('cpt',c))),pSrv(150)], + pac:()=>[pChk(tr('progress.1_6t_on_every_hop_from'),fastPath('lax','syd',1600)),pChk(tr('progress.a_path_from_los_angeles_to'),pathExists('lax','tok')),pSrv(150)], + atl:()=>[pChk(tr('progress.1_6t_on_every_hop_from_a90b'),fastPath('mia','mad',1600)),pChk(tr('progress.1_6t_on_every_hop_from_da01'),fastPath('lis','lag',1600)),pSrv(100)], + darien:()=>[...['bog','lim','scl','sao'].map(c=>pChk(tr('progress.city_on_your_network',{city:CITY[c].name}),pathExists('pan',c))),pSrv(150)], + gangnam:()=>{const sf=S.pops.icn?sfOf(R,'icn'):0,pr=R.revMo-R.costMo;return [pReach(),pSrv(GN_G),{l:tr('progress.seoul_served_well'),v:sf,max:GN_Q,txt:`${pct(sf)} / ${pct(GN_Q)}`},{l:tr('progress.monthly_profit'),v:R.costMo>0?Math.min(1,R.revMo/R.costMo):1,max:1,txt:fmt$(Math.round(pr))}];}, + fttb:()=>[...AU_BB.map(c=>pChk(tr('progress.broadband_in_city',{city:CITY[c].name}),!!(S.pops[c]&&S.pops[c].bb))),{l:tr('common.cables_overseas'),v:Math.min(2,auExits()),max:2,txt:`${auExits()} / 2`},pSrv(FTTB_G)], + flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll(); + return [{l:tr('common.floods_held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('progress.terabit_floods_held'),v:big,max:5,txt:`${big} / 5`},{l:tr('progress.floods_that_got_through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('progress.under_attack_now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`})));},baltic:()=>[{l:tr('progress.days_in_a_row_with_99'),v:S.stats.clean||0,max:90,txt:tr('progress.n_of_m',{n:S.stats.clean||0,m:90})}]}; +function scnProg(){const sc=S&&S.scn;if(!sc)return null; + if(sc.wk){const G=sc.wk.goal;let items=[];try{items=WS_GOALS[G.t].prog(G.p);}catch(e){}const meas=items.filter(x=>x.max);return {goal:wsGoalTxt(sc.wk),items,f:sc.done?1:meas.length?meas.reduce((a,x)=>a+Math.min(1,x.v/x.max),0)/meas.length:0};} + if(sc.id==='weekly')return {goal:tr('common.serve_as_much_traffic_as_you'),items:[{l:tr('progress.your_score_peak_traffic'),v:0,max:0,txt:fmtG(S.stats.peak||0)}],f:Math.min(1,S.day/sc.days)}; + const def=SCN.find(x=>x.id===sc.id),fn=SCN_PROG[sc.id];if(!def)return null;let items=[];try{items=fn?fn():[];}catch(e){items=[];} + const meas=items.filter(x=>x.max),f=sc.done?1:meas.length?meas.reduce((a,x)=>a+Math.min(1,x.v/x.max),0)/meas.length:0;return {goal:def.goal,items,f};} +const pRow=x=>`
${esc(x.l)}${esc(x.txt)}
${x.max?`
`:''}`; +function scnCard(){const sc=S.scn,P=scnProg();if(!sc||!P)return '';const left=Math.max(0,sc.days-S.day); + const st=sc.done?`${tr('progress.done_in_d_days',{d:sc.done})}`:sc.failed?`${tr('common.time_s_up')}`:tr('common.n_days_left',{n:left}); + return `
${tr('common.scenario')} · ${Math.round(P.f*100)}%
${esc(sc.name)}
🎯 ${esc(P.goal)}
${P.items.map(pRow).join('')}
${tr('common.time')}${st}
`;} +function lvlItems(){const lv=S.lvl||1,pk=S.stats.peak||0,pops=Object.keys(S.pops).length,G=(l,v,max,txt)=>({l,v,max,txt}),q=LV_REQ[lv];if(!q)return []; + const out=[G(tr('common.peak_traffic'),pk,q.pk,`${fmtG(pk)} / ${fmtG(q.pk)}`),G(tr('common.pops'),pops,q.pops,`${pops} / ${q.pops}`)],rg=lvReg(lv);if(rg)out.push(G(tr('common.continents'),regionsCount(),rg,`${regionsCount()} / ${rg}`));return out;} +// Lost Tier 1 status explains itself where you look for it, not only in a toast you may have missed (#73). +const t1Note=()=>S.won&&!isTier1()?`

${tr('progress.not_tier_1_right_now_why',{why:esc(t1Why())})}

`:''; +function lvlCard(){const lv=S.lvl||1,nx=LEVELS[lv]; + return `
${tr('progress.customer_level_lv_of_max',{lv,max:LEVELS.length})}
${esc(LEVELS[lv-1].n)}
${esc(LEVELS[lv-1].q)}
${t1Note()}${nx?`
${tr('progress.next_name_unlocks_what',{name:esc(nx.n),what:esc(lc1(nx.unlock))})}
${broker()?`
🚢 ${tr('broker.your_glass_gear_is_already_yours')}
`:''}${lvlItems().map(pRow).join('')}`:`
${tr('common.every_customer_type_is_unlocked_go')}
`}
`;} diff --git a/src/game/94-dashboard/20-meet-a-network.js b/src/game/94-dashboard/20-meet-a-network.js new file mode 100644 index 0000000..736005a --- /dev/null +++ b/src/game/94-dashboard/20-meet-a-network.js @@ -0,0 +1,33 @@ +/* ---------- where to meet a network (#12, #111, #121) ---------- */ +// Static: the cities where a network takes PNIs and the exchanges it sits on. Built once, on first use. +let PLACES=null; +function netPlaces(id){if(!PLACES){PLACES={};for(const n of NETS)PLACES[n.id]={p:n.pops.filter(c=>CITY[c]&&!CITY[c].off),x:[]}; + for(const c of CITIES)if(c.ix&&!c.off)for(const n of NETS)if(n.ix==='ALL'||(Array.isArray(n.ix)&&n.ix.includes(c.id)))PLACES[n.id].x.push(c.id); + for(const X of XIX)for(const m of X.members)if(PLACES[m])PLACES[m].x.push(X.id);}return PLACES[id];} +// km from each city to your nearest POP, cached until the set of POPs changes. +let NEARK='',NEARM=null; +function popNear(){const ps=Object.keys(S.pops),k=ps.join();if(k!==NEARK||!NEARM){NEARK=k;NEARM={};for(const c of CITIES)NEARM[c.id]=ps.length?Math.min(...ps.map(q=>q===c.id?0:kmBetween(q,c.id))):0;}return NEARM;} +// One entry per city: can you PNI there, which of its exchanges have them. Your POPs first, then nearest. +let SPOTK='',SPOTM={}; +function meetSpots(id){const near=popNear();if(SPOTK!==NEARK){SPOTK=NEARK;SPOTM={};}if(SPOTM[id])return SPOTM[id];const P=netPlaces(id),m={};if(!P)return []; + for(const c of P.p)(m[c]||(m[c]={c,pni:false,ix:[]})).pni=true; + for(const x of P.x){const c=ixCity(x);if(CITY[c])(m[c]||(m[c]={c,pni:false,ix:[]})).ix.push(x);} + return SPOTM[id]=Object.values(m).sort((a,b)=>(!!S.pops[b.c]-!!S.pops[a.c])||(near[a.c]-near[b.c])||(a.c[x.pni?'PNI':'',...x.ix.map(ixName)].filter(Boolean).join(' · '); + return `
${tr('meet_a_network.where_to_meet_them')}
${sp.slice(0,max).map(x=>btn(`${esc(CITY[x.c].name)} ${esc(lab(x))}`,'meetGo',{city:x.c},S.pops[x.c]?'sm':'ghost sm')).join('')}${sp.length>max?btn(tr('dashboard.n_more',{n:sp.length-max}),'netFocus',{id:n.id},'ghost sm'):''}
`;} +// The nearest place to meet a network you have no POP for, for one-line hints. +function nearestSpot(id){const x=meetSpots(id)[0];return x&&!S.pops[x.c]?x:null;} +// Networks you reach only through transit, biggest first: what stands between you and Tier 1. +const ntLost=()=>NETS.filter(n=>!R.nt[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id]); +function t1Card(){const cur=GOALS.find(g=>S.done[g.id]===undefined);if(!((cur&&cur.id==='t1')||S.won)||isTier1())return ''; + const need=t1Need(),miss=need.filter(n=>!S.pni.some(p=>p.net===n.id&&pniOn(p))),club=t1Club(),lost=ntLost(),nb=n=>btn(esc(n.name),'netFocus',{id:n.id},'ghost sm'); + let h=`
${tr('common.goal')} · ${tr('common.go_transit_free_tier_1')}
${tr('meet_a_network.road_to_tier_1')}
`; + h+=pRow({l:tr('meet_a_network.transit_ports_to_cancel'),v:S.transit.length?0:1,max:1,txt:S.transit.length?String(S.transit.length):'✓'}); + h+=pRow({l:tr('meet_a_network.pnis_with_every_tier_1'),v:need.length-miss.length,max:need.length,txt:`${need.length-miss.length} / ${need.length}`}); + if(miss.length)h+=`
${miss.map(nb).join('')}
`+(club.ok?'':`

${tr('meet_a_network.tier_1s_only_take_a_pni',{list:club.missing.join(', ')})}

`); + h+=pRow({l:tr('meet_a_network.reach_without_transit'),v:Math.min(R.reachNT,0.999),max:0.999,txt:`${reachPct(R.reachNT)} / 99.9%`}); + // Their customers come along for free (#85): say how many, so the long tail does not look like homework. + {const nc=Object.keys(R.cone||{}).length;h+=`

${nc?trn('meet_a_network.peer_with_the_tier_1_club_n',nc):tr('meet_a_network.peer_with_the_tier_1_club')}

`;} + if(lost.length)h+=`
${lost.slice(0,3).map(nb).join('')}${btn(trn('meet_a_network.all_n_out_of_reach',lost.length),'netFilter',{f:'out'},'pink sm')}
`; + return h+'
';} diff --git a/src/game/94-dashboard/30-customers.js b/src/game/94-dashboard/30-customers.js new file mode 100644 index 0000000..e0f1fe3 --- /dev/null +++ b/src/game/94-dashboard/30-customers.js @@ -0,0 +1,34 @@ +/* ---------- customers overview (#13, #14, #15) ---------- */ +const bizMo=b=>{const T=BIZ_T[b.type];return T.event?0:T.fiber?b.rate:b.bw*b.rate;}; +// Why a customer is unhappy, in the same terms the daily mood update uses. +function bizWhy(b){const T=BIZ_T[b.type],out=[];if(T.event&&!eventLive(b))return out;if(capPend(b))return capWhy(b); + const sf=bizSf(b);if(sf<0.95)out.push(T.fiber?tr('customers.their_fiber_is_down'):tr('customers.getting_only_p_of_the_bandwidth',{p:pct(sf)})); + if(!(T.l2||T.fiber)&&R.reach<=0.99&&!scnRule('local'))out.push(tr('customers.you_cannot_reach_the_whole_internet',{p:pct(R.reach)})); + if(b.type==='scrub'&&!hasScrub())out.push(tr('common.needs_a_scrubbing_center')); + {const q=b.type==='scrub'&&scrubFar(b.city);if(q)out.push(tr('customers.attacks_on_city_are_hauled_to',{city:CITY[b.city].name,to:CITY[q.to].name,ms:Math.round(q.ms)}));} + for(const k of b.reqs||[])if(REQS[k]&&!REQS[k].ok(b))out.push(typeof REQS[k].l==='function'?REQS[k].l(b):REQS[k].l); + return out;} +const moodCls=m=>m<30?'bad':m<60?'warn':''; +const custStats=()=>{const bz=S.biz.filter(b=>!BIZ_T[b.type].event),mo=bz.reduce((a,b)=>a+bizMo(b),0); + return {n:bz.length,unhappy:bz.filter(b=>b.mood<60).length,furious:bz.filter(b=>b.mood<30).length,avg:bz.length?(mo>0?bz.reduce((a,b)=>a+b.mood*bizMo(b),0)/mo:bz.reduce((a,b)=>a+b.mood,0)/bz.length):100,risk:bz.filter(b=>b.mood<60).reduce((a,b)=>a+bizMo(b),0)};}; +// Long lists show their first rows and grow on request: a thousand rows of buttons take the browser a long time to +// lay out again every day, worst of all on a phone. Filters, sorting and totals still cover every row. +const LIST_PAGE=100,listN=k=>(UI.listN&&UI.listN[k])||LIST_PAGE,listReset=k=>{if(UI.listN)delete UI.listN[k];}; +const listMore=(k,n,lab)=>n>listN(k)?`
${btn(lab(Math.min(LIST_PAGE,n-listN(k))),'listMore',{k},'ghost sm')}
`:''; +function custSection(){const F=UI.kf||{};let h=`

${tr('common.customers')}

`; + if(!S.biz.length)return h+`

${tr('customers.no_customers_yet_offers_show_up')}

`; + const st=custStats(); + h+=`

${tr('customers.everyone_who_pays_you_happiest_last')}

`; + h+=`
${tr('common.happiness')}
${Math.round(st.avg)}%
${tr('customers.weighted_by_what_they_pay')}
${tr('common.unhappy')}
${st.unhappy}
${trn('customers.n_furious',st.furious)}
${tr('common.at_risk')}
${tr('common.price_mo',{price:fmt$(st.risk)})}
${tr('customers.from_unhappy_customers')}
`; + const cities=[...new Set(S.biz.map(b=>b.city))].sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); + h+=`
${btn(tr('dashboard.all_n',{n:S.biz.length}),'custF',{v:''},!F.f?'pink sm':'ghost sm')}${btn(tr('customers.unhappy_n',{n:S.biz.filter(b=>b.mood<60).length}),'custF',{v:'sad'},F.f==='sad'?'pink sm':'ghost sm')}
`; + const rows=S.biz.filter(b=>(!F.f||b.mood<60)&&(!F.city||b.city===F.city||b.city2===F.city||(b.sites||[]).includes(F.city))); + const sk=UI.custSort||'mood',dir=UI.custDir||1,val=b=>sk==='name'?b.name.toLowerCase():sk==='city'?CITY[b.city].name:sk==='mo'?bizMo(b):b.mood; + rows.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||a.mood-b.mood;}); + if(!rows.length)return h+`

${F.f?tr('customers.nobody_is_unhappy_enjoy_it_while'):tr('customers.no_customers_here')}

`; + const where=b=>b.sites?b.sites.map(c=>CITY[c].name).join(', '):b.city2?`${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:CITY[b.city].name; + const trend=b=>b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' ▲':' ▼'; + const sorts=[['mood',tr('common.happiness')],['mo',tr('common.per_month')],['name',tr('common.name')],['city',tr('common.where')]]; + h+=`
${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; + h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `
${esc(b.name)} ${esc(BIZ_T[b.type].l)}
${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('common.price_mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}${clTermTxt(b)?' · '+clTermTxt(b):''}
${bRisk(b)}${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('common.happiness_p',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('common.open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); + return h+listMore('cust',rows.length,n=>trn('customers.n_more_customer',n))+`
`;} diff --git a/src/game/94-dashboard/35-unbuilt-pops.js b/src/game/94-dashboard/35-unbuilt-pops.js new file mode 100644 index 0000000..7a4b23e --- /dev/null +++ b/src/game/94-dashboard/35-unbuilt-pops.js @@ -0,0 +1,13 @@ +/* ---------- cities with no POP of yours yet ---------- */ +function popsSection(){const F=UI.popF||{},q=popStdQuote(),cost=c=>popCost(c)+(q?q.cost:0),mo=c=>popMo(c)+(q?q.mo:0); + const all=CITIES.filter(C=>cityOn(C.id)&&!S.pops[C.id]); + let h=`

${tr('unbuilt_pops.cities_without_a_pop_n',{n:all.length})}

`; + if(!all.length)return h+`

${tr('unbuilt_pops.you_have_a_pop_in_every')}

`; + h+=`

${tr('unbuilt_pops.every_city_where_you_could_still')}

`; + const sk=UI.popSort||'eye',dir=UI.popDir||-1,val=C=>sk==='name'?C.name.toLowerCase():sk==='cost'?cost(C.id):eyeP(C.id); + h+=`
`; + h+=`
${[['eye',tr('common.eyeballs')],['cost',tr('common.cost')],['name',tr('common.name')]].map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'popsSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; + const rows=all.filter(C=>!F.reg||C.reg===F.reg).sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||a.name.localeCompare(b.name);}); + if(!rows.length)return h+`

${tr('unbuilt_pops.nothing_left_to_build_in_this')}

`; + h+=rows.slice(0,listN('pops')).map(C=>{const ix=ixName(C.id);return `
${esc(C.name)} ${esc(REG[C.reg])}
${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(C.id))})}${ix?` · ${tr('city_panel.ix_ix',{ix:esc(ix)})}`:''} · ${tr('unbuilt_pops.cost_then_mo',{cost:fmt$(cost(C.id)),mo:fmt$(mo(C.id))})}
${C.cn&&!cnOk()?`
${tr('unbuilt_pops.needs_a_license_first')}
`:''}
${btn(tr('common.open'),'popGo',{city:C.id},'ghost sm')}
`;}).join(''); + return h+listMore('pops',rows.length,n=>trn('unbuilt_pops.n_more_city',n))+`
`;} diff --git a/src/game/94-dashboard/40-connections.js b/src/game/94-dashboard/40-connections.js new file mode 100644 index 0000000..7234dc8 --- /dev/null +++ b/src/game/94-dashboard/40-connections.js @@ -0,0 +1,82 @@ +/* ---------- connections overview (#31, #33, #38) ---------- + Every transit port, PNI, IX port, cache and fabric port in one list, filterable by type, city and + network, with a jump to the POP that holds it. The Networks tab shows the same per network. */ +const CONN_K={t:N_('common.transit'),p:'PNI',ix:'IX',c:N_('common.cache'),nni:'NNI'},CONN_ORD=['t','p','ix','c','nni'],CONN_COL={t:'#FF8A3D',p:'#7B61FF',ix:'#2DB7F5',c:'#16A866',nni:'#1E2640'}; +const connTab=k=>k==='t'?'up':k==='nni'?'links':'peer'; +// How many rows conns() gives, without building them (the Networks tab only shows the count). +const connsN=()=>S.transit.length+S.pni.length+Object.keys(S.ixp).length+new Set(S.caches.map(x=>x.city+'|'+x.net)).size+(S.nni||[]).filter(x=>FAB[x.prov]&&NNI[x.tier]).length; +function conns(){const out=[],pn=(tier,n)=>(n||1)>1?`${n}×${PORT[tier].n} LAG`:PORT[tier].n; + for(const t of S.transit){const q=(R.p95&&R.p95[t.id])||0;out.push({k:'t',id:t.id,city:t.city,net:t.net,name:NET[t.net].name,port:pn(t.tier,t.n),cap:lagCap(PORT[t.tier].g,t.n),use:R.useT[t.id]||0,mo:transitMo(t,q),down:t.down>S.day||!popUp(t.city),low:t.pref==='low',note:tr('connections.95th_percentile_g',{g:fmtG(q)})});} + for(const x of S.pni){const u=R.usePni[x.id]||0;out.push({k:'p',id:x.id,city:x.city,net:x.net,name:NET[x.net].name,port:x.g1?((x.n||1)>1?x.n+'×1G':'1G'):pn(x.tier,x.n),cap:lagCap(pniG(x),x.n),use:u,mo:pniMo(x,u),down:!popUp(x.city)||!pniOn(x),low:x.pref==='low',note:!pniOn(x)?tr('connections.on_order_n_days',{n:x.ready-S.day}):NET[x.net].pol==='paid'?tr('common.paid_peering'):''});} + for(const c in S.ixp){const ses=ixSessions(c),mine=!!S.myIx[c];out.push({k:'ix',id:c,city:ixCity(c),net:null,nets:[...ses],name:ixName(c),port:mine?tr('common.your_exchange'):pn(S.ixp[c],(S.ixn||{})[c]),cap:ixCap(c),use:R.useIx[c]||0,mo:ixMo(c),mine,down:!!(S.ev.ixdown&&S.ev.ixdown[c]>S.day),low:(S.ixPref&&S.ixPref[c])==='low',note:trn('connections.n_peering_session',ses.size)+(isRemote(c)?' · '+tr('common.remote'):'')});} + const cg={};for(const x of S.caches){const key=x.city+'|'+x.net;(cg[key]=cg[key]||[]).push(x);} + for(const key in cg){const g=cg[key],x=g[0];out.push({k:'c',id:x.id,n:g.length,city:x.city,net:x.net,name:NET[x.net].cache.name,port:trn('common.n_box',g.length),cap:g.reduce((a,y)=>a+cacheG(y),0),use:g.reduce((a,y)=>a+(R.useCache[y.id]||0),0),mo:g.reduce((a,y)=>a+cacheMo(y),0),down:!popUp(x.city),low:false,note:tr('common.from_net',{net:NET[x.net].name})});} + for(const x of S.nni||[])if(FAB[x.prov]&&NNI[x.tier])out.push({k:'nni',id:x.city+'|'+x.prov,city:x.city,net:null,name:FAB[x.prov].name,port:pn(x.tier,x.n),cap:nniCap(x),use:nniUsed(x.city,x.prov),mo:nniMo(x),down:!popUp(x.city),low:false,note:tr('connections.virtual_circuits_and_fabric')}); + return out;} +// Cancel straight from the list, with the same "Really?" step as the POP panel. +// Grow a connection from the list: the next port size and one more LAG member, same actions and prices as the POP panel. +// nx looks up the next size in that kind of port's own table: fabric ports (NNI) stop at 400G. +function connUp(r){if(r.mine)return '';const nx=(t,T=PORT)=>T[t+1]&&portShown(t+1)?t+1:-1;let h=''; + if(r.k==='t'){const t=S.transit.find(x=>x.id===r.id);if(!t)return '';const n=t.n||1,i=nx(t.tier); + if(i>=0){const a={port:PORT[i].n,cost:fmt$(PORT[i].setup*n),mo:fmt$(PORT[i].tmo*n)};h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a),'buyTransit',{city:t.city,net:t.net,tier:i},'sm',S.cashx.id===r.id);if(!p)return '';if(!pniOn(p)||p.up||msfNope(p.net,p.city))return `${!pniOn(p)||p.up?tr('common.on_order'):''}`;const n=p.n||1,i=p.g1?0:nx(p.tier),c=i>=0?(1500+PORT[i].setup/2)*n:0; + if(i>=0){const a={port:PORT[i].n,cost:fmt$(c),mo:fmt$(PORT[i].pni*n)};h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a),'pni',{city:p.city,net:p.net,tier:i},'sm',!portOk(p.city,i)||S.cash=0)h+=btn(tr('common.upgrade_port_price',{port:PORT[i].n,price:portMo(ixPortMo(c,i)*n)}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)); + if(S.pops[city]&&!S.myIx[c]&&n=0){const c=NNI[i].mo*n;h+=btn(n>1?tr('common.upgrade_all_to_port_cost_mo',{port:NNI[i].n,cost:fmt$(c),mo:fmt$(c)}):tr('common.upgrade_port_price_mo',{port:NNI[i].n,price:fmt$(c)}),'buyNni',{city,prov,tier:i},'sm',S.cashbtn(tr('link_panels.downgrade_port_price',{port,price}),act,args,'ghost sm'),less=(act,args)=>btn(tr('common.member'),act,{...args,d:-1},'ghost sm');let h=''; + if(r.k==='t'){const t=S.transit.find(x=>x.id===r.id);if(!t)return '';const n=t.n||1; + if(t.tier>0)h+=dn(PORT[t.tier-1].n,portMo(PORT[t.tier-1].tmo*n),'downT',{id:t.id});if(n>1)h+=less('lagT',{id:t.id});} + else if(r.k==='p'){const p=S.pni.find(x=>x.id===r.id);if(!p)return '';const n=p.n||1,chase=btn(tr('common.chase_it'),'pniChase',{id:p.id},'ghost sm'); + if(!pniOn(p))return chase; + if(p.up)h+=chase;else if(!p.g1&&p.tier>pniMin(p.net)&&!msfNope(p.net,p.city))h+=dn(PORT[p.tier-1].n,portMo(PORT[p.tier-1].pni*n),'downP',{id:p.id}); + if(n>1)h+=less('lagP',{id:p.id});} + else if(r.k==='ix'){const c=r.id,n=(S.ixn||{})[c]||1; + if(n>1)h+=less('lagIx',{city:c});if(S.ixp[c]>0)h+=dn(PORT[S.ixp[c]-1].n,portMo(ixPortMo(c,S.ixp[c]-1)*n),'downIx',{city:c});} + else if(r.k==='nni'){const [city,prov]=r.id.split('|'),pt=nniPort(city,prov);if(pt&&(pt.n||1)>1)h+=less('lagNni',{city,prov});} + return h;} +function connX(r){if(r.mine)return '';const on=UI.confirm==='cc:'+r.k+':'+r.id; + return btn(on?(r.k==='ix'?tr('common.really_leave'):r.k==='t'?tr('common.really_cancel'):tr('common.really_remove')):r.k==='ix'?tr('common.leave_ix'):r.k==='t'?tr('common.cancel'):r.k==='c'&&r.n>1?tr('common.box_6ee3'):r.k==='nni'?tr('common.remove_port'):tr('common.remove'),'connCancel',{k:r.k,id:r.id},on?'red sm':'ghost sm');} +function connMatch(r,F){return (!F.k||r.k===F.k)&&(!F.city||r.city===F.city)&&(!F.net||r.net===F.net||(r.nets&&r.nets.includes(F.net)));} +function connSection(){const all=conns(),F=UI.cf||{}; + let h=`

${tr('common.connections')}

${tr('connections.every_port_that_connects_you_to')}

`; + if(!all.length)return h+`

${tr('connections.no_connections_yet_buy_transit_or')}

`; + const cnt=k=>all.filter(r=>r.k===k&&connMatch(r,{...F,k:null})).length; + h+=`
${btn(tr('dashboard.all_n',{n:all.filter(r=>connMatch(r,{...F,k:null})).length}),'connF',{f:'k',v:''},!F.k?'pink sm':'ghost sm')}${CONN_ORD.filter(k=>all.some(r=>r.k===k)).map(k=>btn(`${tr(CONN_K[k])} (${cnt(k)})`,'connF',{f:'k',v:k},F.k===k?'pink sm':'ghost sm')).join('')}
`; + const cities=[...new Set(all.map(r=>r.city))].sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); + const nets=[...new Set(all.flatMap(r=>r.net?[r.net]:(r.nets||[])))].filter(id=>NET[id]&&!NET[id].tail).sort((a,b)=>NET[a].name.localeCompare(NET[b].name)); + h+=`
${F.k||F.city||F.net?btn(tr('common.clear_filters'),'connF',{f:'all',v:''},'ghost sm'):''}
`; + const rows=all.filter(r=>connMatch(r,F)); + const sk=UI.connSort||'k',dir=UI.connDir||1,val=r=>sk==='city'?CITY[r.city].name:sk==='name'?r.name.toLowerCase():sk==='use'?(r.cap?r.use/r.cap:0):sk==='mo'?r.mo:CONN_ORD.indexOf(r.k); + rows.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||CONN_ORD.indexOf(a.k)-CONN_ORD.indexOf(b.k)||CITY[a.city].name.localeCompare(CITY[b.city].name)||a.name.localeCompare(b.name);}); + const tc=rows.reduce((a,r)=>a+r.cap,0),tu=rows.reduce((a,r)=>a+r.use,0),tm=rows.reduce((a,r)=>a+r.mo,0); + if(isPhone()){const st=(r)=>r.down?` ${tr('common.down')}`:r.low?` ${tr('common.backup')}`:''; + h+=`
${[['k',tr('common.type')],['city',tr('common.where')],['use',tr('common.in_use')],['mo',tr('common.per_month')]].map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'connSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; + h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `
${N?logo(N):``}
${esc(r.name)} ${tr(CONN_K[r.k])}${st(r)}
${esc(CITY[r.city].name)} · ${esc(r.port)} · ${tr('common.price_mo',{price:fmt$(r.mo)})}${r.note?' · '+esc(r.note):''}
${tr('common.in_use')}${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}
${r.mine?'':`
${connUp(r)}${connDown(r)}${connX(r)}
`}
${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}
`;}).join(''); + return h+listMore('conn',rows.length,n=>trn('connections.n_more_connection',n))+`
${trn('connections.n_connection',rows.length)}${fmtG(tu)} / ${fmtCap(Math.round(tc))} · ${tr('common.price_mo',{price:fmt$(tm)})}
`;} + const th=(k,l,c)=>`${k?``:l}`; + h+=`
${th('k',tr('common.type'))}${th('city',tr('common.where'))}${th('name',tr('common.with'))}${th('',tr('common.port'))}${th('use',tr('common.in_use'),'r')}${th('mo',tr('common.per_month'),'r')}`; + h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return ``;}).join(''); + h+=`
${tr(CONN_K[r.k])}${esc(CITY[r.city].name)}${N?logo(N):''}${esc(r.name)}${r.note?`
${esc(r.note)}`:''}
${esc(r.port)}${r.down?` ${tr('common.down')}`:r.low?` ${tr('common.backup')}`:''}${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}
${fmt$(r.mo)}
${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}${connUp(r)}${connDown(r)}${connX(r)}
${trn('connections.n_connection',rows.length)}${fmtG(tu)} / ${fmtCap(Math.round(tc))}${fmt$(tm)}
${listMore('conn',rows.length,n=>trn('connections.n_more_connection',n))}
`; + return h;} +// Where you connect to one network, as buttons that jump to the POP (Networks tab). +// Where you connect to each network, as [label, city, kind]: transit, PNIs, IX sessions, then caches. Built for all +// networks at once, so the network list works out each IX port's sessions a single time, not once per network. +function netWhereIdx(){const B={t:{},p:{},ix:{},c:{}},add=(k,id,x)=>(B[k][id]||(B[k][id]=[])).push(x); + for(const t of S.transit)add('t',t.net,[tr('common.transit'),t.city,'t']); + for(const x of S.pni)add('p',x.net,['PNI',x.city,'p']); + for(const c in S.ixp){const nm=ixName(c),ct=ixCity(c);for(const id of ixSessions(c))add('ix',id,[nm,ct,'ix']);} + const seen=new Set();for(const x of S.caches){const k=x.net+'|'+x.city;if(!seen.has(k)){seen.add(k);add('c',x.net,[tr('common.cache'),x.city,'c']);}} + return id=>[].concat(B.t[id]||[],B.p[id]||[],B.ix[id]||[],B.c[id]||[]);} +function netWhere(n,where){const ch=(where||netWhereIdx())(n.id); + if(!ch.length)return '';const MAX=6; + return `
${ch.slice(0,MAX).map(([l,c,k])=>btn(`${esc(l)} ${esc(CITY[c].name)}`,'goConn',{city:c,k},'ghost sm')).join('')}${ch.length>MAX?btn(tr('dashboard.n_more',{n:ch.length-MAX}),'connFor',{net:n.id},'ghost sm'):''}
`;} +const DTABS=['overview','cust','conn','traffic','infra','pops','lease','market']; diff --git a/src/game/94-dashboard/50-lease-swaps.js b/src/game/94-dashboard/50-lease-swaps.js new file mode 100644 index 0000000..19b26c4 --- /dev/null +++ b/src/game/94-dashboard/50-lease-swaps.js @@ -0,0 +1,37 @@ +/* Leased lines you could swap for your own glass: waves, fabric circuits and IRUs between two of your POPs, + priced against digging (land) or laying a cable (subsea), with enough optics to match what you lease today. */ +function swapOptics(km,cap,sub,sys){for(let r=0;r<=(sub?0:REGEN_MAX);r++){const l={km,regen:r,sub};let b=null; + for(const o in OPT){if(OPT[o].lvl>glassLvl()||sys==='lite'&&OPT[o].sys==='roadm')continue;const g=optG(o,l),c=optCost(o);if(g&&(!b||c/gls.reduce((s,l)=>s+(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?(l.ch||[]).reduce((t,o)=>t+optG(o,l),0):LT[l.tier].g),0); +const swapOpt=(k,up,omo,days,mo)=>{const save=mo-omo;return {k,up,omo,days,save,pay:save>0?Math.ceil(up/save):0};}; +// Lighting leased capacity on a fiber you already have (#72 review): needs free channels, and optics cost money. +function litOn(L,cap){const free=chMax(L)-(L.ch||[]).length-soldSlots(L)-xpSlots(L);let b=null; + for(const o in OPT){const O=OPT[o];if(O.lvl>glassLvl()||(O.sys==='roadm'&&!isRdm(L.sys))||[L.a,L.b].some(c=>S.pops[c]&&RG[S.pops[c].rgen||0].cls{const [a,b]=k.split('|'),sub=isSub(a,b),mo=ls.reduce((s,l)=>s+(l.mo||0),0),cap=leaseCap(ls); + const x={a,b,sub,ls,mo,cap,opts:[],own:pairLinks(a,b).find(l=>l.kind==='df'&&l.own&&l.ready<=S.day)};if(x.own){x.fit=litOn(x.own,cap);if(x.fit.fits)x.best=mo;return x;} + // Waves and fabric circuits can also move onto a leased fiber pair: cheaper glass, but you buy the gear. + const ws=ls.filter(l=>l.kind!=='df'),wmo=ws.reduce((s,l)=>s+(l.mo||0),0),sc=sub?subDfCable(a,b):null;x.iru=ls.find(l=>l.kind==='df'); + if(ws.length&&x.iru){x.fit=litOn(x.iru,leaseCap(ws));if(x.fit.fits)x.lit=wmo;} + else if(ws.length&&glassLvl()>=2&&(sub?sc:dfAllowed(a,b))){const km=sc?sc.km:kmBetween(a,b),sys=glassLvl()>=3?'roadm':'lite',wc=leaseCap(ws),op=swapOptics(km,wc,sub,sys); + if(op&&op.n<=DF_SYS[sys].max)x.opts.push(swapOpt('iru',DF_SYS[sys].cost+ampCount(km)*AMP_COST+op.up,dfLeaseMo(km)+ampCount(km)*AMP_MO+op.mo,leadDays(IRU_DAYS),wmo));} + // Dig on land, lay a cable between landing stations (even ones that share a landmass), or both. + const whys=[];for(const cab of [false,true]){if(cab?!seaCab(a,b):sub)continue; + const why=cab?ownCabWhy(a,b):!dfAllowed(a,b)?tr('lease_swaps.nobody_lets_you_dig_on_this'):glassLvl()<2?tr('lease_swaps.digging_your_own_fiber_unlocks_at'):''; + if(why){whys.push(why);continue;}const km=cab?ownCabKm(a,b):kmBetween(a,b),op=swapOptics(km,cap,cab,'roadm'); + if(!op){whys.push(tr('lease_swaps.no_optic_you_can_buy_reaches',{km:km.toLocaleString()}));continue;} + x.opts.push(swapOpt(cab?'cab':'own',(cab?ownCabCost(km):digCost(km)+DF_SYS.roadm.cost+ampCount(km)*AMP_COST)+op.up,(cab?ownCabMo(km):Math.round(km*0.15)+ampCount(km)*AMP_MO)+op.mo,cab?ownCabDays(km):dfBuildDays(km),mo));} + x.why=x.opts.some(o=>o.k!=='iru')?'':whys.join(' '); + const sv=[...x.opts.map(o=>o.save),x.lit].filter(v=>v!==undefined);if(sv.length)x.best=Math.max(...sv);return x;}) + .sort((p,q)=>((p.best===undefined)-(q.best===undefined))||(q.best||0)-(p.best||0)||q.mo-p.mo);} +function leaseTab(){const xs=leaseSwaps(),tot=xs.reduce((s,x)=>s+x.mo,0); + const kind=l=>l.kind==='vxc'?tr('lease_swaps.cap_fabric_circuit',{cap:capName(l)}):l.kind==='df'?tr('lease_swaps.cap_on_a_dark_fiber_iru',{cap:capName(l)}):tr('lease_swaps.cap_wave',{cap:capName(l)}); + const line=(x,o)=>{const a={up:fmt$(o.up),mo:fmt$(o.omo),n:o.days};return `
${o.k==='iru'?tr('lease_swaps.lease_dark_fiber_up_up_front',a):o.k==='cab'?tr('lease_swaps.your_own_cable_up_up_front',a):tr('lease_swaps.your_own_fiber_up_up_front',a)} ${o.save>0?tr('lease_swaps.saves_price_mo_pays_for_itself',{price:fmt$(o.save),n:o.pay}):tr('lease_swaps.costs_more_than_leasing_at_this')}
`;}; + const plan=(x,o)=>btn(o.k==='iru'?tr('lease_swaps.plan_dark_fiber'):o.k==='cab'?tr('lease_swaps.plan_a_cable'):tr('lease_swaps.plan_your_own_fiber'),'leaseSwap',{a:x.a,b:x.b,src:o.k==='iru'?'lease':o.k==='cab'?'cable':'build'},o.save>0&&o.save===x.best?'pink sm':'ghost sm'); + return `

${tr('common.leased_lines')}

${tr('lease_swaps.every_wave_fabric_circuit_and_dark')}

+ ${xs.length?`
${tr('lease_swaps.you_pay_for_leases')}${tr('common.price_mo',{price:fmt$(tot)})}
`+xs.map(x=>`
${CITY[x.a].name} ⇄ ${CITY[x.b].name} ${x.sub?tr('common.subsea'):tr('common.land')}
${Object.entries(x.ls.reduce((m,l)=>(m[kind(l)]=(m[kind(l)]||0)+1,m),{})).map(([k,n])=>n>1?`${n} × ${k}`:k).join(', ')} · ${tr('common.price_mo',{price:fmt$(x.mo)})}
+ ${x.fit&&x.fit.fits?`
${x.own?tr('lease_swaps.you_already_own_fiber_here_light',{n:x.fit.n,up:fmt$(x.fit.up),price:fmt$(x.best)}):tr('lease_swaps.you_already_lease_dark_fiber_here',{n:x.fit.n,up:fmt$(x.fit.up),price:fmt$(x.lit)})}
`:x.fit?`
${x.fit.n?tr('lease_swaps.your_fiber_here_has_room_for',{free:Math.max(0,x.fit.free),n:x.fit.n}):tr('lease_swaps.no_optic_you_can_buy_works')}
`:''}${x.opts.map(o=>line(x,o)).join('')}${!x.own&&x.why?`
${esc(x.why)}
`:''} +
${x.own?btn(tr('lease_swaps.open_your_fiber'),'dashLink',{id:x.own.id},'pink sm'):''}${x.iru&&x.fit?btn(tr('lease_swaps.open_your_dark_fiber'),'dashLink',{id:x.iru.id},x.lit!==undefined?'pink sm':'ghost sm'):''}${x.opts.map(o=>plan(x,o)).join('')}${btn(tr('common.open_lease'),'dashLink',{id:(x.ls.find(l=>l.kind!=='df')||x.ls[0]).id},'ghost sm')}
`).join(''):`

${tr('lease_swaps.you_do_not_lease_any_lines')}

`}
`;} diff --git a/src/game/94-dashboard/55-market.js b/src/game/94-dashboard/55-market.js new file mode 100644 index 0000000..844b97a --- /dev/null +++ b/src/game/94-dashboard/55-market.js @@ -0,0 +1,38 @@ +/* ---------- the capacity market tab (37-fiber-market.js) ---------- + Your settings (what the broker may sell, from what demand and price, and how much it keeps back), the news, and + every route you hold dark fiber on: per product what is wanted, sold and listed, as a bar with your threshold on + it, and today's price against your floor. A Cable broker also sees where each route is heading, and routes it could + build. Markup is deterministic (the NOC window copies it). */ +const CM_NAME={spec:N_('market.p_spec'),w100:N_('market.p_w100'),w400:N_('market.p_w400'),w800:N_('market.p_w800'),w1600:N_('market.p_w1600'),iru:N_('market.p_iru')}; +const CM_DESC={spec:N_('market.p_spec_d'),w100:N_('market.p_w100_d'),w400:N_('market.p_w400_d'),w800:N_('market.p_w800_d'),w1600:N_('market.p_w1600_d'),iru:N_('market.p_iru_d')}; +const cmN=v=>v>=10?String(Math.round(v)):v.toFixed(1).replace(/\.0$/,''); +// Why nothing is listed although the route wants it and the price is right: no optic that big, or no room left on +// the fiber after what you keep back. Growing means lighting more. +// A bar: sold (green) of what the route wants (the dark line), and your minimum (the pink tick) when the broker lists. +function cmBar(D,sold,min){const top=Math.max(D,sold,min||0,1)*1.15,w=v=>(100*Math.min(1,v/top)).toFixed(1)+'%'; + return `
${min?``:''}
`;} +const cmSeg=(vals,cur,act,args,f)=>`
${vals.map(v=>btn(f(v),act,{...args,v},v===cur?'pink sm':'ghost sm')).join('')}
`; +function cmHeatTag(r){const H=cmHeat(r,'spec',S.day);return H>=1.15?`${tr('market.hot',{x:H.toFixed(1)})}`:H<=0.85?`${tr('market.cool',{x:H.toFixed(1)})}`:`${tr('market.steady')}`;} +function cmProdLine(r,p,s,L,fc){const C=S.cm.p[p],D=cmDem(r,p,S.day),i=cmIdx(r,p,s,0,S.day),pc=Math.round(i*100),m=mkt()*cmCut(); + const price=p==='iru'?tr('market.price_pair',{up:fmt$(Math.round(cmUpList(r)*i*m)),price:fmt$(Math.round(cmList(r,p)*m)),pct:pc}):tr('market.price',{price:fmt$(Math.round(cmList(r,p)*i*m)),pct:pc}); + return `
${tr(CM_NAME[p])} · ${tr('market.row',{want:cmN(D),sold:s,listed:L})} · ${price}${C.on&&pc${tr('market.below_floor')}`:C.on&&!L&&D>=C.min&&p!=='iru'&&!S.cm.off[r.k]?` ${CM_G[p]&&!r.ls.some(l=>cmOptG(l)>=CM_G[p])?tr('market.needs_optic',{g:fmtCap(CM_G[p])}):tr('market.no_room')}`:''}
+ ${cmBar(D,s,C.on?C.min:0)}${fc?`
${tr('market.forecast',{a:cmN(cmFc(r,p,30)),b:cmN(cmFc(r,p,90))})}
`:''}
`;} +function marketTab(){const C=S.cm,rs=[...cmRoutes().values()].sort((x,y)=>brMarket(y.a,y.b)-brMarket(x.a,x.b)),sold=cmSold(new Map(rs.map(r=>[r.k,r]))),bk=broker(); + const mo=S.biz.reduce((a,b)=>a+(['wwave','mwave','dfpair'].includes(b.type)?bizMo(b):0),0),ago=n=>S.day-n.d<1?tr('market.today'):trn('market.days_ago',S.day-n.d); + let h=`

${tr('market.title')}

${tr('market.lead')}

+
${tr('market.sales')}${tr('common.price_mo',{price:fmt$(mo)})}
+
${tr('market.fee')}${Math.round((1-cmCut())*100)}%${bk?` · ${tr('market.fee_broker')}`:''}
+
${tr('market.hold')}
${tr('market.hold_d')}
${cmSeg(CM_HOLD,C.hold,'mktHold',{},v=>v+'%')}
+ ${CM_P.map(p=>{const c=C.p[p];return `
${tr(CM_NAME[p])} ${btn(c.on?tr('market.selling'):tr('market.not_selling'),'mktCfg',{p,k:'on',v:c.on?0:1},c.on?'pink sm':'ghost sm')}
${tr(CM_DESC[p])}
+ ${c.on?`
${tr('market.min')}
${cmSeg(CM_MIN[p],c.min,'mktCfg',{p,k:'min'},v=>'≥ '+v)}
${tr('market.floor')}
${cmSeg(CM_FLOOR,c.floor,'mktCfg',{p,k:'floor'},v=>v+'%')}`:''}
`;}).join('')} +

${tr('market.news')}

${C.news.length?C.news.slice(0,5).map(n=>`
${ago(n)} · ${cmNewsText(n)}
`).join(''):`

${tr('market.no_news')}

`}
`; + h+=`

${tr('market.routes')}

${rs.length?`

${tr('market.legend')}${bk?'':' '+tr('market.forecast_lock')}

`+rs.map(r=>{const s=sold.get(r.k),off=!!C.off[r.k],L=p=>r.ls.reduce((a,l)=>a+((l.list&&l.list[CM_L[p]])||0),0); + return `
${CITY[r.a].name} ⇄ ${CITY[r.b].name} ${r.sub?tr('common.subsea'):tr('common.land')} ${cmHeatTag(r)}
+
${tr('market.route_meta',{km:Math.round(r.km).toLocaleString(),ms:r.lat.toFixed(1),n:Math.round((r.lp-1)*100)})}
+ ${(()=>{const shown=CM_P.filter(p=>s[p]>0||L(p)>0||cmDem(r,p,S.day)>=0.3||bk&&cmFc(r,p,90)>=0.3),rest=CM_P.filter(p=>!shown.includes(p)); + return shown.map(p=>cmProdLine(r,p,s[p],L(p),bk)).join('')+(rest.length?`
${tr('market.not_yet',{list:rest.map(p=>tr(CM_NAME[p])).join(', ')})}
`:'');})()} +
${btn(off?tr('market.route_off'):tr('market.route_on'),'mktRoute',{k:r.k},off?'ghost sm':'pink sm')}${btn(tr('lease_swaps.open_your_fiber'),'dashLink',{id:r.ls[0].id},'ghost sm')}
`;}).join(''):`

${tr('market.no_routes')}

`}
`; + if(bk){const sc=cmScout();h+=`

${tr('market.scout')}

${tr('market.scout_d')}

${sc.length?sc.map(r=>{const v=CM_P.reduce((a,p)=>a+cmDem(r,p,S.day)*cmList(r,p),0)*mkt()*cmCut(); + return `
${CITY[r.a].name} ⇄ ${CITY[r.b].name} ${r.sub?tr('common.subsea'):tr('common.land')} ${cmHeatTag(r)}
+
${tr('market.scout_spend',{km:Math.round(r.km).toLocaleString(),v:fmt$(Math.round(v))})}
${CM_P.filter(p=>cmDem(r,p,S.day)>=0.3||cmFc(r,p,90)>=0.3).map(p=>`
${tr(CM_NAME[p])} · ${tr('market.forecast_now',{n:cmN(cmDem(r,p,S.day)),a:cmN(cmFc(r,p,30)),b:cmN(cmFc(r,p,90))})}
`).join('')}
`;}).join(''):`

${tr('market.scout_none')}

`}
`;} + return h;} diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js new file mode 100644 index 0000000..8ad93d2 --- /dev/null +++ b/src/game/94-dashboard/60-dashboard.js @@ -0,0 +1,36 @@ +function dashTabs(){const u=custStats().unhappy,cur=UI.dtab||'overview',L={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),pops:tr('unbuilt_pops.no_pop_yet'),lease:tr('common.leased_lines'),market:tr('market.tab')}; + return ``;} +function renderDash(){checkLayer(); + const H=S.hist||[],rows=H.slice(-90),last30=H.slice(-30); + const up=last30.length?last30.reduce((a,r)=>a+(r.dem?Math.min(1,r.srv/r.dem):1),0)/last30.length:1; + const net=R.revMo-R.costMo,tot=Object.values(R.egT).reduce((a,b)=>a+b,0)||1; + const tile=(l,v,sub)=>`
${l}
${v}
${sub?`
${sub}
`:''}
`; + let h=`
AS${S.asn} · ${esc(S.name)} · ${tierLabel()}

${tr('common.noc_dashboard')}

`+dashTabs();const DT=UI.dtab||'overview';if(DT==='overview')h+=` +
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.carried'),fmtVol(S.vol||0),tr('dashboard.carried_sub'))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}
+

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}
+

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')} +

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.leases_cgnat_nat64'),sat:tr('satellites.costs_row'),wisp:tr('wisp.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; + const tT=(R.egT.t||0)||1; + const offMix=(UI.chartOff&&UI.chartOff.mix)||{},filt=Object.keys(offMix).length>0; + // The legend above the table picks which ways in count; "lost" still looks at everything the network gets. + const row=(n,e0,want)=>{const e={};for(const k of ['c','p','ix','t'])e[k]=offMix[k]?0:e0[k];const t=e.c+e.p+e.ix+e.t,all=e0.c+e0.p+e0.ix+e0.t;return {n,e,t,want,cost:(R.cost.transit||0)*e.t/tT,lost:want>0.01?Math.max(0,1-all/want):0};}; + const nets=NETS.filter(n=>!n.tail).map(n=>row(n,R.netEg[n.id]||{c:0,p:0,ix:0,t:0},R.demTo[n.id]||0)); + {const e={c:0,p:0,ix:0,t:0};let w=0;for(const n of NETS)if(n.tail){const x=R.netEg[n.id];if(x)for(const k in e)e[k]+=x[k]||0;w+=R.demTo[n.id]||0;}nets.push(row({id:'_tail',name:tr('dashboard.the_long_tail_n_small_networks',{n:NETS.filter(n=>n.tail).length}),asn:'many',type:'eye',col:'#8A93B8'},e,w));} + for(let i=nets.length-1;i>=0;i--)if(!(nets[i].t>0.01||(!filt&&nets[i].want>0.01)))nets.splice(i,1); + {const k=UI.dashSort||'traffic',dir=UI.dashDir||-1,val=x=>k==='name'?x.n.name.toLowerCase():k==='asn'?x.n.asn:k==='type'?x.n.type:k==='cost'?x.cost:k==='lost'?x.lost:x.t;nets.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||b.t-a.t;});} + if(DT==='cust')h+=clPanel()+custSection(); + if(DT==='conn')h+=connSection(); + if(DT==='traffic')h+=`
${btn(tr('ops.standing_orders'),'opsOpen',{},'sm')}
`; + if(DT==='traffic')h+=`

${tr('dashboard.traffic_by_network_asn')}

${tr('dashboard.where_your_users_traffic_comes_from')}

${chartLegend('mix')}
${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>``).join('')} + ${nets.map(({n,e,t,want,lost})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm pall'):''}${n.asn}${TYPE_L[n.type]}${fmtG(t)}${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(lost):'—'}
`; + if(DT==='traffic'){const top=transitTop(S.transit.map(t=>t.id),8);if(top.length)h+=`

${tr('dashboard.who_your_transit_carries')}

${tr('dashboard.the_networks_you_pay_transit_to')}

${top.map(([id,v])=>`
${logo(NET[id])}
${esc(NET[id].name)} AS${NET[id].asn} · ${fmtG(v)} · ${tr('dashboard.about_price_mo',{price:fmt$((R.cost.transit||0)*v/tT)})}
${esc(offTransitHint(id))}
${btn(tr('common.where_6276'),'netFocus',{id},'ghost sm')}
`).join('')}
`;} + const ls=S.links.filter(l=>capOf(l)>0).map(l=>({l,u:(R.load[l.id]||0)/capOf(l)})).sort((a,b)=>b.u-a.u).slice(0,8); + const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6); + if(DT==='infra')h+=`

${tr('common.busiest_links')}

${ls.length?ls.map(({l,u})=>`
${CITY[l.a].name} ⇄ ${CITY[l.b].name} ${capName(l)} · ${linkLat(l).toFixed(1)} ms
${pct(u)}${btn(tr('common.open'),'dashLink',{id:l.id},'ghost sm')}
`).join(''):'

'+tr('common.no_links_yet')+'

'}
+

${tr('common.router_load')}

${rs.map(({c,u})=>`
${CITY[c].name} ${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}
${pct(u)}
`).join('')} +

${tr('common.your_as')}

${tr('common.as_number')}AS${S.asn}
${tr('common.prefixes')}${(ip4On()&&ip4Pfx())||Math.max(1,Math.ceil(Object.keys(S.pops).length/3))+' × /22'} IPv4, 1 × /32 IPv6
${tr('common.bgp_sessions')}${R.sessions}
${tr('common.upstreams')}${new Set(S.transit.map(t=>t.net)).size}
${tr('common.reach')}${pct(R.reach)}
${tr('common.customers')}${tr('dashboard.n_businesses',{n:S.biz.length})}
`; + if(DT==='pops')h+=popsSection(); + if(DT==='lease')h+=leaseTab(); + if(DT==='market')h+=marketTab(); + if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);} +} diff --git a/src/game/94-dashboard/65-chart-legend.js b/src/game/94-dashboard/65-chart-legend.js new file mode 100644 index 0000000..c6bdc71 --- /dev/null +++ b/src/game/94-dashboard/65-chart-legend.js @@ -0,0 +1,45 @@ +/* The NOC charts: legend entries switch a series on and off (the scale follows what is left), and hovering or + touching a chart shows every visible series on that day. View state only: UI.chartOff is never saved. */ +const CHARTS={ + traffic:{stack:['c','p','ix','t','l2'],lines:['dem'],fmt:v=>fmtG(v),name:k=>k==='dem'?tr('common.demand'):EGC[k][0],col:k=>k==='dem'?'var(--text)':EGC[k][1]}, + mix:{stack:['c','p','ix','t'],lines:[],fmt:v=>fmtG(v),name:k=>EGC[k][0],col:k=>EGC[k][1]}, // the Traffic tab's table + money:{stack:[],lines:['rev','cost'],fmt:v=>fmt$(v),name:k=>k==='rev'?tr('common.revenue'):tr('common.costs'),col:k=>k==='rev'?'#16A866':'#FF4D5E'} +}; +const chartKeys=C=>[...C.stack,...C.lines]; +// The demand line's key is a dashed outline, in the line's own colour (dark ink by day, light text at night). +function chartLegend(id,label){const C=CHARTS[id],off=(UI.chartOff&&UI.chartOff[id])||{}; + return `
${chartKeys(C).map(k=>``).join('')}
`;} +Object.assign(ACT,{ + chartToggle:({c,k})=>{const C=CHARTS[c];if(!C||!chartKeys(C).includes(k))return; + const off=((UI.chartOff=UI.chartOff||{})[c]=UI.chartOff[c]||{});if(off[k])delete off[k];else off[k]=1; + if(chartKeys(C).every(x=>off[x]))UI.chartOff[c]={}; // nothing left to draw: show everything again + renderDash();}, +}); +// The tooltip and its cursor line sit on , outside the dashboard, so the per-tick redraw never removes them. +// Pointer moves are frequent: the tip is only rebuilt (and measured) when what it shows changes, not on every pixel. +let chartTip=null,chartCur=null,chartKey='',chartTw=0,chartTh=0; +function chartHide(){if(chartTip&&!chartTip.hidden){chartTip.hidden=chartCur.hidden=true;chartKey='';}} +function chartEnsure(){if(!chartTip){chartTip=document.createElement('div');chartTip.className='chtip';chartCur=document.createElement('div');chartCur.className='chcur';document.body.append(chartCur,chartTip);}} +// Fill the tip when its content key changes; measure it once, so moving inside the same content reads no layout. +function chartFill(key,html,showCur){if(key===chartKey&&!chartTip.hidden)return false;chartKey=key;chartTip.innerHTML=html;chartTip.hidden=false;chartCur.hidden=!showCur;chartTw=chartTip.offsetWidth;chartTh=chartTip.offsetHeight;return true;} +// Keep the tip inside the window, beside x and above y (below it when there is no room). +function chartPlace(x,cy){const tw=chartTw,th=chartTh; + chartTip.style.left=Math.max(4,Math.min(innerWidth-tw-4,x+12>innerWidth-tw-4?x-tw-12:x+12))+'px'; + chartTip.style.top=Math.max(4,Math.min(innerHeight-th-4,cy-th-8<4?cy+14:cy-th-8))+'px';} +function chartShow(svg,cx,cy){const id=svg.dataset.ch,C=CHARTS[id],H=S&&S.hist||[],n=Math.min(90,H.length),r=svg.getBoundingClientRect(),[bW,bH,bL,bT,bB,bR]=svg.dataset.box?svg.dataset.box.split(',').map(Number):[CHBOX.W,CHBOX.H,CHBOX.L,CHBOX.T,CHBOX.B,CHBOX.R]; + if(!C||n<2||!r.width)return chartHide(); + chartEnsure(); + const sx=r.width/bW,i=Math.max(0,Math.min(n-1,Math.round(((cx-r.left)/sx-bL)/(bW-bL-bR)*(n-1)))),row=H[H.length-n+i],off=(UI.chartOff&&UI.chartOff[id])||{}; + const x=r.left+(bL+(bW-bL-bR)*i/(n-1))*sx; + const key=id+'|'+row.d+'|'+Object.keys(off).join(); + if(chartFill(key,chartHtml(C,row,off),true)||chartCur.dataset.x!==String(x)){chartCur.dataset.x=x;chartCur.style.cssText=`left:${x}px;top:${r.top+bT*sx}px;height:${(bH-bT-bB)*sx}px`;} + chartPlace(x,cy);} +function chartHtml(C,row,off){const ks=chartKeys(C).filter(k=>!off[k]),st=C.stack.filter(k=>!off[k]); + return `${dateStr(row.d)}`+ks.map(k=>`
${C.name(k)}${C.fmt(row[k]||0)}
`).join('')+(st.length>1?`
${tr('dashboard.chart_total')}${C.fmt(st.reduce((a,k)=>a+(row[k]||0),0))}
`:'');} +// The "how it arrives" bars of the Traffic tab: the same tip, with each way in and its share. +function mixShow(el,cx,cy){const raw=el.dataset.mix;chartEnsure(); + if(chartKey!=='mix|'+raw||chartTip.hidden){let m;try{m=JSON.parse(raw);}catch(e){return chartHide();} + const ks=['c','p','ix','t'].filter(k=>m[k]>0),tot=ks.reduce((a,k)=>a+m[k],0); + chartFill('mix|'+raw,ks.length?ks.map(k=>`
${EGC[k][0]}${fmtG(m[k])} · ${pct(m[k]/tot)}
`).join(''):tr('common.nothing_yet'),false);} + chartPlace(cx,cy);} +for(const t of ['pointermove','pointerdown'])document.addEventListener(t,e=>{const c=e.target.closest&&e.target.closest('svg[data-ch],.mix[data-mix]');if(!c)chartHide();else if(c.dataset.mix!==undefined)mixShow(c,e.clientX,e.clientY);else chartShow(c,e.clientX,e.clientY);}); diff --git a/src/game/94-dashboard/70-bank.js b/src/game/94-dashboard/70-bank.js new file mode 100644 index 0000000..53f2724 --- /dev/null +++ b/src/game/94-dashboard/70-bank.js @@ -0,0 +1,34 @@ +function loanSummary(o){return o.model==='transit'?tr('bank.you_pay_pct_of_your_transit',{pct:pct(o.cut||0.3),price:fmt$(o.owe||o.amount)}):o.model==='balloon'?tr('bank.nothing_to_pay_for_n_months',{n:o.term}):tr('bank.pay_mo_for_n_months',{pay:fmt$(o.pay),n:o.term})+(o.share?' '+tr('bank.plus_pct_of_your_revenue_until',{pct:pct(o.share)}):'');} +function loanLine(l){const sh=l.share?' · '+tr('bank.plus_pct_of_revenue',{pct:pct(l.share)}):'',fee=loanFees(l)?' · '+tr('bank.price_mo_in_extras',{price:fmt$(loanFees(l))}):''; + if(l.model==='transit')return tr('bank.pct_of_your_transit_bill_n',{pct:pct(l.cut||0.3),n:l.left})+sh+fee; + if(l.model==='balloon')return tr('bank.nothing_to_pay_until_the_end',{n:l.left,apr:(l.apr*100).toFixed(1)})+sh+fee; + return tr('bank.pay_mo_n_months_left_apr',{pay:fmt$(l.pay),n:l.left,apr:(l.apr*100).toFixed(1)})+(l.model==='storm'?' · '+tr('bank.2_per_open_incident'):l.model==='astro'?' · '+tr('bank.rate_set_by_the_stars_each'):'')+sh+fee;} +function renderBank(){ + if(!S||$('bankBox').hidden)return;const rt=rating(),net=R.revMo-R.costMo; + const terms=(o)=>{const B=BANKS[o.bank],sh=o.share&&!B.equity?`${tr('bank.plus_pct_of_revenue_until_repaid',{pct:pct(o.share)})}`:''; + if(o.model==='transit')return `${tr('bank.pct_of_your_transit_bill',{pct:pct(o.cut||0.3)})}${tr('bank.price_to_repay',{price:fmt$(o.owe||o.amount)})}${tr('bank.n_months',{n:o.term})}${tr('bank.the_rest_is_due_at_the')}${sh}`; + if(o.model==='balloon')return `${tr('bank.nothing_to_pay_until_the_end_2a38')}${tr('bank.apr_apr',{apr:(o.apr*100).toFixed(1)})}${tr('bank.n_months',{n:o.term})}${tr('bank.then_about_price_at_once',{price:fmt$(o.amount*Math.pow(1+o.apr/12,o.term))})}${sh}`; + const extra=o.model==='storm'?`${tr('bank.2_per_open_incident')}`:o.model==='astro'?`${tr('bank.rate_set_by_the_stars_each')}`:''; + return (B.equity?`${tr('common.no_repayments')}${tr('bank.pct_of_revenue_forever',{pct:pct(o.share)})}${tr('bank.buy_out_price',{price:fmt$(o.amount*3)})}`:`${tr('bank.apr_apr',{apr:(o.apr*100).toFixed(1)})}${tr('bank.n_months',{n:o.term})}${tr('common.price_mo',{price:fmt$(o.pay)})}${B.crypto?''+tr('bank.paid_in_tubecoin')+'':''}`)+extra+sh;}; + const covList=(l)=>l.covs.length?l.covs.map(c=>{const ok=COVS[c].ok(l);return `
${ok?'✓':'✗'} ${esc(covLabel(c,l))}
`;}).join(''):'
'+tr('bank.no_conditions_that_is_the_scary')+'
'; + let h=`
AS${S.asn} · ${esc(S.name)}

${tr('common.bank')}

+
${tr('common.cash')}
${fmt$(S.cash)}
${S.cash<0?tr('bank.bankrupt_at_100k'):tr('bank.in_the_vault')}
+
${tr('dashboard.monthly_p_l')}
${net>=0?'+':''}${fmt$(net)}
${tr('bank.after_loan_payments')}
+
${tr('common.credit_rating')}
${rt}
${rIdx(rt)>=5?tr('bank.bankers_return_your_calls'):rIdx(rt)>=3?tr('bank.bankers_return_your_emails'):tr('bank.bankers_pretend_to_be_out')}
+
${tr('common.debt')}
${fmt$(loanDebt())}
${trn('bank.n_loan',S.loans.length)}
`; + const CT=CALL_TERMS[rt]; + if(S.cash${tr('bank.call_the_bank')}`; + h+=CT?`
${tr('bank.bank_picks_up_apr_apr_over',{bank:esc(BANKS[CT.bank].name),apr:(CT.apr*100).toFixed(1),n:CALL_MONTHS,limit:fmt$(lim)})}
${CALL_AMTS.map(a=>btn(fmt$(a),'callBank',{amount:a},'sm',a>lim)).join('')}
`:`

${tr('bank.get_to_an_aa_rating_and')}

`;} + h+=`

${tr('common.offers')}

`; + if(!S.loanOffers.length)h+=`

${tr('bank.no_offers_right_now_banks_get')}

`; + for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`
${tr('bank.bank_offers_amount',{bank:esc(B.name),amount:fmt$(o.amount)})}
${esc(B.blurb)} · ${tr('bank.offer_ends_in_n_d',{n:o.exp-S.day})}
${terms(o)}
${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(seaLink).length}})}
${btn(tr('bank.take_the_money'),'takeLoan',{id:o.id},'pink')}${btn(tr('common.no_thanks'),'declineLoan',{id:o.id},'ghost sm')}
`;} + h+=`

${tr('common.your_loans')}

`; + if(!S.loans.length)h+=`

${tr('bank.debt_free_your_accountant_is')}

`; + for(const l of S.loans){const B=BANKS[l.bank];const cost=repayCost(l,B); + h+=`
${esc(B.name)} · ${fmt$(l.amount)}
+ ${B.equity?`
${tr('bank.taking_pct_of_your_revenue_every',{pct:pct(l.share)})}
`:`
${tr('common.still_owed')}${fmt$(l.bal)}
${loanLine(l)}
`} + ${covList(l)}${l.breach>=1?`
${trn('bank.condition_broken_for_n_day',l.breach)} ${l.breach<10?tr('bank.penalty_in_n_days',{n:10-l.breach}):tr('bank.penalties_are_running')}
`:''} +
${btn(UI.confirm===l.id?tr('bank.really_pay_price',{price:fmt$(cost)}):B.equity?tr('bank.buy_them_out_price',{price:fmt$(cost)}):tr('bank.repay_early_price_incl_2_fee',{price:fmt$(cost)}),'repayLoan',{id:l.id},UI.confirm===l.id?'red sm':'sm',S.cash
`;} + h+=lateBank()+pieGovBank()+ip4Bank(); + if(h!==UI._bh){UI._bh=h;$('bankCard').innerHTML=h;} +} diff --git a/src/game/94-dashboard/72-address-space.js b/src/game/94-dashboard/72-address-space.js new file mode 100644 index 0000000..1427870 --- /dev/null +++ b/src/game/94-dashboard/72-address-space.js @@ -0,0 +1,30 @@ +/* The bank's Address space section (#150, 33-address-space.js): what you hold and who uses it (homes in three groups once + some are IPv6-only), the CGNAT and NAT64 ratios, your blocks, and the transfer market. Phones: the boxes are full + width, the dropdowns stack and every button row wraps. */ +const ip4Pc=x=>(x*100).toFixed(1).replace(/\.0$/,'')+'%'; +function ip4Bank(){if(!S||!ip4On())return '';const I=S.ip4,B=ip4Bill(ip4Eye()),u=B.u,len=ip4LenOk(UI.ip4Len)?UI.ip4Len:IP4_MAX,px=ip4Px(),full=ip4Full(); + const kv=(l,v,bad)=>`
${l}${v}
`,mo=v=>tr('common.price_mo',{price:fmt$(v)}); + let h=`

🔢 ${tr('ip4.section')}

${tr('ip4.note')}

`; + h+=`
${kv(tr('ip4.yours'),ip4N(u.T))}${kv(tr('ip4.business'),ip4N(u.B))}`; + // Public, behind CGNAT, IPv6-only: the three groups once there is a third. + h+=u.H6>0?kv(tr('ip4.homes'),ip4N(u.H))+kv(tr('ip4.homes_public'),ip4N(u.H-u.H6-u.cg))+kv(tr('ip4.homes_behind_cgnat'),ip4N(u.cg))+kv(tr('ip4.homes_v6'),tr('ip4.homes_v6_pool',{n:ip4N(u.H6),pool:ip4N(u.p6)})) + :kv(tr('ip4.homes'),u.cg?tr('ip4.homes_cgnat',{n:ip4N(u.H),p:pct(u.cg/u.H)}):ip4N(u.H)); + h+=kv(tr('ip4.free'),ip4N(Math.max(0,u.free)),u.free<=0); + if(u.over>0){const k=ip4Pools(u);h+=`
${k===1?tr('ip4.squeezed_v6',{p:pct(u.over),r:u.r6}):k?tr('ip4.squeezed_both',{p:pct(u.over),r:u.r,r6:u.r6}):tr('ip4.squeezed',{p:pct(u.over),r:u.r})}
`;} + if(B.lin>0)h+=kv(tr('ip4.leases_in'),mo(B.lin));if(B.box>=1)h+=kv(tr('ip4.cgnat_boxes'),mo(B.box));if(B.box64>=1)h+=kv(tr('ip4.nat64_gateways'),mo(B.box64));if(B.refund>=1)h+=kv(tr('ip4.refunds'),mo(B.refund));if(B.lout>0)h+=kv(tr('ip4.leases_out'),'+'+mo(B.lout)); + h+=kv(tr('ip4.v6_share'),pct(1-B.v4)); + h+=` +

${tr('ip4.cgnat_note',{p:ip4Pc(IP4_ANNOY[I.nat])})}

+ +

${tr('ip4.nat64_note',{p:ip4Pc(IP4_ANNOY64[u.r6]*B.v4/IP4_V4)})}

`; + h+=`
${tr('ip4.blocks')}
`;const inUse=ip4InUse(u); + for(const b of I.b){const n=ip4Sz(b.len),spare=u.free>=n,held=ip4Held(b),sure=UI.confirm===b.id; + const what=b.k==='in'?tr('ip4.leased_in_mo',{price:fmt$(b.mo||0)}):b.out?tr('ip4.leased_out_mo',{price:fmt$(b.mo||0)}):b.k==='buy'?tr('ip4.bought_on',{date:dateStr(b.d)}):tr('ip4.from_rir'); + const btns=b.k==='in'?btn(tr('ip4.give_back'),'ip4Return',{id:b.id},'ghost sm',!spare):b.out?btn(tr('ip4.take_back'),'ip4Back',{id:b.id},'ghost sm') + :btn(tr('ip4.lease_out',{price:fmt$(ip4OutMo(b.len))}),'ip4Out',{id:b.id},'sm',!spare)+btn(sure?tr('ip4.really_sell',{price:fmt$(ip4Value(b.len))}):tr('ip4.sell',{price:fmt$(ip4Value(b.len))}),'ip4Sell',{id:b.id},sure?'red sm':'ghost sm',held||!spare); + // Greyed for want of room: say so (a disabled button never gets to show ip4Busy's toast). + h+=`
/${b.len} · ${trn('ip4.n_addresses',n,{n:ip4N(n)})}
${what}${held&&!b.out?' · '+tr('ip4.movable_from',{date:dateStr(b.d+IP4_HOLD)}):''}
${!spare&&!b.out?`
${inUse}
`:''}
${btns}
`;} + h+=`
${tr('ip4.market')}

${tr('ip4.market_note',{px:fmt$(px),lin:'$'+(IP4_IN*px/IP4_PX).toFixed(2),lout:'$'+(IP4_OUT*px/IP4_PX).toFixed(2),p:pct(IP4_SELL)})}

+ + ${full?`
${tr('ip4.too_many',{n:IP4_BLK})}
`:''}
${btn(tr('ip4.buy',{price:fmt$(ip4Cost(len))}),'ip4Buy',{len},'pink sm',full||S.cash
`; + return h;} diff --git a/src/game/94-dashboard/80-hint.js b/src/game/94-dashboard/80-hint.js new file mode 100644 index 0000000..387fb46 --- /dev/null +++ b/src/game/94-dashboard/80-hint.js @@ -0,0 +1,10 @@ +function renderHint(){ + const hn=$('hint');if(!S||UI.hintOff||(S.tut!==undefined&&S.tut!==null)||(innerWidth<760&&(UI.sel||UI.leftOpen)&&!(UI.drag&&UI.drag.mode==='link'))){hn.hidden=true;return;} + let t=''; + if(pzOn()){t=UI.drag&&UI.drag.mode==='link'?(UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city')):!Object.keys(S.pops).length?tr('puzzles.tap_a_goal_city_to_open'):!S.links.length?(S.ar?tr('architect.drag_from_your_hq'):tr('puzzles.drag_from_a_pink_pop_to')):'';hn.textContent=t;hn.hidden=!t;return;} + if(UI.drag&&UI.drag.mode==='link')t=UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city'); + else if(!S.links.length&&S.done.tr)t=tr('hint.tip_drag_from_your_pink_router'); + else if(!S.done.bb)t=tr('hint.tap_your_city_then_launch_broadband'); + hn.textContent=t;hn.hidden=!t; +} + diff --git a/src/game/94-dashboard/90-noc-window.js b/src/game/94-dashboard/90-noc-window.js new file mode 100644 index 0000000..b985891 --- /dev/null +++ b/src/game/94-dashboard/90-noc-window.js @@ -0,0 +1,78 @@ +/* ---------- The NOC window ---------- + The dashboard in a window of its own, for a second display: this page again, at ?noc=. It never claims the slot, + saves or runs a day: the game window stays the only writer, sends it a copy of S and R, and runs its clicks. + The control channel is small messages, always open so a reloaded game finds its window again; the copies go on a channel + per network, opened once a window says hello, so other games' tabs never unpack them. With no window nothing is sent. */ +const NOC_HB=3000,NOC_LOST=10000,NOC_GAP=1000; +// What a click in the window does: changes only its own view, or runs in the game. Every button the dashboard draws is in one list. +const NOC_LOCAL=['chartToggle','connCity','connF','connNet','connSort','custCity','custF','custSort','dashClose','dashSort','dashTab','listMore','popsReg','popsSort']; +const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','downIx','downP','downT','goConn','ip4Open','lagIx','lagNni','lagP','lagT','leaseSwap','mktCfg','mktHold','mktRoute','netFocus','opsOpen','pni','pniAllOpen','pniChase','popGo']; +const NOC={win:false,id:null,ctl:null,st:null,stId:null,peer:false,until:0,dirty:false,sent:0,speed:1,hid:false,yoAt:0,gone:false}; +{const id=RW_IN?null:new URLSearchParams(location.search).get('noc');if(slotOkId(id)){NOC.win=true;NOC.id=id;}} +if(!RW_IN)try{if(typeof BroadcastChannel==='function'){NOC.ctl=new BroadcastChannel('sot-noc');NOC.ctl.onmessage=e=>{const m=e.data;if(!m||typeof m!=='object'||!slotOkId(m.id))return;if(NOC.win)nocWinMsg(m);else nocGameMsg(m);};}}catch(e){} +const nocPost=m=>{try{if(NOC.ctl)NOC.ctl.postMessage(m);}catch(e){console.error('[tubes] NOC window',e);}}; +const nocHid=()=>document.visibilityState==='hidden'; +// ---------- in the game window ---------- +// R as plain data: the routing tables are left out (the dashboard does not read them), an attack names its attack in S by id. +const NOC_SKIP={ef:1,fl:1,efp:1,flc:1,efg:1}; +function nocR(){const o={};for(const k in R)if(!NOC_SKIP[k])o[k]=k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k];return o;} +// Half a day (its routing still in the worker) is never sent, like it is never saved: it stays due. +function nocSend(now){if(!NOC.peer||!S||S.lost||pzOn()||RW.job||!UI.slot)return; + try{if(NOC.stId!==UI.slot){if(NOC.st)NOC.st.close();NOC.stId=UI.slot;NOC.st=new BroadcastChannel('sot-noc:'+UI.slot);} + NOC.st.postMessage({S,R:nocR(),speed:UI.speed,hid:nocHid()});NOC.dirty=false;NOC.sent=now;} + catch(e){console.error('[tubes] NOC window',e);NOC.peer=false;}} +// Every frame while a window is connected: at most one copy a second, whatever the game's speed. +function nocPump(now){if(now>NOC.until){NOC.peer=false;return;}if(NOC.dirty&&now-NOC.sent>=NOC_GAP)nocSend(now);} +function nocGameMsg(m){if(m.id!==UI.slot)return;const now=performance.now(); + if(m.t==='hello'||m.t==='hi'){const was=NOC.peer;NOC.peer=true;NOC.until=now+NOC_LOST;nocPost({t:'yo',id:m.id,speed:UI.speed,hid:nocHid()}); + if(m.t==='hello'||!was){NOC.dirty=true;nocSend(now);}} + else if(m.t==='bye')NOC.peer=false; + else if(m.t==='act')nocRun(m,now);} +// A click from the window: the same rules as a click here. A window open in the game comes first, like any click outside it. +function nocRun(m,now){const ts=[],t=toast; + if(!NOC_GO.includes(m.act)||typeof ACT[m.act]!=='function'||!S||S.lost||pzOn())return; + if(!$('modal').hidden){nocPost({t:'res',id:m.id,ts:[[tr('noc.the_game_has_a_dialog_open'),'bad']]});return;} + const a=m.args&&typeof m.args==='object'?m.args:{}; + toast=(h,k,x,o)=>{ts.push([h,k]);return t(h,k,x,o);}; + try{if(m.act==='connCancel')UI.confirm='cc:'+a.k+':'+a.id;ACT[m.act](a);}catch(e){console.error('[tubes] NOC window action',m.act,e);}finally{toast=t;} + NOC.dirty=true;nocSend(now);nocPost({t:'res',id:m.id,ts});} +// ---------- in the NOC window ---------- +function nocWinMsg(m){if(m.id!==NOC.id)return; + if(m.t==='yo'){NOC.yoAt=performance.now();NOC.gone=false;NOC.speed=m.speed;NOC.hid=!!m.hid;nocBar();} + else if(m.t==='bye'){NOC.gone=true;nocBar();} + else if(m.t==='focus'){try{window.focus();}catch(e){}} + else if(m.t==='res')for(const [h,k] of m.ts||[])toast(h,k);} +function nocWinState(d){if(!d||!d.S||!d.R)return;S=d.S;R=Object.assign(emptyR(),d.R);const as=ddosAll(S,false);for(const m of R.ddos||[]){m.attack=as.find(a=>a.id===m.attack)||null;m.ports=new Map();} + UI.started=true;NOC.speed=d.speed;NOC.hid=!!d.hid;NOC.gone=false;NOC.yoAt=performance.now();document.title=tr('common.noc_dashboard')+' · '+S.name;nocRender();} +// Not under a finger: a button that moves during a press never gets its click. +function nocRender(){if(pressing){setTimeout(nocRender,150);return;}document.body.classList.toggle('noc-still',!NOC.speed||NOC.gone||!animOn());try{if(S){if(NOCW.view==='wall')nocWall();else renderDash();}}catch(e){console.error('[tubes] NOC window render',e);}nocBar();} +function nocBar(){const b=$('nocBar');if(!b)return; + const why=NOC.gone?tr('noc.the_game_window_is_closed'):!S?tr('noc.waiting_for_the_game_window'):NOC.hid?tr('noc.the_game_window_is_hidden'):!NOC.speed?tr('noc.the_game_is_paused'):''; + const {bad,warn}=NOCW.sum,tab=(v,l)=>``; + const h=`
${S?`AS${S.asn} · ${esc(S.name)} · ${esc(tierLabel())}`:''}
${esc(tr('common.noc_dashboard'))}
` + +(S?`${esc(bad?trn('noc.n_alarms',bad):warn?trn('noc.n_warnings',warn):tr('common.all_quiet'))}${esc(dateStr(S.day))}${esc(fmt$(S.cash))}${NOC.speed?NOC.speed+'×':'❚❚'}`:'') + +`
${tab('wall',tr('noc.wallboard'))}${tab('details',tr('noc.details'))}${document.documentElement.requestFullscreen?``:''}
` + +(why?`
${esc(why)}
`:''); + if(b._h!==h){b._h=h;morph(b,h);}} +function nocBeat(now=performance.now()){nocPost({t:'hi',id:NOC.id});if(now-NOC.yoAt>NOC_LOST&&!NOC.gone){NOC.gone=true;nocBar();}} +function nocFwd(act,a){if(NOC_GO.includes(act))nocPost({t:'act',id:NOC.id,act,args:a||{}});} +function nocWinBoot(){i18nDom();document.body.classList.add('noc-window');UI.dtab='conn';try{UI.anim=localStorage.getItem('sot-anim')||'auto';}catch(e){}$('dash').hidden=true;$('dash').insertAdjacentHTML('beforebegin','
'); + const bd=$('nocBoard');bd.addEventListener('click',nocUiClick);bd.addEventListener('change',e=>{if(e.target.hasAttribute&&e.target.hasAttribute('data-nc-city')){NOCW.city=e.target.value;nocRender();}});bd.addEventListener('pointerdown',e=>{if(e.target.closest('#nocWall'))pressing=true;}); + // The game's keyboard shortcuts are for the map, which is not here. Tab and the browser's own keys still work. + addEventListener('keydown',e=>e.stopImmediatePropagation(),true); + for(const k of Object.keys(ACT))if(!NOC_LOCAL.includes(k))ACT[k]=a=>nocFwd(k,a); + ACT.dashClose=()=>{try{window.close();}catch(e){}}; + ACT.connCancel=a=>{const key='cc:'+a.k+':'+a.id;if(UI.confirm!==key){UI.confirm=key;renderDash();return;}UI.confirm=null;nocFwd('connCancel',a);}; + try{NOC.st=new BroadcastChannel('sot-noc:'+NOC.id);NOC.st.onmessage=e=>nocWinState(e.data);}catch(e){} + addEventListener('pagehide',()=>nocPost({t:'bye',id:NOC.id})); + // A hidden window's timers slow right down, so the game stops sending; coming back asks for the latest. + document.addEventListener('visibilitychange',()=>{if(!nocHid()){NOC.yoAt=performance.now();nocPost({t:'hello',id:NOC.id});}}); + NOC.yoAt=performance.now();nocBar();nocPost({t:'hello',id:NOC.id});if(!window.__TUBES_TEST__)setInterval(nocBeat,NOC_HB);} +addEventListener('pagehide',()=>{if(!NOC.win&&NOC.peer&&UI.slot)nocPost({t:'bye',id:UI.slot});}); +Object.assign(ACT,{ + // A second click finds the window that is already there. A blocked pop-up can only be told by its silence (noopener gives no + // handle): wait as long as a window may go quiet, since a slow machine loading the whole page can take seconds to say hello. + nocWindow:()=>{if(!S||pzOn()||!UI.slot)return;const id=UI.slot;if(NOC.peer){nocPost({t:'focus',id});return;} + window.open(location.pathname+'?noc='+id,'_blank','noopener,popup,width=1320,height=860'); + if(!window.__TUBES_TEST__)setTimeout(()=>{if(!NOC.peer&&UI.slot===id)toast(tr('noc.your_browser_blocked_the_window'),'bad');},NOC_LOST);}, +}); diff --git a/src/game/94-dashboard/91-noc-wall.js b/src/game/94-dashboard/91-noc-wall.js new file mode 100644 index 0000000..5025513 --- /dev/null +++ b/src/game/94-dashboard/91-noc-wall.js @@ -0,0 +1,93 @@ +/* ---------- The NOC window's wallboard ---------- + The first thing the window shows: a dark board to glance at from across the room. Everything is drawn from the copy of S + and R (90-noc-window.js) with the game's own helpers, and the upgrade buttons are the dashboard's (connUp), so prices + and rules cannot drift. Each section is patched with morph(): a flow on the map keeps running and a button stays put. + Only the window runs any of this. */ +const NOCW={view:'wall',city:'',built:false,sum:{bad:0,warn:0}}; +const NW_HOT=0.9,NW_WARM=0.65,NW_FLOWS=40,NW_PORTS=8; +const NW_COL={ok:'#2DD4A7',warn:'#FFB547',bad:'#FF5C6C',idle:'#5A6B94'}; +const nwCol=u=>u>=NW_HOT?NW_COL.bad:u>=NW_WARM?NW_COL.warn:NW_COL.ok; +const nwG=v=>v>=1000?(+(v/1000).toFixed(1))+'T':(v>=10||v===0?Math.round(v):+v.toFixed(1))+'G'; +// ---------- the land: built once, it never changes ---------- +const nwMapBox=()=>{let y0=Infinity,y1=-Infinity;for(const p of COAST){const b=polyBox(p);if(ringArea(p)>=600){y0=Math.min(y0,b[1]);y1=Math.max(y1,b[3]);}}return [0,Math.floor(y0),W,Math.ceil(y1-y0)];}; +function nwLand(){let d='';for(const p of COAST){if(ringArea(p)<600&&!CITIES.some(c=>inPoly(c.x,c.y,p)))continue;d+='M'+p.map(q=>Math.round(q[0])+' '+Math.round(q[1])).join('L')+'Z';}return d;} +// ---------- charts ---------- +function nwChart(rows,stack,lines,fmtY,CW=900,CH=260,L=62,id=''){if(rows.length<2)return `

${tr('link_panels.collecting_data_check_back_in_a')}

`; + const B=22,T=8,Rr=8;let ymax=1;for(const r of rows){let s=0;for(const k of stack)s+=r[k]||0;ymax=Math.max(ymax,s);for(const ln of lines)ymax=Math.max(ymax,r[ln.k]||0);}ymax*=1.1; + const x=i=>+(L+(CW-L-Rr)*i/(rows.length-1)).toFixed(1),y=v=>+(T+(CH-T-B)*(1-v/ymax)).toFixed(1);let g=''; + for(let j=0;j<=4;j++){const v=ymax*j/4,yy=y(v);g+=`${esc(fmtY(v))}`;} + const base=rows.map(()=>0); + for(const k of stack){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`,e=d;for(let i=1;i=0;i--)d+=`L${x(i)},${y(base[i])}`; + g+=``;top.forEach((v,i)=>base[i]=v);} + for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=``;} + g+=`${esc(dateStr(rows[0].d))}${esc(dateStr(rows[rows.length-1].d))}`; + return `${g}`;} +function nwSpark(vals,col){if(vals.length<2)return '';let a=Infinity,b=-Infinity;for(const v of vals){if(vb)b=v;}const sp=b-a||1; + const pts=vals.map((v,i)=>(100*i/(vals.length-1)).toFixed(1)+','+(26-22*(v-a)/sp).toFixed(1)).join(' '); + return ``;} +// ---------- what is wrong ---------- +function nwAlarms(){const A=[]; + for(const a of ddosAll()){const t=tr('noc.under_attack',{who:ddosWho(a),g:fmtG(a.gbps)});A.push({k:'bad',t:esc(t.charAt(0).toUpperCase()+t.slice(1)),m:''});} + for(const i of S.inc)if(i.type!=='ddos'&&i.until>S.day)A.push({k:'bad',t:incTitle(i.type),m:esc(i.msg||''),s:shipSea(i)?'🚢 '+esc(shipStatus(i)):esc(trn('hud_and_panels.auto_fix_in_n_day',i.until-S.day))}); + const hot=hotPorts().filter(h=>h.k==='t'||h.k==='p'||h.k==='ix').length,sad=custStats().unhappy; + if(hot)A.push({k:'warn',t:esc(trn('noc.n_ports_over_90_full',hot)),m:''}); + if(sad)A.push({k:'warn',t:esc(trn('noc.n_unhappy_customers',sad)),m:''}); + return A;} +// ---------- sections ---------- +function nwTiles(){const H=(S.hist||[]).slice(-60),last30=(S.hist||[]).slice(-30),net=R.revMo-R.costMo; + const up=last30.length?last30.reduce((a,r)=>a+(r.dem?Math.min(1,r.srv/r.dem):1),0)/last30.length:1; + const tile=(l,v,sub,sp,cls='')=>`
${l}
${v}
${sub||' '}
${sp||''}
`; + return tile(tr('common.traffic_now'),esc(fmtG(R.served)),esc(tr('dashboard.of_g_wanted',{g:fmtG(R.demand)})),nwSpark(H.map(r=>r.srv),NW_COL.ok)) + +tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%','',nwSpark(H.map(r=>r.dem?Math.min(1,r.srv/r.dem):1),NW_COL.ok),up<0.99?'warn':'') + +tile(tr('common.peering_ratio'),pct(R.peerShare||0),'',nwSpark(H.map(r=>r.srv?(r.c+r.p+r.ix)/r.srv:0),'#7B8CFF')) + +tile(tr('noc.net_per_month'),esc(fmt$(net)),'',nwSpark(H.map(r=>r.rev-r.cost),net<0?NW_COL.bad:NW_COL.ok),net<0?'bad':'') + +tile(tr('common.peak'),esc(fmtG(S.stats.peak)),esc(tr('common.reach'))+' '+reachPct(R.reach||0)) + +tile(tr('common.bgp_sessions'),String(R.sessions||0),esc(tr('noc.n_pops_n_links',{pops:Object.keys(S.pops).length,links:S.links.length})));} +// Parallel links between two cities are one line on so small a map: their load over their capacity, down only when all are. +function nwMap(){const by=new Map(); + for(const l of S.links){const k=edgeKey(l);let e=by.get(k);if(!e)by.set(k,e={k,a:l.a,b:l.b,load:0,cap:0,up:0});if(!linkDown(l)&&!l.standby){e.up++;e.load+=(R.load&&R.load[l.id])||0;e.cap+=capOf(l)||0;}} + const E=[...by.values()],fl=new Set(E.filter(e=>e.load>0&&e.up).sort((a,b)=>b.load-a.load).slice(0,NW_FLOWS).map(e=>e.k));let g=''; + for(const e of E){const A=CITY[e.a],B=CITY[e.b],dx=wrapDx(A.x,B.x),bx=A.x+dx,u=e.cap>0?e.load/e.cap:0,len=Math.hypot(dx,B.y-A.y); + const arc=o=>`M${Math.round(A.x+o)} ${Math.round(A.y)}Q${Math.round(A.x+o+dx/2)} ${Math.round((A.y+B.y)/2-len*0.09)} ${Math.round(bx+o)} ${Math.round(B.y)}`; + const d=arc(0)+(bx<0?arc(W):bx>W?arc(-W):''),col=e.up?nwCol(u):NW_COL.bad,wd=e.up?(1.5+Math.min(4,Math.log10(1+e.cap)*0.9)).toFixed(1):'2.5'; + g+=``; + if(fl.has(e.k))g+=``;} + const inc=new Set();for(const i of S.inc)if(i.until>S.day&&isCity(i.ref))inc.add(i.ref);for(const a of ddosAll())inc.add(a.city); + let dots='',labs=''; + for(const c of Object.keys(S.pops)){const C=CITY[c],up=popUp(c),u=(R.nodeLoad[c]||0)/(R.nodeCap[c]||1),on=NOCW.city===c,alarm=!up||inc.has(c),col=!up?NW_COL.bad:nwCol(u); + dots+=`${esc(CITY[c].name)} · ${pct(u)}${alarm?``:''}${on?``:''}`; + if(on||alarm||u>=NW_HOT)labs+=`${esc(CITY[c].name)}`;} + const v=NOCW.box.join(' ');return `${g}${dots}${labs}`;} +// An exchange port's row only knows about the exchange: its POP going dark takes it down as well. A remote port has no POP here. +const nwDown=r=>r.down||(!!S.pops[r.city]&&!popUp(r.city)); +function nwPorts(){const all=conns().filter(r=>r.k==='t'||r.k==='p'||r.k==='ix'),city=NOCW.city&&all.some(r=>r.city===NOCW.city)||S.pops[NOCW.city]?NOCW.city:'';NOCW.city=city; + const cities=[...new Set(all.map(r=>r.city))].sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); + const sel=``; + const rows=all.filter(r=>city?r.city===city:!nwDown(r)).map(r=>({r,u:r.cap>0?r.use/r.cap:0})).sort((a,b)=>(nwDown(b.r)?1:0)-(nwDown(a.r)?1:0)||b.u-a.u).slice(0,city?60:NW_PORTS); + const row=({r,u})=>`
${esc(tr(CONN_K[r.k]))}
${esc(CITY[r.city].name)} ${esc(r.name)}
${esc(fmtG(r.use))} / ${esc(r.port)}
${nwDown(r)?esc(tr('noc.legend_down')):pct(u)}
${connUp(r)}${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}
`; + return `

${esc(tr('noc.hottest_ports'))}

${sel}
${rows.length?rows.map(row).join(''):`

${esc(tr('noc.no_ports_here'))}

`}`;} +function nwAlarmsHtml(A){return `

${esc(tr('noc.alarms'))}

`+(A.length?A.map(a=>`
${a.t}${a.m?`
${a.m}
`:''}${a.s?`
${a.s}
`:''}
`).join(''):`

${esc(tr('noc.nothing_on_fire'))}

`);} +const nwBars=(title,rows)=>`

${esc(title)}

`+rows.map(([n,m,u])=>`
${esc(n)} ${esc(m)}
${pct(u)}
`).join(''); +function nwBuild(){const w=$('nocWall');NOCW.box=nwMapBox(); + w.innerHTML=`
+

${esc(tr('noc.your_network'))}

${esc(tr('noc.legend_ok'))}${esc(tr('noc.legend_warm'))}${esc(tr('noc.legend_hot'))}
+
+
+
+
+
`;NOCW.built=true;} +function nocWall(){if(!NOCW.built)nwBuild();const rows=(S.hist||[]).slice(-90),A=nwAlarms(); + NOCW.sum={bad:A.filter(a=>a.k==='bad').length,warn:A.filter(a=>a.k==='warn').length}; + const put=(id,h)=>{const e=$(id);if(e._h!==h){e._h=h;morph(e,h);}}; + put('nwTiles',nwTiles());put('nwOver',nwMap());put('nwAlarms',nwAlarmsHtml(A)); + put('nwTraffic',`

${esc(tr('dashboard.traffic_by_way_out'))}

${Object.keys(EGC).filter(k=>(R.egT[k]||0)>0.01||rows.some(r=>(r[k]||0)>0)).map(k=>`${esc(EGC[k][0])} ${esc(fmtG(R.egT[k]||0))}`).join('')}${esc(tr('common.demand'))}
${nwChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#E8EEFA',dash:true}],nwG,900,260,62,'traffic')}`); + put('nwPorts',nwPorts()); + put('nwRouters',nwBars(tr('common.router_load'),Object.keys(S.pops).map(c=>[CITY[c].name,`${S.pops[c].routers||1} × ${RG[S.pops[c].rgen||0].n}`,(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)]).sort((a,b)=>b[2]-a[2]).slice(0,6))); + put('nwLinks',nwBars(tr('common.busiest_links'),S.links.filter(l=>capOf(l)>0).map(l=>[`${CITY[l.a].name} ⇄ ${CITY[l.b].name}`,capName(l),(R.load[l.id]||0)/capOf(l)]).sort((a,b)=>b[2]-a[2]).slice(0,6))); + put('nwMoney',`

${esc(tr('dashboard.money_per_month'))}

${esc(tr('common.revenue'))}${esc(tr('common.costs'))}
${nwChart(rows,[],[{k:'rev',col:NW_COL.ok},{k:'cost',col:NW_COL.bad}],fmt$,520,220,74,'money')}`);} +// The window's own controls never reach the game: they change what this screen shows. +function nocUiClick(e){const b=e.target.closest&&e.target.closest('[data-nc]');if(!b)return;const v=b.getAttribute('data-nc'); + if(v==='wall'||v==='details')nocView(v); + else if(v==='fs'){try{if(document.fullscreenElement)document.exitFullscreen();else document.documentElement.requestFullscreen();}catch(err){}} + else if(v.startsWith('pop:')){const c=v.slice(4);NOCW.city=NOCW.city===c?'':c;nocRender();}} +function nocView(v){NOCW.view=v;$('dash').hidden=v==='wall';$('nocWall').hidden=v!=='wall';UI._dh=null;nocRender();try{scrollTo(0,0);}catch(e){}} diff --git a/src/game/95-modals/10-toasts.js b/src/game/95-modals/10-toasts.js new file mode 100644 index 0000000..770309a --- /dev/null +++ b/src/game/95-modals/10-toasts.js @@ -0,0 +1,13 @@ +/* ---------- toasts & modals ---------- */ +function toast(html,kind='',actions=[],open=null){ + if(S)logNote(html,kind,actions,open); + toastPop(html,kind,actions,UI.tick);} +// The toast on screen only (the log line is toast()'s). tick: the day announced it (UI.tick when it was said). +function toastPop(html,kind='',actions=[],tick=false){ + // Quiet notifications: what the day announces pops up only for trouble and milestones; the rest stays in the NOC log. + if(tick&&kind!=='bad'&&kind!=='goal'&&quietOn())return; + const el=document.createElement('div');el.className='toast '+kind;el.dataset.born=performance.now(); + el.innerHTML=`
${html}
${actions.map(a=>btn(a.l,a.act,a.args,'sm')).join('')}`; + const box=$('toasts');box.prepend(el);const max=innerWidth<760?2:3;while(box.children.length>max)box.lastChild.remove(); + setTimeout(()=>{el.style.transition='opacity .4s';el.style.opacity=0;setTimeout(()=>el.remove(),400);},actions.length?8000:4500); +} diff --git a/src/game/95-modals/20-notifications.js b/src/game/95-modals/20-notifications.js new file mode 100644 index 0000000..1a2be8a --- /dev/null +++ b/src/game/95-modals/20-notifications.js @@ -0,0 +1,33 @@ +/* ---------- notifications: the NOC keeps the last ten minutes, readable and openable ---------- */ +const LOG_KEEP=60,LOG_MS=10*60*1000,LOG_KINDS=['','good','bad','goal'],LOG_OPEN=['city','link','cust','bank','ip4','tab','ops'],LOG_TABS=['goals','deals','noc','nets']; +// What a notification is about, from the button it came with: the same place its own button would take you. +function openOf(actions){for(const a of actions||[]){const g=a.args||{}; + if(a.act==='focusCity'&&isCity(g.city))return {a:'city',v:g.city};if(a.act==='selLink'&&g.id)return {a:'link',v:String(g.id)}; + if(a.act==='custGo'&&g.id)return {a:'cust',v:String(g.id)};if(a.act==='bank')return {a:'bank'};if(a.act==='ip4Open')return {a:'ip4'};if(a.act==='leftTab'&&LOG_TABS.includes(g.t))return {a:'tab',v:g.t};}return null;} +// Otherwise from the text: a link between two of your cities it names, or the first of your cities it names. +function openFromText(t){const cs=Object.keys(S.pops).map(c=>[c,t.indexOf(CITY[c].name)]).filter(([,i])=>i>=0).sort((a,b)=>a[1]-b[1]).map(([c])=>c); + if(cs.length>=2){const l=S.links.find(l=>(l.a===cs[0]&&l.b===cs[1])||(l.a===cs[1]&&l.b===cs[0]));if(l)return {a:'link',v:l.id};}return cs.length?{a:'city',v:cs[0]}:null;} +// An incident points at a link, a trench, a city, or a port in a city. +function incOpen(i){const r=i&&i.ref;if(typeof r!=='string')return null;const l=S.links.find(l=>l.id===r||l.trench===r);if(l)return {a:'link',v:l.id}; + if(isCity(r))return {a:'city',v:r};const x=S.transit.find(t=>t.id===r)||S.pni.find(t=>t.id===r);if(x)return {a:'city',v:x.city};if(isIx(r)&&isCity(ixCity(r)))return {a:'city',v:ixCity(r)};return null;} +// A kind the log does not keep (the capacity market's 'info' and 'warn') is a plain line, as a reload makes it (sanitize()). +function logNote(html,kind,actions,open){S.log=S.log||[];if(!LOG_KINDS.includes(kind))kind='';const tmp=document.createElement('div');tmp.innerHTML=html.replace(/
/g,' ');const t=tmp.textContent.trim(); + const b=tmp.firstElementChild&&tmp.firstElementChild.tagName==='B'&&html.startsWith('')?tmp.firstElementChild.textContent.trim():''; + const o=open||openOf(actions)||openFromText(t),now=Date.now(),key=(b||t).replace(/[\d.,]+/g,'#'),last=S.log[0]; + // The same notice again within a minute folds into the last one, with a count: twenty "new sessions" read as one line. + if(last&&last.at&&now-last.at<60000&&last.k===kind&&(last.h||last.t).replace(/[\d.,]+/g,'#')===key&&JSON.stringify(last.o||null)===JSON.stringify(o)){last.n=(last.n||1)+1;last.t=t;last.h=b;last.at=now;last.d=S.day;return;} + S.log.unshift({id:uid(),d:S.day,t,h:b,k:kind,at:now,o,n:1});if(S.log.length>LOG_KEEP)S.log.length=LOG_KEEP;} +const logRecent=()=>{const now=Date.now();return (S.log||[]).filter(e=>e.at&&now-e.atlogRecent().filter(e=>e.at>(UI.logSeen||0)).length; +const agoStr=at=>{const m=Math.floor((Date.now()-at)/60000);return m<1?tr('common.just_now'):trn('notifications.n_min_ago',m);}; +// The list is the NOC tab: a notice that would open the NOC gets no Open button, since it would do nothing (#226). +function logSection(){const L=logRecent(),MAX=5,all=UI.logAll,sh=all?L:L.slice(0,MAX); + let h=`

${tr('common.notifications')} ${tr('notifications.last_10_minutes')}

`; + if(!L.length)return h+`

${tr('notifications.nothing_in_the_last_10_minutes')}

`; + h+=sh.map(e=>{const body=e.h&&e.t.startsWith(e.h)?e.t.slice(e.h.length).trim():e.t; + return `
${e.h?`
${esc(e.h)}${e.n>1?` ×${e.n}`:''}
`:''}${body?`
${esc(body)}${!e.h&&e.n>1?` ×${e.n}`:''}
`:''}
${agoStr(e.at)} · ${dateStr(e.d)}
${e.o&&!(e.o.a==='tab'&&e.o.v==='noc')?btn(tr('common.open'),'logOpen',{id:e.id},'ghost sm'):''}
`;}).join(''); + if(L.length>MAX)h+=`
${btn(all?tr('common.show_fewer'):tr('notifications.show_all_n',{n:L.length}),'logAll',{},'ghost sm')}
`; + return h;} +const markLayer=()=>{UI.layerAt=performance.now();}; +// Which layers are open: when that changes (a sheet, the dashboard, the bank, a selection), taps in flight are void. +function checkLayer(){const q=id=>{const e=$(id);return e?(e.hidden?0:1):0;},sig=[q('modal'),q('dash'),q('bankBox'),UI.leftOpen?1:0,UI.left||'',UI.sel?UI.sel.type+UI.sel.id:'',UI.tab||''].join('|');if(sig!==UI._layer){UI._layer=sig;markLayer();}} diff --git a/src/game/95-modals/30-modal-and-names.js b/src/game/95-modals/30-modal-and-names.js new file mode 100644 index 0000000..5c9f272 --- /dev/null +++ b/src/game/95-modals/30-modal-and-names.js @@ -0,0 +1,28 @@ +// Keyboard focus moves into the modal, so Enter or Space can't keep pressing a hidden button behind it. +// The link check on phones sits above the tab bar and is not modal, so the tabs stay usable. +function openModal(html,cls=''){HOOKS.modal?.(true);$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}} +function closeModal(){if(!$('modal').hidden)markLayer();pieGlobeClose();$('modal').hidden=true;UI.pending=null;HOOKS.modal?.(false);} +const NETWORK_NAMES=[ + 'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom', + 'Mostly Online','Buffering & Sons','Lord of the Pings','The Ping Dynasty', + 'LAN Before Time','Bits Please','Hopless Networks','Route of All Evil', + 'TTL You Later','Fiber McFiberface','RFC 1149 Avian Carriers','Spanning Tree Huggers', + 'Dial-Up & Cry','404 Telecom','Loss Leaders','Last Mile Standing', + 'Have You Tried Off & On','Bogon Voyage','Default Route 66','Anycast Away', + 'Hot Potato Routing','Null Route Rangers','Looking Glass Half Full','Jumbo Frame Shop', + 'Route Flap Jacks','Split Horizon & Co.','Path of Least Resistance', +]; +function randomNetworkName(current){ + // Naming must not advance a running scenario's seeded simulation. + const names=NETWORK_NAMES.filter(n=>n!==current); + return names[Math.floor(_rand()*names.length)]; +} +const HTIW='https://tkjaer.github.io/how-the-internet-works/'; +// The real thing: an interactive, zoomable guide to how packets actually travel. Go read it. +// Where players hang out: the community Signal group. +const SIGNAL='https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ'; +const chatHtml=()=>`${tr('modal_and_names.join_the_noc_chat')}${tr('modal_and_names.our_signal_group_screenshots_chat')}${tr('common.join')}`; +// Bugs and ideas go to GitHub, where they get tracked; the chat is for chatting. Its forms sort them by kind. +const ISSUES='https://github.com/fjaeckel/seriesoftubes/issues/new/choose'; +const issueHtml=()=>`${tr('modal_and_names.found_a_bug_or_have_an')}${tr('modal_and_names.tell_us_on_github_a_short')}${tr('modal_and_names.open')}`; +const plugHtml=(big)=>`${tr('modal_and_names.how_the_internet_works')}${big?tr('modal_and_names.the_real_thing_by_thomas_kj'):tr('modal_and_names.the_real_thing_follow_a_packet')}${tr('common.explore')}`; diff --git a/src/game/95-modals/35-pni-all.js b/src/game/95-modals/35-pni-all.js new file mode 100644 index 0000000..0e5f817 --- /dev/null +++ b/src/game/95-modals/35-pni-all.js @@ -0,0 +1,21 @@ +// msg: why the sheet is shown again (the quote changed). +function pniAllModal(net,tier=1,msg=''){const b=pniBatch(net,tier);if(!b)return;UI.pniAll={net,tier}; + const all=net===null,n=NET[net],port=tier===-1?'1G':PORT[tier].n,up=b.orders.filter(q=>q.ex).length,byNet={}; + if(all)for(const q of b.orders)(byNet[q.net]||(byNet[q.net]=[])).push(q.city); + const controls=`
${btn(all?tr('pni_all.all_at_port',{port}):tr('pni_all.peer_at_port',{port}),'pniAll',{net,tier,q:b.cost},'pink',!b.orders.length||S.cash`; + const blocked=b.blocked.map(q=>`

${all?esc(NET[q.net].name)+' · ':''}${esc(CITY[q.city].name)}: ${q.why}

`).join(''); + openModal(`
${all?tr('common.all_networks'):`AS${n.asn} · ${esc(n.name)}`}

${all?tr('pni_all.peer_all_networks'):tr('pni_all.peer_on_all_pops')}

+

${tr('pni_all.order_missing_and_upgrade_smaller')}

${msg?`

${esc(msg)}

`:''} +
+
${tr('pni_all.new_and_upgrades',{fresh:b.orders.length-up,up})}${all?tr('pni_all.n_of_total_connections',{n:b.orders.length,total:b.shared.length}):tr('pni_all.n_of_total_pops',{n:b.orders.length,total:b.shared.length})}
+
${tr('pni_all.setup_total')}${fmt$(b.cost)}
+
${tr('pni_all.additional_per_month')}${tr('common.price_mo',{price:fmt$(b.mo)})}
+ ${b.raised?`

${trn('pni_all.n_at_their_minimum_size',b.raised)}

`:''} + ${all?`

${tr('pni_all.delivery_and_traffic_charges')}

`:n.perG?`

${tr('pni_all.traffic_charges_apply',{price:fmt$(n.perG)})}

`:''} + ${S.cash${tr('interface.not_enough_cash_wait_for_revenue')}

`:''} + ${all?controls:''} + ${all&&b.orders.length?`
${trn('pni_all.n_networks',Object.keys(byNet).length)}${Object.entries(byNet).map(([id,cities])=>`
${esc(NET[id].name)}${trn('save.n_pop',cities.length)}
${pniChip(id,null)}

${cities.map(c=>esc(CITY[c].name)).join(' · ')}

`).join('')}
`:b.orders.length?`
${pniChip(net,null)}

${b.orders.map(q=>esc(CITY[q.city].name)).join(' · ')}

${pniEta(net)}

`:''} + ${b.kept?`

${trn('pni_all.n_existing_or_pending_unchanged',b.kept)}

`:''} + ${b.blocked.length?(all?`
${trn('pni_all.n_blocked_connections',b.blocked.length)}${blocked}
`:`

${trn('pni_all.n_blocked_pops',b.blocked.length)}

${blocked}`):''} + ${!b.shared.length?`

${all?tr('pni_all.no_shared_locations'):tr('pni_all.no_shared_pops')}

`:''} + ${all?'':controls}`);} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js new file mode 100644 index 0000000..33548ec --- /dev/null +++ b/src/game/95-modals/40-title.js @@ -0,0 +1,53 @@ +// Five suggested homes, or any city with someone selling transit there. Hidden cities and China (which needs +// a license first) can't be a home, and neither can a city where nobody sells transit: you'd start cut off. +const homeOk=c=>own(CITY,c)&&!CITY[c].off&&!CITY[c].cn&&NETS.some(n=>sellsAt(n,c)); +const START5=['fra','nyc','sin','sao','syd']; +// One drawer for the home city: the five suggested homes first, then every city with transit by continent. +const START_D=()=>({fra:tr('title.crossroads_of_europe_de_kicks_ix'),nyc:tr('title.huge_eyeball_market_pricey'),sin:tr('title.asia_hub_great_peering_far_from'),sao:tr('title.big_hungry_market_few_providers'),syd:tr('title.hard_mode_pricey_everything')}); +function homePick(){const cs=Object.keys(CITY).filter(c=>homeOk(c)&&!START5.includes(c)),cur=UI.startCity,opt=c=>``; + return ``;} +// The line under the drawer: what the suggested home is like, or which continent another city is on. +const homeWhat=()=>START5.includes(UI.startCity)?esc(START_D()[UI.startCity]):`${esc(CITY[UI.startCity].name)} · ${esc(REG[CITY[UI.startCity].reg])}`; +/* Your own AS number (#135): any public 16- or 32-bit ASN, but not AS 0, AS_TRANS, the documentation and private ranges, or + one a network on the map already uses. Left empty, the game picks one from the private-looking 200000s as before. */ +const asnOk=a=>Number.isInteger(a)&&a>=1&&a<=4294967294&&a!==23456&&!(a>=64496&&a<=131071)&&!(a>=4200000000)&&!NETS.some(n=>n.asn===a); +const asnSuggest=()=>{for(;;){const a=200000+Math.floor(Math.random()*15000);if(asnOk(a))return a;}}; +function showTitle(){ + const list=slotIdx(true),top=slotTop(list),many=list.length>1||(list.length===1&&list[0]!==top); + if(UI.nm==null)UI.nm=randomNetworkName();if(UI.asnSug==null)UI.asnSug=asnSuggest(); + openModal(`
${langPick('langTitle')}
+

Series
of Tubes

+

${tr('title.build_an_internet_lay_fiber_between')}

${isPhone()?installRow():''} + ${top?`
${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}
`:''} + ${many?slotsHtml():''} +
+ ${doorsHtml()}${MP_API?mpDoorHtml():''} + ${homePick()}

${homeWhat()}

+
${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); + $('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;}); + $('asnIn').addEventListener('input',e=>{UI.asnTxt=e.target.value.replace(/\D/g,'').slice(0,10);if(e.target.value!==UI.asnTxt)e.target.value=UI.asnTxt;e.target.classList.toggle('bad',!!UI.asnTxt&&!asnOk(+UI.asnTxt));}); +} +// "What's new": shown once to returning players after an update, or on demand. +function whatsNew(returning,force){ + if(IS_DEV||(!RELEASE_NOTES.length&&!RELEASE_STORY.length))return false;let seen=null; + try{seen=localStorage.getItem('sot-seen-version');localStorage.setItem('sot-seen-version',APP_VERSION);}catch(e){} + if(!force&&(!returning||seen===APP_VERSION))return false; + openModal(`
${tr('common.release_notes')}

${tr('title.new_in_series_of_tubes_v',{v:esc(APP_VERSION)})}

+ ${notesHtml(RELEASE_NOTES,APP_VERSION)} + ${returning&&S?`

${tr('title.your_network_name_was_saved_and',{name:esc(S.name)})}

`:''} +
${btn(UI.started?tr('title.back_to_my_network'):tr('common.got_it'),UI.started?'closeModal':'helpClose',{},'pink big')}${notesLong(RELEASE_NOTES)||RELEASE_STORY.length?'':`${tr('common.full_changelog')}`}
`); + return true;} +/* The four doors: one game, its rules picked here and locked for the network's life. Normal and Sandbox stay on this + screen (presets / chaos below), Puzzles and Scenarios open their own lists. Choices toggle in place (no re-render). */ +const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot_no_clock')],['sandbox','🏖️',tr('common.sandbox'),tr('title.a_billion_dollars_and_every_toy')],['normal','📟',tr('common.normal'),tr('title.the_real_game_climb_from_tier')],['scn','🏆',tr('title.scenarios_amp_weekly'),tr('title.hand_built_crises_and_one_world')]]; +const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'}; +// The chosen preset in one line: its joke, then what actually changes. +const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)} ${PRESETS[k].ip4===false?tr('ip4.preset_plenty'):tr('ip4.preset_scarce')}`; +// The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js). +const presetBtns=pr=>`
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}

${presetWhat(pr)}

`; +function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'; + return `
${DOORS.map(([k,i,n,d])=>``).join('')}
+
${presetBtns(pr)}
+
${Object.entries(CHAOS).map(([k,C])=>``).join('')}
+

🔒 ${tr('title.rules_are_picked_once_and_locked')}

`;} diff --git a/src/game/95-modals/45-slots.js b/src/game/95-modals/45-slots.js new file mode 100644 index 0000000..0dcbd90 --- /dev/null +++ b/src/game/95-modals/45-slots.js @@ -0,0 +1,37 @@ +/* "Your networks" on the title screen: drawn from the index alone, so it stays instant however big the saves are. */ +function slotAgo(t){const m=Math.max(0,Math.round((Date.now()-t)/60000)); + return m<1?tr('slots.just_now'):m<60?trn('notifications.n_min_ago',m):m<1440?trn('slots.n_h_ago',Math.round(m/60)):trn('slots.n_day_ago',Math.round(m/1440));} +const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'?'🏖️':(PRESETS[e.preset]||PRESETS.oncall).i; +// The network to continue: the most recent one that is not open in another window (or damaged). +function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;} +function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete'); + const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);if(MP_API&&e.mp)bits.push('🌐 '+mpShow(e.mp.slice(0,6))); + return bits.filter(Boolean).join(' · ');} +function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network')); + const tag=busy?`${tr('slots.open_in_another_window')}`:top?`▶ ${tr('slots.continue')}`:''; + return `
`;} +function slotListHtml(){const list=slotByAt(slotIdx()),top=slotTop(list); + return list.map(e=>slotRow(e,e===top)).join('');} +function slotsHtml(){const list=slotIdx(true);if(!list.length)return ''; + SLOT.html=slotListHtml();return `
${SLOT.html}
`;} +// Another window saved, opened or closed a network: the list follows (only when it is on screen and changed). +function slotRefresh(){const el=$('slotList');if(!el||UI.started)return;const h=slotListHtml();if(h!==SLOT.html){SLOT.html=h;el.innerHTML=h;}} +function slotMenuHtml(id){const e=slotIdx().find(x=>x.id===id);if(!e)return '';const nm=esc(e.name||tr('common.unnamed_network')); + return `
${slotIcon(e)} ${slotLine(e)}

${nm}

+

${e.at?tr('slots.last_played_ago',{ago:slotAgo(e.at)}):''}${e.size?' · '+tr('slots.size_on_this_device',{size:slotSize(e.size)}):''}

+ `;} +const slotSize=n=>n>=1e6?(n/1e6).toFixed(1)+' MB':Math.max(1,Math.round(n/1e3))+' kB'; +function slotBusyModal(id){const e=slotIdx().find(x=>x.id===id),nm=esc(e&&e.name||tr('common.unnamed_network')); + openModal(`
🪟 ${tr('slots.two_windows_one_network')}

${tr('slots.name_is_open_in_another_window',{name:nm})}

+

${tr('slots.only_one_window_can_play_a')}

${btn(tr('slots.switch_to_that_window'),'slotSwitch',{id},'pink big')}${btn(tr('slots.take_over_here'),'slotTake',{id},'big')}${btn(tr('slots.your_networks'),'slotBack',{},'ghost')}
`);} +// Shown in the window that stepped aside: calm, and nothing here writes. +function slotLostModal(id,name,why){const nm=esc(name||tr('common.unnamed_network')); + openModal(`
🪟 ${tr('slots.two_windows_one_network')}

${why==='newer'?tr('slots.name_was_saved_in_another_window',{name:nm}):tr('slots.name_opened_in_another_window',{name:nm})}

+

${why==='newer'?tr('slots.this_window_stopped_saving_so_it'):tr('slots.this_window_stepped_aside_so_the')}

${btn(why==='newer'?tr('slots.load_the_newest_version'):tr('slots.take_it_back_here'),why==='newer'?'cont':'slotTake',{id},'pink big')}${btn(tr('slots.your_networks'),'slotBack',{},'ghost big')}
`);} +const slotOthers=()=>slotIdx().filter(e=>e.id!==UI.slot); +// Out of room: which other networks take space, with export and delete right there. +function slotSpaceHtml(){const l=slotOthers().sort((a,b)=>b.size-a.size); + return `
💾 ${tr('slots.storage_on_this_device')}

${tr('slots.free_up_space')}

+

${tr('slots.your_other_networks_share_this_browser')}

+ ${l.length?l.map(e=>`
${slotIcon(e)} ${esc(e.name||tr('common.unnamed_network'))}
${slotSize(e.size)}${e.at?' · '+slotAgo(e.at):''}
${btn(tr('common.export_save'),'slotExport',{id:e.id},'ghost sm')}${btn(tr('slots.delete'),'slotDel',{id:e.id,back:'space'},'red sm')}
`).join(''):`

${tr('slots.no_other_networks_here')}

`} +
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}
`;} diff --git a/src/game/95-modals/46-transfer.js b/src/game/95-modals/46-transfer.js new file mode 100644 index 0000000..e52c244 --- /dev/null +++ b/src/game/95-modals/46-transfer.js @@ -0,0 +1,16 @@ +/* Moving a network to another device (#263): the save file through the share sheet, or the link; on the other side, + where to open it. */ +function xferHtml(){const x=UI.xfer,nm=esc(x.name||tr('common.unnamed_network')); + return `
📲 ${tr('transfer.send_to_another_device')}

${nm}

+ ${x.mp?xferMpHtml(x):`

${x.file?tr('transfer.send_the_save_file_to_your'):tr('transfer.download_the_save_file_and_send')}

+
${x.file?btn(tr('transfer.send_the_save_file'),'xferShare',{},'pink big'):btn(tr('common.export_save'),'xferFile',{},'pink big')}${x.link?btn(tr('transfer.copy_the_link'),'xferLink',{},''):''}
+ ${x.link?`

${tr('transfer.or_copy_the_link_and_paste')}

`:''}

${tr('transfer.nothing_is_uploaded_anywhere_the_file')}

`}`;} +// A network of a multiplayer session (mpXfer()): the session's link first, which keeps it in the session; the file is a copy. +function xferMpHtml(x){const f=x.file?btn(tr('transfer.send_the_save_file'),'xferShare',{},x.link?'':'pink big'):btn(tr('common.export_save'),'xferFile',{},x.link?'':'pink big'); + return `${x.link?`

${tr('mp.move_note')}

`:''}
${x.link?btn(tr('mp.copy_link'),'xferLink',{},'pink big'):''}${f}
+ ${x.link?`

${tr('mp.move_warn')}

`:''}

${tr('mp.xfer_copy',{code:mpShow(x.mp)})}

`;} +function xferRecvHtml(){return `
📲 ${tr('transfer.from_another_device')}

${tr('transfer.moving_a_network_here')}

+

${tr('transfer.on_the_device_with_your_network')}

+
${btn(tr('common.import_a_save'),'importPick',{},'pink big')}
+ +
${btn(tr('common.open'),'xferPaste',{},'')}
`;} diff --git a/src/game/95-modals/48-multiplayer.js b/src/game/95-modals/48-multiplayer.js new file mode 100644 index 0000000..77767c9 --- /dev/null +++ b/src/game/95-modals/48-multiplayer.js @@ -0,0 +1,73 @@ +/* Multiplayer on screen (89-multiplayer.js has the logic): the title screen's door, the start/join sheet, the session + panel (leaderboard, feed and chat, the code to share, the link to another device) and the HUD chip. Only ever drawn + when the build stamped MP_API. Everything another player wrote is escaped here. */ +const MP_FEED_L={join:N_('mp.feed_join'),leave:N_('mp.feed_leave'),t2:N_('mp.feed_t2'),t1:N_('mp.feed_t1'),t1first:N_('mp.feed_t1first')}; +const mpDoorHtml=()=>`
`; +function mpStartHtml(){const pr=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall'; + return `
🌐 ${tr('mp.multiplayer')}

${tr('mp.play_with_friends')}

+

${tr('mp.intro')}

+ + ${homePick()}

${homeWhat()}

+

${tr('mp.start_a_session')}

${presetBtns(pr)} + +
${btn(tr('mp.start_a_session'),'mpStart',{},'pink big mpgo')}
+

${tr('mp.join_a_session')}

+
${btn(tr('mp.join'),'mpJoin',{},'big mpgo')}
+

${tr('mp.join_note')}

+ +
${btn(tr('common.back'),'mpBack',{},'ghost')}
`;} +function mpBusy(on){UI.mpBusy=on;document.querySelectorAll('.mpgo').forEach(b=>{b.disabled=on;});const b=$('mpBusy');if(b)b.hidden=!on;} +function mpErr(e){const st=e&&e.status;sfx('err'); + toast(st===404?tr('mp.err_no_session'):st===409?tr('mp.err_full'):st===429?tr('mp.err_slow'):st===503?tr('mp.err_server_full'):st===400?tr('mp.err_refused'):tr('mp.err_offline'),'bad');} +const mpNameIn=()=>{const n=$('mpName'),v=String((n&&n.value)||UI.nm||randomNetworkName()).trim().slice(0,24)||randomNetworkName();UI.nm=v;return v;}; +// The server said yes: the token goes to this browser's storage, the rest into a new game. +function mpBegin(j,nm,home,joined){const m=mpJoinOk(j);if(!m){toast(tr('mp.err_offline'),'bad');return;} + mpTokSet(m.code,m.pid,m.token);delete m.token;beginGame(nm,home,{mode:'normal',preset:m.preset,mp:{...m,joined}});} +// Called by beginGame just before its first save, which then pushes the day-0 save and the card: this player is on the +// leaderboard at once, and a link to another device works from the start. +function mpStarted(m){mpReset({day:-1,last:-1e9});mpHud();UI.mpLater={joined:!!(m&&m.joined)};} +// The code to share, with its buttons. A new Normal game asks for its charter first, on top of everything: the code +// waits until it is signed (ACT.charter), or its buttons could not be pressed. +function mpStartTell(){const b=UI.mpLater;if(!b||!mpIs())return;if(!$('modal').hidden&&$('modal').className==='charter')return;UI.mpLater=null; + const code=mpShow(S.mp.code),acts=[{l:tr('common.share'),act:'mpShare',args:{}},{l:tr('mp.session'),act:'mpOpen',args:{}}]; + toast(b.joined?tr('mp.joined',{code}):tr('mp.session_live',{code}),'goal',acts);} +/* ---------- the session panel ---------- */ +function mpBoardHtml(){const r=MP.roster;if(MP.gone)return `

${tr('mp.not_in_session')}

`; + // Another device moved on: the toast with the choice is long gone, the choice stays here until it is made. + const st=MP.stale?`

${tr('mp.moved_on_elsewhere')}

${btn(tr('mp.load_newer'),'mpNewer',{},'pink')}${btn(tr('mp.keep_mine'),'mpKeep',{},'')}
`:''; + if(st)return st;if(!r)return `

${tr('mp.loading')}

`;const me=S&&S.mp&&S.mp.pid; + return mpRank(r.players).map((p,i)=>{const c=p.card,mine=p.pid===me; + const meta=c?[`AS${p.asn}`,c.t1?'Tier 1':c.tier==='t2'?'Tier 2':'Tier 3',trn('mp.n_pops',c.pops.length),fmtG(c.peak),trn('mp.n_customers',c.cust)].join(' · '):`AS${p.asn} · ${tr('mp.no_card')}`; + return `
${i+1}
${esc(p.name)}${mine?` ${tr('mp.you')}`:''}
${meta}
${p.seen?slotAgo(p.seen):''}
`;}).join('');} +function mpFeedHtml(){const r=MP.roster;if(!r)return '';const f=r.feed.slice(-30).reverse();if(!f.length)return `

${tr('mp.feed_empty')}

`; + const col=pid=>{const p=r.players.find(x=>x.pid===pid);return p?p.color:'#888888';}; + return f.map(x=>{const who=`${esc(x.name)}`,t=x.k==='chat'?`${who}: ${esc(x.text)}`:tr(MP_FEED_L[x.k],{name:who}); + return `
${t}${x.at?slotAgo(x.at):''}
`;}).join('');} +function mpPanelHtml(){const m=S.mp,code=mpShow(m.code),link=mpLink(m); + return `
🌐 ${tr('mp.session')} · ${esc(PRESETS[m.preset].n)}

${m.title?esc(m.title):tr('mp.session_code',{code})}

+
${tr('mp.code')}${code}
${btn(tr('common.share'),'mpShare',{},'pink')}
+

${tr('mp.share_note')}

+

${tr('mp.leaderboard')}

${mpBoardHtml()}
+

${tr('mp.feed')}

${btn(tr('mp.send'),'mpChat',{},'')}
${mpFeedHtml()}
+ ${link?`
${tr('mp.move_device')}

${tr('mp.move_note')}

${tr('mp.move_warn')}

${btn(tr('mp.copy_link'),'mpCopyLink',{},'')}
`:''} +
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${btn(tr('mp.leave'),'mpLeaveAsk',{},'ghost')}
`;} +// The roster moved on: only the leaderboard and the feed are redrawn, so a chat line being typed stays. +function mpPanelUpdate(){const b=$('mpBoard'),f=$('mpFeed');if(!b||$('modal').hidden)return;b.innerHTML=mpBoardHtml();if(f)f.innerHTML=mpFeedHtml();} +// While the panel is open, the roster every 5 s; it stops by itself once the panel is gone. +function mpPoll(){clearInterval(MP.poll);MP.poll=null;if(!mpIs())return;mpRefresh();if(!window.__TUBES_TEST__)MP.poll=setInterval(mpPollTick,MP_POLL);} +function mpPollTick(){if($('modal').hidden||!$('mpPanel')||!mpIs()){clearInterval(MP.poll);MP.poll=null;return;}mpRefresh(true);} +/* The HUD chip: the session code and where you stand. A phone's top bar has no room for it (the menu has the session): + there, and on a tablet whose top bar is still too full (fitHud's last step), where you stand is a badge on the menu + button instead. Made the first time a session network is on screen. */ +function mpHud(){let c=$('hMp');const on=mpIs(); + if(!c){if(!on)return;c=document.createElement('button');c.className='chip mpchip hide-sm';c.id='hMp';c.dataset.act='mpOpen'; + c.innerHTML='';const n=$('hNoc');n.parentNode.insertBefore(c,n.nextSibling); + const b=document.createElement('span');b.className='badge mpbadge num';b.id='hMpB';b.setAttribute('aria-hidden','true');const mb=document.querySelector('#hud .menubtn');if(mb)mb.appendChild(b);} + const b=$('hMpB');c.hidden=!on;if(b)b.hidden=!on;if(!on)return; + const r=MP.roster,i=r?mpRank(r.players).findIndex(p=>p.pid===S.mp.pid):-1,rk=i>=0?`#${i+1}/${r.players.length}`:'—'; + c.setAttribute('aria-label',tr('mp.session'));c.title=tr('mp.session');c.style.borderColor=S.mp.color; + $('hMpCode').textContent=mpShow(S.mp.code);$('hMpRank').textContent='🌐 '+rk;if(b)b.textContent=i>=0?`#${i+1}`:'🌐';} +// Share text: the phone's share sheet, or the clipboard. +function mpSend(t){const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'); + if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;} + try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}} diff --git a/src/game/95-modals/50-release-notes.js b/src/game/95-modals/50-release-notes.js new file mode 100644 index 0000000..eadfb36 --- /dev/null +++ b/src/game/95-modals/50-release-notes.js @@ -0,0 +1,19 @@ +/* In-app notes stay short: at most NOTE_MAX changes, each cut to its first sentence. When anything was cut, a + link leads to the full notes of this version on GitHub. The CHANGELOG and the GitHub release keep every word. */ +const NOTE_MAX=5,NOTE_CH=140; +function slimNote(n){const m=String(n).match(/^(.+?[.!?])(\s|$)/);let t=m?m[1]:String(n);if(t.length>NOTE_CH)t=t.slice(0,NOTE_CH-1).replace(/\s+\S*$/,'')+'…';return t;} +const notesLong=ns=>ns.length>NOTE_MAX||ns.some(n=>slimNote(n)!==n); +// A release with a story tells it in full, then points to every change on GitHub. +const storyHtml=(ps,ver)=>`
${ps.map(p=>`

${esc(p).replace(/\*\*(.+?)\*\*/g,'$1')}

`).join('')}

${tr('release_notes.read_the_full_notes_on_github')}

`; +function notesHtml(ns,ver){if(RELEASE_STORY.length&&ver===APP_VERSION&&ns===RELEASE_NOTES)return storyHtml(RELEASE_STORY,ver);const more=Math.max(0,ns.length-NOTE_MAX); + return `
    ${ns.slice(0,NOTE_MAX).map(n=>`
  • ${esc(slimNote(n))}
  • `).join('')}${more?`
  • ${trn('release_notes.and_n_more_change',more)}
  • `:''}
`+ + (notesLong(ns)?`

${tr('release_notes.read_the_full_notes_on_github')}

`:'');} +function newerVer(a,b){const x=String(a).split('.').map(Number),y=String(b).split('.').map(Number);for(let i=0;i<3;i++){if((x[i]||0)>(y[i]||0))return true;if((x[i]||0)<(y[i]||0))return false;}return false;} +// While the game is open, look for a newer release now and then and offer a reload. +function checkUpdate(){ + if(IS_DEV||location.protocol==='file:'||!window.fetch)return;const now=Date.now();if(now-(UI.updChecked||0)<60000)return;UI.updChecked=now; + fetch('/version.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(j=>{ + if(!j||!j.version||!newerVer(j.version,APP_VERSION))return;if(UI.updLater&&now-UI.updLater<6*3600*1000)return; + const top=(j.notes||[])[0]||'';$('update').innerHTML=`
${tr('release_notes.series_of_tubes_v_is_out',{v:esc(j.version)})}${top?`
${esc(top.length>120?top.slice(0,117)+'…':top)}`:''}
${tr('release_notes.your_game_is_saved_automatically')}
${btn(tr('common.reload_now'),'updateNow',{},'pink sm')}${btn(tr('common.later'),'updateLater',{},'ghost sm')}`;$('update').hidden=false; + }).catch(()=>{}); +} diff --git a/src/game/95-modals/60-help.js b/src/game/95-modals/60-help.js new file mode 100644 index 0000000..5a3b075 --- /dev/null +++ b/src/game/95-modals/60-help.js @@ -0,0 +1,24 @@ +function showHelp(){ + openModal(`

${tr('help.how_the_internet_works_here')}

+

${tr('help.controls_drag_the_map_to_pan')}

+
+
${tr('common.eyeballs')}
${tr('help.home_broadband_users_they_mostly')}
+
POP
${tr('help.point_of_presence_your_router_in')}
+
${tr('common.ip_transit')}
${tr('help.you_pay_a_bigger_network_per')}
+
Tier 1 / Tier 2
${tr('help.tier_1s_reach_the_whole_internet_cones')}
+
CDN
${tr('help.content_networks_like_netchill_and')}
+
${tr('help.ix_internet_exchange')}
${tr('help.a_shared_switch_in_a_city')}
+
PNI
${tr('help.private_network_interconnect_a_cable')}
+
${tr('help.pni_lead_times')}
${tr('help.a_cross_connect_with_a_small')}
+
${tr('common.supply_chain')}
${tr('help.routers_optics_and_new_builds_get')}
+
${tr('common.backhaul_latency')}
${tr('help.users_feel_the_round_trip_to')}
+
${tr('common.peering_policy')}
${tr('help.every_ix_port_brings_requests')}
+
${tr('common.embedded_cache')}
${tr('help.a_cdn_s_server_in_your')}
+
DE-KICKS
${tr('help.the_group_behind_several_big')}
${tr('common.remote_peering')}
${tr('help.reach_an_ix_over_a_fabric')}
${tr('common.peering_policy')}
${tr('help.open_peers_with_anyone_selective')}
+
${tr('common.waves')}
${tr('help.your_fiber_links_are_leased_waves')}
${tr('common.95th_percentile')}
${tr('help.transit_bills_sample_your_usage')}
${tr('common.routers')}
${tr('help.each_pop_s_router_model_caps')}
${tr('common.dark_fiber')}
${tr('help.lease_an_iru_or_build_your')}
${tr('common.subsea_cables')}
${tr('help.subsea_waves_can_only_follow_cable')}
${tr('common.latency')}
${tr('help.every_link_has_latency_high')}
${tr('common.noc_dashboard')}
${tr('help.the_chart_button_at_the_top')}
${tr('common.asia')}
${tr('help.a_weird_underserved_market_transit')}
${tr('common.russia')}
${tr('help.moscow_needs_a_mandatory_government')}
${tr('help.events_chains_and_wholesale')}
${tr('help.event_networks_a_final_a_festival')}
${tr('common.bank')}
${tr('help.tap_your_cash_to_open_the')}
${tr('common.lags')}
${tr('help.out_of_port_speed_bundle_up')}
${tr('common.traffic_engineering')}
${tr('help.tap_a_link_to_see_which')}
${tr('common.china')}
${tr('help.mainland_china_needs_a_license_and')}
${tr('common.weird_requirements')}
${tr('help.some_customers_come_with_conditions')}
${tr('common.customer_levels')}
${tr('help.as_your_peak_traffic_and_footprint')}
${tr('help.l2vpn_ddos_protection')}
${tr('help.businesses_may_want_a_private')}
${tr('common.ddos_attack')}
${tr('help.ddos_a_flood_comes_from')}
${tr('common.scrubbing_centers')}
${tr('help.scrubbing_a_center_pulls_floods')}
${tr('common.nni_fabrics')}
${tr('help.megapork_pocketfabric_and')}
+
${tr('common.conferences')}
${tr('help.nanog_ripe_denog_and_friends_come')}
${tr('common.modes')}
${tr('help.one_game_four_doors_and_the')}
${tr('common.traceroute')}
${tr('help.tap_traceroute_on_any_of_your')}
${tr('common.badges')}
${tr('help.below_your_goals_sits_a_wall')}
${tr('common.the_giants')}
${tr('help.at_customer_level_3_and_4')}
RouteScript
${tr('help.once_auto_te_is_installed_you')}
Auto-TE
${tr('help.traffic_follows_the_shortest_path_by')}
${tr('common.metro_diversity')}
${tr('help.a_pop_is_one_building_until')}
${tr('common.wave_markets')}
${tr('help.what_a_wave_costs_depends_on')}
${tr('common.regional_quirks')}
${tr('help.in_the_gulf_saudi_pops_need')}
${tr('common.boot_times')}
${tr('help.some_routers_take_forever_to_boot')}
${tr('common.failures')}
${tr('help.things_break_all_the_time_fiber')}
+
RouteScript
${tr('help.rules_for_your_auto_te_controller')}
+

${tr('help.want_to_know_how_it_really')}

${plugHtml(true)}${chatHtml()}${issueHtml()}
${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}${isPhone()?'':btn(tr('keys.keyboard_shortcuts'),'keys',{},'ghost sm')}
`); +} +function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`
${btn(tr('help.share_my_network'),'share',{},'pink')}

${tr('help.you_built_a_cartoon_internet_now')}

${plugHtml(true)}`);},0);openModal(`

${tr('help.you_re_a_tier_1')}

${tr('help.name_as_asn_is_transit_free',{name:esc(S.name),asn:S.asn,days:netAge(),n:S.stats.incidents})}

${btn(tr('common.keep_building'),'keepPlaying',{},'pink big')}`);sfx('coin');} +function showLose(){openModal(`

${tr('common.bankrupt')}

${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:netAge(),peak:fmtG(S.stats.peak)})}

${btn(tr('common.try_again'),'newgame',{},'pink big')}`);if(UI.slot){const id=UI.slot;slotDrop(id);slotFree(id);}} diff --git a/src/game/95-modals/70-link-modal.js b/src/game/95-modals/70-link-modal.js new file mode 100644 index 0000000..9b8edee --- /dev/null +++ b/src/game/95-modals/70-link-modal.js @@ -0,0 +1,28 @@ +function openLinkModal(a,b){ + {const nt=noTalk(a,b);if(nt){openModal(`

${tr('common.not_happening')}

${tr(nt)}

`);return;}} + if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`

${tr('link_modal.not_without_a_license')}

${tr('link_modal.building_into_mainland_china_needs_a',{city:CITY[cnCity(a)?a:b].name})}

`);return;} + let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'); + if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),jn=sib.length?routeJoin(a,b):null,ts=landTrenches(a,b),mult=(sib.length&&!(jn&&jn.k===(ts[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); + if(border)route+=`

${tr('link_modal.cross_border_circuits_into_mainland')}

${a==='hkg'||b==='hkg'?`
${btn(tr('common.regular_crossing'),'cnPrem',{v:0},!UI.cnPrem?'pink':'ghost')}${btn(tr('link_modal.premium_crossing_60_3_loss'),'cnPrem',{v:1},UI.cnPrem?'pink':'ghost')}
`:`

${tr('link_modal.premium_crossings_are_only_sold_in')}

`}`; + if(sib.length&&!(isSub(a,b)&&cablesFor(a,b).length)&&!(UI.via&&UI.via!=='land'&&cablesFor(a,b).some(c=>c.cid===UI.via))){route+=`

${trn('link_modal.you_already_have_n_link_here',sib.length,{list:sib.map(l=>capName(l)).join(', ')})}

+
${ts.length>1?ts.map((t,i)=>btn(`${i?tr('link_modal.diverse_route_n',{n:i}):tr('common.main_route')} ${esc(t.caps.join(', '))}${i?' · +40%':''}`,'route',{r:'t:'+t.k},jn&&jn.k===t.k?'pink':'ghost')).join('')+btn(tr('link_modal.new_diverse_route_40_survives_cuts'),'route',{r:'diverse'},!jn?'pink':'ghost'):btn(tr('link_modal.diverse_route_40_survives_cuts_alone'),'route',{r:'diverse'},!jn?'pink':'ghost')+btn(tr('link_modal.same_trench_cheaper_one_backhoe_cuts'),'route',{r:'same'},jn?'pink':'ghost')}
${ts.length>1?`

${tr('link_modal.waves_on_the_same_route_share')}

`:''}`;} + // Express (#58): only where your ROADM fibers already chain from a to b. The path a fiber's panel offered comes first. + const xp1=UI.xpPath?xpParse(a,b,UI.xpPath):null,xr0=xpPaths(a,b),xr=xp1&&!xr0.some(r=>r.sp.length===xp1.length&&r.sp.every((s,i)=>s===xp1[i]))?[{to:b,sp:xp1,km:xp1.reduce((x,s)=>x+s.km,0)},...xr0.slice(0,2)]:xr0; + const mode=UI.lmode==='df'?'df':UI.lmode==='xp'&&xr.length?'xp':'wave',tabs=`
${btn(tr('link_modal.lease_a_wave'),'dfMode',{m:'wave'},mode==='wave'?'pink':'ghost')}${btn(tr('common.dark_fiber'),'dfMode',{m:'df'},mode==='df'?'pink':'ghost')}${xr.length?btn(tr('express.tab'),'xpOpen',xp1?{a,b,via:UI.xpPath}:{a,b},mode==='xp'?'pink':'ghost'):''}
`; + const head=`
${sub?tr('common.subsea_a6be'):tr('common.terrestrial_19e4')} · ${km.toLocaleString()} km

${CITY[a].name} → ${CITY[b].name}

${tabs}`; + if(mode==='df'){openModal(head+dfModalBody(a,b,km,pop));return;} + if(mode==='xp'){openModal(head+xpModalBody(a,b,xr));return;} + if(sub&&!cablesOk(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))],dry=[a,b].find(c=>!landing(c)); + // a beach with no cable yet (#321): hopping cannot help, only a road in, a cable of your own, or a satellite (#83) + const bare=!dry&&[a,b].find(c=>!CABLE_PAIRS.some(p=>p.a===c||p.b===c)),road=bare&&CITIES.some(x=>x.id!==bare&&!isSub(bare,x.id)),far=dry||bare,sat=!!far&&satCan(far); + openModal(head+`

${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):bare?(road?tr('link_modal.no_subsea_cable_lands_in_city_land',{city:CITY[bare].name}):sat?tr('link_modal.no_subsea_cable_lands_in_city_own_sat',{city:CITY[bare].name}):tr('link_modal.no_subsea_cable_lands_in_city_own',{city:CITY[bare].name})):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}

${sat?satNoCable(far):''}${(cabOpen()?!ownCabWhy(a,b):bare)?ownCabTeaser(a,b):''}`);return;} + if(isSub(a,b)&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city)){openModal(head+`

${tr('link_modal.the_landing_permit_dispute_in_city',{city:CITY[S.ev.landban.city].name,n:S.ev.landban.until-S.day})}

`);return;} + if(uaePair(a,b)||andesPair(a,b)||rainPair(a,b)||borderPair(a,b))route+=`

${landWhy(a,b)}

`; + if(S.ev.gulf>S.day&&gulfPair(a,b))route+=`

${tr('link_modal.the_borders_around_qatar_are_closed')} ${tr('link_panels.back_in_n_days',{n:S.ev.gulf-S.day})}

`; + route+=`

📈 ${esc(marketNote(a,b,sub))}

`; + const wr=waveRoute(a,b,mult,border); + openModal(`${head} +

${tr('link_modal.waves_are_leased_at_a_flat')}

+ ${pop?`

${tr('link_modal.includes_a_new_pop_in_city',{city:CITY[b].name,price:fmt$(pop),extra:ruCity(b)?', '+tr('link_modal.government_box_included'):CITY[b].uae?', '+tr('link_modal.free_zone_license_included'):CITY[b].saudi?', '+tr('link_modal.local_telecom_licence_included'):''})}

`:''}${route}${viaSeg(a,b)} +
${LT.map((T,i)=>{const lc=Math.round(waveMo(wr.km,wr.sub,i)*wr.wm),c=lc+pop,sw=subWaveWhy(i,wr.km,wr.sub),so=!sw&&soldOut(a,b,i,wr.cab),ok=waveOk(a,b,i)&&!sw&&!so;return !waveShown(i)?'':``;}).join('')}
`); +} diff --git a/src/game/95-modals/80-own-cable.js b/src/game/95-modals/80-own-cable.js new file mode 100644 index 0000000..5e1a434 --- /dev/null +++ b/src/game/95-modals/80-own-cable.js @@ -0,0 +1,224 @@ +/* Your own subsea cable (#22). Tier 1 networks lay their own: very expensive, slow to build, and it pays for + itself after a few years if it replaces enough leased waves. Both ends need a cable landing station. You own + up to eight fiber pairs; the first comes lit with a ROADMaster, the repeaters are powered from shore. */ +const SEA_DELAYS=[N_('own_cable.a_whale_has_parked_on_the'),N_('own_cable.the_cable_ship_s_coffee_machine'),N_('own_cable.a_fishing_fleet_is_trawling_exactly'),N_('own_cable.the_seabed_survey_found_an_old'),N_('own_cable.storm_season_the_ship_is_sheltering'),N_('own_cable.the_crew_fished_out_somebody_else')]; +const OWNCAB_LAND=3000000,OWNCAB_KM=6000,OWNCAB_OM=25; +const OWNCAB_NAMES=['Big Blue Tube','Davy Jones’ Backhaul','Kraken-1','Mariana Trench Coat','The Wet Ethernet','Sea-ya Later','Deep Pockets Express','Salty Sea Dog','Poseidon’s Patch Cable','Neptune Neutrality','Moby Disk','Fibre Nemo','The Long Splice Home','Bermuda Triangle Routing','Seabed & Breakfast','Atlantis Backhaul']; +const landing=c=>!!CITY[c].beach||CABLE_PAIRS.some(p=>p.a===c||p.b===c); +const nearLanding=c=>CITIES.filter(x=>x.id!==c&&landing(x.id)).sort((x,y)=>kmBetween(c,x.id)-kmBetween(c,y.id))[0].id; +const ownCabKm=(a,b)=>seaRoutes(a,b)[0]?.km||Infinity; +const ownCabCost=km=>Math.round((2*OWNCAB_LAND+km*OWNCAB_KM+DF_SYS.roadm.cost)*hwMul('build')); +const ownCabMo=km=>Math.round(km*OWNCAB_OM)+ampCount(km)*AMP_MO; +const ownCabDays=km=>leadDays(Math.round(300+km*0.05)); +// Marine routing uses the same coastline as the map, in geographic coordinates. +// A quarter-degree grid keeps narrow passages open; edges are checked against +// coastline segments as well as water cells, so diagonal steps cannot cut land. +// Nothing is built until an order is quoted; topology and finished routes are reused. +const SEA_NAV={step:0.25,nx:1440,ny:641,rows:new Map(),edges:null,tiles:new Map(),fine:new Set(),routes:new Map(),ports:new Map(),pass:null,closed:new Set()}; +// Real Europe–Asia cables land at Port Said and cross Egypt beside the canal to Suez; PAN AM crosses Panama by land. +// Each is an overland edge between two sea cells, priced as the distance it covers. +const SEA_PASS=[{id:'suez',a:[32.30,31.30],b:[32.58,29.85]},{id:'panama',a:[-79.90,9.40],b:[-79.50,8.85]}]; +function seaSnap(p){const cx=Math.round((seaLon(p[0])+180)/SEA_NAV.step)%SEA_NAV.nx,cy=Math.round((p[1]+80)/SEA_NAV.step);let best=null; + for(let r=0;r<=16&&!best;r++)for(let dy=-r;dy<=r;dy++)for(let dx=-r;dx<=r;dx++){if(Math.max(Math.abs(dx),Math.abs(dy))!==r)continue;const x=(cx+dx+SEA_NAV.nx)%SEA_NAV.nx,y=cy+dy;if(!seaWater(x,y)||!seaNode(x,y))continue;const id=y*SEA_NAV.nx+x;if(!seaOpen(id))continue;const d=hav(...p,...seaPoint(id));if(!best||d(a((x+180)%360+360)%360-180; +function seaInit(){if(SEA_NAV.edges)return; + SEA_NAV.edges=Array.from({length:181},()=>[]); + for(const poly of COAST_LL)for(let i=0,j=poly.length-1;i{let inside=false;for(const e of SEA_NAV.edges[clamp(Math.floor(lat)+90,0,180)])if((e[1]>lat)!==(e[3]>lat)&&x<(e[2]-e[0])*(lat-e[1])/(e[3]-e[1])+e[0])inside=!inside;return inside;}; + return ray(lon)||(lon<-170&&ray(lon+360)); +} +function seaWater(x,y){if(y<0||y>=SEA_NAV.ny)return false;x=(x+SEA_NAV.nx)%SEA_NAV.nx; + let row=SEA_NAV.rows.get(y);if(!row){row=new Uint8Array(SEA_NAV.nx);const lat=-80+y*SEA_NAV.step;for(let i=0;i=0&&t<=1&&v>=0&&v<=1; +} +function seaClear(A,B,margin=0){const a=[A[0],A[1]],b=[a[0]+seaLon(B[0]-a[0]),B[1]],n=Math.max(1,Math.ceil(Math.max(Math.abs(b[0]-a[0]),Math.abs(b[1]-a[1]))/0.25)); + const checked=new Set(); + for(let i=0;i<=n;i++){const t=i/n,x=a[0]+(b[0]-a[0])*t,y=a[1]+(b[1]-a[1])*t; + if(seaLand(x,y))return false; + if(margin&&[[margin,0],[-margin,0],[0,margin],[0,-margin]].some(([dx,dy])=>seaLand(x+dx,y+dy)))return false; + const tx=Math.floor(x/2),ty=Math.floor(y/2); + // Include adjacent tiles so segments touching a tile boundary are checked too. + for(let v=ty-1;v<=ty+1;v++)for(let u=tx-1;u<=tx+1;u++){const k=(((u+90)%180+180)%180)+','+v;if(checked.has(k))continue;checked.add(k); + for(const e of SEA_NAV.tiles.get(k)||[])if(seaCross(a,b,e))return false;} + }return true; +} +const seaPoint=id=>[-180+(id%SEA_NAV.nx)*SEA_NAV.step,-80+Math.floor(id/SEA_NAV.nx)*SEA_NAV.step]; +const seaNode=(x,y)=>x%4===0&&y%4===0||SEA_NAV.fine.has(Math.floor(-180+x*SEA_NAV.step)+','+Math.floor(-80+y*SEA_NAV.step)); +// A coarse city marker must not snap into a tiny disconnected estuary or lake. +function seaOpen(id){if(!SEA_NAV.connected)SEA_NAV.connected=new Map();if(SEA_NAV.connected.has(id))return SEA_NAV.connected.get(id); + const seen=new Set([id]),queue=[id];let open=false; + for(let i=0;i256){open=true;break;}const x=v%SEA_NAV.nx,y=Math.floor(v/SEA_NAV.nx); + for(const stride of (x%4===0&&y%4===0?[4,1]:[1]))for(let sy=-1;sy<=1;sy++)for(let sx=-1;sx<=1;sx++){if(!sx&&!sy)continue;const dx=sx*stride,dy=sy*stride,xx=(x+dx+SEA_NAV.nx)%SEA_NAV.nx,yy=y+dy,n=yy*SEA_NAV.nx+xx; + if(seen.has(n)||!seaNode(xx,yy)||!seaWater(xx,yy)||!seaStep(v,dx,dy))continue;seen.add(n);queue.push(n);} + }for(const v of seen)SEA_NAV.connected.set(v,open);return open; +} +function seaPorts(city){if(SEA_NAV.ports.has(city))return SEA_NAV.ports.get(city); + const c=CITY[city],p=[c.lon,c.lat],cx=Math.round((seaLon(c.lon)+180)/SEA_NAV.step)%SEA_NAV.nx,cy=Math.round((c.lat+80)/SEA_NAV.step),wet=!seaLand(...p),bins=new Map(); + // Inland city markers may reach more than one sea (Cairo, for example). + // Keep shore approaches in different directions; routing chooses the right sea. + for(let r=0;r<=16;r++)for(let dy=-r;dy<=r;dy++)for(let dx=-r;dx<=r;dx++){ + if(Math.max(Math.abs(dx),Math.abs(dy))!==r)continue;const x=(cx+dx+SEA_NAV.nx)%SEA_NAV.nx,y=cy+dy;if(!seaWater(x,y)||!seaNode(x,y))continue; + const id=y*SEA_NAV.nx+x,q=seaPoint(id),d=hav(...p,...q),angle=Math.atan2(q[1]-p[1],seaLon(q[0]-p[0])*Math.cos(c.lat*Math.PI/180)),bin=Math.floor((angle+Math.PI)*8/Math.PI)%16+'|'+Math.floor(d/100); + if(d>350||bins.has(bin)&&d>=bins.get(bin).d)continue; + if(wet&&!seaClear(p,q))continue; + if(!wet){const n=Math.max(2,Math.ceil(d/2));let water=false,ok=true;for(let i=0;i<=n;i++){const t=i/n,pt=[p[0]+seaLon(q[0]-p[0])*t,p[1]+(q[1]-p[1])*t];if(!seaLand(...pt)){water=true;if(!seaClear(pt,q)){ok=false;break;}}else if(water){ok=false;break;}}if(!ok)continue;} + if(seaOpen(id))bins.set(bin,{id,d,bin}); + } + // Nearby approaches are the default. A low-latency survey may also land further off and backhaul overland, like real + // transatlantic systems that land in the west of England and run to London on land. + const sorted=[...bins.values()].sort((a,b)=>a.d-b.d),limit=sorted.length?(sorted[0].d<30?sorted[0].d+15:sorted[0].d*1.75):0,dir=new Set(),ports=sorted.map(p=>{const k=p.bin.split('|')[0]>>1;const first=!dir.has(k);dir.add(k);return {id:p.id,d:p.d,near:first&&p.d<=limit};});SEA_NAV.ports.set(city,ports);return ports; +} +const seaPort=city=>seaPorts(city)[0]?.id??null,seaNear=ps=>ps.filter(p=>p.near); +// The grid topology is shared by all designs. Test each edge only once. +function seaStep(id,dx,dy){if(!SEA_NAV.known){const n=SEA_NAV.nx*SEA_NAV.ny;SEA_NAV.known=new Uint8Array(n);SEA_NAV.open=new Uint8Array(n);SEA_NAV.knownWide=new Uint8Array(n);SEA_NAV.openWide=new Uint8Array(n);} + const wide=Math.abs(dx)>1||Math.abs(dy)>1,sx=Math.sign(dx),sy=Math.sign(dy),bit=1<<((sy+1)*3+sx+1-(sy>0||sy===0&&sx>0?1:0)),known=wide?SEA_NAV.knownWide:SEA_NAV.known,open=wide?SEA_NAV.openWide:SEA_NAV.open; + if(known[id]&bit)return !!(open[id]&bit);known[id]|=bit; + const a=seaPoint(id),b=[a[0]+dx*SEA_NAV.step,a[1]+dy*SEA_NAV.step]; + for(let y=Math.floor(Math.min(a[1],b[1])/2);y<=Math.floor(Math.max(a[1],b[1])/2);y++)for(let x=Math.floor(Math.min(a[0],b[0])/2);x<=Math.floor(Math.max(a[0],b[0])/2);x++) + for(const e of SEA_NAV.tiles.get((((x+90)%180+180)%180)+','+y)||[])if(seaCross(a,b,e))return false; + open[id]|=bit;return true; +} +function seaSearch(starts,ends,target,clearance){const PASS=seaPasses(); + const dist=new Map(),prev=new Map(),done=new Set(),heap=[],goals=new Map(ends.map(p=>[p.id,p.d]));let goal=Infinity,goalEnd=null; + const put=(id,g)=>{const v={id,g,f:g+(id===-1?0:hav(...seaPoint(id),...target))};let i=heap.length;heap.push(v);while(i){const p=(i-1)>>1;if(heap[p].f<=v.f)break;heap[i]=heap[p];i=p;}heap[i]=v;}; + const take=()=>{const out=heap[0],v=heap.pop();if(heap.length){let i=0;while(i*2+1=v.f)break;heap[i]=heap[j];i=j;}heap[i]=v;}return out;}; + for(const p of starts){dist.set(p.id,p.d);put(p.id,p.d);} + while(heap.length){const {id,g}=take();if(id===-1){const path=[];for(let v=goalEnd;v!==undefined;v=prev.get(v))path.push(seaPoint(v));return path.reverse();}if(done.has(id))continue;done.add(id);if(goals.has(id)&&g+goals.get(id)i+1&&!seaClear(path[i],path[j],margin))j--;out.push(path[j]);i=j;}return out;} +function seaDensify(path){const out=[path[0].slice()];for(let i=1;i[Math.cos(la*r)*Math.cos(lo*r),Math.cos(la*r)*Math.sin(lo*r),Math.sin(la*r)],A=v(a),B=v(b),w=Math.acos(Math.min(1,A[0]*B[0]+A[1]*B[1]+A[2]*B[2])); + const n=Math.max(1,Math.ceil(w/r/0.5)),out=[];if(w<1e-9)return [b.slice()];for(let i=1;i<=n;i++){const t=i/n,f=Math.sin((1-t)*w)/Math.sin(w),g=Math.sin(t*w)/Math.sin(w),x=f*A[0]+g*B[0],y=f*A[1]+g*B[1],z=f*A[2]+g*B[2];out.push([seaLon(Math.atan2(y,x)/r),Math.atan2(z,Math.hypot(x,y))/r]);}return out;} +// A straight line on the map is not the shortest way across an ocean. Long legs follow the great circle where it stays at sea. +function seaGreat(path,margin){const out=[path[0]];for(let i=1;i300){const gc=seaGC(a,b);let ok=true,q=a;for(const p of gc){if(!seaClear(q,p,margin)){ok=false;break;}q=p;}if(ok){out.push(...gc);continue;}}out.push(b);}return out;} +const seaLength=pts=>Math.round(pts.slice(1).reduce((s,p,i)=>s+hav(...pts[i],...p),0)); +function seaRoutes(a,b){seaSync();const reverse=a>b,key=seaKey(a,b);let routes=SEA_NAV.routes.get(key); + if(!routes){const A=reverse?b:a,B=reverse?a:b,PA=seaPorts(A),PB=seaPorts(B);routes=[]; + if(seaNear(PA).length&&seaNear(PB).length)for(const [penalty,margin,all] of [[1,0.5,false],[0.3,0.25,false],[0,0,true]]){ + const raw=seaSearch(all?PA:seaNear(PA),all?PB:seaNear(PB),[CITY[B].lon,CITY[B].lat],penalty);if(!raw)break; + const pts=seaDensify(seaGreat([[CITY[A].lon,CITY[A].lat],...seaSimplify(raw,margin),[CITY[B].lon,CITY[B].lat]],margin)),r={pts,km:seaLength(pts),shore:[raw[0],raw[raw.length-1]]}; + // A survey can reuse the previous feasible route if its new candidate is longer. + routes.push(routes.length&&r.km>routes[routes.length-1].km?routes[routes.length-1]:r); + }SEA_NAV.routes.set(key,routes); + } + return reverse?routes.map(r=>({km:r.km,pts:r.pts.slice().reverse(),shore:r.shore.slice().reverse()})):routes; +} +// Surveys run off the UI thread in browsers. Tests and browsers without workers +// use the same deterministic router synchronously. Switching designs uses the cache. +const SEA_SURVEY={worker:null,pending:new Set(),failed:false}; +function seaReady(a,b){seaSync();const key=seaKey(a,b); + if(SEA_NAV.routes.has(key)||typeof Worker==='undefined'||SEA_SURVEY.failed)return true; + if(SEA_SURVEY.pending.has(key))return false; + try{ + if(!SEA_SURVEY.worker){ + const helpers=[seaSnap,seaPasses,seaGC,seaGreat,seaNear,seaKey,seaSync,seaLon,seaInit,seaLand,seaWater,seaCross,seaClear,seaPoint,seaNode,seaOpen,seaPorts,seaPort,seaStep,seaSearch,seaSimplify,seaDensify,seaLength,seaRoutes,hav,clamp]; + const code='const SEA_PASS='+JSON.stringify(SEA_PASS)+';const COAST_LL='+JSON.stringify(COAST_LL)+';const CITY='+JSON.stringify(Object.fromEntries(CITIES.map(c=>[c.id,{lon:c.lon,lat:c.lat}])))+';const SEA_NAV={step:0.25,nx:1440,ny:641,rows:new Map(),edges:null,tiles:new Map(),fine:new Set(),routes:new Map(),ports:new Map(),pass:null,closed:new Set()};'+ + helpers.map(f=>'const '+f.name+'='+f.toString()+';').join('')+'onmessage=({data:{a,b,key,closed}})=>{try{SEA_NAV.closed=new Set(closed||[]);postMessage({key,routes:seaRoutes(a,b)});}catch(e){postMessage({key,error:String(e)});}};'; + const url=URL.createObjectURL(new Blob([code],{type:'text/javascript'})); + try{SEA_SURVEY.worker=new Worker(url);}finally{URL.revokeObjectURL(url);} + const refresh=key=>{if(!S)return;const survey=$('modalCard').querySelector('[data-sea-survey]');if(UI.pending&&!$('modal').hidden&&survey&&(!key||survey.dataset.seaSurvey===key))openLinkModal(UI.pending.a,UI.pending.b);renderPanel();renderLeft();if(!$('dash').hidden)renderDash();}; + SEA_SURVEY.worker.onmessage=({data})=>{SEA_SURVEY.pending.delete(data.key);if(data.error){SEA_SURVEY.failed=true;SEA_SURVEY.worker.terminate();SEA_SURVEY.worker=null;SEA_SURVEY.pending.clear();}else SEA_NAV.routes.set(data.key,data.routes);refresh(data.error?undefined:data.key);}; + SEA_SURVEY.worker.onerror=()=>{SEA_SURVEY.failed=true;SEA_SURVEY.worker.terminate();SEA_SURVEY.worker=null;SEA_SURVEY.pending.clear();refresh();}; + } + SEA_SURVEY.pending.add(key);const [from,to]=key.split('|');SEA_SURVEY.worker.postMessage({a:from,b:to,key,closed:[...SEA_NAV.closed]});return false; + }catch(e){SEA_SURVEY.failed=true;if(SEA_SURVEY.worker)SEA_SURVEY.worker.terminate();SEA_SURVEY.worker=null;SEA_SURVEY.pending.clear();return true;} +} +const seaSurveyAttr=(a,b)=>{seaSync();const k=seaKey(a,b);return SEA_SURVEY.pending.has(k)?`data-sea-survey="${k}"`:'';}; +// The ends sit on the cities' dots, which the map may nudge off their exact lon/lat (#305). +function seaMapPoints(pts,a,b){const out=[];for(const p of pts){const q=proj(...p);if(out.length)q[0]+=W*Math.round((out[out.length-1][0]-q[0])/W);out.push(q);} + const n=out.length,end=(i,c)=>{if(c)out[i]=[c.x+W*Math.round((out[i][0]-c.x)/W),c.y];};if(n>1){end(0,CITY[a]);end(n-1,CITY[b]);}return out;} + +// Designs pay for progressively tighter surveys; all use a feasible marine path. +const SEA_DESIGNS={standard:{n:N_('common.standard'),cost:1,time:1},optimized:{n:N_('common.optimized'),cost:3,time:1.3},express:{n:N_('common.low_latency'),cost:7,time:1.7}}; +function seaReference(a,b,express){ + const cs=cablesFor(a,b).filter(c=>express||(CAB[c.cid].lat||1)>=1); + return cs.sort((x,y)=>x.km*(express?(CAB[x.cid].lat||1):1)-y.km*(express?(CAB[y.cid].lat||1):1))[0]; +} +// Routing asks for link latency often; the cables on a route never change, so the express factor is worked out once. +const SEA_XF=new Map(); +function seaLatencyFactor(l){if(l.seaDesign==='optimized')return 1;if(l.seaDesign!=='express')return 1.1; + const k=CIDX[l.a]*4096+CIDX[l.b];let f=SEA_XF.get(k);if(f===undefined){const c=seaReference(l.a,l.b,true);SEA_XF.set(k,f=Math.min(0.9,c?(CAB[c.cid].lat||1):0.9));}return f;} +// The low-latency survey may also follow the corridor of the fastest cable already on this route, where that is shorter +// (only a cable that is in service: one cut by a crisis proves nothing): +// that cable proves the path, and it keeps the fastest design as fast as the fastest cable on the map. +function seaCorridor(a,b){const c=cablesOk(a,b).sort((x,y)=>x.km*(CAB[x.cid].lat||1)-y.km*(CAB[y.cid].lat||1))[0];if(!c)return null;const P=CAB[c.cid].pairs.find(([x,y])=>x===c.a&&y===c.b);if(!P)return null; + let ll=[[CITY[c.a].lon,CITY[c.a].lat],...P[2],[CITY[c.b].lon,CITY[c.b].lat]].map(q=>[seaLon(q[0]),q[1]]);if(c.a!==a)ll=ll.reverse(); + const pts=[ll[0]];for(let i=1;i{const up={terminal:!!UI.seaterminal,engineering:!!UI.seaengineering}; + for(const k of ['engineering','terminal'])if(up[k]&&!subHelps(km,k,up[subOther(k)]))up[k]=false;return up;}; +// Some pairs share a landmass and still have cables between them (Marseille–Singapore, Cairo–Palermo) (#67). +const seaCab=(a,b)=>isSub(a,b)||(landing(a)&&landing(b)&&cablesFor(a,b).length>0); +// What you get back for giving up your own subsea cable (#88): what you paid for it (design and upgrades included) +// if no optic can light it even with both upgrades, +// one still being laid returns most of the part not laid yet, a working one is yours for good. +const cabBack=l=>{if(!l||l.kind!=='df'||!l.own||!l.sub)return 0;const c=l.paid>0?l.paid:ownCabCost(l.km);if(!subNeed(l.km))return c; + if(l.ready>S.day){const tot=Math.max(1,l.ready-(l.day||0));return Math.round(c*0.75*Math.min(1,(l.ready-S.day)/tot));}return 0;}; +// Your own subsea cable is a Tier 1 privilege, or a sandbox toy (open gates). +// Your own subsea cable: after the Tier 1 win, from customer level CAB_LV (a big Tier 2 lays cables too, #300), or from +// day one as a Cable broker. +const CAB_LV=9,cabOpen=()=>!!S.won||gatesOpen()||broker()||lvl()>=CAB_LV; +function ownCabWhy(a,b){if(!seaCab(a,b))return tr('own_cable.this_route_is_on_land_build'); + if(!cabOpen())return tr('own_cable.your_own_subsea_cable_needs_level',{n:CAB_LV}); + for(const c of [a,b])if(!landing(c))return tr('own_cable.city_has_no_cable_landing_station',{city:CITY[c].name}); + if(cnCity(a)||cnCity(b))return tr('own_cable.nobody_gives_a_foreign_network_a'); + if(!seaReady(a,b))return tr('own_cable.surveying_a_sea_route'); + const routes=seaRoutes(a,b);if(!routes.length)return tr('own_cable.no_navigable_sea_route_connects'); + const km=Math.min(...routes.map(r=>r.km));if(!subNeed(km))return tr('own_cable.km_km_is_more_than_any',{km:km.toLocaleString(),max:Math.round(SUB_MAXKM()).toLocaleString()}); + return '';} +function ownCabTeaser(a,b){const why=ownCabWhy(a,b);return `
${btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_level_n',{n:CAB_LV}),'ownCab',{},cabOpen()&&!why?'pink':'ghost',!!why)}
${why&&cabOpen()?`

${esc(why)}

`:''}`;} +function ownCabBody(a,b,pop){const why=ownCabWhy(a,b);if(why)return `

${esc(why)}

${btn(tr('common.back'),'dfSrc',{v:'lease'},'ghost sm')}`; + const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',upgrades=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,upgrades),{km,cost,days}=q,lack=seaLack(km,upgrades),mo=ownCabMo(km),wt=subMaxTier(km),w=Math.round(waveMo(km,true,wt)*waveMarket(a,b,true).m),save=10*w*LT[4].g/LT[wt].g-mo,pay=save>0?Math.ceil(cost/save):0; + return `

${tr('own_cable.your_very_own_subsea_cable_a')}

+

${tr('common.cable_design')}

${Object.entries(SEA_DESIGNS).map(([v,D])=>{const o=seaQuote(a,b,v,upgrades);return ``;}).join('')}
+

${tr('common.submarine_transmission')}

${Object.entries(SUB_UPGRADES).map(([k,U])=>btn(`${tr(U.n)} ${upgrades[k]?'✓ · ':''}${fmt$(subUpgradeCost({km},k))} · ${tr('own_cable.n_days',{n:U.days})}`,'seaPackage',{k},upgrades[k]?'green sm':'ghost sm',!upgrades[k]&&!subHelps(km,k,upgrades[subOther(k)]))).join('')} + ${lack.length?`

${lack[0]==='design'?tr('own_cable.this_design_s_route_is_km',{km:km.toLocaleString()}):tr('own_cable.km_km_is_too_far_for',{km:km.toLocaleString(),what:lack.length>1?tr('own_cable.a_and_b',{a:tr(SUB_UPGRADES[lack[0]].n),b:tr(SUB_UPGRADES[lack[1]].n)}):tr(SUB_UPGRADES[lack[0]].n)})}

`:`

${tr('common.up_to_g_per_channel',{g:fmtG(submarineRate({a,b,km,kind:'df',own:true,sub:true,subterminal:upgrades.terminal?S.day:undefined,subengineering:upgrades.engineering?S.day:undefined}))})} · ${tr('common.better_terminals_and_optical_tuning')}

`} +
${tr('common.estimated_latency')}${tr('common.ms_ms_one_way',{ms:q.ms.toFixed(1)})}
+
${tr('common.route')}${tr('own_cable.km_km_of_seabed',{km:km.toLocaleString()})}
+
${tr('common.fiber_pairs')}${tr('own_cable.n_in_the_cable_the_first',{n:SUB_PAIRS_MAX})}
+
${tr('common.landing_stations')}${tr('own_cable.a_and_b',{a:CITY[a].name,b:CITY[b].name})}
+
${tr('common.build_time')}${tr('own_cable.about_n_days',{n:days})}
+
${tr('common.due_now')}${fmt$(cost+pop)}
${tr('common.monthly')}${tr('common.price_mo',{price:fmt$(mo)})}
+

${subCarrier(km)?`${tr('own_cable.a_leased_wave_wave_on_this',{wave:LT[wt].n,price:fmt$(w)})} ${pay?tr('own_cable.replace_16_tbps_of_them_and',{n:pay}):''} `:''}${tr('own_cable.cuts_still_happen_anchors_and_sharks')}

+
${btn(tr('own_cable.lay_the_cable_price',{price:fmt$(cost+pop)}),'orderCable',{},'pink big',S.cash0)}${btn(tr('common.back'),'dfSrc',{v:'lease'},'ghost')}
`;} diff --git a/src/game/95-modals/90-fiber-modals.js b/src/game/95-modals/90-fiber-modals.js new file mode 100644 index 0000000..2cba83d --- /dev/null +++ b/src/game/95-modals/90-fiber-modals.js @@ -0,0 +1,35 @@ +function dfModalBody(a,b,km,pop){ + if(seaCab(a,b)&&UI.dfSrc==='cable')return ownCabBody(a,b,pop); + const sea=!isSub(a,b)&&seaCab(a,b)?ownCabTeaser(a,b):''; + if(isSub(a,b)&&!subDfCable(a,b))return `

${tr('fiber_modals.nobody_sells_dark_fiber_on_a')}

`+ownCabTeaser(a,b); + const sc=isSub(a,b)?subDfCable(a,b):null;if(sc)km=sc.km; + if(uaePair(a,b))return `

${tr('fiber_modals.no_dark_fiber_inside_the_uae')}

`+sea; + if(landX(a,b)&&cnCity(a)===cnCity(b))return `

${tr('fiber_modals.nobody_sells_one_fiber_pair_across')}

`+sea; + if(!dfAllowed(a,b))return `

${tr('fiber_modals.dark_fiber_across_the_chinese_border')}

`+sea; + if(glassLvl()<2)return `

${tr('fiber_modals.dark_fiber_unlocks_at_customer_level')}

`+sea; + const src=UI.dfSrc==='build'&&!sc?'build':'lease',sys=DF_SYS[UI.dfSys]&&techOk('sys',UI.dfSys,DF_SYS[UI.dfSys].lvl)?UI.dfSys:'lite',amps=ampCount(km); + const up=(src==='build'?digCost(km):0)+sysCost(sys)+amps*AMP_COST+pop,mo=(src==='build'?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO; + const w=Math.round(waveMo(km,false,4)); + return `${S.ev.gulf>S.day&&gulfPair(a,b)?`

${tr('link_modal.the_borders_around_qatar_are_closed')} ${tr('link_panels.back_in_n_days',{n:S.ev.gulf-S.day})}

`:''}

${tr('fiber_modals.a_fiber_pair_of_your_own',{km:AMP_EVERY})}

+

${tr('common.the_glass')}

${btn(tr('fiber_modals.lease_an_iru_price_mo_ready_n',{price:fmt$(dfLeaseMo(km)),n:leadDays(IRU_DAYS)}),'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${sc?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_level_n',{n:CAB_LV}),'ownCab',{},'ghost',!!ownCabWhy(a,b)):btn(glassLvl()>=3?tr('fiber_modals.build_your_own_price_n_days',{price:fmt$(dfBuildCost(km)),n:dfBuildDays(km)}):tr('specialist.dig_your_own_as_a_pioneer',{price:fmt$(digCost(km)),n:dfBuildDays(km),p:Math.round((PIONEER-1)*100)}),'dfSrc',{v:'build'},src==='build'?'pink':'ghost')}${sea?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_level_n',{n:CAB_LV}),'ownCab',{},'ghost',!!ownCabWhy(a,b)):''}
${sc?`

${tr('fiber_modals.a_fiber_pair_on_cable_km',{cable:esc(CAB[sc.cid].name),km:sc.km.toLocaleString()})}

`:''} + ${src==='build'?`

${tr('fiber_modals.your_own_trench_almost_no_rent')}

`:''} +

${tr('common.line_system')}

${Object.keys(DF_SYS).map(k=>btn(`${DF_SYS[k].n} ${!techOk('sys',k,DF_SYS[k].lvl)?tr('fiber_modals.level_n',{n:DF_SYS[k].lvl}):fmt$(sysCost(k))}`,'dfSys',{v:k},sys===k?'pink':'ghost',!techOk('sys',k,DF_SYS[k].lvl))).join('')}
${Object.keys(DF_SYS).filter(k=>!techOk('sys',k,DF_SYS[k].lvl)&&demoCan(DF_SYS[k].lvl)).map(k=>`
${demoBtn('sys',k,DF_SYS[k].lvl,'','ghost sm')} ${DF_SYS[k].n}
`).join('')} +

${esc(DF_SYS[sys].blurb)} ${trn('fiber_modals.plus_n_in_line_amplifier_price',amps,{price:fmt$(AMP_COST),mo:fmt$(AMP_MO)})}

${km>reachOn(OPT.tp16.reach,!!sc)?`

${tr('fiber_modals.km_km_is_longer_than_any',{km:km.toLocaleString()})}

`:''} +
${tr('common.due_now')}${fmt$(up)}
${tr('common.monthly')}${tr('common.price_mo',{price:fmt$(mo)})}
+

${tr('fiber_modals.for_comparison_a_leased_1_6t',{price:fmt$(w)})}

+
${btn(`${src==='build'?tr('common.start_construction'):tr('fiber_modals.sign_the_iru')} ${fmt$(up)}`,'orderDf',{},'pink big',S.cash`; +} +function openVxcModal({from,to,prov}){ + let rows='';const row=(f,a,b)=>{const km=kmBetween(a,b),sub=isSub(a,b),pb=S.pops[b]?nniPort(b,f.id):null,remote=!S.pops[b]; + const label=remote?tr('fiber_modals.remote_peering_at_ix_discouraged',{ix:esc(CITY[b].ix)}):pb?tr('common.your_pop'):tr('fiber_modals.your_pop_needs_a_fabric_port'); + const freeA=nniCap(nniPort(a,f.id))-nniUsed(a,f.id),freeB=remote?1e9:pb?nniCap(pb)-nniUsed(b,f.id):0; + return `
${CITY[a].name} → ${CITY[b].name}
${label} · ${km.toLocaleString()} km${sub?' '+tr('common.subsea'):''}
+
${VXC.map((V,t)=>btn(`${V.n} ${tr('common.price_mo',{price:fmt$(vxcMo(km,sub,t))})}`,'buyVxc',{a,b,prov:f.id,t},'sm',(!remote&&!pb)||V.g>freeA||V.g>freeB||S.cash
`;}; + for(const f of FABS){if(prov&&f.id!==prov)continue; + if(from){if(!nniPort(from,f.id))continue;for(const b of f.cities){if(b===from)continue;if(!S.pops[b]&&!CITY[b].ix)continue;rows+=row(f,from,b);}} + else if(to&&f.cities.includes(to)){for(const a of Object.keys(S.pops))if(a!==to&&nniPort(a,f.id))rows+=row(f,a,to);}} + if(!rows){const fs=FABS.filter(f=>!to||f.cities.includes(to));rows=`

${tr('fiber_modals.you_need_a_fabric_port_at',{list:fs.map(f=>`${esc(f.name)} (${f.cities.filter(c=>S.pops[c]).map(c=>CITY[c].name).join(', ')||tr('fiber_modals.no_pop_of_yours_on_it')})`).join(', ')})}

`;} + openModal(`
${tr('fiber_modals.virtual_circuit_over_an_nni_fabric')}

${from?tr('fiber_modals.from_city',{city:CITY[from].name}):tr('fiber_modals.to_city',{city:CITY[to].name})}

+

${tr('fiber_modals.no_install_fee_live_in_minutes')}

${rows}`); +} + diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js new file mode 100644 index 0000000..529e81a --- /dev/null +++ b/src/game/95-modals/95-puzzles.js @@ -0,0 +1,165 @@ +/* ---------- puzzles: the card, the panels, the link picker, the results and the list ---------- */ +const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫',off:'📍'}; +function pzTwistTxt(t){if(t.k==='sub')return tr('puzzles.no_subsea_cables');return tr('puzzles.one_ring_through_every_pop');} +// The short version, for the puzzle list: what has to be carried, and the twists. +function pzDemTag(d){const t=[];const eye=d.dem.filter(f=>f.t==='eye'),l2=d.dem.filter(f=>f.t==='l2'); + if(eye.length)t.push(tr('puzzles.n_g_of_eyeballs',{n:fmtG(eye.reduce((a,f)=>a+f.g,0))}));if(l2.length)t.push(trn('puzzles.n_circuits',l2.length)); + if(d.dem.some(f=>f.ms))t.push(tr('puzzles.latency_caps'));if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} +// A cable carrying several of your waves is named on its own: cutting it takes them all. +const pzUnitName=u=>{const ls=S.links.filter(x=>pzUnit(x)===u),l=ls[0];return !l?'':l.cable&&ls.length>1?esc(CAB[l.cable].name):`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`;}; +// Each flow on the card: what it is, how much of it arrives, and a circuit's latency against its cap. +function pzFlowRow(x){const f=x.f,ok=x.full&&x.fast,u=f.g?Math.min(1,x.g/f.g):0; + const lat=f.ms?` · ${x.ms==null?tr('common.no_path'):x.ms.toFixed(1)+' ms'} / ${f.ms} ms`:''; + return `
${f.t==='l2'?'🔗':'👀'} ${esc(pzFlowName(f))}${f.be?` ${tr('puzzles.best_effort')}`:''}${fmtG(x.g)} / ${fmtG(f.g)}
${lat?`
${tr('puzzles.latency')}${lat}
`:''}${f.t==='l2'?pzRouteCtl(x.i):''}
`;} +// A circuit's path: the metrics, or the lowest latency. +function pzRouteCtl(i){const b=S.biz.find(x=>x.id===pzFlowId(i));if(!b)return '';return `
${['normal','fast'].map(m=>btn(RT[m],'pzRoute',{i,m},b.route===m?'pink sm':'ghost sm')).join('')}
`;} +// The three stars as three goals in plain words, in star order. The first one not met is the current one: it says what +// is wrong and what to do, and `look` is where "Show me" takes the map. mark: what the map rings in red (pzDrawMarks). +function pzGoals(e){const P=S.pz,cn=c=>esc(CITY[c].name),list=cs=>{const nm=cs.map(cn);try{return new Intl.ListFormat(LANG,{type:'conjunction'}).format(nm);}catch(e){return nm.join(', ');}}; + const g1={done:e.goal,t:tr('puzzles.goal_deliver')},g2={done:e.goal&&e.cheap,t:tr('puzzles.goal_budget'),v:P.budget?tr('puzzles.goal_x_of_y',{x:fmt$(e.spend),y:fmt$(P.budget)}):''},g3={done:e.goal&&e.n1,t:tr('puzzles.goal_n1')}; + const x=e.flows.slice().sort((a,b)=>(a.f.be?1:0)-(b.f.be?1:0)).find(x=>!(x.full&&x.fast)); + if(x){const f=x.f,got=fmtG(x.g),g=fmtG(f.g),eye=f.t==='eye',nm=esc(pzFlowName(f)); + g1.hint=eye?(x.g>0?tr('puzzles.hint_eye_short',{city:cn(f.a),got,g}):tr('puzzles.hint_eye_none',{city:cn(f.a)})) + :!x.full?(x.g>0?tr('puzzles.hint_l2_short',{name:nm,got,g}):tr('puzzles.hint_l2_none',{name:nm})):tr('puzzles.hint_l2_slow',{name:nm,ms:x.ms==null?'—':x.ms.toFixed(1),cap:f.ms}); + g1.look={c:f.a};g1.mark={cities:eye?[f.a]:[f.a,f.b]};} + else{const t=e.tw.find(t=>!t.ok);if(t)g1.hint=`${pzTwistTxt(t)}.`;} + if(e.goal&&!e.cheap)g2.hint=tr('puzzles.hint_over',{x:fmt$(e.spend-P.budget)}); + if(!P.budget)g2.v=tr('puzzles.free'); + if(e.goal&&e.cheap&&!e.n1&&e.worst){const w=e.worst,cs=[...new Set(w.lost.flatMap(q=>{const f=P.dem[q.i];return f.t==='l2'?[f.a,f.b]:[f.a];}))],l=S.links.find(q=>pzUnit(q)===w.u); + g3.hint=tr('puzzles.hint_cut',{where:pzUnitName(w.u),list:list(cs),g:fmtG(w.g)});g3.look={u:w.u};g3.mark={cities:cs,link:l&&l.id};} + else if(e.goal&&!e.cheap&&!e.n1&&e.worst){const w=e.worst,l=S.links.find(q=>pzUnit(q)===w.u);g3.mark={cities:[],link:l&&l.id};} + const gs=[g1,g2,g3],cur=gs.findIndex(g=>!g.done);if(cur>=0)gs[cur].cur=true;return gs;} +// One goal row: ⭐ met (each goal is a star), 👉 the one to work on (with its hint and Show me), a number while it waits its turn. +function pzGoalRow(g,i){const ic=g.done?'⭐':g.cur?'👉':`${i+1}`; + return `
${ic}${g.t}${g.v?`${g.v}`:''}
` + +(g.cur&&g.hint?`
${g.hint}${g.look?' '+btn(tr('puzzles.show_me'),'pzLook',g.look,'sm pzshow'):''}
`:'')+`
`;} +// A delivered eyeball flow is a chip; anything still short, a circuit or a latency cap keeps its full row. +const pzChip=x=>`👀 ${esc(CITY[x.f.a].name)} ${fmtG(x.f.g)} ✓`; +function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false;el.classList.toggle('ar',!!S.ar);UI._pzPhone=isPhone();if(S.ar){el.classList.toggle('dock',UI._pzPhone);(UI._pzPhone?arDock:arRender)(el);return;} + const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack); + // A phone gets fixed overlays that never scroll (97-puzzles-phone.js). + el.classList.toggle('dock',UI._pzPhone);if(UI._pzPhone){pzDock(el,e);return;} + const sp=fmt$(e.spend); + // The status bar stays at the top of the card, whatever scrolls: the puzzle, its stars, the money, undo and the menu. + let h=`
${pk?esc(pk.n):P.theme&&own(PZ_WK_THEMES,P.theme)?`${PZ_WK_THEMES[P.theme].i} ${tr('puzzles.weekly_puzzle')} · ${tr(PZ_WK_THEMES[P.theme].t)}`:tr('puzzles.weekly_puzzle')}

${esc(pzName(d||P))}

` + +`${btn('☰','puzzleMenu',{},'ghost sm')}
`; + const gs=pzGoals(e),cur=gs.find(g=>g.cur);UI.pzMark=!UI.pzMk&&cur&&cur.mark||null; + h+=`
${gs.map(pzGoalRow).join('')}
`; + if(d)h+=`

${esc(d.j)}

`;else if(P.wj)h+=`

${esc(pzTxt(P.wj))}

`; + if(P.src.length)h+=`
🗄️ ${tr('puzzles.content_lives_in_list',{list:P.src.map(c=>esc(CITY[c].name)).join(', ')})}
`; + const chip=x=>x.f.t==='eye'&&!x.f.ms&&!x.f.be&&x.full&&x.fast,rows=e.flows.filter(x=>!chip(x)).sort((a,b)=>(a.full&&a.fast?1:0)-(b.full&&b.fast?1:0)),chips=e.flows.filter(chip); + h+=`
${rows.map(pzFlowRow).join('')}${chips.length?`
${chips.map(pzChip).join('')}
`:''}
`; + // Cities to avoid cannot be built in at all, so they read as a rule, not as a box to tick. + for(const t of e.tw)h+=t.k==='avoid'?`
🚫 ${tr('puzzles.rule_not_via_list',{list:P.avoid.map(c=>esc(CITY[c].name)).join(', ')})}
`:`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; + if(!P.budget)h+=`
${tr('puzzles.spent_x',{x:sp})}${tr('puzzles.no_budget_star_on_the_house')}
`; + if(e.n1)h+=`
🛡 ${tr('puzzles.survives_any_single_cut_under_load')}
`; + if(UI.pzMk)h+=`
${btn('⏩ '+tr('puzzles.skip_the_monkey'),'pzMkSkip',{},'big')}
`;else if(e.goal)h+=`
${btn(tr('puzzles.let_the_chaos_monkey_loose'),'pzMonkey',{},'sm')}
`; + // Undo sits in the status bar; leaving is in ☰ with the puzzle list. + h+=`
${btn(tr('puzzles.reset'),'pzReset',{},'ghost sm',!S.links.length&&!Object.keys(S.pops).length)}${(UI.pzTop||0)>0&&(UI.pzTop||0)<3?btn(tr('puzzles.finish_here'),'pzFinish',{},'sm'):''}
`; + if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} +// Trenches on a pair get numbers, cables their names, so parallel links say where they run. +function pzTrench(l){if(l.cable)return esc(CAB[l.cable].name);const us=[...new Set(pairLinks(l.a,l.b).filter(x=>!x.cable).map(pzUnit))];return tr('puzzles.trench_n',{n:us.indexOf(pzUnit(l))+1});} +const pzLoadTxt=l=>`${fmtG(R.load[l.id]||0)} / ${fmtG(capOf(l))}`; +function pzPopSection(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1,G=RG[g],cap=nodeCap(c),ld=R.nodeLoad[c]||0,u=cap?ld/cap:0,pu=portsUsed(c),pm=portsMax(c),cur=pzRtCost(g,rt); + const dl=v=>(v>=0?'+':'−')+fmt$(Math.abs(v)); + let h=`

${tr('puzzles.your_pop')}

${rt>1?rt+' × ':''}${esc(G.n)}${tr('puzzles.price_per_year',{price:fmt$(cur)})}
+
${tr('puzzles.router_load')}${fmtG(ld)} / ${fmtG(cap)}
+
${tr('puzzles.ports')}${tr('puzzles.u_of_m_used',{u:fmtPorts(pu),m:pm})}
${tr('puzzles.biggest_wave')}${LT[G.maxLT].n}
+
${btn(tr('puzzles.add_a_router_cost',{cost:dl(pzRtCost(g,rt+1)-cur)}),'pzRtAdd',{city:c},'sm',rt>=RMAX)}${rt>1?btn(tr('puzzles.remove_a_router'),'pzRtRm',{city:c},'ghost sm'):''}
+

${tr('puzzles.router_model')}

`; + h+=PZ_RG.map(i=>{const M=RG[i],why=i===g?'':modelFits(c,i);return `
${esc(M.n)}${i===g?` ${tr('puzzles.installed')}`:''}
${tr('puzzles.model_facts',{cap:fmtG(M.cap),ports:M.ports,wave:LT[M.maxLT].n})}
${why?`
${esc(why)}
`:''}
${i===g?'':btn(dl(pzRtCost(i,rt)-cur),'pzRtModel',{city:c,g:i},'ghost sm',!!why)}
`;}).join(''); + return h;} +function pzPanel(sel){if(S.ar)return arPanel(sel);if(isPhone())return pzPanelPhone(sel);const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; + if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c],P=S.pz;if(!k)return ''; + const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):k==='off'?tr('puzzles.not_in_the_plan'):tr('puzzles.off_limits'); + let h=head(`${PZ_ICON[k]} ${eb}`,esc(C.name),p?`${tr('common.your_pop')}`:'')+'
'; + if(k==='avoid')return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

`; + // What this city sends or asks for. + const fl=P.dem.map((f,i)=>({f,i})).filter(({f})=>f.a===c||f.b===c),ev=pzEval(); + if(P.src.includes(c))h+=`

🗄️ ${tr('puzzles.the_content_origin_lives_here')}

`; + if(fl.length)h+=`
${fl.map(({i})=>pzFlowRow(ev.flows[i])).join('')}
`; + if(k==='off'&&!p)h+=`

${tr('puzzles.no_traffic_starts_or_ends_here')}

`; + if(!p)return h+`

${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(popMo(c))})}

${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}
`; + h+=pzPopSection(c); + // Every pair this POP has links on, with what each member carries, so a second link is never a guess. + const nb=[...new Set(S.links.filter(l=>l.a===c||l.b===c).map(l=>l.a===c?l.b:l.a))]; + h+=`

${tr('common.links')}

`; + if(!nb.length)h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

`; + for(const x of nb){const ls=pairLinks(c,x),ld=ls.reduce((a,l)=>a+(R.load[l.id]||0),0),cp=ls.filter(l=>!linkDown(l)).reduce((a,l)=>a+capOf(l),0); + h+=`
${esc(CITY[x].name)} · ${groupLabel(ls,ls)}${fmtG(ld)} / ${fmtG(cp)}
${ls.map(l=>`
${capName(l)} · ${pzTrench(l)}${l.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(l)} · ${linkLat(l).toFixed(1)} ms
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`).join('')}
`;} + const others=[...P.cities,...P.via].filter(x=>x!==c); + h+=`

${tr('puzzles.lease_a_wave_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}

${tr('puzzles.or_drag_to_any_city_on_the_map')}

`; + h+=`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`; + return h+'
';} + const l=S.links.find(x=>x.id===sel.id);if(!l)return '';const pl=pairLinks(l.a,l.b); + let h=head(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`${capName(l)}${l.km.toLocaleString()} km${linkLat(l).toFixed(1)} ms${tr('puzzles.price_per_year',{price:fmt$(l.mo*PZ_YEAR)})}`)+'
'; + // What it carries now: each circuit by name, the eyeball traffic by where it is going. + {const rec=R.ef[edgeKey(l)],u=capOf(l)?(R.load[l.id]||0)/capOf(l):0;h+=`
${tr('puzzles.this_link')}${pzLoadTxt(l)}
`; + if(rec){const rows=[];let l2=0;S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){rows.push([pzFlowName(f),v]);}}); + const byc={};for(const k in rec.dst)byc[k]=rec.dst[k];S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){byc[f.b]=(byc[f.b]||0)-v;l2+=v;}}); + for(const k in byc)if(byc[k]>0.01)rows.push([tr('puzzles.flow_eyeballs_in_city',{city:CITY[k].name}),byc[k]]); + if(rows.length)h+=`

${pl.length>1?tr('puzzles.carrying_on_this_pair',{n:pl.length}):tr('puzzles.carrying')}

`+rows.map(([n,v])=>`
${esc(n)}${fmtG(v)}
`).join('');void l2;}} + if(pl.length>1)h+=`

${tr('puzzles.n_links_on_this_pair',{n:pl.length,what:groupLabel(pl,pl)})}

`+pl.map(x=>`
${capName(x)} · ${pzTrench(x)}${x.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(x)}
${x===l?'':btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join(''); + h+=`

${tr('puzzles.size')}

${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=pzWaveWhy(l.a,l.b,i,r);return btn(`${LT[i].n} ${why?esc(why):tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
`; + h+=`

${tr('puzzles.add_another_link_here')}

${btn(l.cable?tr('puzzles.another_wave_on_this_cable'):tr('puzzles.same_trench_cheaper'),'pzAddPar',{id:l.id,div:0},'sm')}${btn(l.cable?tr('puzzles.a_different_route'):tr('puzzles.a_diverse_route'),'pzAddPar',{id:l.id,div:1},'pink sm')}
`; + h+=metricSection(l)+linkCheckControl(l); + return h+`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} +// The link picker: overland or one of the real cables between the two cities, and a size. Prices are for a year. +function pzLinkModal(a,b,keep){if(S.ar)return arLinkModal(a,b,keep);const kb=pzKind(b); + if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.not_a_city_you_can_build_in'),'bad');sfx('err');return;} + if(!keep){UI.pzVia=null;UI.pzDiv=true;UI.pzTrench=null;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz; + const head=`
${kmBetween(a,b).toLocaleString()} km

${esc(CITY[a].name)} → ${esc(CITY[b].name)}

`; + if(!rs.length){openModal(head+`

${tr('puzzles.no_cable_lands_in_both_try',{a:esc(CITY[a].name),b:esc(CITY[b].name)})}

`);return;} + const r=rs.find(x=>x.via===UI.pzVia)||rs.find(x=>!(P.noSub&&x.sub))||rs[0];UI.pzVia=r.via; + const pl=pairLinks(a,b),land=!r.sub&&pl.some(l=>!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b); + let h=head; + if(pl.length)h+=`

${tr('puzzles.already_here_list',{list:groupLabel(pl,pl)+' · '+[...new Set(pl.map(pzTrench))].join(', ')})}

`; + h+=`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}
`; + if(P.noSub&&r.sub)h+=`

${tr('puzzles.the_sharks_say_no')}

`; + if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}

`; + if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_the_monkey'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_snip_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; + if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; + const full=[a,b].filter(c=>!pzPortsFree(c));if(full.length)h+=`

${tr('puzzles.no_free_ports_in_list',{list:full.map(c=>esc(CITY[c].name)).join(', ')})}

`; + h+=`
${PZ_TIERS.map(i=>{const why=pzWaveWhy(a,b,i,r),c=pzLinkCost(r,i,div)+pop;return ``;}).join('')}
`; + openModal(h);} +// ---------- results ---------- +function pzLine(e){return e.stars>=3?tr('puzzles.a_chaos_monkey_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_monkey'):!e.n1?tr('puzzles.one_monkey_away_from_a_very'):tr('puzzles.rock_solid_and_gold_plated_the');} +// Stars still to win in this puzzle's pack, from the progress just saved. +function pzPackLeft(P){const d=pzDef(P.id);if(!d)return null;const p=pzLoad(),xs=PZ.filter(x=>x.pack===d.pack);return xs.length*3-xs.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);} +function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF'];let h=''; + for(let i=0;i<28;i++)h+=``; + return ``;} +function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left=pzPackLeft(P),done=e.stars>=3; + const row=(ok,l,v)=>`
${ok?'⭐':'☆'} ${l}${v}
`; + const stars=[0,1,2].map(i=>`⭐`).join(''); + openModal(`
${e.stars>=3?pzConfetti():''}
${done?tr('puzzles.puzzle_solved'):tr('puzzles.your_stars_so_far')}

${esc(pzName(pzDef(P.id)||P))}

+
${stars}

${pzLine(e)}

${left==null?'':`

${left?trn('puzzles.n_stars_left_in_this_pack',left):tr('puzzles.every_star_in_this_pack_is')}

`} + ${row(true,tr('puzzles.delivered'),tr('puzzles.every_bit_arrives'))}${row(e.cheap,tr('puzzles.budget'),P.budget?tr('puzzles.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(P.budget)}):tr('puzzles.on_the_house'))}${row(e.n1,'N-1',e.n1?tr('puzzles.survives_any_single_cut_under_load'):tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(e.worst.u),g:fmtG(e.worst.g)}))} +
${nx?btn(tr('puzzles.next_puzzle')+(done?' →':''),'pzStart',{id:nx.id},'pink big pznext'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big pznext')}${!done?btn(tr('puzzles.retry_for_3_stars'),'pzRetry',{},''):''}${btn(tr('common.share_2cd9'),'pzShare',{},done?'ghost':'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`); + // Three stars: Next is the one big obvious tap (and the keyboard's default). + if(done){const b=document.querySelector('#modalCard .pznext');if(b)try{b.focus({preventScroll:true});}catch(_){}} + for(let i=prev;i{sfx('star');haptic(15);},Math.max(0,i-prev)*450+150); + if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);} +function pzCheer(e,prev){toast(`${'⭐'.repeat(e.stars)}${'☆'.repeat(3-e.stars)}
${pzLine(e)}`,'goal');for(let i=prev;i{sfx('star');haptic(15);},(i-prev)*450+150);} +// ---------- the list ---------- +// The weekly row: the published puzzle once it has come (or the seeded one), its countdown and the streak. +function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=pzWkRec(p,w),st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzDemTag(w); + return `
📅 ${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})}${wr?'':` ${tr('puzzles.new_this_sunday')}`}
+
${load?tr('puzzles.loading_this_week_s_puzzle'):`${T?T.i+' ':''}${esc(pzName(w))}`} ${wr?`${pzStarStr(wr.st)}`:''}
${w.wj?`
${esc(pzTxt(w.wj))}
`:''} +
${pzCities(w).map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · '+tg.join(' · ')+'':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}
+
${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}
⏳ ${pzWkNext(Date.now())}
${btn(tr('common.play'),'pzWeekly',{},wr&&wr.st>=3?'ghost':'pink',load)}
`;} +function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot); + let h=`
${tr('puzzles.puzzles')}

${tr('puzzles.small_networks_real_traffic')}

+

${tr('puzzles.no_clock_no_bills_real_traffic')}

`; + // Once, after the puzzles got traffic: the old stars are kept on the wall, the new set starts at zero. + if(p.old&&!p.noted){h+=`
🖼️ ${tr('puzzles.puzzles_got_traffic_note',{n:p.old})}
`;p.noted=1;pzStore(p);} + if(pzOn())h+=`
${isPhone()&&!S.ar?btn(tr('puzzles.reset'),'pzReset',{},'ghost',!S.links.length&&!Object.keys(S.pops).length):''}${(UI.pzTop||0)>0&&(UI.pzTop||0)<3?btn(tr('puzzles.finish_here'),'pzFinish',{},'sm'):''}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; + h+=arMenuRows(); + h+=pzWkRow(); + // The packs' own total, right above them: it is what unlocks the next pack (#231). Runs and weeklies count their own. + h+=`
${tr('puzzles.stars_from_the_packs')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}${p.old?`
🖼️ ${tr('puzzles.framed_n_stars_from_the_old',{n:p.old})}
`:''}
`; + for(const pk of PZ_PACKS){const open=tot>=pk.need,got=PZ.filter(x=>x.pack===pk.id).reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0),n=PZ.filter(x=>x.pack===pk.id).length; + h+=`

${open?'':'🔒 '}${esc(pk.n)} ⭐ ${got}/${n*3}

${open?esc(pk.d):tr('puzzles.unlocks_at_n_stars',{n:pk.need})}

`; + for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzDemTag(d); + h+=`
${esc(d.n)} ${pzStarStr(r?r.st:0)}
${esc(d.j)}
${pzCities(d).map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · '+tg.join(' · ')+'':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}
${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}
`;}} + openModal(h);} diff --git a/src/game/95-modals/96-architect.js b/src/game/95-modals/96-architect.js new file mode 100644 index 0000000..42412e3 --- /dev/null +++ b/src/game/95-modals/96-architect.js @@ -0,0 +1,81 @@ +/* ---------- architect runs (prototype): the card, the panels, the link picker, the results and the list rows ---------- */ +const arDarkNow=c=>!!((UI.arShow&&UI.arShow.dark.includes(c))||(UI.arFail&&UI.arFail.dark.includes(c))); +const arHide=c=>arOn()&&!arKind(c); +function arRender(el){const A=S.ar,run=arRun(),b=arBrief(),e=arEval(),sh=UI.arShow,f=UI.arFail,n=run.briefs.length,nm=c=>esc(CITY[c].name); + let h=`
🏗️ ${esc(run.n)}

${tr('architect.brief_n_of_m',{n:A.bi+1,m:n})}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; + h+=`
${run.briefs.map((x,i)=>``).join('')}
`; + h+=`

${esc(b.t)}

`; + h+=`
${e.sites.map(s=>`${s.hq?'🏠':s.gold?'🚨':s.ok?'✓':'○'} ${nm(s.c)}${s.hq?'':` ${s.ok&&!s.full?arG(s.got)+'/':''}${arG(s.dem)}`}`).join('')}
`; + if(A.gold.length)h+=`
🚨 ${tr('architect.gold_must_survive',{list:A.gold.map(nm).join(', ')})}
`; + for(const r of e.rings)h+=`
💍 ${tr('architect.ring_list',{list:r.cs.map(nm).join(' · ')})} ${r.ok?'✓':''}
`; + if(e.lat)h+=`
⏱ ${nm(e.lat.a)} ⇄ ${nm(e.lat.b)}: ${e.lat.ms==null?tr('common.no_path'):e.lat.ms.toFixed(1)+' ms'} / ${e.lat.cap} ms
`; + for(const c of S.pz.avoid)h+=`
🚫 ${tr('architect.closed_city',{city:nm(c)})}
`; + const T=e.tubes;if(T.max!=null)h+=`
${tr('architect.tubes_this_brief')}${'●'.repeat(Math.min(T.u,T.max))}${'○'.repeat(Math.max(0,T.max-T.u))}${T.over?` ${tr('architect.n_over_plan',{n:T.over})}`:''}
`; + h+=`
${tr('architect.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(e.budget)})}${e.cheap?'⭐':'☆'}
${A.sunk?`
${tr('architect.x_paid_for_and_gone',{x:fmt$(A.sunk)})}
`:''}
`; + if(sh)h+=`
🐒 ${tr('architect.cut_n_of_m',{n:sh.i+1,m:sh.units.length})}${sh.dark.length?`
${tr('architect.dark_list',{list:sh.dark.map(nm).join(', ')})}`:''}
`; + else if(f)h+=`
💥 ${f.gold.length?tr('architect.cut_on_x_cuts_off_y',{x:pzUnitName(f.u),y:f.gold.map(nm).join(', ')}):tr('architect.cut_on_x_no_room',{x:pzUnitName(f.u),y:f.short.map(nm).join(', ')})}
${tr('architect.fix_it_and_send_it_again')}
`; + else if(e.passed)h+=`
✅ ${tr('architect.review_passed')}
`; + else if(!e.ready)h+=`
${esc(e.why)}
`; + else h+=`
${A.gold.length?tr('architect.ready_send_the_backhoe'):tr('architect.ready_no_gold_yet')}
`; + const main=sh?btn('⏩ '+tr('architect.skip'),'pzArSkip',{},'big'):e.passed?btn(arLast()?tr('architect.finish_the_run')+' 🎉':tr('architect.next_brief')+' →','pzArNext',{},'pink big'):btn('▶ '+tr('architect.send_the_backhoe'),'pzArGo',{},'pink big',!e.ready); + h+=`
${main}${btn('↶ '+tr('puzzles.undo'),'pzUndo',{},'ghost sm',!!sh||!(UI.pzHist&&UI.pzHist.length))}${btn(tr('architect.reset_brief'),'pzReset',{},'ghost sm',!!sh)}${btn(UI.arAll?tr('architect.hide_other_cities'):tr('architect.show_all_cities'),'pzArAll',{},'ghost sm')}
`; + if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} +function arPanel(sel){const A=S.ar,head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; + const old=x=>(x.br|0)${tr('architect.built_in_an_earlier_brief')}

`:''; + if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c];if(!k)return ''; + const eb=c===A.hq?'🏠 '+tr('architect.hq'):A.gold.includes(c)?'🚨 '+tr('architect.gold_site'):k==='goal'?'🎯 '+tr('architect.site'):k==='via'?'🪨 '+tr('puzzles.stepping_stone_optional'):k==='avoid'?'🚫 '+tr('architect.closed'):'📍 '+tr('puzzles.not_in_the_plan'); + let h=head(eb,esc(CITY[c].name),p?`${tr('common.your_pop')}${tr('puzzles.price_per_year',{price:fmt$(arPopCost(c))})}`:'')+'
'; + if(c===A.hq)h+=`

${tr('architect.hq_lead')}

`;else if(A.gold.includes(c))h+=`

${tr('architect.gold_lead')}

`; + if(k==='avoid'&&!p)return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

`; + if(!p){const pc=pzPopCost(c)+pzRtCost(0,1);return h+`
${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pc)}),'pzPop',{city:c},'pink big')}

${tr('architect.or_drag_a_tube_here')}

`;} + if(k==='avoid')h+=`

${tr('architect.closed_lead')}

`; + {const G=RG[p.rgen||0],cap=nodeCap(c),ld=R.nodeLoad[c]||0;h+=`
${tr('architect.router_x',{x:esc(G.n)})}${pzRtCost(p.rgen||0,1)?tr('puzzles.price_per_year',{price:fmt$(pzRtCost(p.rgen||0,1))}):tr('puzzles.free')}
${tr('architect.router_follows')} · ${fmtG(ld)} / ${fmtG(cap)}
`;} + const ls=S.links.filter(l=>l.a===c||l.b===c); + h+=`

${tr('common.links')}

`; + if(!ls.length)h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

`; + for(const l of ls){const o=l.a===c?l.b:l.a;h+=`
→ ${esc(CITY[o].name)}
${pzTrench(l)} · ${linkLat(l).toFixed(1)} ms · ${tr('puzzles.price_per_year',{price:fmt$(arLinkCost(l))})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + if(k!=='avoid'){const others=[...S.pz.cities,...S.pz.via].filter(x=>x!==c&&!S.pz.avoid.includes(x));if(others.length)h+=`

${tr('architect.lay_a_tube_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}
`;} + if(c!==A.hq)h+=old(p)+`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`; + return h+'
';} + const l=S.links.find(x=>x.id===sel.id);if(!l)return ''; + let h=head(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`${l.km.toLocaleString()} km${linkLat(l).toFixed(1)} ms${tr('puzzles.price_per_year',{price:fmt$(arLinkCost(l))})}`)+'
'; + h+=`

${pzTrench(l)}${l.cable?' · '+esc(CAB[l.cable].blurb):''}

`; + {const u=capOf(l)?(R.load[l.id]||0)/capOf(l):0;h+=`
${tr('puzzles.this_link')}${pzLoadTxt(l)}
`;} + h+=`

${tr('architect.size')}

${AR_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=subWaveWhy(i,l.km,l.sub);return btn(`${LT[i].n} ${why?esc(why):tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
${arAge(l)${tr('architect.changing_an_old_tube')}

`:''}`; + h+=`

${tr('puzzles.add_another_link_here')}

${btn(l.cable?tr('puzzles.another_wave_on_this_cable'):tr('puzzles.same_trench_cheaper'),'pzAddPar',{id:l.id,div:0},'sm')}${btn(l.cable?tr('puzzles.a_different_route'):tr('puzzles.a_diverse_route'),'pzAddPar',{id:l.id,div:1},'pink sm')}
`; + return h+old(l)+`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} +// The tube picker: overland or one of the real cables, a diverse trench when there is one already, and one price. +function arLinkModal(a,b,keep){const kb=pzKind(b); + if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.not_a_city_you_can_build_in'),'bad');sfx('err');return;} + if(!keep){UI.pzVia=null;UI.pzDiv=true;UI.pzTrench=null;}UI.pending={a,b};const rs=pzRoutes(a,b),cost1=x=>pzLinkCost(x,AR_TIER,false); + const head=`
${kmBetween(a,b).toLocaleString()} km

${esc(CITY[a].name)} → ${esc(CITY[b].name)}

`; + if(!rs.length){openModal(head+`

${tr('puzzles.no_cable_lands_in_both_try',{a:esc(CITY[a].name),b:esc(CITY[b].name)})}

`);return;} + const r=rs.find(x=>x.via===UI.pzVia)||rs.slice().sort((x,y)=>cost1(x)-cost1(y))[0];UI.pzVia=r.via; + const pl=pairLinks(a,b),land=!r.sub&&pl.some(l=>!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b)+pzRtCost(0,1); + let h=head; + if(pl.length)h+=`

${tr('puzzles.already_here_list',{list:[...new Set(pl.map(pzTrench))].join(', ')})}

`; + h+=`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms · ${tr('architect.from_x',{x:fmt$(pzLinkCost(x,0,false))})}${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost')).join('')}
`; + if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}

`; + if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_the_monkey'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_snip_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; + if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; + const T=arTubes();if(T.max!=null&&T.u>=T.max)h+=`

${tr('architect.this_tube_is_over_the_plan')}

`; + h+=`

${tr('architect.size')}

${AR_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),rt=arRouterDelta(a,i)+(S.pops[b]?arRouterDelta(b,i):arRouterDelta(b,i)),c=pzLinkCost(r,i,div); + return ``;}).join('')}
`; + openModal(h);} +// ---------- results ---------- +const arLine=st=>st>=3?tr('architect.line_3'):st===2?tr('architect.line_2'):tr('architect.line_1'); +function arResults(done){const A=S.ar,run=arRun(),sp=arSpend(),br=done?run.briefs.length:A.bi,st=done?arStars(sp):0,sh=arShape();arRecord(st,br,sp); + const ri=AR_RUNS.indexOf(run),nx=ri>=0?AR_RUNS[ri+1]||null:null,stars=[0,1,2].map(i=>`⭐`).join(''); + openModal(`
${st>=3?pzConfetti():''}
🏗️ ${done?tr('architect.run_complete'):tr('architect.run_over')}

${esc(run.n)}

+
${stars}

${done?arLine(st):tr('architect.the_cfo_pulled_the_plug')}

+
${done?'⭐':'☆'} ${tr('architect.briefs_done')}${br} / ${run.briefs.length}
+
${arOver()?'☆':'⭐'} ${tr('architect.tubes_over_plan')}${arOver()}
+
${sp<=run.budget+1e-6?'⭐':'☆'} ${tr('architect.spent')}${fmt$(sp)} / ${fmt$(run.budget)}
+ ${sh?`
${tr('architect.your_shape')}${sh.i} ${esc(sh.n)}
`:''} +
${nx&&done?btn(tr('architect.next_run')+' →','pzArStart',{id:nx.id},'pink big'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big')}${btn(tr('architect.try_again'),'pzRetry',{},'')}${done?btn(tr('common.share_2cd9'),'pzShare',{},'ghost'):btn(tr('architect.keep_going'),'closeModal',{},'ghost')}
`); + for(let i=0;i{sfx('star');haptic(15);},i*450+150);if(st>=3)setTimeout(()=>sfx('fanfare'),3*450+250);} +// ---------- the list ---------- +function arMenuRows(){const p=arLoad(),got=AR_RUNS.reduce((a,r)=>a+((p.runs[r.id]||{}).st|0),0);let h=`

🏗️ ${tr('architect.architect_runs')} ⭐ ${got}/${AR_RUNS.length*3} ${tr('architect.new')}

${tr('architect.runs_lead')}

`;arWkEnsure();h+=arWkRow(); + for(const r of AR_RUNS){const x=p.runs[r.id]; + h+=`
${esc(r.n)} ${pzStarStr(x?x.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)}${' · '+tr('puzzles.budget_x',{x:fmt$(r.budget)})}${x&&x.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(x.sp)}):x&&x.br?' · '+tr('architect.best_n_briefs',{n:x.br}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},x&&x.st>=3?'ghost':'pink')}
`;} + return h;} diff --git a/src/game/95-modals/97-puzzles-phone.js b/src/game/95-modals/97-puzzles-phone.js new file mode 100644 index 0000000..53a59f8 --- /dev/null +++ b/src/game/95-modals/97-puzzles-phone.js @@ -0,0 +1,95 @@ +/* ---------- puzzles on a phone: fixed overlays that never scroll ---------- + A bar pinned at the top says how the puzzle stands (its name, the three stars, the money, undo and the menu), the one + thing to do next and what each flow gets, as chips. A city or a link opens a card at the bottom whose content is + split into tabs, so each tab fits on the screen. Desktop keeps the side card (pzRender, pzPanel). */ +// A rate in a few characters, for the chips: 30G, 2.5G, 1.2T. +const pzG=g=>g>=1000?(g/1000).toFixed(g>=10000?0:1)+'T':g>=10||g===0?Math.round(g)+'G':g.toFixed(1)+'G'; +// One flow as a chip: what it is, how much of it arrives, a circuit's latency against its cap. Tapping it shows the city. +function pzFlowChip(x){const f=x.f,ok=x.full&&x.fast,part=x.g>0&&!ok; + const lat=f.ms?` · ${x.ms==null?'—':x.ms.toFixed(1)}/${f.ms} ms`:''; + return ``;} +// The rules of this puzzle as chips: the content's home, the cities to avoid, no subsea cables, the ring. +function pzRuleChips(e){const P=S.pz;let h=''; + if(P.src.length)h+=`🗄️ ${P.src.map(c=>esc(CITY[c].name)).join(', ')}`; + for(const t of e.tw)h+=t.k==='avoid'?`🚫 ${P.avoid.map(c=>esc(CITY[c].name)).join(', ')}`:`${t.ok?'✓':'✗'} ${pzTwistTxt(t)}`; + return h;} +function pzDock(el,e){const P=S.pz,d=pzDef(P.id),gs=pzGoals(e),cur=gs.find(g=>g.cur);UI.pzMark=!UI.pzMk&&cur&&cur.mark||null; + const stars=gs.map((g,i)=>`${g.done?'⭐':i+1}`).join(''); + const bud=P.budget?`${fmt$(e.spend)} / ${fmt$(P.budget)}`:`${tr('puzzles.free')}`; + let h=`
${esc(pzName(d||P))}${stars}${bud}` + +`${btn('☰','puzzleMenu',{},'ghost sm')}
`; + // The one thing to do: the goal being worked on, what is wrong and Show me; the monkey once the traffic arrives. + const act=UI.pzMk?btn('⏩ '+tr('puzzles.skip_the_monkey'),'pzMkSkip',{},'sm'):e.goal?btn('🐒 '+tr('puzzles.let_the_chaos_monkey_loose'),'pzMonkey',{},'ghost sm'):''; + if(cur)h+=`
👉
${cur.t}${cur.hint?` ${cur.hint}`:''}
${cur.look?btn(tr('puzzles.show_me'),'pzLook',cur.look,'sm pzshow'):''}${act}
`; + else h+=`
🛡
${tr('puzzles.survives_any_single_cut_under_load')}
${act}
`; + h+=`
${e.flows.map(pzFlowChip).join('')}${pzRuleChips(e)}
`; + if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} +// The bar's height, for what must sit under it (toasts) or stop short of it (the card): it changes with its content and +// when a card opens, so it is watched rather than measured after each render. +try{new ResizeObserver(()=>{const H=$('pzBox').offsetHeight||0;document.documentElement.style.setProperty('--pzdock',H+'px');}).observe($('pzBox'));}catch(e){} +// An architect run on a phone: the same bar. The brief, its sites and rules as chips, and the review with its one button. +function arDock(el){const A=S.ar,run=arRun(),b=arBrief(),e=arEval(),sh=UI.arShow,f=UI.arFail,n=run.briefs.length,nm=c=>esc(CITY[c].name),T=e.tubes; + let h=`
🏗️ ${tr('architect.brief_n_of_m',{n:A.bi+1,m:n})}${fmt$(e.spend)} / ${fmt$(e.budget)} ${e.cheap?'⭐':'☆'}` + +`${btn('☰','puzzleMenu',{},'ghost sm')}
`; + h+=`
${run.briefs.map((x,i)=>``).join('')}

${esc(b.t)}

`; + let ch=e.sites.map(s=>`${s.hq?'🏠':s.gold?'🚨':s.ok?'✓':'○'} ${nm(s.c)}${s.hq?'':` ${s.ok&&!s.full?arG(s.got)+'/':''}${arG(s.dem)}`}`).join(''); + for(const r of e.rings)ch+=`💍 ${r.cs.map(nm).join(' · ')}`; + if(e.lat)ch+=`⏱ ${e.lat.ms==null?'—':e.lat.ms.toFixed(1)}/${e.lat.cap} ms`; + for(const c of S.pz.avoid)ch+=`🚫 ${nm(c)}`; + if(T.max!=null)ch+=`${tr('architect.tubes_this_brief')} ${T.u}/${T.max}`; + h+=`
${ch}
`; + const rev=sh?`🐒 ${tr('architect.cut_n_of_m',{n:sh.i+1,m:sh.units.length})}${sh.dark.length?' · '+sh.dark.map(nm).join(', '):''}`:f?`💥 ${f.gold.length?tr('architect.cut_on_x_cuts_off_y',{x:pzUnitName(f.u),y:f.gold.map(nm).join(', ')}):tr('architect.cut_on_x_no_room',{x:pzUnitName(f.u),y:f.short.map(nm).join(', ')})}` + :e.passed?`✅ ${tr('architect.review_passed')}`:!e.ready?esc(e.why):A.gold.length?tr('architect.ready_send_the_backhoe'):tr('architect.ready_no_gold_yet'); + const main=sh?btn('⏩ '+tr('architect.skip'),'pzArSkip',{},'sm'):e.passed?btn(arLast()?tr('architect.finish_the_run')+' 🎉':tr('architect.next_brief')+' →','pzArNext',{},'pink sm'):btn('▶ '+tr('architect.send_the_backhoe'),'pzArGo',{},'pink sm',!e.ready); + h+=`
${rev}${A.gold.length&&!sh&&!f&&!e.passed?`
🚨 ${tr('architect.gold_must_survive',{list:A.gold.map(nm).join(', ')})}`:''}
${main}
`; + if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} +// The tabs of a card; the one shown is kept per kind of card (city or link) while the puzzle runs. +const pzTabs=(kind,tabs,cur)=>``; +const pzTabOf=(kind,tabs,def)=>{const t=(UI.pzTab||{})[kind];return tabs.some(([k])=>k===t)?t:def;}; +// The card's head in two short lines: what it is (and whether it is yours) above the name, the facts beside the name. +const pzHead=(eb,name,facts)=>`
${eb}

${name}${facts?` ${facts}`:''}

`; +function pzPanelPhone(sel){ + if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c],P=S.pz;if(!k)return ''; + const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):k==='off'?tr('puzzles.not_in_the_plan'):tr('puzzles.off_limits'); + let h=pzHead(`${PZ_ICON[k]} ${eb}${p?` · ${tr('common.your_pop')}`:''}`,esc(C.name),'')+'
'; + if(k==='avoid')return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

`; + const ev=pzEval(),fl=ev.flows.filter(x=>x.f.a===c||x.f.b===c); + const chips=fl.length||P.src.includes(c)?`
${P.src.includes(c)?`🗄️ ${tr('puzzles.the_content_origin_lives_here')}`:''}${fl.map(pzFlowChip).join('')}
`:''; + if(!p)return h+chips+(k==='off'?`

${tr('puzzles.no_traffic_starts_or_ends_here')}

`:'')+`
${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}

${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(popMo(c))})}

`; + const nb=[...new Set(S.links.filter(l=>l.a===c||l.b===c).map(l=>l.a===c?l.b:l.a))]; + const tabs=[['links',tr('common.links')],['router',tr('puzzles.router_model')]];if(fl.length)tabs.push(['traffic',tr('puzzles.carrying')]); + const t=pzTabOf('city',tabs,'links');h+=pzTabs('city',tabs,t); + if(t==='links'){ + if(!nb.length)h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

`; + for(const x of nb){const ls=pairLinks(c,x),ld=ls.reduce((a,l)=>a+(R.load[l.id]||0),0),cp=ls.filter(l=>!linkDown(l)).reduce((a,l)=>a+capOf(l),0); + h+=`
→ ${esc(CITY[x].name)} ${groupLabel(ls,ls)} · ${pzG(ld)}/${pzG(cp)}
${btn(tr('common.open'),'selLink',{id:ls[0].id},'ghost sm')}
`;} + const others=[...P.cities,...P.via].filter(x=>x!==c); + h+=`

${tr('puzzles.lease_a_wave_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}
`; + h+=`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`;} + else if(t==='router'){const g=p.rgen||0,rt=p.routers||1,G=RG[g],cap=nodeCap(c),ld=R.nodeLoad[c]||0,u=cap?ld/cap:0,cur=pzRtCost(g,rt),dl=v=>(v>=0?'+':'−')+fmt$(Math.abs(v)); + h+=`
${rt>1?rt+' × ':''}${esc(G.n)} · ${tr('puzzles.u_of_m_used',{u:fmtPorts(portsUsed(c)),m:portsMax(c)})}${pzG(ld)}/${pzG(cap)}
`; + h+=`
${btn(tr('puzzles.add_a_router_cost',{cost:dl(pzRtCost(g,rt+1)-cur)}),'pzRtAdd',{city:c},'sm',rt>=RMAX)}${rt>1?btn(tr('puzzles.remove_a_router'),'pzRtRm',{city:c},'ghost sm'):''}
`; + // Every model at once, two to a row: what it can do, or why it does not fit; its price against the installed one. + h+=`
${PZ_RG.map(i=>{const M=RG[i],why=i===g?'':modelFits(c,i); + return ``;}).join('')}
`;} + else{if(P.src.includes(c))h+=`

🗄️ ${tr('puzzles.the_content_origin_lives_here')}

`;h+=`
${fl.map(x=>pzFlowRow(x)).join('')}
`;} + return h+'
';} + const l=S.links.find(x=>x.id===sel.id);if(!l)return '';const pl=pairLinks(l.a,l.b); + let h=pzHead(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`${capName(l)} · ${l.km.toLocaleString()} km · ${linkLat(l).toFixed(1)} ms · ${tr('puzzles.price_per_year',{price:fmt$(l.mo*PZ_YEAR)})}`)+'
'; + const u=capOf(l)?(R.load[l.id]||0)/capOf(l):0; + h+=`
${tr('puzzles.this_link')}${pzLoadTxt(l)}
`; + const tabs=[['size',tr('puzzles.size')],['traffic',tr('puzzles.carrying')],['routing',tr('common.routing_metric')]],t=pzTabOf('link',tabs,'size');h+=pzTabs('link',tabs,t); + if(t==='size'){ + h+=`
${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=pzWaveWhy(l.a,l.b,i,r);return btn(`${LT[i].n} ${why?esc(why):tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
`; + h+=`

${tr('puzzles.add_another_link_here')}

${btn(l.cable?tr('puzzles.another_wave_on_this_cable'):tr('puzzles.same_trench_cheaper'),'pzAddPar',{id:l.id,div:0},'sm')}${btn(l.cable?tr('puzzles.a_different_route'):tr('puzzles.a_diverse_route'),'pzAddPar',{id:l.id,div:1},'pink sm')}
`; + h+=`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} + else if(t==='traffic'){const rec=R.ef[edgeKey(l)],rows=[]; + if(rec){S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01)rows.push([pzFlowName(f),v]);}); + const byc={};for(const k in rec.dst)byc[k]=rec.dst[k];S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01)byc[f.b]=(byc[f.b]||0)-v;}); + for(const k in byc)if(byc[k]>0.01)rows.push([tr('puzzles.flow_eyeballs_in_city',{city:CITY[k].name}),byc[k]]);} + h+=rows.length?rows.map(([n,v])=>`
${esc(n)}${fmtG(v)}
`).join(''):`

—

`; + if(pl.length>1)h+=`

${tr('puzzles.n_links_on_this_pair',{n:pl.length,what:groupLabel(pl,pl)})}

`+pl.map(x=>`
${capName(x)} · ${pzTrench(x)}${x.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(x)}
${x===l?'':btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join('');} + else h+=`
${metricSection(l)}${linkCheckControl(l)}
`; + return h+'
';} +// A phone turned or a window resized can switch between the two layouts: draw the puzzle again in the one that fits. +addEventListener('resize',()=>{if(!S||!pzOn())return;const ph=isPhone();if(ph===UI._pzPhone)return;UI._pzh=null;UI._ph=null;pzRender();renderPanel();}); diff --git a/src/game/96-map/10-canvas.js b/src/game/96-map/10-canvas.js new file mode 100644 index 0000000..ff76dfb --- /dev/null +++ b/src/game/96-map/10-canvas.js @@ -0,0 +1,18 @@ +/* ================= CANVAS ================= */ +// ctx is the 2D context draw() paints with: the map's own (CTX0), or with WebGL on the overlay above the card (56-webgl.js). +const cv=$('map'),CTX0=cv.getContext('2d');let ctx=CTX0; +const cam={x:1050,y:330,z:0.8}; +let CW=0,CH=0,DPR=1; +/* Installed on an iPhone home screen with a translucent status bar, iOS can report a viewport one status bar + shorter than the screen while drawing from the very top, leaving an empty strip under the tab bar. + Measure the screen instead, on standalone iPhones only. It must not depend on the gap it fixes: once + the page is sized to the screen, iOS reports a full viewport, and switching back would bring the strip back. */ +function fixStandaloneHeight(){const R0=document.documentElement; + const sa=window.navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches); + const sh=screen&&screen.width&&screen.height?(innerWidth>innerHeight?Math.min(screen.width,screen.height):Math.max(screen.width,screen.height)):0,gap=sh-innerHeight; + const on=sa&&/iPhone|iPod/.test(navigator.userAgent)&&sh>0&&gap>=0&&gap<=80; + R0.classList.toggle('iosfix',on);if(on)R0.style.setProperty('--app-h',sh+'px');else R0.style.removeProperty('--app-h');return on?sh:0;} +function resize(){const ah=fixStandaloneHeight();DPR=Math.min(2,window.devicePixelRatio||1);CW=innerWidth;CH=ah||innerHeight;cv.width=CW*DPR;cv.height=CH*DPR;} +addEventListener('resize',()=>{resize();WL.key=null;renderLeft();fitHud();});resize(); +// iOS settles the standalone viewport a moment after launch and after rotating. +for(const t of [300,1000])setTimeout(()=>{resize();WL.key=null;},t);addEventListener('pageshow',()=>{resize();WL.key=null;}); diff --git a/src/game/96-map/15-palette.js b/src/game/96-map/15-palette.js new file mode 100644 index 0000000..0e3fca2 --- /dev/null +++ b/src/game/96-map/15-palette.js @@ -0,0 +1,11 @@ +/* The map's colours by theme (#80): the cartoon day, and a night under the same stickers (cities and markers keep + theirs; a dark outline round a white sticker reads on either). Both renderers read them when they paint: the 2D map + in drawFrame()/paintWorld(), the card in glBegin()/glFrame() (glPal()). Labels: the pill, its text and its edge. + What is only an outline turns light at night, or it would vanish into the dark land and sea: the tubes' casing + (casing) and a puzzle's stepping-stone ring (via). */ +const MAP_PAL={ + light:{sea:'#62CBEA',sea2:'#43AED6',wave:'rgba(255,255,255,.45)',cloud:'rgba(255,255,255,.55)',shadow:'rgba(20,90,130,.35)',sand:'#F8E6A8',land:'#9BDA6C',hill:'#86CB5B',shine:'rgba(255,255,255,.18)',coast:'#1E2640', + pill:'#FFFFFF',pillInk:'#1E2640',pillEdge:'#1E2640',halo:'rgba(255,255,255,.85)',casing:'#1E2640',via:'rgba(30,38,64,.7)'}, + dark:{sea:'#173E5E',sea2:'#0B2440',wave:'rgba(160,210,255,.14)',cloud:'rgba(200,220,255,.1)',shadow:'rgba(0,0,0,.35)',sand:'#4E5440',land:'#2E5A3A',hill:'#284F31',shine:'rgba(255,255,255,.05)',coast:'#081020', + pill:'#1A2340',pillInk:'#E9EFFB',pillEdge:'#070B16',halo:'rgba(8,16,32,.85)',casing:'#A9B7D8',via:'rgba(233,239,251,.75)'}}; +const MPAL=()=>THEME.dark?MAP_PAL.dark:MAP_PAL.light; diff --git a/src/game/96-map/20-land-and-clouds.js b/src/game/96-map/20-land-and-clouds.js new file mode 100644 index 0000000..bfe3b10 --- /dev/null +++ b/src/game/96-map/20-land-and-clouds.js @@ -0,0 +1,23 @@ +function rng(seed){return()=>{seed|=0;seed=seed+0x6D2B79F5|0;let t=Math.imul(seed^seed>>>15,1|seed);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};} +// A point outside a ring's bounding box is outside the ring: the box is kept on the ring, so the hundreds of tests +// at load (sea waves, hills, which islets the far view keeps) skip nearly every coastline without walking it. +const polyBox=pts=>{let b=pts.box;if(!b){let x0=Infinity,y0=Infinity,x1=-Infinity,y1=-Infinity;for(const [x,y] of pts){if(xx1)x1=x;if(yy1)y1=y;}b=pts.box=[x0,y0,x1,y1];}return b;}; +function inPoly(x,y,pts){const b=polyBox(pts);if(xb[2]||yb[3])return false;let ins=false;for(let i=0,j=pts.length-1;iy)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;} +function smoothPath(pts){const p=new Path2D();const n=pts.length;const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(pts[n-1],pts[0]);p.moveTo(m[0],m[1]);for(let i=0;i{let a=0;for(let i=0,j=p.length-1;iringArea(p)>=600||CITIES.some(c=>inPoly(c.x,c.y,p))?LANDP_ALL[i]:null).filter(Boolean); +const ALLPOLY=COAST; +const onLand=(x,y)=>ALLPOLY.some(p=>inPoly(x,y,p)); +const R1=rng(7),WAVES=[],HILLS=[]; +while(WAVES.length<220){const x=R1()*W,y=R1()*H;if(!onLand(x,y)&&!onLand(x+12,y)&&!onLand(x-12,y))WAVES.push([x,y,R1()]);} +while(HILLS.length<130){const x=R1()*W,y=R1()*H;if(onLand(x,y)&&!CITIES.some(c=>Math.hypot(c.x-x,c.y-y)<40))HILLS.push([x,y,6+R1()*10,R1()]);} +const CLOUDS=Array.from({length:7},(_,i)=>({x:R1()*W,y:60+R1()*(H-120),s:.7+R1()*.6,v:3+R1()*4})); +const FLOATS=[]; +// Stamped with the map's animation clock, which stops while paused: on the real clock, every floater born after a +// pause lingered off-screen for as long as the pause had lasted, and paydays piled up hundreds of them. +// Each belongs to the network that raised it (s): a new game starts paused, and the last one's, frozen with the clock, +// stayed on its map until a reload. +function floater(x,y,text,col){if(!animOn()||UI.mapHid)return;FLOATS.push({x,y,text,col,t:animT,s:S});} diff --git a/src/game/96-map/30-settings.js b/src/game/96-map/30-settings.js new file mode 100644 index 0000000..fdf4132 --- /dev/null +++ b/src/game/96-map/30-settings.js @@ -0,0 +1,45 @@ +// Static markup: elements with data-i18n="label" get their text, and data-i18n-aria-label / data-i18n-title +// their attribute, from the dictionary once at boot. The English stays in the markup for search engines. +function i18nDom(){if(LANG==='en')return;for(const el of document.querySelectorAll('[data-i18n]'))el.textContent=tr(el.dataset.i18n); + for(const a of ['aria-label','title'])for(const el of document.querySelectorAll(`[data-i18n-${a}]`))el.setAttribute(a,tr(el.getAttribute('data-i18n-'+a)));} +// One button per [value,label] option; the current one is highlighted. +// One dropdown instead of a button per language: the list keeps growing, and on phones the system picker opens. +// Each language is named in itself (lang= lets screen readers say it right). +const langPick=id=>``; +function segBtns(act,cur,opts){return opts.map(([v,l])=>btn(l,act,{v},cur===v?'pink sm':'ghost sm')).join('');} +/* Animation setting: auto follows the system's reduced-motion preference, or force it on or off. */ +/* Settings are per device (localStorage), not part of the save: they are about how you like to play. */ +const PREF_DEF={pauseFurious:true,warnUnhappy:true,pauseIncident:false,quiet:false}; +let PREFS=(()=>{try{const j=JSON.parse(localStorage.getItem('sot-prefs')||'{}');return j&&typeof j==='object'?j:{};}catch(e){return {};}})(); +const pref=k=>typeof PREFS[k]==='boolean'?PREFS[k]:PREF_DEF[k]; +// Quiet notifications: the player's choice once made, until then on in Best Effort only. +const quietOn=()=>typeof PREFS.quiet==='boolean'?PREFS.quiet:rulePreset()==='soft'; +function setPref(k,v){if(!own(PREF_DEF,k))return;PREFS[k]=!!v;try{localStorage.setItem('sot-prefs',JSON.stringify(PREFS));}catch(e){}} +// Stop the clock for something the player must see. Nothing happens if the game is already paused, or not the player's. +function autoPause(){if(!S||!UI.speed||UI.clockLocked)return false;UI.resumeSpeed=UI.lastSpeed=UI.speed;UI.speed=0;renderHUD();return true;} +// Space and the phone's play button: pause, or play again at the speed it ran before (#299). +function playPause(){if(pzOn()||UI.clockLocked||(S&&!rule('clock')))return false;if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();return true;} +// Put the clock back at a speed (a new game, a loaded or resumed one): unless it is locked, then it runs as the lock says. +function setSpeed(v){UI.speed=UI.clockLocked&&HOOKS.speed?HOOKS.speed():v;} +const resumeAct=()=>({l:tr('common.resume'),act:'speed',args:{v:UI.resumeSpeed||1}}); +function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`
${lab}
${segBtns(act,cur,opts)}
${note?`

${note}

`:''}`; + const onoff=k=>[[k+':1',tr('common.on')],[k+':0',tr('common.off')]],cur=k=>k+':'+((k==='quiet'?quietOn():pref(k))?1:0); + return `

⚙️ ${tr('common.settings')}

${tr('settings.saved_on_this_device')}

${HOOKS.settings?HOOKS.settings():''} +

${tr('settings.customers_and_alerts')}

+ ${seg(tr('settings.pause_when_a_customer_is_furious'),'prefSet',cur('pauseFurious'),onoff('pauseFurious'),tr('settings.the_game_stops_so_you_can'))} + ${seg(tr('settings.warn_when_a_customer_gets_unhappy'),'prefSet',cur('warnUnhappy'),onoff('warnUnhappy'),tr('settings.an_early_heads_up_below_60'))} + ${seg(tr('settings.pause_on_outages_that_hurt'),'prefSet',cur('pauseIncident'),onoff('pauseIncident'),tr('settings.stops_the_game_when_a_failure'))} + ${seg(tr('settings.quiet_notifications'),'prefSet',cur('quiet'),onoff('quiet'),tr('settings.only_trouble_and_milestones_pop_up'))} +

${tr('settings.display_and_sound')}

+ ${seg(tr('settings.theme'),'themeSet',THEME.pref,[['auto',tr('common.auto')],['light',tr('settings.light')],['dark',tr('settings.dark')]],tr('settings.auto_follows_your_device_s_light'))} + ${seg(tr('common.animations'),'animSet',UI.anim||'auto',[['auto',tr('common.auto')],['on',tr('common.on')],['off',tr('common.off')]],tr('settings.auto_follows_your_device_s_reduce'))} + ${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glCan()?' '+tr('settings.this_browser_cannot_so_the_map'):''))} + ${seg(tr('common.sound'),'soundSet',UI.muted?'off':'on',[['on',tr('common.on')],['off',tr('common.off')]])} +
${langPick('langSel')}
+ ${seg(tr('settings.diagnostic_info'),'vpSet',DIAG.on?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_bug_reports_shows_your_screen'))} + ${installRow()}
${btn(tr('common.done_8dd3'),'settingsClose',{},'pink')}
`;} +const refreshSettings=()=>{if(UI.setOpen)openModal(settingsHtml());}; +function animOn(){const m=UI.anim||'auto';if(m==='on')return true;if(m==='off')return false;try{return !matchMedia('(prefers-reduced-motion: reduce)').matches;}catch(e){return true;}} +function applyAnim(){const r=document.documentElement;r.classList.toggle('no-anim',UI.anim==='off');r.classList.toggle('anim-force',UI.anim==='on');if(!animOn())FLOATS.length=0;} +const toS=(wx,wy,k=0)=>[(wx+k*W-cam.x)*cam.z+CW/2,(wy-cam.y)*cam.z+CH/2]; +const iconScale=()=>clamp(Math.sqrt(cam.z),0.7,1.35); diff --git a/src/game/96-map/40-level-of-detail.js b/src/game/96-map/40-level-of-detail.js new file mode 100644 index 0000000..5336f30 --- /dev/null +++ b/src/game/96-map/40-level-of-detail.js @@ -0,0 +1,8 @@ +/* Level of detail (#37): zoomed out the map turns into a network map, with dots for cities, small + router pills for your POPs and thinner links. Phones switch a little earlier, the screen is small. */ +const lodFar=()=>cam.z<(innerWidth<=760?0.95:0.72); +// One native call draws the same rounded box where the browser has it and the corners fit (hundreds per frame). +function rr(x,y,w,h,r){ctx.beginPath();if(ctx.roundRect&&2*r<=w&&2*r<=h){ctx.roundRect(x,y,w,h,r);return;}ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath();} +// Enough world copies to cover any screen width at any zoom (the map wraps horizontally). +function visibleKs(){const ks=[];for(let k=-5;k<=5;k++){const a=toS(0,0,k)[0],b=toS(W,0,k)[0];if(b>-200&&a{const pr=l.a{const ks=[];for(const x of pl||pairLinks(l.a,l.b)){const k=gKey(x);if(!ks.includes(k))ks.push(k);}return ks.indexOf(gKey(l));}; +// pairLinks() for every pair at once (same links, same order), for code that asks about all of them. +function pairIdx(){const m=new Map();for(const l of S.links){const k=edgeKey(l),a=m.get(k);if(a)a.push(l);else m.set(k,[l]);}return m;} +function linkGroups(){const m=new Map();for(const l of S.links){const key=gKey(l);const g=m.get(key);if(g)g.push(l);else m.set(key,[l]);}return [...m.values()];} +// Mixed sizes are spelled out per size ("2×800G + 400G"): "2 × 1.2T" read like two 1.2T waves (#56). +function groupLabel(grp,up){const n=[];for(const x of grp)n[x.tier]=(n[x.tier]||0)+1;let s='';for(let t=n.length-1;t>=0;t--)if(n[t])s+=(s?' + ':'')+(n[t]>1||n[t]===grp.length?n[t]+'×':'')+LT[t].n;return s+(up.lengthp.slice());const same=pairLinks(l.a,l.b).filter(x=>x.cable===l.cable).indexOf(l);if(same>0)for(let j=1;jx.kind==='df'&&x.own&&x.sub).indexOf(l),c0=cablesFor(l.a,l.b).slice().sort((x,y)=>x.km-y.km)[0],cp=c0&&cablePair(c0.cid,l.a,l.b); + if(cp)pts=besideLine(cp.pts,2+k*1.5); + else{const g=bezGeom(l,k);pts=[];for(let j=0;j<=20;j++)pts.push(qpt(g,j/20));}} + // An express follows the fibers it rides, a little to one side, so it shows passing the cities on the way. + if(!pts&&l.kind==='xp')pts=xpGeom(l); + if(!pts){const g=bezGeom(l);pts=[];for(let j=0;j<=20;j++)pts.push(qpt(g,j/20));} + const cum=[0];let L=0;for(let j=1;jv/L),t),a=polyAt(sp,c.map(v=>v/L),Math.max(0,t-.02)),b=polyAt(sp,c.map(v=>v/L),Math.min(1,t+.02)),dx=b[0]-a[0],dy=b[1]-a[1],n=Math.hypot(dx,dy)||1,f=d*Math.sin(Math.PI*t);out.push([q[0]+dy/n*f,q[1]-dx/n*f]);}return out;} +function polyAt(sp,cum,t){let i=1;while(it0?(t-t0)/(t1-t0):0;return [sp[i-1][0]+(sp[i][0]-sp[i-1][0])*f,sp[i-1][1]+(sp[i][1]-sp[i-1][1])*f];} +// polyAt() on screen points kept in two arrays (draw() reuses them for every link instead of making new points). +function polyAtXY(X,Y,cum,t){let i=1;while(it0?(t-t0)/(t1-t0):0;return [X[i-1]+(X[i]-X[i-1])*f,Y[i-1]+(Y[i]-Y[i-1])*f];} +let SX=new Float64Array(64),SY=new Float64Array(64); +function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const t=clamp(((x-a[0])*dx+(y-a[1])*dy)/L,0,1);return Math.hypot(x-a[0]-t*dx,y-a[1]-t*dy);} +// `cached`: the cables are already painted into the world layer. Zoomed in, the layer is painted without +// them (#49), so they are drawn here every frame instead. +// Cable names are drawn in one font, so each width is measured once. +const LBW=new Map(),labW=t=>{let w=LBW.get(t);if(w===undefined)LBW.set(t,w=ctx.measureText(t).width);return w;}; +try{document.fonts&&document.fonts.ready.then(()=>LBW.clear());}catch(e){} +function drawCables(ks){const G=glOn(),z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab)&&!G; + // On the card the cables are drawn by glBegin(); here only their labels are left. + if(!selC&&z<1.7&&cached)return;if(G&&!selC&&z<1.7)return; + ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle'; + // Labels that would sit on another, or on a segment shorter than the name, are left out (a selected city's always show). + // Placed labels go in a 64px grid, so each check only looks at its neighbours. + const LG=new Map(),lbOk=(x,y,w,sp,hot)=>{const b=[x-w/2-3,y-7,x+w/2+3,y+7],c0=Math.floor(b[0]/64),c1=Math.floor(b[2]/64),r0=Math.floor(b[1]/64),r1=Math.floor(b[3]/64); + if(!hot){const a=sp[0],z=sp[sp.length-1];let L=Math.hypot(z[0]-a[0],z[1]-a[1]);if(Lq[0]&&b[1]q[1])return false;}} + for(let cx=c0;cx<=c1;cx++)for(let cy=r0;cy<=r1;cy++){const k=cx*8192+cy;let o=LG.get(k);if(!o)LG.set(k,o=[]);o.push(b);}return true;}; + const ar=arOn();for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;const col=cableCol(C); + for(const k of ks){const sp=cp.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]mx)mx=q[0];}if(mx<-20||mn>CW+20)continue; + if(!G&&(hot||!cached)){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,MPAL().halo,3,m[0],m[1]-8);} + ctx.globalAlpha=1;}}} +function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit; + const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} + // Puzzles bow diverse paths well apart, so two routes never read as one. + const wide=!!S&&pzOn(),base=Math.max(4,Math.min(len*0.1,90)),step=wide?Math.min(30,len*.14):Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?(wide?0.9:0.2):1)+Math.ceil(i/2)*step); + const mx=(A.x+bx)/2,my=(A.y+by)/2; + const sg=Math.sign(off0)||1,mag=Math.abs(off0); + // Bend around cities in the way, but gently: short links need less room, no curve bows out more than about a + // third of its length, and when nothing clears, a modest curve beats a giant loop around the neighbourhood. + const need=Math.min(24,Math.max(7,len*0.2)),cap=Math.max(mag,len*0.32),lim=o=>Math.sign(o)*Math.min(Math.abs(o),cap); + const cand=[1,1.5,2.1,2.9,3.8].map(k=>lim(sg*mag*k)).concat([1,1.5,2.1,2.9,3.8].map(k=>lim(-sg*Math.max(mag,base)*k))); + /* Only cities that could come within `need` of a candidate curve count: a curve stays inside the box of its end and + control points, so a city further than `need` outside the box of all of them only ever measures as clear, and + min(clearance, need) comes out the same without it (the map's first frame did this for every city and link). */ + let x0=Math.min(A.x,bx),x1=Math.max(A.x,bx),y0=Math.min(A.y,by),y1=Math.max(A.y,by); + for(const off of cand){const cx=mx+nx*off,cy=my+ny*off;if(cxx1)x1=cx;if(cyy1)y1=cy;} + const obs=[];for(const c of CITIES){if(c.id===l.a||c.id===l.b)continue;const ox=mx+wrapDx(mx,c.x),oy=c.y;if(ox>=x0-need&&ox<=x1+need&&oy>=y0-need&&oy<=y1+need)obs.push([ox,oy]);} + const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(d=need){best=[cx,cy];break;}const sc=Math.min(c,need)-Math.abs(off)*0.35;if(sc>bs){bs=sc;best=[cx,cy];}} + const g={ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};GEO.set(key,g);return g;} +const qpt=(g,t)=>[(1-t)*(1-t)*g.ax+2*(1-t)*t*g.cx+t*t*g.bx,(1-t)*(1-t)*g.ay+2*(1-t)*t*g.cy+t*t*g.by]; +const utilCol=u=>u<=0.001?'#AFC0D6':u<0.65?'#22C47A':u<0.9?'#FFAA1F':'#FF4D5E'; +// How many separate paths (trenches or cables) join this tube's two cities. +const arPaths=l=>new Set(pairLinks(l.a,l.b).map(gKey)).size; +const AR_PILLS=[]; // filled while the links are drawn, painted after the cities diff --git a/src/game/96-map/51-express-geometry.js b/src/game/96-map/51-express-geometry.js new file mode 100644 index 0000000..3a6abf4 --- /dev/null +++ b/src/game/96-map/51-express-geometry.js @@ -0,0 +1,5 @@ +// An express lightpath (65-express.js) is drawn along the fibers it rides, end to end from a, pushed a little to one +// side (easing to nothing at both ends), so it reads as one line that passes the cities in between. +function xpGeom(l){const sp=xpSpans(l),cs=sp&&xpCities(l.a,sp);if(!cs)return null;const pts=[]; + sp.forEach((s,i)=>{let q=linkGeom(s).pts;if(s.a!==cs[i])q=q.slice().reverse();for(let j=pts.length?1:0;j1?besideLine(pts,4):null;} diff --git a/src/game/96-map/55-link-look.js b/src/game/96-map/55-link-look.js new file mode 100644 index 0000000..2ec50c9 --- /dev/null +++ b/src/game/96-map/55-link-look.js @@ -0,0 +1,18 @@ +/* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in + 58-webgl-links.js), so they cannot drift apart. */ +// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable, +// 7 a link being dragged out, 8 an express lightpath. +const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12],[14,5]]; +// A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash. +function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; + const cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',xp=l.kind==='xp',st=l.kind==='sat',bld=(df||st)&&l.ready>day,cut=!bld&&!xp&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length||xp&&linkDown(l),vx=l.kind==='vxc'||st,idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); + return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx||xp?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), + col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?(st?SAT_PROV[SATS[l.bird].p].col:FAB[l.prov].col):l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:xp?8:bld?3:idle?4:0, + pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills +// The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the +// links and with the day's routing (R), not with the camera, so it is kept until one of those changes. +let MLK=null; +function mapLinks(day){const key=[S.links,S.links.length,R,day]; + if(MLK&&key.every((v,i)=>v===MLK.key[i]))return MLK; + const PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))); + return MLK={key,PI,LG,GM,looks:LG.map(g=>linkLook(g,day))};} diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js new file mode 100644 index 0000000..0fe11a7 --- /dev/null +++ b/src/game/96-map/56-webgl.js @@ -0,0 +1,103 @@ +/* The map on the graphics card (WebGL2), wherever the browser can; Settings › Map drawing › Always 2D keeps the 2D + canvas instead (a choice per device). A late-game map sends the 2D canvas several strokes per tube every frame (thousands on a + big network) and repaints the land whenever you pan; here the card draws it all from buffers that change only with + the network, so a frame costs the processor a few draws and uniforms. + Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and + packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for + the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used. + Puzzles, and any browser without WebGL2 or whose context fails, keep the 2D map; a lost context, until it is back. So does WebGL drawn by + the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs + microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */ +const GLX={want:true,dead:false,lost:false,sleep:false,losses:0,lose:null,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''}; +try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){} +// Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark). +const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i; +const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit(); +// Whether the card can draw the map, as far as is known without asking it: Settings says so without making a context +// (on the title screen or in a puzzle that made the 64 MB atlas for a map drawn in 2D). A card not tried yet counts as able. +const glCan=()=>!GLX.dead&&typeof WebGL2RenderingContext!=='undefined'; +// Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not. +// Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back. +function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){} + if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false; + // A context the browser will not give back would leave the map waiting for it all session: give the card up instead. + try{GLX.lose.restoreContext();}catch(e){if(GLX.ctx&&GLX.ctx.isContextLost&&GLX.ctx.isContextLost()===false)GLX.lost=false;else glKill(e);}} + GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;} +function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;} +// Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame. +function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;} +function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true; + const gl=GLX.ctx;GLX.gl=GLX.ctx=null;spritesDrop();glFree(gl);glShow(false);} +/* The card given up for good (not Always 2D: glSleep()) still held what was sent to it, the atlas alone + 64 MB, while the 2D map starts painting its own pictures. So its biggest things are deleted and the context let go + (WEBGL_lose_context, where the browser has it), unless the browser already lost it, which freed them. glInit() keeps + the context in GLX.ctx from the start, so a setup that fails half-way is let go too. */ +function glFree(gl){try{if(gl&&gl.isContextLost()===false){for(const x of [GLS.tex,GLX.tex])if(x)gl.deleteTexture(x);if(GLS.buf)gl.deleteBuffer(GLS.buf); + const L=gl.getExtension('WEBGL_lose_context');if(L&&typeof L.loseContext==='function')L.loseContext();}}catch(e){} + GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;GLX.tex=null;GLX.land={};GLS_PAD.cv=GLS_PAD.g=null;} +/* A lost context comes back. The browser may lose it (a driver reset; on a phone, sometimes just leaving the app) and + give it back (webglcontextrestored): the 2D map draws meanwhile, and everything on the card is built again on the + same context, as for the first frame. A card lost more than GL_LOSSES times is given up for the session, so a card + that keeps failing does not keep the map switching. Always 2D lets the context go the same way (WEBGL_lose_context) + and Auto asks for it back, so 64 MB of atlas and the rest are not held for a map that is not drawn. */ +const GL_LOSSES=2; +// Forgets what was on the card (the context itself is kept): glInit() builds it all again. +function glForget(){GLX.gl=null;spritesDrop();GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;Object.assign(GLX,{tex:null,land:{},ckey:null,key:[]});glShow(false);UI.drawnAt=0;} +function glLost(e){if(GLX.dead)return;e.preventDefault();if(GLX.lost)return; // let go by Always 2D (glSleep()) + if(++GLX.losses>GL_LOSSES){glKill('the graphics context was lost '+GLX.losses+' times');return;} + GLX.lost=true;glForget();} +function glRestored(){if(GLX.dead)return;GLX.lost=false;glForget();if(!GLX.want)glSleep();} +// Always 2D: lets the context go, unless the browser has it already (its restore then finds Always 2D and lets it go). +function glSleep(){const L=GLX.lose;if(!GLX.ctx||GLX.dead||!L||typeof L.restoreContext!=='function')return; + if(GLX.lost){GLX.sleep=true;return;}glForget();GLX.sleep=GLX.lost=true;try{L.loseContext();}catch(e){GLX.sleep=GLX.lost=false;}} +/* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for + getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big + uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never + every frame: each read waits for the card. Up to four flags are read, as one call returns only one. */ +function glMem(gl,what){for(let i=0;i<4;i++){const e=gl.getError();if(!e||e===gl.CONTEXT_LOST_WEBGL)return; + if(e===gl.OUT_OF_MEMORY)throw glErr(new Error('the graphics card is out of memory ('+what+')'));}} +const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n'; +// Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing). +const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n'; +function glProg(gl,vs,fs){const sh=(t,s)=>{const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))throw new Error('shader: '+gl.getShaderInfoLog(x));return x;}; + const p=gl.createProgram();gl.attachShader(p,sh(gl.VERTEX_SHADER,vs));gl.attachShader(p,sh(gl.FRAGMENT_SHADER,fs));gl.linkProgram(p); + if(!gl.getProgramParameter(p,gl.LINK_STATUS))throw new Error('link: '+gl.getProgramInfoLog(p)); + const u={},n=gl.getProgramParameter(p,gl.ACTIVE_UNIFORMS);for(let i=0;ia+x,0)*4; + gl.bindVertexArray(v);gl.bindBuffer(gl.ARRAY_BUFFER,b);if(data)gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW); + let off=0;sizes.forEach((n,i)=>{gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,n,gl.FLOAT,false,stride,off);gl.vertexAttribDivisor(i,div);off+=n*4;}); + gl.bindVertexArray(null);return {v,b};} +function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false; + try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers'); + const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'}); + if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl; + if(!GLX.lose){c.addEventListener('webglcontextlost',glLost);c.addEventListener('webglcontextrestored',glRestored);try{GLX.lose=gl.getExtension('WEBGL_lose_context')||{};}catch(e){GLX.lose={};}} + // Firefox names the card in RENDERER and warns that the extension is going away; other browsers need it. + try{const x=/Firefox\//.test(navigator.userAgent)?null:gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){} + if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu); + const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)}; + // The tubes' points for the packets: floats read with texelFetch, never filtered. + const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST); + glsInit(gl); + // The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every + // frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself. + const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype; + if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}} + const V=s=>glVao(gl,s); + Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4,4]),hv:V([4,4,4,4]),pv:V([4,4]),cb:V([4,4,4,4]),wv:V([4,4,4,4]),dv:V([4,4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;} + catch(e){glKill(e);return false;}} +// Colours as [r,g,b,a] from '#rrggbb', '#rgb' or 'rgba(r,g,b,a)', kept by string. +const GLCOL=new Map(); +function glColor(s){let v=GLCOL.get(s);if(v)return v;let r=0,g=0,b=0,a=1; + if(s[0]==='#'){let h=s.slice(1);if(h.length===3)h=h.replace(/./g,x=>x+x);r=parseInt(h.slice(0,2),16)/255;g=parseInt(h.slice(2,4),16)/255;b=parseInt(h.slice(4,6),16)/255;} + else{const m=/rgba?\(([^)]*)\)/.exec(s);if(m){const p=m[1].split(',').map(x=>parseFloat(x));r=p[0]/255;g=p[1]/255;b=p[2]/255;a=p.length>3?p[3]:1;}} + v=[r,g,b,a];GLCOL.set(s,v);return v;} +// Sets a line or a point program's view for copy k of the map (wm: the line width multiplier). +function glSet(gl,P,k,wm){gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.uniform1f(P.u.uWMul,wm);gl.uniform1f(P.u.uDpr,DPR);} +// A full-screen fill, from one premultiplied colour at the bottom to another at the top (the sea), or of one colour +// (the land and the clouds, through the stencil). +const FILL_VS=GL_HEAD+`void main(){vec2 p=vec2((gl_VertexID&1)==0?-1.:1.,(gl_VertexID&2)==0?-1.:1.);gl_Position=vec4(p,0.,1.);}`; +const FILL_FS=GL_HEAD+`uniform vec4 uTop,uBot;uniform float uH;out vec4 o;void main(){o=mix(uBot,uTop,gl_FragCoord.y/uH);}`; +function glFill(gl,top,bot=top){const P=GLX.fill;gl.useProgram(P.p);gl.uniform4fv(P.u.uTop,top);gl.uniform4fv(P.u.uBot,bot);gl.uniform1f(P.u.uH,GLX.c.height);gl.bindVertexArray(GLX.empty);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);} diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js new file mode 100644 index 0000000..c2a97de --- /dev/null +++ b/src/game/96-map/57-webgl-background.js @@ -0,0 +1,134 @@ +/* The background on the card, painted first each frame: the sea, the land, the waves, the clouds and the cables, as + the 2D map paints them (drawFrame(), paintWorld()) and in the same colours. The land and the cables are geometry + built once, so panning and zooming repaint nothing; only the waves and the clouds move. */ +const glPm=s=>{const [r,g,b,a]=glColor(s);return [r*a,g*a,b*a,a];}; // premultiplied, as the card blends +// The theme's colours (MPAL(), 15-palette.js) as the card takes them, worked out again only when the theme changes. +const GLP={m:null}; +function glPal(){const m=MPAL();if(GLP.m!==m)Object.assign(GLP,{m,seaTop:glPm(m.sea),seaBot:glPm(m.sea2),cloud:glPm(m.cloud),shadow:glPm(m.shadow),grass:glPm(m.land), + hill:glPm(m.hill),shine:glPm(m.shine),wave:glColor(m.wave),sand:glColor(m.sand),edge:glColor(m.coast),casing:glColor(m.casing)});return GLP;} +// The land's fill: a fan of triangles per coastline, counted in the stencil (how many times the coasts wind round each +// pixel: glLandFill()), then one cover where the count is not zero. uOff shifts it in CSS px (the shadow). +const FAN_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec2 aV;uniform vec2 uView,uOff;uniform vec3 uCam; +void main(){gl_Position=clip((aV-uCam.xy)*uCam.z+uView*.5+uOff,uView,0.);}`; +const FAN_FS=GL_HEAD+`out vec4 o;void main(){o=vec4(0.);}`; +// Ellipses (the hills and their shine): centre and radii in map units, one premultiplied colour, smooth edges. +const ELL_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aE;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out vec2 vr; +void main(){vec2 c=(aE.xy-uCam.xy)*uCam.z+uView*.5,r=aE.zw*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m.x:m.x,(gl_VertexID&2)==0?-m.y:m.y);vr=r;gl_Position=clip(c+vq,uView,0.);}`; +const ELL_FS=GL_HEAD+`in vec2 vq;flat in vec2 vr;uniform vec4 uCol;uniform float uDpr;out vec4 o; +void main(){float d=(length(vq/vr)-1.)*min(vr.x,vr.y),a=clamp(.5-d*uDpr,0.,1.);if(a<=0.)discard;o=uCol*a;}`; +// Discs for the stencil only (the clouds' puffs): centre and radius in map units. +const CIRC_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aC;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out float vr; +void main(){vec2 c=(aC.xy-uCam.xy)*uCam.z+uView*.5;float r=aC.z*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vr=r;gl_Position=clip(c+vq,uView,0.);}`; +const CIRC_FS=GL_HEAD+`in vec2 vq;flat in float vr;out vec4 o;void main(){if(length(vq)>vr)discard;o=vec4(1.);}`; +/* The land, built once per level of detail (the far view leaves out the islets as LANDP_FAR does) and per zoom level + lv (powers of 2): the fan for the fills, the coastlines as line segments (paintWorld()'s curves, four segments each) + for the sand and the dark edge, and the hills. Zoomed out a coastline has far more points than pixels, and its + vertices were most of the card's work: at level lv it is simplified so that no point moves more than COAST_TOL px at + the level's zoom (Douglas-Peucker). Without lv, the whole coastline. COAST and onLand() are not touched. + Each level stays on the card once built (GLX.land, freed with the card): from 0.4 MB zoomed out to 3 MB at the + closest zoom, about 15 MB if a game visits every zoom, so zooming back never builds one again mid-gesture. */ +const COAST_TOL=0.25,COASTP=[]; +// A coastline as paintWorld() draws it (smoothPath(): a quadratic curve from the middle of each side to the next, +// through the corner between them), four segments per curve; the first point is repeated at the end. +function coastPts(ri){let P=COASTP[ri];if(P)return P;const ring=COAST[ri],n=ring.length;P=[]; + const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(ring[n-1],ring[0]);P.push(m); + for(let i=0;i0))return P;const keep=new Uint8Array(n),st=[0,n-1],t2=tol*tol;keep[0]=keep[n-1]=1; + while(st.length){const b=st.pop(),a=st.pop(),ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;let m=-1,md=t2; + for(let i=a+1;i1?1:t;const ex=ax+t*dx-P[i][0],ey=ay+t*dy-P[i][1],d=ex*ex+ey*ey;if(d>md){md=d;m=i;}} + if(m>=0){keep[m]=1;st.push(a,m,m,b);}} + const o=[];for(let i=0;icur||z{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return; + const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return; + coastFan(P,fan); + // A closed ring (its first point repeated at the end), joined all round. + const s0=sand.length/LINE_STRIDE;for(let i=0;i+1{const x=glVao(gl,sz,div,new Float32Array(a));bufs.push(x);return x.v;}; + G={fan:V([2],0,fan),nFan:fan.length/2,sand:V([4,4,4,4],1,sand),edge:V([4,4,4,4],1,edge),nSeg:sand.length/LINE_STRIDE, + hills:V([4],1,hills),shine:V([4],1,shine),nHill:HILLS.length,bufs}; + glMem(gl,'the land');return GLX.land[key]=G;} +// A theme change (themeRepaint()): every level of the land is built again, in the new colours, when next drawn. +function glLandDrop(){const gl=GLX.gl,L=GLX.land;GLX.land={};if(!gl||!L)return; + try{if(gl.isContextLost())return;for(const G of Object.values(L))for(const x of G.bufs||[]){gl.deleteVertexArray(x.v);gl.deleteBuffer(x.b);}}catch(e){}} +// Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map. +// The stencil counts the coasts' windings (+1 for a triangle facing one way, -1 the other: coastFan()), as the 2D +// canvas's nonzero rule does; counting only odd or even made two overlapping coasts cancel out into sea. +function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST); + gl.useProgram(P.p);gl.uniform2f(P.u.uView,CW,CH);gl.uniform2f(P.u.uOff,ox,oy);gl.bindVertexArray(G.fan); + gl.colorMask(false,false,false,false);gl.stencilFunc(gl.ALWAYS,0,255);gl.stencilMask(255); + gl.stencilOpSeparate(gl.FRONT,gl.KEEP,gl.KEEP,gl.INCR_WRAP);gl.stencilOpSeparate(gl.BACK,gl.KEEP,gl.KEEP,gl.DECR_WRAP); + for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArrays(gl.TRIANGLES,0,G.nFan);} + // The cover paints where the count is not zero and sets the stencil back to zero for the next user. + gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,255);gl.stencilOp(gl.ZERO,gl.ZERO,gl.ZERO); + glFill(gl,col);gl.disable(gl.STENCIL_TEST);} +function glEllipses(gl,vao,n,ks,col){const P=GLX.ell;gl.useProgram(P.p);gl.bindVertexArray(vao);gl.uniform2f(P.u.uView,CW,CH);gl.uniform1f(P.u.uDpr,DPR);gl.uniform4fv(P.u.uCol,col); + for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}} +// In paintWorld()'s order: the shadow (5, 7 px down and right), the sand, the grass, the hills, the coastline. +function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z)),P=glPal(); + glLandFill(gl,G,ks,5,7,P.shadow); + glLines(gl,G.sand,G.nSeg,ks); + glLandFill(gl,G,ks,0,0,P.grass); + glEllipses(gl,G.hills,G.nHill,ks,P.hill);glEllipses(gl,G.shine,G.nHill,ks,P.shine); + glLines(gl,G.edge,G.nSeg,ks);} +// The waves: each one two quadratic curves of four segments, swaying with the map's clock as in drawFrame(). They are +// written into the same array every frame (no garbage for the collector to pick up while you play). +function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900,WAVE_COL=glPal().wave;let m=0; + for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3,m0=m; + // Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame). + for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y; + for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}} + glJoin(A,m0,m,false);} + gl.bindBuffer(gl.ARRAY_BUFFER,GLX.wv.b);gl.bufferData(gl.ARRAY_BUFFER,A.subarray(0,m*LINE_STRIDE),gl.DYNAMIC_DRAW);glLines(gl,GLX.wv.v,m,ks);} +// The clouds: their puffs are stencilled as one shape, then filled once, so overlapping puffs do not stack. +function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)return; + // Written into one array kept from frame to frame, grown when more copies of the map show. + if(!GLX.ca||GLX.ca.lengthv!==GLX.ckey[i])){const A=[]; + for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue; + const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4],s0=A.length/LINE_STRIDE;let cum=0; + for(let j=0;j+12; + for(let i=i0;ii0?i-1:closed?i1-1:-1,n=i+1=0){const q=p*LINE_STRIDE;A[o+12]=A[q+2]-A[q];A[o+13]=A[q+3]-A[q+1];}else A[o+12]=A[o+13]=0; + if(n>=0){const q=n*LINE_STRIDE;A[o+14]=A[q+2]-A[q];A[o+15]=A[q+3]-A[q+1];}else A[o+14]=A[o+15]=0;}} +/* One instance per segment, a quad around it; the fragment keeps what lies within half the line width of the segment + (or of a dash of it, both with round ends), which also gives round joins and caps. Where two segments of a line + meet, their round ends overlap: each keeps only its side of the corner's bisector, so a see-through line (the + halo, the cables, the waves, the fiber's dots) is blended once there, as the 2D canvas strokes a path once. */ +const GL_LINE_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aSeg;layout(location=1) in vec4 aP;layout(location=2) in vec4 aC;layout(location=3) in vec4 aN; +uniform vec2 uView;uniform vec3 uCam,uCas;uniform float uWMul,uDpr,uBusy;uniform int uPass; +out vec2 vLoc;out float vLen,vS0,vHalf,vButt;flat out vec4 vCol,vK;flat out vec2 vDash,vEnd; +// The corner's bisector between directions u and v, in the segment's own frame (t along it, n across), and whether there is one. +vec3 cut(vec2 u,vec2 v,vec2 t,vec2 n){vec2 m=u+v;float l=length(m);if(length(u)<.5||length(v)<.5||l<1e-3)return vec3(0.);m/=l;return vec3(dot(t,m),dot(n,m),1.);} +vec2 dashOf(int k){${LDASH.map((d,i)=>d.length?`if(k==${i})return vec2(${d[0]}.,${d[1]}.);`:'').join('')}return vec2(0.);} +void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCam.z+h; + float w=aP.y*uWMul,hw=w*.5;int fl=int(aP.w+.5);vec4 col=vec4(aC.yzw,1.);vec2 dash=dashOf(int(aP.z+.5));bool skip=false; + if(uPass==${LP.halo}){hw=(w+14.)*.5;col=vec4(1.,79./255.,154./255.,.35);dash=vec2(0.);skip=(fl&${LINE_SEL})==0;} + else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(uCas,1.);} + else if(uPass==${LP.dots}){hw=max(1.,w*.25)*.5;col=vec4(1.,1.,1.,.75);dash=dashOf(5);skip=(fl&${LINE_FIBER})==0||uBusy>.5;} + else if(uPass==${LP.plain})col.a=aC.x; + if(skip){gl_Position=vec4(2.,2.,2.,1.);return;} + vec2 d=b-a;float L=length(d);vec2 t=L>1e-4?d/L:vec2(1.,0.),n=vec2(-t.y,t.x);float m=hw+1./uDpr; + float sx=(gl_VertexID&1)==0?-m:L+m,sy=(gl_VertexID&2)==0?-m:m; + vLoc=vec2(sx,sy);vLen=L;vS0=aP.x*uCam.z;vHalf=hw;vCol=col;vDash=dash;vButt=uPass==${LP.plain}&&(fl&${LINE_ROUND})==0?1.:0.; + float lp=length(aN.xy),ln=length(aN.zw);vec3 c0=L>1e-4&&lp>1e-9?cut(aN.xy/lp,t,t,n):vec3(0.),c1=L>1e-4&&ln>1e-9?cut(t,aN.zw/ln,t,n):vec3(0.); + vK=vec4(c0.xy,c1.xy);vEnd=vec2(c0.z,c1.z); + gl_Position=clip(a+t*sx+n*sy,uView,(uPass==${LP.plain}?.9998:aC.x)*2.-1.);}`; +const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol,vK;flat in vec2 vDash,vEnd;uniform float uDpr;out vec4 o; +void main(){float x=vLoc.x,y=vLoc.y,d; + // A corner: the side of the bisector that belongs to the neighbour is the neighbour's to paint. + if(vEnd.x>.5&&x*vK.x+y*vK.y<0.)discard; + if(vEnd.y>.5&&(x-vLen)*vK.z+y*vK.w>0.)discard; + // Flat ends only where the line really ends; its corners are joined. + if(vButt>.5&&((vEnd.x<.5&&x<0.)||(vEnd.y<.5&&x>vLen)))discard; + if(vDash.x<=0.){float c=clamp(x,0.,vLen);d=length(vec2(x-c,y));} + else{float P=vDash.x+vDash.y,g=vS0+x,k=floor(g/P);d=1e9; + for(int i=-1;i<=1;i++){float a0=(k+float(i))*P,lo=max(a0,vS0),hi=min(a0+vDash.x,vS0+vLen);if(lo<=hi){float c=clamp(g,lo,hi);d=min(d,length(vec2(g-c,y)));}}} + float al=clamp((vHalf-d)*uDpr+.5,0.,1.);if(al<=0.)discard;o=vec4(vCol.rgb*vCol.a*al,vCol.a*al);}`; +// Plain lines (coasts, waves, cables): colour and opacity from the data, flat ends unless LINE_ROUND, under the tubes. +function glLines(gl,vao,n,ks){const L=GLX.line;gl.useProgram(L.p);gl.bindVertexArray(vao);gl.uniform1i(L.u.uPass,LP.plain);gl.uniform1f(L.u.uBusy,0); + for(const k of ks){glSet(gl,L,k,1);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}} +/* Packets: one instance per packet; where it is on its tube comes from the tube's points (a float texture of x, y and + the share of the length so far, GL_PTS_W texels a row), found by bisection the way polyAtXY() finds it. */ +const GL_PTS_W=2048; +const GL_PK_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aK;layout(location=1) in vec4 aQ; +uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uT,uFar;uniform highp sampler2D uPts; +out vec2 vLoc;flat out float vR,vLw; +vec4 P(int i){return texelFetch(uPts,ivec2(i%${GL_PTS_W},i/${GL_PTS_W}),0);} +void main(){float n=uFar>.5?max(1.,floor(aK.w*.5)):aK.w,i=aQ.x;if(i>=n){gl_Position=vec4(2.,2.,2.,1.);return;} + float t=fract(uT*90./max(aK.z*uCam.z,40.)+i/n);if(mod(i,2.)>.5)t=1.-t; + int o=int(aK.x+.5),lo=1,hi=int(aK.y+.5)-1;for(int s=0;s<16&&lop0.z?(t-p0.z)/(p1.z-p0.z):0.;vec2 c=(mix(p0.xy,p1.xy,f)-uCam.xy)*uCam.z+uView*.5; + float w=aQ.y*uWMul,r=uFar>.5?1.6:max(2.2,w*.42),lw=uFar>.5?1.:1.5,m=r+lw*.5+1./uDpr; + vec2 q=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vLoc=q;vR=r;vLw=lw; + gl_Position=clip(c+q,uView,aQ.z*2.-1.);}`; +const GL_PK_FS=GL_HEAD+`in vec2 vLoc;flat in float vR,vLw;uniform float uDpr;out vec4 o; +void main(){float d=length(vLoc),out_=clamp((vR+vLw*.5-d)*uDpr+.5,0.,1.);if(out_<=0.)discard; + float inn=clamp((vR-vLw*.5-d)*uDpr+.5,0.,1.);vec3 c=mix(vec3(30./255.,38./255.,64./255.),vec3(1.),inn);o=vec4(c*out_,out_);}`; +/* The tubes as instance data: their segments (see LINE_STRIDE; later tubes are nearer), their packets (first point, + points, length, packets | which, base width, depth, -), and every tube's points in the texture. */ +const glDepth=(gi,N)=>1-(gi+1)/(N+2); +function glBuild(LG,GM,looks){const gl=GLX.gl,N=LG.length;let ns=0,np=0,nk=0; + for(let gi=0;gix.id===selId))continue;const L=looks[gi],{pts,cum,len}=GM[gi],dep=glDepth(gi,N),col=glColor(L.col); + const s0=A.length/LINE_STRIDE;for(let j=0;j+1{gl.useProgram(L.p);gl.bindVertexArray(v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass); + gl.uniform3f(L.u.uCas,cas[0],cas[1],cas[2]); + for(const k of ks){glSet(gl,L,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}; + if(GLX.nSeg)for(const pass of [LP.casing,LP.colour,LP.dots])lines(pass); + if(GLX.nPk){gl.useProgram(K.p);gl.bindVertexArray(GLX.pv.v);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.uniform1i(K.u.uPts,0); + gl.uniform1f(K.u.uT,now/1000);gl.uniform1f(K.u.uFar,far?1:0);for(const k of ks){glSet(gl,K,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,GLX.nPk);}} + // The selection's halo goes over earlier tubes but under its own line and later ones, as in 2D. + if(GLX.nHalo){gl.depthFunc(gl.LESS);gl.depthMask(false);lines(LP.halo,GLX.hv.v,GLX.nHalo);gl.depthMask(true);} + gl.bindVertexArray(null);} +// The link being dragged out (x,y in CSS px): the dotted line in the tubes' casing colour, then the pink one running +// along it, over the tubes and, since the pictures are drawn after it, under the cities, as in 2D. +const DRAG_PINK=glColor('#FF4F9A'); +function glDrag(ax,ay,tx,ty,now){const gl=GLX.gl,A=GLX.da||(GLX.da=new Float32Array(2*LINE_STRIDE)),z=cam.z,mx=x=>(x-CW/2)/z+cam.x,my=y=>(y-CH/2)/z+cam.y; + glSegAt(A,0,mx(ax),my(ay),mx(tx),my(ty),0,7,7,LINE_ROUND,1,glPal().casing); + glSegAt(A,1,mx(ax),my(ay),mx(tx),my(ty),-now/30/z,4,7,LINE_ROUND,1,DRAG_PINK); + gl.bindBuffer(gl.ARRAY_BUFFER,GLX.dv.b);gl.bufferData(gl.ARRAY_BUFFER,A,gl.DYNAMIC_DRAW); + gl.disable(gl.DEPTH_TEST);glLines(gl,GLX.dv.v,2,[0]);gl.bindVertexArray(null);} diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js new file mode 100644 index 0000000..997e7a1 --- /dev/null +++ b/src/game/96-map/59-gl-sprites.js @@ -0,0 +1,151 @@ +/* Pictures on the card. Cities, labels, markers and everything that bobs or pulses on them (cones, ships, offer + bubbles, hot badges, floaters) are painted once with the 2D canvas, packed into one texture (the atlas), and drawn + as instanced quads, with the small round things (lights, steam, glows) as discs, in one draw per frame after the + tubes. Without WebGL the same calls draw the pictures with the 2D canvas, so the map's code does not care which. */ +const SPR_MAX=1400,SPR_STRIDE=13; +// The card's pictures (SPRS) and the 2D map's (SPRC), by key; both at the screen's pixel density SPR_DPR. +const SPRS=new Map(),SPRC=new Map();let SPR_DPR=0; +/* The 2D map's pictures each keep a canvas, so they are also held to a size: a long zoom on a big network paints every + city again at each step, and the list (only capped at SPR_MAX) held up to 180 MB of them where a frame shows 2 to + 23 MB. At the end of a frame over SPRC_BUDGET bytes, the pictures it did not use go, those unused the longest first, + down to 3/4 of the budget (so this happens once in a while, not every frame). The frame's own are always kept: a + screen that needs more than the budget keeps what it needs. A canvas let go is emptied (0×0) at once, which frees + its pixels without waiting for the collector. The card's atlas has its own fixed size (GLS.size). + SPR_F counts frames (draw()); finding or drawing a picture marks it as used in this one (e.f). */ +const SPRC_BUDGET=48*1048576;let SPRC_B=0,SPR_F=0; +const sprFree=e=>{if(e.cv){e.cv.width=e.cv.height=0;e.cv=null;}}; +function sprcTrim(){if(SPRC_B<=SPRC_BUDGET)return;const old=[];for(const [k,e] of SPRC)if(e.fa[0]-b[0]);const goal=SPRC_BUDGET*0.75; + for(const [,k,e] of old){if(SPRC_B<=goal)break;SPRC.delete(k);SPRC_B-=e.pw*e.ph*4;sprFree(e);}} +const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0,up:0,upq:false,memT:-1e9}; +/* One record is 13 floats: x,y,w,h (CSS px) | u0,v0,u1,v1 (atlas) | r,g,b,a | kind. A picture (kind 0) takes its + colours from the atlas and a from the record; a disc (kind 1) is centred on x,y with radius w, in colour r,g,b,a. */ +const SPR_VS=GL_HEAD+`layout(location=0) in vec4 aP;layout(location=1) in vec4 aUV;layout(location=2) in vec4 aC;layout(location=3) in float aK; +uniform vec2 uDev;uniform float uDpr;out vec2 vUV,vQ;out vec4 vC;flat out float vK,vR; +void main(){vec2 c=vec2((gl_VertexID&1)==0?0.:1.,(gl_VertexID&2)==0?0.:1.),p; + if(aK>.5){float m=aP.z+1./uDpr;vQ=(c*2.-1.)*m;vR=aP.z;vUV=vec2(0.);p=aP.xy+vQ;} + else{vQ=vec2(0.);vR=0.;vUV=mix(aUV.xy,aUV.zw,c);p=aP.xy+c*aP.zw;} + vC=aC;vK=aK;gl_Position=vec4(p.x*uDpr/uDev.x*2.-1.,1.-p.y*uDpr/uDev.y*2.,0.,1.);}`; +const SPR_FS=GL_HEAD+`uniform sampler2D uTex;uniform float uDpr;in vec2 vUV,vQ;in vec4 vC;flat in float vK,vR;out vec4 o; +void main(){if(vK>.5){float a=clamp((vR-length(vQ))*uDpr+.5,0.,1.)*vC.a;if(a<=0.)discard;o=vec4(vC.rgb*a,a);} + else o=texture(uTex,vUV)*vC.a;}`; +function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4,4,1]);GLS.vao=v;GLS.buf=b; + // 4096 px square (64 MB), or what the card allows if that is less (some phones). A card that has not the memory for + // it gets 2048 (16 MB: more resets of the atlas, the same map); without even that, the map stays 2D (glMem). + GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);glMem(gl,'setup'); + for(GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096);;GLS.size>>=1){ + gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null); + try{glMem(gl,'the pictures');break;}catch(e){if(GLS.size<=2048)throw e;}} + for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR); + for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE); + GLS.shx=GLS.shy=GLS.shh=0;GLS.memT=-1e9;GLS.upq=false;} +// Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it). +function spritesReset(){glsDrawNow();for(const e of SPRC.values())sprFree(e);SPRS.clear();SPRC.clear();SPRC_B=0;GLS.shx=GLS.shy=GLS.shh=0;} +// The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten. +function spritesDrop(){GLS.n=GLS.up=0;GLS.upq=false;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} +/* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a + canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context + and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas. + Each picture goes in with a clear border of GLS_GAP px: the card blends the texels around the point it reads, so a + picture drawn off whole pixels or a little stretched read half a texel past its edge, and showed a thin line of its + neighbour in the atlas (or of a picture from before the last reset, which leaves the texture as it was). */ +const GLS_GAP=1; +const GLS_PAD={cv:null,g:null}; +function glsPad(pw,ph){const P=GLS_PAD;if(!P.cv){P.cv=document.createElement('canvas');P.cv.width=P.cv.height=256;} + if(P.cv.width{const e=sprMap().get(key);if(e)e.f=SPR_F;return e;}; +// A picture of w×h CSS px with its anchor at (ax,ay): painted once by paint(g) (the 2D canvas, at the screen's pixel +// density), and kept by key in SPRS (the card's) or SPRC (the 2D map's). +function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M.get(key);if(e){e.f=SPR_F;return e;} + if(SPRS.size+SPRC.size>=SPR_MAX)spritesReset(); + const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx; + e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1,f:SPR_F}; + const G=GLS_GAP; + if(gpu&&pw+2*G<=GLS.size&&ph+2*G<=GLS.size){const P=glsPad(pw+2*G,ph+2*G),g=P.g; + // Clipped to the picture, as its own canvas would be, so the border stays clear. + g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw+2*G,ph+2*G);g.beginPath();g.rect(G,G,pw,ph);g.clip();ctx=g; + try{g.setTransform(DPR,0,0,DPR,G,G);sprPen(g);paint(g);}finally{ctx=saved;g.restore();} + // A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next. + try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);} + }else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g; + try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;}e.cv=cv; + if(M===SPRC)SPRC_B+=pw*ph*4;} + M.set(key,e);return e;} +/* A picture starts with the pen the map's own canvas has when it draws cities and markers: the tubes leave it with + round line ends and corners, the labels with text centred on its middle. Drawn straight on the map, the dashed rings, + the cones' tips and a sleeping POP's "zzz" took those, and a new canvas has others (square ends, text on its baseline). */ +function sprPen(g){g.lineCap='round';g.lineJoin='round';g.textAlign='center';g.textBaseline='middle';} +// Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame. +function glsEnsure(e){if(e.up)return true;const gl=GLX.gl,G=GLS_GAP;if(!gl||!GLS.prog||!e.cv)return false; + if(e.pw+2*G>GLS.size||e.ph+2*G>GLS.size)return false; + const P=glsPad(e.pw+2*G,e.ph+2*G),g=P.g;g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,e.pw+2*G,e.ph+2*G);g.drawImage(e.cv,G,G); + try{return glsPut(gl,e,P.cv);}catch(x){throw glErr(x);}} +// src holds the picture at (GLS_GAP,GLS_GAP), in a clear border that goes into the atlas with it. +function glsPut(gl,e,src){const G=GLS_GAP,pw=e.pw+2*G,ph=e.ph+2*G,A=GLS.size;if(pw>A||ph>A)return false; + if(GLS.shx+pw>A){GLS.shx=0;GLS.shy+=GLS.shh;GLS.shh=0;} + if(GLS.shy+ph>A){spritesReset();return false;} + const x=GLS.shx,y=GLS.shy;GLS.shx+=pw;GLS.shh=Math.max(GLS.shh,ph); + gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true); + // Only the picture's corner of the source (with its border): the pad is bigger than most pictures. + gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,pw,ph,gl.RGBA,gl.UNSIGNED_BYTE,src);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false); + GLS.up++;Object.assign(e,{up:true,u0:(x+G)/A,v0:(y+G)/A,u1:(x+pw-G)/A,v1:(y+ph-G)/A});return true;} +// The next record in GLS.data, which grows as needed: take it before reading GLS.data, which it may replace. +function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;} +// Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas. +function blit(e,x,y,w,h){if(GLS.frame&&glsEnsure(e)){const o=glsNext(),d=GLS.data; + d[o]=x;d[o+1]=y;d[o+2]=w;d[o+3]=h;d[o+4]=e.u0;d[o+5]=e.v0;d[o+6]=e.u1;d[o+7]=e.v1;d[o+8]=d[o+9]=d[o+10]=0;d[o+11]=ctx.globalAlpha;d[o+12]=0;} + else if(e.cv)ctx.drawImage(e.cv,x,y,w,h);} +// A round dot of radius r at (x,y), in colour col (CSS colour string) at opacity a, on the card or the 2D canvas. +function dot(x,y,r,col,a){if(GLS.frame){const c=glColor(col),o=glsNext(),d=GLS.data; + d[o]=x;d[o+1]=y;d[o+2]=r;d[o+3]=d[o+4]=d[o+5]=d[o+6]=d[o+7]=0;d[o+8]=c[0];d[o+9]=c[1];d[o+10]=c[2];d[o+11]=(a===undefined?ctx.globalAlpha:a)*c[3];d[o+12]=1;} + else{const sa=ctx.globalAlpha;if(a!==undefined)ctx.globalAlpha=a;ctx.fillStyle=col;ctx.beginPath();ctx.arc(x,y,r,0,7);ctx.fill();ctx.globalAlpha=sa;}} +/* Pictures that grow with the zoom (cities, ships, badges) are painted at steps of 1/24 of their scale. On the card, + while the zoom moves, they keep the step of the scale they had when it began, stretched by up to 1.25× either way + (the card filters them smoothly), and are painted again at the right step once the zoom rests (ZOOM_REST ms): a + pinch otherwise repainted every city at every step, hundreds of pictures a frame, and filled the atlas over and + over. ZH.sc is the icon scale held, ZH.f how much a picture is painted smaller (<1) or bigger than it shows. */ +const CSPR_STEP=24,ZOOM_REST=250,ZH={z:0,t:-1e9,sc:0,f:1}; +function zoomHold(sc,G){const t=performance.now();if(cam.z!==ZH.z){ZH.z=cam.z;ZH.t=t;} + if(!G||!ZH.sc||t-ZH.t>=ZOOM_REST||sc/ZH.sc>1.25||ZH.sc/sc>1.25)ZH.sc=sc;ZH.f=ZH.sc/sc;} +// The zoom moved a moment ago: the pictures may be stretched, so a still map is drawn again once it rests (mapStill()). +const zoomMoving=()=>performance.now()-ZH.tMath.max(1/CSPR_STEP,Math.round(k*ZH.f*CSPR_STEP)/CSPR_STEP); +// A small picture w×h px at scale k with its anchor at (ax,ay), painted once by paint(g) with the origin on the anchor +// (k in steps of 1/24, as the cities; zoomed: k grows with the zoom, and is held while it moves, sprQ()), then drawn with +// the anchor at (x,y). Things that bob or pulse are drawn as these at a moving place, so the overlay above the card +// stays untouched (repainting it costs a whole screen of pixels). +// The full key of a stamp at scale kq, kept per key: it was built again for every stamp on every frame. +const STK=new Map(); +function stamp(key,w,h,ax,ay,k,x,y,paint,zoomed){const kq=zoomed?sprQ(k):Math.max(1/CSPR_STEP,Math.round(k*CSPR_STEP)/CSPR_STEP),r=k/kq; + let m=STK.get(key);if(!m||m.kq!==kq){if(STK.size>4000)STK.clear();STK.set(key,m={kq,k:key+'|'+kq});} + const e=spriteHas(m.k)||spriteEntry(m.k,Math.ceil(w*kq),Math.ceil(h*kq),ax*kq,ay*kq,g=>{g.translate(ax*kq,ay*kq);g.scale(kq,kq);paint(g);}); + blit(e,x-e.ax*r,y-e.ay*r,e.w*r,e.h*r);} +// Text with an outline, centred on (x,y), as a picture placed on whole device pixels; tw is its width, px its size. +function textStamp(t,font,px,tw,fill,stroke,lw,x,y){const W=Math.ceil(tw+lw+4),H=Math.ceil(px*1.5+lw+2); + const e=spriteEntry(['txt',t,font,fill,stroke,lw].join('|'),W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.font=font;g.textAlign='center';g.textBaseline='middle'; + if(lw){g.lineWidth=lw;g.lineJoin='round';g.strokeStyle=stroke;g.strokeText(t,0,0);}g.fillStyle=fill;g.fillText(t,0,0);}); + blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);} +// Sends the queued pictures to the card in one draw. +function glsDrawNow(){const gl=GLX.gl,n=GLS.n;GLS.n=0;if(!gl||!GLS.prog||!n)return; + try{glsDraw(gl,n);}catch(x){throw glErr(x);}} +function glsDraw(gl,n){gl.useProgram(GLS.prog.p);gl.bindVertexArray(GLS.vao);gl.bindBuffer(gl.ARRAY_BUFFER,GLS.buf); + gl.bufferData(gl.ARRAY_BUFFER,GLS.data.subarray(0,n*SPR_STRIDE),gl.STREAM_DRAW); + gl.uniform2f(GLS.prog.u.uDev,GLX.c.width,GLX.c.height);gl.uniform1f(GLS.prog.u.uDpr,DPR);gl.uniform1i(GLS.prog.u.uTex,0); + gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex); + gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST); + gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);gl.bindVertexArray(null);} +/* The end of a frame on the card: the pictures go up over the tubes. The frame is over even if that draw fails. + Pictures sent are checked (did the card take them?): a card short of memory may refuse one without throwing, and the + picture would be kept as sent. It then gives the map to 2D (glMem() throws, draw() draws the frame again there and + glKill() forgets the card's pictures). Each read waits for the card to finish everything sent so far, so it is done + at most once every GL_MEM_EVERY ms: the card keeps an error until it is read, so a later read still finds it, and a + picture refused in between shows at worst as a dark box for that time. The first pictures sent into a new atlas are + checked at once (a card that allocates it lazily refuses there). A frame that only reuses the atlas asks nothing. */ +const GL_MEM_EVERY=1000; +function glsFrameEnd(){if(!GLS.frame)return;GLS.frame=false;if(GLS.up)GLS.upq=true;GLS.up=0; + if(GLS.upq&&GLX.gl){const t=performance.now();if(t-GLS.memT>=GL_MEM_EVERY){GLS.memT=t;GLS.upq=false;glMem(GLX.gl,'the pictures');}} + glsDrawNow();} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js new file mode 100644 index 0000000..721926a --- /dev/null +++ b/src/game/96-map/60-draw.js @@ -0,0 +1,154 @@ +/* A frame. An error from the card itself (glErr()) gives WebGL up for this session and draws the same frame again in + 2D, once; any other error goes on to the loop's tickErr(). Either way the 2D context and the sprite queue are reset. */ +function draw(now){for(let pass=0;;pass++){let err=null;DFC=new Map();SPR_F++; + try{drawFrame(now);}catch(e){err=e;} + try{glsFrameEnd();}catch(e){if(!err)err=e;}finally{DFC=null;GLS.frame=false;GLS.n=0;ctx=CTX0;sprcTrim();} + if(!err)return;if(!err.glErr||pass)throw err;glKill(err);}} +// Rectangles on a 64 px grid: a new one is compared only with the few that share its cells (a plain list made the +// label placement quadratic in the number of cities). +class RGrid{constructor(){this.m=new Map();} + cells(r,f){for(let cx=Math.floor(r.x/64);cx<=Math.floor((r.x+r.w)/64);cx++)for(let cy=Math.floor(r.y/64);cy<=Math.floor((r.y+r.h)/64);cy++)f(cx*100003+cy);} + push(r){this.cells(r,k=>{const a=this.m.get(k);if(a)a.push(r);else this.m.set(k,[r]);});} + hits(r){let h=false;this.cells(r,k=>{if(h)return;const a=this.m.get(k);if(a)for(const q of a)if(r.x