2679 lines
378 KiB
HTML
2679 lines
378 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||
<title>Series of Tubes — Build the Internet, One Tube at a Time</title>
|
||
<meta name="description" content="A free cartoon browser game about building the internet. Lay fiber and subsea cables, buy transit, peer at internet exchanges, host CDN caches and survive backhoes, sharks and BGP leaks on your way to Tier 1.">
|
||
<meta name="keywords" content="internet game, network simulation, BGP, peering, internet exchange, IXP, transit, CDN, subsea cables, dark fiber, browser game, Tier 1">
|
||
<meta name="author" content="Frederic Jung">
|
||
<meta name="robots" content="index, follow, max-image-preview:large">
|
||
<meta name="theme-color" content="#57C4E5">
|
||
<meta name="color-scheme" content="light">
|
||
<meta name="application-name" content="Series of Tubes">
|
||
<meta name="apple-mobile-web-app-title" content="Series of Tubes">
|
||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||
<meta name="mobile-web-app-capable" content="yes">
|
||
<meta name="format-detection" content="telephone=no">
|
||
<meta name="generator" content="Series of Tubes __VERSION__">
|
||
<link rel="canonical" href="https://seriesoftub.es/">
|
||
|
||
<!-- Open Graph -->
|
||
<meta property="og:type" content="website">
|
||
<meta property="og:site_name" content="Series of Tubes">
|
||
<meta property="og:title" content="Series of Tubes — Build the Internet, One Tube at a Time">
|
||
<meta property="og:description" content="Lay fiber, buy transit, peer at IXs and keep the eyeballs happy while backhoes, sharks and route leaks try to stop you. A free cartoon game about how the internet really works.">
|
||
<meta property="og:url" content="https://seriesoftub.es/">
|
||
<meta property="og:locale" content="en_US">
|
||
<meta property="og:image" content="https://seriesoftub.es/images/og-image.png">
|
||
<meta property="og:image:type" content="image/png">
|
||
<meta property="og:image:width" content="1200">
|
||
<meta property="og:image:height" content="630">
|
||
<meta property="og:image:alt" content="Series of Tubes: a cartoon world map with fiber links, subsea cables and routers">
|
||
|
||
<!-- Twitter / X -->
|
||
<meta name="twitter:card" content="summary_large_image">
|
||
<meta name="twitter:title" content="Series of Tubes — Build the Internet, One Tube at a Time">
|
||
<meta name="twitter:description" content="A free cartoon game about building the internet: fiber, transit, peering, CDNs, and a lot of backhoes.">
|
||
<meta name="twitter:image" content="https://seriesoftub.es/images/og-image.png">
|
||
<meta name="twitter:image:alt" content="Series of Tubes: a cartoon world map with fiber links, subsea cables and routers">
|
||
|
||
<!-- Icons -->
|
||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||
<link rel="icon" type="image/x-icon" href="/favicon.ico" sizes="32x32 16x16">
|
||
<link rel="icon" type="image/png" sizes="192x192" href="/icon-192.png">
|
||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||
<link rel="manifest" href="/site.webmanifest">
|
||
|
||
<!-- Fonts -->
|
||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||
<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
|
||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;700;800&family=Nunito:wght@500;700;800;900&display=swap">
|
||
|
||
<!-- Structured data -->
|
||
<script type="application/ld+json">
|
||
{
|
||
"@context": "https://schema.org",
|
||
"@type": "WebSite",
|
||
"name": "Series of Tubes",
|
||
"url": "https://seriesoftub.es/",
|
||
"description": "A free cartoon browser game about building the internet."
|
||
}
|
||
</script>
|
||
<script type="application/ld+json">
|
||
{
|
||
"@context": "https://schema.org",
|
||
"@type": "VideoGame",
|
||
"name": "Series of Tubes",
|
||
"url": "https://seriesoftub.es/",
|
||
"image": "https://seriesoftub.es/images/og-image.png",
|
||
"description": "Build an internet: lay terrestrial and subsea fiber, buy IP transit, peer at internet exchanges, set up PNIs and CDN caches, sign business customers and survive constant failures on your way to becoming a Tier 1 network.",
|
||
"genre": ["Simulation", "Strategy", "Tycoon"],
|
||
"gamePlatform": "Web browser",
|
||
"applicationCategory": "Game",
|
||
"operatingSystem": "Any",
|
||
"playMode": "SinglePlayer",
|
||
"inLanguage": "en",
|
||
"isAccessibleForFree": true,
|
||
"softwareVersion": "__VERSION__",
|
||
"dateModified": "__BUILD_DATE__",
|
||
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },
|
||
"author": { "@type": "Person", "name": "Frederic Jung", "url": "https://github.com/fjaeckel" }
|
||
}
|
||
</script>
|
||
<style>
|
||
/* Layout: full-bleed cartoon world map on canvas; sticker-style panels float above it (HUD top, goals left, inspector right / bottom sheet on phones). Single committed bright look. */
|
||
:root{
|
||
--sea:#57C4E5; --sea2:#3AA6CF; --wave:#9BE2F2; --land:#9BDA6C; --land2:#7FC455; --sand:#F8E6A8;
|
||
--ink:#1E2640; --ink2:#55608A; --paper:#FFFFFF; --soft:#EEF5FB; --line:#D5DEEC;
|
||
--me:#FF4F9A; --sun:#FFD23F; --ok:#22C47A; --warn:#FFAA1F; --bad:#FF4D5E;
|
||
--t1:#7B61FF; --t2:#2F8CFF; --cdn:#FF8A3D; --eye:#16A866;
|
||
--display:'Baloo 2','Trebuchet MS',system-ui,sans-serif;
|
||
--body:'Nunito',system-ui,-apple-system,sans-serif;
|
||
color-scheme:light;
|
||
}
|
||
[hidden]{display:none!important}
|
||
html,body{height:100%}
|
||
body{margin:0}
|
||
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
|
||
.ver{font-size:11.5px;color:var(--ink2);margin-top:10px}
|
||
.ver a{color:inherit}
|
||
body{background:var(--sea);color:var(--ink);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased}
|
||
#map{position:fixed;inset:0;width:100%;height:100%;touch-action:none;display:block;cursor:grab}
|
||
#map.linking{cursor:crosshair}
|
||
.num{font-variant-numeric:tabular-nums}
|
||
h2,h3,h4{font-family:var(--display);margin:0;text-wrap:balance;line-height:1.1}
|
||
button{font:inherit;color:inherit}
|
||
:focus-visible{outline:3px solid var(--me);outline-offset:2px}
|
||
|
||
/* sticker surfaces */
|
||
.card{background:var(--paper);border:3px solid var(--ink);border-radius:18px;box-shadow:4px 4px 0 var(--ink)}
|
||
|
||
/* HUD */
|
||
#hud{position:fixed;top:calc(env(safe-area-inset-top,0px) + 10px);left:max(12px,env(safe-area-inset-left,0px));right:max(12px,env(safe-area-inset-right,0px));display:flex;gap:8px;align-items:stretch;flex-wrap:wrap;pointer-events:none;z-index:5}
|
||
#hud>*{pointer-events:auto}
|
||
.chip{background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:3px 3px 0 var(--ink);padding:3px 11px;display:flex;flex-direction:column;justify-content:center;min-height:46px}
|
||
.chip .lbl{font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--ink2)}
|
||
.chip .val{font-family:var(--display);font-weight:800;font-size:19px;line-height:1.05;white-space:nowrap}
|
||
.chip .sub{font-size:11px;font-weight:800;white-space:nowrap}
|
||
.brand{flex-direction:row;align-items:center;gap:9px;background:var(--me);color:#fff}
|
||
.brand .val{font-size:20px}
|
||
.brand .lbl{color:#FFE0EE}
|
||
.tube{width:30px;height:30px;flex:none}
|
||
.up{color:var(--ok)} .down{color:var(--bad)}
|
||
.speed{flex-direction:row;align-items:center;gap:4px;padding:4px 6px}
|
||
.speed button{border:2.5px solid var(--ink);background:var(--paper);border-radius:9px;min-width:34px;height:32px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13px}
|
||
.speed button.on{background:var(--sun)}
|
||
.spacer{flex:1}
|
||
.noc{cursor:pointer;border:3px solid var(--ink)}
|
||
.hotk{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:24px;padding:0 4px;border-radius:12px;border:2px solid var(--ink,#1E2640);font:900 11px Nunito,sans-serif;margin-right:8px;color:#fff;background:#FF4D5E}
|
||
.hotk.hk-ix{color:#1E2640;background:#FFD23F}
|
||
.noc.hot{background:var(--bad);color:#fff;animation:throb 1s ease-in-out infinite}
|
||
.noc.hot .lbl{color:#FFE1E4}
|
||
@keyframes throb{50%{transform:scale(1.05)}}
|
||
.minibar{height:6px;border-radius:4px;background:var(--line);overflow:hidden;margin-top:2px;width:100%}
|
||
.minibar i{display:block;height:100%;background:var(--ok)}
|
||
|
||
/* drawers */
|
||
#left{position:fixed;top:calc(env(safe-area-inset-top,0px) + 76px);left:max(12px,env(safe-area-inset-left,0px));width:300px;max-height:calc(100% - 96px - env(safe-area-inset-top,0px) - env(safe-area-inset-bottom,0px));display:flex;flex-direction:column;z-index:4}
|
||
#panel{position:fixed;top:calc(env(safe-area-inset-top,0px) + 76px);right:max(12px,env(safe-area-inset-right,0px));width:370px;max-height:calc(100% - 96px - env(safe-area-inset-top,0px) - env(safe-area-inset-bottom,0px));display:flex;flex-direction:column;z-index:4}
|
||
.scroll{overflow:auto;padding:12px 14px 14px;overscroll-behavior:contain}
|
||
.tabs{display:flex;gap:4px;padding:8px 8px 0;border-bottom:3px solid var(--ink);flex:none}
|
||
.tabs button{border:2.5px solid var(--ink);border-bottom:none;border-radius:11px 11px 0 0;background:var(--soft);padding:4px 10px 3px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13.5px;position:relative;top:3px}
|
||
.tabs button.on{background:var(--paper);padding-bottom:6px}
|
||
.tabs .cnt{display:inline-block;background:var(--me);color:#fff;border-radius:9px;padding:0 6px;font-size:11px;margin-left:4px}
|
||
.tabs .cnt.red{background:var(--bad)}
|
||
#leftToggle{display:none}
|
||
|
||
.ph{display:flex;align-items:flex-start;gap:8px;padding:12px 14px 8px;border-bottom:3px solid var(--ink);flex:none}
|
||
.ph h2{font-size:26px}
|
||
.eyebrow{font-size:10.5px;font-weight:900;letter-spacing:.09em;text-transform:uppercase;color:var(--ink2)}
|
||
.x{margin-left:auto;border:2.5px solid var(--ink);background:var(--paper);border-radius:10px;width:32px;height:32px;font-size:20px;line-height:1;cursor:pointer;font-weight:900;flex:none}
|
||
.facts{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}
|
||
.fact{background:var(--soft);border:2px solid var(--ink);border-radius:9px;padding:1px 8px;font-size:12px;font-weight:700}
|
||
.fact.ixf{background:#FFF3C4}
|
||
.fact.mine{background:var(--me);color:#fff}
|
||
.fact.down{background:var(--bad);color:#fff}
|
||
section{padding:10px 0;border-bottom:2px dashed var(--line)}
|
||
section:last-child{border-bottom:none}
|
||
section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap:8px}
|
||
.lead{margin:0 0 8px;color:var(--ink2);font-size:12.5px;line-height:1.45}
|
||
.note{margin:6px 0 0;color:var(--ink2);font-size:12.5px;line-height:1.4}
|
||
.kv{display:flex;justify-content:space-between;gap:8px;font-size:13px;margin:3px 0}
|
||
.kv b{font-variant-numeric:tabular-nums}
|
||
.row{display:flex;align-items:center;gap:8px;padding:7px 0;border-top:1px solid var(--line)}
|
||
.row:first-of-type{border-top:none}
|
||
.row .grow{flex:1;min-width:0}
|
||
.row .nm{font-weight:800;font-size:13.5px;line-height:1.2}
|
||
.row .meta{font-size:11.5px;color:var(--ink2);line-height:1.3}
|
||
.btns{display:flex;flex-wrap:wrap;gap:5px;margin-top:5px}
|
||
.why{font-size:11px;color:#B23A48;font-weight:700;margin-top:3px;line-height:1.3}
|
||
|
||
.b{font-family:var(--display);font-weight:800;border:2.5px solid var(--ink);border-radius:11px;background:var(--sun);box-shadow:0 3px 0 var(--ink);padding:4px 11px 3px;cursor:pointer;font-size:14px;line-height:1.2;white-space:nowrap;transition:transform .06s}
|
||
.b:hover{filter:brightness(1.05)}
|
||
.b:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)}
|
||
.b:disabled{opacity:.42;cursor:not-allowed;transform:none;box-shadow:0 3px 0 var(--ink)}
|
||
.b.ghost{background:var(--paper)}
|
||
.b.pink{background:var(--me);color:#fff}
|
||
.b.red{background:var(--bad);color:#fff}
|
||
.b.green{background:var(--ok);color:#fff}
|
||
.b.sm{font-size:12px;padding:2px 8px 1px;border-radius:9px;box-shadow:0 2px 0 var(--ink)}
|
||
.b.big{font-size:18px;padding:7px 18px 5px}
|
||
.b small{font-family:var(--body);font-weight:800;font-size:10.5px;opacity:.85;margin-left:3px}
|
||
|
||
.logo{width:30px;height:30px;border-radius:50%;background:var(--c);border:2.5px solid var(--ink);display:grid;place-items:center;color:#fff;font-family:var(--display);font-weight:800;font-size:11px;flex:none;letter-spacing:-.02em}
|
||
.tag{display:inline-block;border:1.8px solid var(--ink);border-radius:7px;padding:0 5px;font-size:10px;font-weight:900;letter-spacing:.03em;text-transform:uppercase;vertical-align:1px;color:#fff;background:var(--ink2)}
|
||
.tag.t1{background:var(--t1)} .tag.t2{background:var(--t2)} .tag.cdn{background:var(--cdn)} .tag.eye{background:var(--eye)}
|
||
.tag.open{background:var(--ok)} .tag.selective{background:var(--warn);color:var(--ink)} .tag.restrictive{background:var(--bad)} .tag.paid{background:var(--me)}
|
||
.tag.st{background:var(--paper);color:var(--ink)}
|
||
.tag.st.on{background:var(--ink);color:#fff}
|
||
.bar{height:11px;border:2px solid var(--ink);border-radius:7px;background:var(--paper);overflow:hidden;margin:3px 0}
|
||
.stack{display:flex;height:16px;border:2px solid var(--ink);border-radius:8px;overflow:hidden;margin:4px 0 6px;background:var(--paper)}
|
||
.stack i{display:block;height:100%}
|
||
.sub4{font-size:13.5px;margin:10px 0 3px}
|
||
.dot{display:inline-block;width:10px;height:10px;border-radius:50%;border:1.5px solid var(--ink);margin-right:6px;vertical-align:-1px}
|
||
.bar>i{display:block;height:100%;background:var(--ok);transition:width .3s}
|
||
.bar.warn>i{background:var(--warn)} .bar.bad>i{background:var(--bad)} .bar.me>i{background:var(--me)}
|
||
|
||
.goal{display:flex;gap:9px;padding:8px 0;border-top:1px solid var(--line)}
|
||
.goal:first-child{border-top:none}
|
||
.goal .ck{width:22px;height:22px;border:2.5px solid var(--ink);border-radius:7px;flex:none;display:grid;place-items:center;font-weight:900;background:var(--paper);font-size:13px}
|
||
.goal.done .ck{background:var(--ok);color:#fff}
|
||
.goal.done .gt{text-decoration:line-through;color:var(--ink2)}
|
||
.goal.cur{background:#FFF6CF;margin:0 -14px;padding:9px 14px;border-top:2px solid var(--ink);border-bottom:2px solid var(--ink)}
|
||
.goal .gt{font-weight:900;font-size:13.5px}
|
||
.goal .gd{font-size:12px;color:var(--ink2);line-height:1.4;margin-top:2px}
|
||
.goal .gr{font-size:11px;font-weight:900;color:var(--eye);margin-top:2px}
|
||
.empty{color:var(--ink2);font-size:12.5px;line-height:1.45;padding:6px 0}
|
||
.inc{border:2.5px solid var(--ink);border-radius:12px;padding:8px 10px;margin-bottom:8px;background:#FFF0F1}
|
||
.inc .nm{font-weight:900}
|
||
.inc .meta{font-size:12px;color:var(--ink2);margin-top:2px;line-height:1.35}
|
||
|
||
/* toasts */
|
||
#toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom,0px) + 14px);display:flex;flex-direction:column-reverse;gap:8px;z-index:8;width:min(460px,calc(100% - 32px));pointer-events:none}
|
||
.toast{pointer-events:none;background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:3px 3px 0 var(--ink);padding:9px 12px;display:flex;gap:10px;align-items:center;animation:pop .25s cubic-bezier(.3,1.6,.6,1)}
|
||
.toast.good{background:#DFFBEA} .toast.bad{background:#FFE1E4} .toast.goal{background:#FFF3C4}
|
||
.toast .b{pointer-events:auto}
|
||
.seg{display:flex;flex-wrap:wrap;gap:6px}
|
||
.seg .b{white-space:normal;text-align:left}
|
||
.toast .tx{flex:1;font-size:13px;line-height:1.35}
|
||
.toast .tx b{font-family:var(--display);font-size:14.5px}
|
||
@keyframes pop{from{transform:scale(.8) translateY(10px);opacity:0}}
|
||
|
||
#hint{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 76px);background:var(--ink);color:#fff;border-radius:12px;padding:6px 12px;font-weight:800;font-size:12.5px;z-index:3;pointer-events:none;max-width:min(440px,calc(100% - 32px));text-align:center;box-shadow:3px 3px 0 rgba(30,38,64,.25)}
|
||
|
||
/* modal */
|
||
.seg.site{margin-top:4px;align-items:center}
|
||
.seg.site .meta{margin-right:4px}
|
||
.badges{display:grid;grid-template-columns:repeat(auto-fill,minmax(118px,1fr));gap:6px}
|
||
.bdg{border:2px solid #C9CEDD;border-radius:12px;padding:6px 7px;background:#F3F4F8;opacity:.6;display:flex;flex-direction:column;gap:1px;min-width:0}
|
||
.bdg .bi{font-size:20px;filter:grayscale(1)}
|
||
.bdg .bt{font:800 12.5px/1.2 "Baloo 2",sans-serif;color:var(--ink)}
|
||
.bdg .br{font:900 10px Nunito,sans-serif;color:var(--rc);text-transform:uppercase;letter-spacing:.04em}
|
||
.bdg .bd{font-size:11px;color:#5A6280;line-height:1.25}
|
||
.bdg.ever{opacity:.85;border-style:dashed;border-color:var(--rc)}
|
||
.bdg.on{opacity:1;border-color:var(--rc);background:#fff;box-shadow:0 2px 0 var(--rc)}
|
||
.bdg.on .bi,.bdg.ever .bi{filter:none}
|
||
.scn{display:flex;gap:10px;align-items:center;border:2px solid #DDE1EC;border-radius:12px;padding:8px 10px;margin-top:8px}
|
||
.scn.wk{border-color:var(--me);background:#FFF0F6}
|
||
.scn .nm{font-weight:900}
|
||
.term{background:#1E2640;color:#7CFFB2;font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;padding:10px 12px;border-radius:10px;overflow-x:auto;white-space:pre;margin:8px 0}
|
||
.trsel{display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end;margin-top:8px}
|
||
.trsel label{display:flex;flex-direction:column;font:800 12px Nunito,sans-serif;gap:2px}
|
||
.trsel select{font:700 14px Nunito,sans-serif;padding:4px 6px;border:2px solid var(--ink);border-radius:8px;max-width:240px}
|
||
.fact.trb{cursor:pointer;font:inherit;border:2px solid var(--ink);background:#fff}
|
||
#coach{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 74px);z-index:16;width:min(520px,calc(100% - 24px));background:#fff;border:3px solid var(--ink);border-radius:14px;box-shadow:0 4px 0 var(--ink);padding:8px 10px;display:flex;gap:8px;align-items:center}
|
||
#coach .ct{flex:1;font-weight:800;font-size:14px;line-height:1.35}
|
||
#coach .cs{display:block;font:900 10px Nunito,sans-serif;color:var(--me);text-transform:uppercase;letter-spacing:.05em}
|
||
.coach-glow{animation:coachglow 1s ease-in-out infinite;position:relative;z-index:2}
|
||
@keyframes coachglow{0%,100%{box-shadow:0 0 0 0 rgba(255,79,154,.9)}50%{box-shadow:0 0 0 6px rgba(255,79,154,.35)}}
|
||
@media (prefers-reduced-motion:reduce){:root:not(.anim-force) .coach-glow{animation:none;outline:3px solid #FF4F9A}}
|
||
:root.no-anim .coach-glow{outline:3px solid #FF4F9A}
|
||
.setline{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:4px 0}
|
||
.setline>span{font-weight:800}
|
||
.menu-list{display:flex;flex-direction:column;gap:8px;margin-top:12px}
|
||
.menu-list .b{justify-content:space-between;width:100%}
|
||
#mega{position:fixed;left:0;right:0;bottom:0;z-index:17;background:#7A86B8;border-top:3px solid var(--ink);overflow:hidden;white-space:nowrap;pointer-events:none;animation:megaflash 1.2s steps(2) infinite}
|
||
#mega .mtrack{display:inline-block;padding:7px 0;animation:megascroll 40s linear infinite;font:900 16px "Baloo 2",sans-serif;color:#fff;text-shadow:0 2px 0 var(--ink)}
|
||
#mega span{margin:0 28px}
|
||
#mega span::after{content:"🐘";margin-left:56px}
|
||
@keyframes megascroll{from{transform:translateX(0)}to{transform:translateX(-50%)}}
|
||
@keyframes megaflash{0%{background:#7A86B8}50%{background:#FF4D5E}}
|
||
@media (prefers-reduced-motion:reduce){#mega,#mega .mtrack{animation:none}}
|
||
#update{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 70px);z-index:18;width:min(520px,calc(100% - 24px));pointer-events:auto}
|
||
#update .b{pointer-events:auto}
|
||
.notes{margin:10px 0 0;padding-left:20px;line-height:1.5}
|
||
.notes li{margin:4px 0}
|
||
#bankBox{position:fixed;inset:0;background:rgba(30,38,64,.35);z-index:16;overflow:auto;padding:calc(env(safe-area-inset-top,0px) + 12px) max(12px,env(safe-area-inset-right,0px)) 16px max(12px,env(safe-area-inset-left,0px))}
|
||
#bankCard{max-width:760px;margin:0 auto;padding:16px 18px 18px;background:var(--paper)}
|
||
.menubtn{cursor:pointer;text-align:left;font:inherit;border-color:var(--ink)}
|
||
.menubtn .caret{font-size:13px;margin-left:2px;opacity:.85}
|
||
.cashbtn{cursor:pointer;text-align:left;font:inherit;color:inherit;position:relative}
|
||
.cashbtn .badge{position:absolute;top:-8px;right:-8px;background:var(--me);color:#fff;border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 6px;line-height:16px}
|
||
.loan{border:2.5px solid var(--ink);border-radius:14px;padding:10px 12px;margin-top:10px;display:flex;gap:10px;align-items:flex-start}
|
||
.loan .grow{flex:1;min-width:0}
|
||
.loan .terms{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0}
|
||
.grade{font-family:var(--display);font-weight:800;font-size:30px;line-height:1;border:3px solid var(--ink);border-radius:12px;padding:4px 10px;background:var(--sun)}
|
||
#dash{position:fixed;inset:0;background:rgba(30,38,64,.35);z-index:15;overflow:auto;padding:calc(env(safe-area-inset-top,0px) + 12px) max(12px,env(safe-area-inset-right,0px)) 16px max(12px,env(safe-area-inset-left,0px))}
|
||
#dashCard{max-width:980px;margin:0 auto;padding:16px 18px 18px;background:var(--paper)}
|
||
.dgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin:10px 0}
|
||
.tile{border:2.5px solid var(--ink);border-radius:13px;padding:6px 10px;background:var(--soft)}
|
||
.tile .lbl{font-size:10px;font-weight:900;letter-spacing:.08em;text-transform:uppercase;color:var(--ink2)}
|
||
.tile .val{font-family:var(--display);font-weight:800;font-size:22px;line-height:1.1;font-variant-numeric:tabular-nums}
|
||
.tile .sub{font-size:11.5px;color:var(--ink2);font-weight:700}
|
||
.dcols{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr);gap:12px}
|
||
@media (max-width:760px){.dcols{grid-template-columns:minmax(0,1fr)}}
|
||
.panel2{border:2.5px solid var(--ink);border-radius:14px;padding:10px 12px;min-width:0}
|
||
.panel2 h3{font-size:17px;margin-bottom:4px}
|
||
.chart{width:100%;height:auto;display:block}
|
||
.legend{display:flex;flex-wrap:wrap;gap:10px;font-size:11.5px;font-weight:800;color:var(--ink2);margin-top:4px}
|
||
.legend i{display:inline-block;width:11px;height:11px;border-radius:3px;border:1.5px solid var(--ink);margin-right:5px;vertical-align:-1px}
|
||
.tbl{width:100%;border-collapse:collapse;font-size:12.5px;font-variant-numeric:tabular-nums}
|
||
.tbl th{text-align:left;font-size:10px;letter-spacing:.07em;text-transform:uppercase;color:var(--ink2);padding:4px 6px;border-bottom:2px solid var(--ink)}
|
||
.tbl td{padding:5px 6px;border-bottom:1px solid var(--line);vertical-align:middle}
|
||
.tbl td.r,.tbl th.r{text-align:right}
|
||
.mix{display:flex;height:10px;width:100px;border:1.5px solid var(--ink);border-radius:5px;overflow:hidden;background:var(--paper)}
|
||
.mix i{display:block;height:100%}
|
||
.tscroll{overflow-x:auto}
|
||
#modal{position:fixed;inset:0;background:rgba(30,38,64,.45);display:grid;place-items:center;z-index:20;padding:16px max(16px,env(safe-area-inset-right,0px)) 16px max(16px,env(safe-area-inset-left,0px))}
|
||
#modal .card{width:min(560px,100%);max-height:calc(100% - 20px);overflow:auto;padding:20px 22px}
|
||
.title-art{display:flex;align-items:center;gap:14px}
|
||
.title-art h1{font-family:var(--display);font-weight:800;font-size:clamp(34px,7vw,52px);line-height:.95;margin:0;letter-spacing:-.01em}
|
||
.title-art h1 span{color:var(--me)}
|
||
.tagline{color:var(--ink2);font-size:14.5px;line-height:1.45;margin:10px 0 14px}
|
||
label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink2);margin:12px 0 5px}
|
||
input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 12px;font-family:var(--display);font-weight:800;font-size:18px;background:var(--soft)}
|
||
.starts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
|
||
.start{border:3px solid var(--ink);border-radius:14px;padding:8px 10px;background:var(--paper);cursor:pointer;text-align:left;box-shadow:0 3px 0 var(--ink)}
|
||
.start.on{background:#FFE3F0;border-color:var(--me);box-shadow:0 3px 0 var(--me)}
|
||
.start b{font-family:var(--display);font-size:17px;display:block}
|
||
.start span{font-size:12px;color:var(--ink2);line-height:1.3;display:block}
|
||
.tiers{display:grid;gap:7px;margin-top:10px}
|
||
.tierbtn{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:13px;padding:8px 12px;background:var(--paper);cursor:pointer;box-shadow:0 3px 0 var(--ink);text-align:left}
|
||
.tierbtn:hover{background:#FFF6CF}
|
||
.tierbtn:disabled{opacity:.4;cursor:not-allowed}
|
||
.tierbtn .sz{font-family:var(--display);font-weight:800;font-size:22px;width:70px}
|
||
.tierbtn .grow{flex:1}
|
||
.tierbtn .pr{font-family:var(--display);font-weight:800;font-size:18px}
|
||
.gl dt{font-family:var(--display);font-weight:800;font-size:16px;margin-top:10px}
|
||
.gl dd{margin:2px 0 0;color:var(--ink2);line-height:1.45;font-size:13px}
|
||
.kbd{display:inline-block;border:2px solid var(--ink);border-radius:6px;padding:0 5px;font-weight:900;font-size:11px;background:var(--soft)}
|
||
|
||
@media (max-width:760px){
|
||
.chip{min-height:40px;padding:2px 8px}
|
||
.chip .val{font-size:16px}
|
||
.chip .lbl{font-size:9px}
|
||
.brand .val{font-size:16px}
|
||
.hide-sm{display:none !important}
|
||
#hud{gap:6px}
|
||
.chip{min-height:34px;padding:2px 7px;border-width:2.5px;box-shadow:2px 2px 0 var(--ink);border-radius:11px}
|
||
.chip .val{font-size:14px}
|
||
.chip .sub{font-size:10px}
|
||
.brand .tube{width:22px;height:22px}
|
||
.brand>div{display:none}
|
||
.speed{padding:2px 4px;gap:3px}
|
||
.speed button{min-width:28px;height:26px;font-size:11.5px;border-width:2px;border-radius:7px}
|
||
.spacer{display:none}
|
||
#left{top:auto}
|
||
#left{top:auto;bottom:calc(env(safe-area-inset-bottom,0px) + 8px);left:8px;right:8px;width:auto;max-height:55%}
|
||
#left.closed{display:none}
|
||
#leftToggle{display:flex;position:fixed;left:max(12px,env(safe-area-inset-left,0px));bottom:calc(env(safe-area-inset-bottom,0px) + 14px);z-index:4}
|
||
#panel{top:auto;bottom:calc(env(safe-area-inset-bottom,0px) + 8px);left:8px;right:8px;width:auto;max-height:58%;z-index:6}
|
||
.ph h2{font-size:22px}
|
||
#hint{top:auto;bottom:calc(env(safe-area-inset-bottom,0px) + 70px)}
|
||
#toasts{bottom:auto;top:calc(env(safe-area-inset-top,0px) + 112px);flex-direction:column;width:calc(100% - 24px)}
|
||
.toast{padding:6px 10px;border-width:2.5px;box-shadow:2px 2px 0 var(--ink)}
|
||
.toast .tx{font-size:12px}
|
||
.toast .tx b{font-size:13px}
|
||
}
|
||
@media (prefers-reduced-motion:reduce){:root:not(.anim-force) *{animation:none !important;transition:none !important}}
|
||
:root.no-anim *{animation:none !important;transition:none !important}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<header class="sr-only">
|
||
<h1>Series of Tubes: build the internet, one tube at a time</h1>
|
||
<p>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.</p>
|
||
</header>
|
||
<noscript>
|
||
<div style="max-width:640px;margin:40px auto;padding:0 16px;font:16px/1.5 system-ui,sans-serif;color:#1E2640;background:#fff">
|
||
<h1>Series of Tubes</h1>
|
||
<p>Series of Tubes is a cartoon game about building the internet: fiber, transit, peering, CDNs and a lot of backhoes. It runs entirely in your browser and needs JavaScript to play.</p>
|
||
<p><a href="https://github.com/fjaeckel/seriesoftubes">Source code on GitHub</a></p>
|
||
</div>
|
||
</noscript>
|
||
<canvas id="map" aria-label="World map of your network"></canvas>
|
||
|
||
<header id="hud">
|
||
<button class="chip brand menubtn" data-act="menu" aria-label="Network menu: save, load or start over">
|
||
<svg class="tube" viewBox="0 0 32 32" aria-hidden="true"><path d="M4 22c0-7 5-12 12-12h6" fill="none" stroke="#1E2640" stroke-width="7" stroke-linecap="round"/><path d="M4 22c0-7 5-12 12-12h6" fill="none" stroke="#FFD23F" stroke-width="3.5" stroke-linecap="round"/><circle cx="25" cy="10" r="5" fill="#fff" stroke="#1E2640" stroke-width="2.5"/></svg>
|
||
<div><div class="val" id="hName">Series of Tubes</div><div class="lbl" id="hAsn">AS —</div></div><span class="caret" aria-hidden="true">▾</span>
|
||
</button>
|
||
<button class="chip cashbtn" data-act="bank" aria-label="Cash and bank"><span class="lbl">Cash · Bank</span><span class="val num" id="hCash">$0</span><span class="sub num" id="hRate">—</span><span class="badge" id="hBank" hidden></span></button>
|
||
<div class="chip hide-sm"><div class="lbl">Traffic served</div><div class="val num" id="hTraffic">0</div><div class="minibar"><i id="hTrafBar" style="width:0"></i></div></div>
|
||
<div class="chip"><div class="lbl">Reach</div><div class="val num" id="hReach">0%</div></div>
|
||
<div class="chip hide-sm"><div class="lbl">Rank</div><div class="val" id="hTier">Tier 3</div></div>
|
||
<button class="chip noc" id="hNoc" data-act="leftTab" data-args='{"t":"noc"}'><span class="lbl">NOC</span><span class="val num" id="hNocVal">All quiet</span></button>
|
||
<div class="spacer"></div>
|
||
<div class="chip"><div class="lbl">Date</div><div class="val num" id="hDate">Y1 · Jan 1</div></div>
|
||
<div class="chip speed" role="group" aria-label="Game speed">
|
||
<button data-act="speed" data-args='{"v":0}' id="sp0" aria-label="Pause">❚❚</button>
|
||
<button data-act="speed" data-args='{"v":0.5}' id="sp0.5" aria-label="Half speed">½×</button>
|
||
<button data-act="speed" data-args='{"v":1}' id="sp1">1×</button>
|
||
<button data-act="speed" data-args='{"v":2}' id="sp2">2×</button>
|
||
<button data-act="speed" data-args='{"v":4}' id="sp4">4×</button>
|
||
<button data-act="speed" data-args='{"v":8}' id="sp8">8×</button>
|
||
<button data-act="dash" aria-label="NOC dashboard" title="NOC dashboard"><svg width="16" height="14" viewBox="0 0 16 14" aria-hidden="true"><path d="M1 13h14M2 10l4-5 3 3 5-6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
|
||
<button data-act="help" aria-label="How to play">?</button>
|
||
<button data-act="mute" id="muteBtn" aria-label="Toggle sound">♪</button>
|
||
</div>
|
||
</header>
|
||
|
||
<aside id="left" class="card">
|
||
<nav class="tabs" id="leftTabs"></nav>
|
||
<div class="scroll" id="leftBody"></div>
|
||
</aside>
|
||
<button id="leftToggle" class="b pink" data-act="toggleLeft">Goals & NOC</button>
|
||
|
||
<aside id="panel" class="card" hidden>
|
||
<div id="panelBody" style="display:flex;flex-direction:column;min-height:0;flex:1"></div>
|
||
</aside>
|
||
|
||
<div id="hint" hidden></div>
|
||
<div id="coach" hidden role="status"></div>
|
||
<div id="toasts" aria-live="polite"></div>
|
||
<div id="mega" hidden role="alert"><div class="mtrack"><span>🐘 BREAKING: CVE-2026-31337 IN PHP TAKES DOWN HALF THE INTERNET</span><span>Every WordPress-ish site on Earth is now a crypto miner</span><span><?php echo "sorry"; ?></span><span>Eyeball traffic down 30%</span><span>Hosting customers patching at 3 a.m.</span><span>Security team asks: “are we on PHP?” Everyone: “define we”</span><span>🐘 BREAKING: CVE-2026-31337 IN PHP TAKES DOWN HALF THE INTERNET</span><span>Every WordPress-ish site on Earth is now a crypto miner</span><span><?php echo "sorry"; ?></span><span>Eyeball traffic down 30%</span><span>Hosting customers patching at 3 a.m.</span><span>Security team asks: “are we on PHP?” Everyone: “define we”</span></div></div>
|
||
<div id="update" class="toast goal" hidden role="status"></div>
|
||
<div id="bankBox" hidden><div class="card" id="bankCard" role="dialog" aria-label="Bank"></div></div>
|
||
<div id="dash" hidden><div class="card" id="dashCard" role="dialog" aria-label="NOC dashboard"></div></div>
|
||
<div id="modal" hidden><div class="card" id="modalCard" role="dialog" aria-modal="true"></div></div>
|
||
|
||
<script>
|
||
'use strict';
|
||
/* ================= 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__*/[];
|
||
const IS_DEV=APP_VERSION.startsWith('__');
|
||
// Only report from the real site; previews, localhost and the Claude viewer stay silent.
|
||
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)?'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];
|
||
/* ================= CONSTANTS ================= */
|
||
const W=2000, H=1000, KM=14;
|
||
const POP_COST=20000, POP_MO=1500, EYE_RATE=150, CACHE_CAP=100, CACHE_MO=400;
|
||
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;
|
||
const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000;
|
||
const SITE2_N=['The Other Building','Campus B (the one with parking)','Across-the-River DC','The Annex','Suburban Mega-shed','The Cheaper One','Formerly a Shopping Mall','Bunker Two'];
|
||
const siteName=(c,s)=>s==='b'?SITE2_N[hstr(c)%SITE2_N.length]:CITY[c].dc;
|
||
const popCost=c=>POP_COST+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0);
|
||
const CN_LIC=150000, CN_JV_MO=6000, SCRUB_COST=60000, SCRUB_MO=5000;
|
||
const MYIX_COST=80000, MYIX_MO=3000, MYIX_FEE=1500, START_CASH=200000;
|
||
const LT=[{n:'10G',g:10,m:1},{n:'100G',g:100,m:2.8},{n:'400G',g:400,m:6},{n:'1.6T',g:1600,m:13},{n:'6.4T',g:6400,m:28}];
|
||
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}];
|
||
const RG=[
|
||
{n:'Rusty Router 9000',pn:'100G',cap:400,cost:0,mo:0,maxLT:1,maxP:1,lvl:1,boot:6,slowP:10,chip:'a mystery ASIC',blurb:'Bought used on eBuy. The fans sound like a jet engine.'},
|
||
{n:'Edge Lord 400',pn:'400G',cap:3200,cost:30000,mo:1000,maxLT:2,maxP:2,lvl:2,boot:11,slowP:20,chip:'merchant silicon',blurb:'Sharp, edgy, and finally speaks 400G and 400ZR+.'},
|
||
{n:'Chonk 800',pn:'800G',cap:12800,cost:90000,mo:3000,maxLT:4,maxP:3,lvl:3,boot:25,slowP:45,chip:'Junipurr PacketOinker™',blurb:'An absolute unit with 800G ports, built around the Junipurr PacketOinker™ forwarding chip. Oinks at line rate. Takes 800ZR+ optics.'},
|
||
{n:'Absolute Unit 1.6T',pn:'1.6T',cap:51200,cost:250000,mo:8000,maxLT:4,maxP:3,lvl:4,boot:40,slowP:60,chip:'PacketOinker² (two pigs, one chassis)',blurb:'1.6T ports, its own weather system and two PacketOinker² chips per line card. Needs a forklift.'},
|
||
];
|
||
/* 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=['is oinking through the self-test of every PacketOinker on every line card','is running fsck on a compact flash card older than your interns','found a newer firmware on the USB stick someone left in it, and is installing it','is counting to 2 million routes. Out loud. One at a time','is waiting for the line cards to agree on who is the primary','booted, panicked about a missing fan tray, and started again','is "synchronising the routing engines". Nobody knows what that means'];
|
||
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<RG[g].slowP;}
|
||
function bootMin(c){const p=S.pops[c],G=RG[(p&&p.rgen)||0];return slowBoot(c)?G.boot*9+40:G.boot;}
|
||
const routerCost=g=>Math.round(ROUTER_COST+RG[g].cost*0.8);
|
||
// dark fiber & optical gear
|
||
const DF_SYS={
|
||
lite:{n:'Rainbow-in-a-Box DWDM',max:16,cost:25000,lvl:2,blurb:'Fixed mux plus amplifiers. Up to 16 channels, no remote switching.'},
|
||
roadm:{n:'ROADMaster 9000',max:64,cost:60000,lvl:3,blurb:'Full C-band, remotely reconfigurable, takes long-haul transponders. Up to 64 channels.'},
|
||
};
|
||
const AMP_EVERY=100, AMP_COST=8000, AMP_MO=300;
|
||
const OPT={
|
||
zr4:{n:'Ackackia 400ZR+',g:400,cost:12000,reach:1500,rg:1,lvl:2,sys:'lite',blurb:'Coherent pluggable in the router. No transponder shelf.'},
|
||
zr8:{n:'Sizzle 800ZR+',g:800,cost:22000,reach:900,rg:2,lvl:3,sys:'lite',blurb:'Twice the speed, shorter reach.'},
|
||
tp16:{n:'Sienna WaveMagic 1.6T',g:1600,cost:70000,reach:4000,rg:2,lvl:4,sys:'roadm',blurb:'Big shelf, big reach, big invoice.'},
|
||
};
|
||
const dfLeaseMo=km=>Math.round(400+km*1.0);
|
||
const dfBuildCost=km=>Math.round(25000+km*120);
|
||
const dfBuildDays=km=>Math.round(120+km*0.25);
|
||
const ampCount=km=>Math.max(0,Math.floor(km/AMP_EVERY));
|
||
const fmtCap=g=>g>=1000?(+(g/1000).toFixed(1))+'T':g+'G';
|
||
const WAVECO=['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','Bolt Technology','youNetworks','GTT (Got Tangled Twice)'];
|
||
const MONTHS=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
|
||
const REG={AM:'Americas',SA:'South America',EU:'Europe',AF:'Africa',AS:'Asia',OC:'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:['icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','mrs','sto','mad','sin','hkg','tok','syd','jnb'],blurb:'Elastic interconnection, now with bacon. Spin up a circuit in 59 seconds, oink in 60.'},
|
||
{id:'pkf',name:'PocketFabric',col:'#00A896',cities:['sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra'],blurb:'A whole network fabric that fits in your pocket.'},
|
||
{id:'ccn',name:'Consolation Connect',col:'#8E44AD',cities:['icn','lon','fra','ams','mrs','bom','sin','hkg','tok','syd','lag','jnb'],blurb:'Strong in Asia and Africa. Every circuit comes with a consolation prize.'},
|
||
];
|
||
const FAB=Object.fromEntries(FABS.map(f=>[f.id,f]));
|
||
const NNI=[{n:'10G',g:10,mo:500},{n:'100G',g:100,mo:1200}];
|
||
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:'Prefer',f:0.5},normal:{l:'Normal',f:1},avoid:{l:'Avoid',f:4},backup:{l:'Backup only',f:60}};
|
||
const PREF={high:'Prefer',normal:'Normal',low:'Backup only'};
|
||
const edgeKey=l=>l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;
|
||
const dfCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=OPT[c].g;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)=>OPT[a].g-OPT[b].g)[0];if(fo)g-=OPT[fo].g;}return Math.max(0,g);};
|
||
const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1);
|
||
const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=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==='df'?(l.ready>S.day?'building':(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+OPT[c].g,0))+' DF':'dark'):LT[l.tier].n;
|
||
|
||
/* ================= WORLD ================= */
|
||
// Real-ish 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:55.3,lat:24.9,r:26,m:1.2},{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)));}
|
||
const LANDS_LL=[{id:'am',ll:[[-166,68],[-157,71.2],[-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,47],[-59,46.5],[-61,45.2],[-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],[-57,6],[-52,5],[-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],[-130,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],[-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],[51.6,24.2],[52.6,24.2],[54.6,24.5],[56,26.2],[56.4,24.5],[57.8,23.8],[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],[23.5,38],[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],[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]]},{id:'af',ll:[[-17.5,14.7],[-17,21],[-16,24],[-13,27.5],[-9.8,30],[-9.2,32.5],[-6.8,34],[-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],[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.4,5.4],[-11.5,6.9],[-13.2,8.7],[-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.5,-34.6],[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:'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:'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.
|
||
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], [-57, 6], [-52, 5], [-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]]});
|
||
const LANDS=LANDS_LL.map(l=>({id:l.id,hide:!!l.hide,pts:l.ll.map(q=>proj(q[0],q[1]))}));
|
||
const DECOR=[[[-73,78],[-60,81.5],[-35,82.5],[-20,81.5],[-18,77],[-20,72],[-23,70],[-30,68],[-38,65.5],[-43,60],[-48,61],[-52,64.5],[-54,68],[-55,71],[-60,76],[-68,77]],[[-80,73.5],[-72,71.5],[-67,69.5],[-62,66.5],[-64,63],[-71,62.5],[-78,64],[-83,66],[-88,70],[-85,73]],[[-110,76],[-95,77],[-80,79],[-70,82],[-90,82.3],[-105,79]],[[-118,73],[-105,72],[-100,69.5],[-110,68.8],[-118,70]],[[140,41.5],[141.6,42.4],[143.3,42],[145.6,43.3],[144.5,44],[141.9,45.5],[141.4,43.4],[140,42.6]],[[120.1,23],[121,25.2],[121.9,25],[121.5,22.5],[120.8,21.9]],[[122,11],[125.5,11.5],[126.5,9.5],[126.2,6.5],[124,6.5],[122,7]],[[95.3,5.6],[98,4],[100.3,2],[103.8,-1],[106,-3],[106,-5.9],[104.5,-5.9],[102.3,-4],[100.3,-1],[97.5,2.4],[95.2,4]],[[109.6,2],[111,1.6],[113,3.2],[115.5,5.2],[117.2,6.9],[119,5],[118,2],[117.5,0.6],[116.2,-2.5],[116,-4],[114.5,-3.4],[111.7,-3],[110,-1.6],[109,0.5]],[[119,-5.5],[120.5,-1],[121.5,1],[125,1.5],[123,-1],[121.5,-4.5]],[[131,-1.2],[134,-0.8],[138,-1.6],[141,-2.6],[145,-4.3],[147.5,-6],[147.5,-8],[146,-8],[143.4,-9.1],[141,-9.1],[139,-8],[138,-8.5],[137.7,-5.6],[134,-4],[132,-2.8]],[[172.6,-40.5],[174.3,-41.7],[173,-43.5],[171.2,-44.5],[170.6,-45.9],[169.2,-46.6],[166.5,-46],[167,-45],[168.4,-44],[170.8,-42.6],[171.5,-41.7]],[[144.6,-40.7],[148.3,-40.9],[148,-43.2],[146,-43.5]],[[49.3,-12],[50.5,-15.5],[49.5,-17.5],[47.1,-24.9],[45,-25.5],[43.8,-23.6],[43.3,-21],[44.4,-16.2],[46.5,-15.7],[48,-13.5]],[[79.8,9.8],[81.9,7.5],[81.2,6.2],[80,6],[79.7,8.2]],[[-85,21.9],[-82,23.2],[-77.5,22.3],[-74.2,20.2],[-77.7,19.9],[-80.5,21.8]],[[-74.5,18.5],[-72,19.9],[-68.4,18.6],[-70,18.2]],[[12.4,38.1],[15.6,38.3],[15.1,36.7]],[[8.2,41],[9.8,41.1],[9.6,39.1],[8.4,39]],[[11,78],[17,80],[27,80],[20,77]],[[52,71],[56,74],[64,76.5],[68,77],[58,74],[54,71]],[[142,46],[143.5,49],[143,54],[142,53],[141.8,48]],[[108.7,19],[111,19.7],[110,18.2]]].map(poly=>poly.map(q=>proj(q[0],q[1])));
|
||
const CITY_LL={"kyv":[30.52,50.45],"mel":[144.96, -37.81],"bne":[153.03, -27.47],"drw":[131.05,-12.46],"osa":[135.5, 34.69],"kul":[101.69, 3.14],"bkk":[100.5, 13.76],"sgn":[106.66, 10.76],"khi":[67.14,25.0],"dac":[90.41, 23.81],"cbo":[80.0, 6.95],"waw":[21.01, 52.23],"prg":[14.42, 50.08],"vie":[16.37, 48.21],"bud":[19.04, 47.5],"buh":[26.1, 44.43],"tll":[24.45,58.9],"ist":[28.98, 41.01],"for":[-38.54, -3.73],"rio":[-43.11,-22.57],"bue":[-58.38, -34.6],"scl":[-70.67, -33.45],"lim":[-76.85,-12.05],"bog":[-74.07, 4.71],"pan":[-79.52, 8.98],"del":[77.21, 28.61],"maa":[80.18,13.25],"blr":[77.59, 12.97],"hyd":[78.49, 17.39],"tpe":[121.56, 25.03],"auh":[54.37, 24.45],"fuj":[56.15,25.07],"cpt":[18.42, -33.92],"stg":[9.18,48.78],"ber":[13.4,52.52],"zrh":[8.54,47.37],"nbo":[36.82,-1.29],"cai":[31.24,30.04],"sea":[-122.33,47.61],"sjc":[-121.89,37.34],"lax":[-118.24,34.05],"dal":[-96.8,32.78],"chi":[-87.63,41.88],"ash":[-77.49,39.04],"nyc":[-74.0,40.71],"mia":[-80.19,25.76],"tor":[-79.38,43.65],"mtl":[-73.57,45.5],"mex":[-99.13,19.43],"sao":[-46.63,-23.55],"lon":[-0.13,51.51],"dub":[-6.26,53.35],"rek":[-21.94,64.15],"ams":[4.9,52.37],"fra":[8.68,50.11],"par":[2.35,48.86],"mrs":[5.37,43.3],"mad":[-3.7,40.42],"sto":[18.07,59.33],"osl":[10.75,59.91],"cph":[12.57,55.68],"hel":[24.94,60.17],"beg":[20.46,44.79],"sof":[23.32,42.7],"mos":[37.62,55.76],"lag":[3.38,6.52],"jnb":[28.05,-26.2],"dxb":[55.27,25.2],"bom":[72.88,19.08],"sin":[103.82,1.35],"jkt":[106.85,-6.2],"mnl":[120.98,14.6],"hkg":[114.17,22.32],"sha":[121.47,31.23],"pek":[116.4,39.9],"icn":[126.98,37.57],"tok":[139.69,35.69],"syd":[151.21,-33.87],"per":[115.86,-31.95],"akl":[174.76,-36.85]};
|
||
const CITIES=[
|
||
{id:'sea',name:'Seattle',x:205,y:245,land:'am',reg:'AM',P:300,ix:'Sea-IX',dc:'Westin-ish Carrier Hotel'},
|
||
{id:'sjc',name:'San Jose',x:240,y:345,land:'am',reg:'AM',P:500,ix:'Silly-Con Valley IX',dc:'Equinox SV-ish'},
|
||
{id:'dal',name:'Dallas',x:385,y:415,land:'am',reg:'AM',P:450,ix:'Yee-Haw-IX',dc:'Infomart-ish'},
|
||
{id:'chi',name:'Chicago',x:470,y:270,land:'am',reg:'AM',P:600,ix:'Windy-IX',dc:'350 Cermak-ish'},
|
||
{id:'ash',name:'Ashburn',x:572,y:332,land:'am',reg:'AM',P:250,ix:'Equinox Ashburn IX',dc:'Data Center Alley',note:'The data-center capital. Rumor says 70% of the internet passes through here, and nobody has checked.'},
|
||
{id:'nyc',name:'New York',x:615,y:283,land:'am',reg:'AM',P:1200,ix:'NY-Yikes',dc:'60 Hudson-ish'},
|
||
{id:'mia',name:'Miami',x:530,y:482,land:'am',reg:'AM',P:400,ix:'Miam-IX',dc:'NAP of the Americas-ish',note:'Cable landing hub for South America.'},
|
||
{id:'sao',name:'São Paulo',x:640,y:730,land:'sa',reg:'SA',P:900,br:true,andes:'e',ix:'IX.brrr',ixCheap:0.3,dc:'Digital Reality SP',note:'South America’s biggest market, and home of IX.brrr: run by a nonprofit, public prices, and nearly everyone is on it.'},
|
||
{id:'lon',name:'London',x:935,y:275,land:'uk',reg:'EU',P:1000,ix:'LYNX',dc:'Telehouse-ish Docklands',note:'On an island, so every link off it is a subsea cable.'},
|
||
{id:'ams',name:'Amsterdam',x:1015,y:245,land:'eu',reg:'EU',P:350,ix:'HAMS-IX',dc:'Science Park-ish'},
|
||
{id:'fra',name:'Frankfurt',x:1075,y:295,land:'eu',reg:'EU',P:600,ix:'DE-KICKS',dc:'Kleyer-ish Campus',note:'Europe\'s crossroads. Lots of networks, lots of sausages.'},
|
||
{id:'par',name:'Paris',x:990,y:320,land:'eu',reg:'EU',P:900,ix:'Fromage-IX',dc:'Interaction PAR'},
|
||
{id:'mrs',name:'Marseille',x:1045,y:378,land:'eu',reg:'EU',P:250,ix:'Bouilla-IX',dc:'Cable Landing Station',note:'Subsea cables to Africa and Asia land here.'},
|
||
{id:'tor',name:'Toronto',x:548,y:252,land:'am',reg:'AM',P:500,ix:'Sorry-IX',dc:'151 Front Street-ish',note:'Canada’s hub. Polite packets, long winters, free cooling.'},
|
||
{id:'mtl',name:'Montreal',x:598,y:238,land:'am',reg:'AM',P:300,ix:'Poutine-IX',dc:'Hydro-powered Hangar',note:'Cheap hydro power makes it a data center favorite.'},
|
||
{id:'lax',name:'Los Angeles',x:270,y:395,land:'am',reg:'AM',P:900,ix:'Any2-Anywhere',dc:'One Wilshire-ish',note:'Pacific cables land nearby, and everyone meets in one famous building downtown.'},
|
||
{id:'mex',name:'Mexico City',x:368,y:470,land:'am',reg:'AM',P:700,ix:'',dc:'Querétaro-ish Campus',note:'Huge mobile market. Most of its traffic still detours through the US.'},
|
||
{id:'rek',name:'Reykjavik',x:850,y:170,land:'is',reg:'EU',P:60,ix:'',dc:'Geothermal Bitcoin Barn',note:'Free cooling and geothermal power. Plenty of data centers, very few cables.'},
|
||
{id:'dub',name:'Dublin',x:876,y:268,land:'ie',reg:'EU',P:250,ix:'Craic-IX',dc:'Hyperscale Campus Clonsilla-ish',note:'Every hyperscaler’s European HQ, mostly for tax reasons. The power grid is nervous.'},
|
||
{id:'osl',name:'Oslo',x:1062,y:172,land:'eu',reg:'EU',P:200,ix:'NIX-NIX',dc:'Fjord-cooled Mountain Hall'},
|
||
{id:'cph',name:'Copenhagen',x:1085,y:215,land:'eu',reg:'EU',P:250,ix:'Hygge-IX',dc:'Danish Design DC',note:'Landing point for cables from the US, Iceland and the Baltic.'},
|
||
{id:'hel',name:'Helsinki',x:1168,y:140,land:'eu',reg:'EU',P:200,ix:'Sauna-IX',dc:'Underground Sauna Bunker',note:'Fast fiber east and west, and one very nervous subsea cable to Germany.'},
|
||
{id:'beg',name:'Belgrade',x:1122,y:338,land:'eu',reg:'EU',P:250,ix:'',dc:'Danube Docks DC'},
|
||
{id:'sof',name:'Sofia',x:1165,y:358,land:'eu',reg:'EU',P:250,ix:'Rakija-IX',dc:'Vitosha-ish DC',note:'Balkan peering hub with famously cheap ports.'},
|
||
{id:'dxb',name:'Dubai',x:1292,y:428,land:'eu',reg:'AS',P:400,uae:true,ix:'Sand-IX',dc:'Air-conditioned Mirage DC',note:'Crossroads for cables between Europe, Asia and Africa. Some voice apps are blocked, and the A/C bill is legendary.'},
|
||
{id:'mos',name:'Moscow',x:1235,y:192,land:'eu',reg:'EU',P:900,ru:true,arpu:0.5,ix:'Borscht-IX',dc:'Very Secure Bunker',note:'Sovereign internet rules: every POP needs a government box in the rack, Goggle video is throttled, and the national firewall runs drills.'},
|
||
{id:'akl',name:'Auckland',x:1964,y:826,land:'nz',reg:'OC',P:250,ix:'Kiwi-IX',dc:'Sheep-cooled Shed',note:'Far from everything. Every packet here has a long journey home.'},
|
||
{id:'per',name:'Perth',x:1712,y:785,land:'oc',reg:'OC',P:200,ix:'',dc:'Very Remote DC',note:'The most isolated big city on Earth. Asia is closer than Sydney.'},
|
||
{id:'jkt',name:'Jakarta',x:1614,y:624,land:'idn',reg:'AS',P:900,ix:'Nasi-IX',dc:'Monsoon-proof DC',note:'270 million people on 17,000 islands. Mobile first, and very hungry for bandwidth.'},
|
||
{id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',P:600,ix:'',dc:'Typhoon-rated DC',note:'Typhoons, earthquakes and a lot of very online people.'},
|
||
{id:'ber',name:'Berlin',x:0,y:0,land:'eu',reg:'EU',P:450,ix:'Currywurst-IX',dc:'Former Brewery DC',note:'Startups, techno and a surprising number of data centers in old breweries.'},
|
||
{id:'zrh',name:'Zurich',x:0,y:0,land:'eu',reg:'EU',P:250,ix:'Cuckoo-IX',dc:'Bank Vault DC',note:'Banks, very punctual packets, and racks inside old bank vaults.'},
|
||
{id:'nbo',name:'Nairobi',x:0,y:0,land:'af',reg:'AF',P:350,ix:'Safari-IX',dc:'Silicon Savannah Campus',note:'East Africa’s hub. Cables land in Mombasa, and mobile money runs everything.'},
|
||
{id:'cai',name:'Cairo',x:0,y:0,land:'af',reg:'AF',P:600,ix:'Pharaoh-IX',dc:'Pyramid-adjacent DC',note:'Almost every Europe–Asia cable crosses Egypt. The tolls are legendary.'},
|
||
{id:'stg',name:'Stuttgart',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Spätzle-IX',dc:'Kehrwoche-certified DC',ixOnly:true,note:'Cars, engineers and Kehrwoche: every rack is swept on a strict rota. Nobody sells transit here, there is only the Spätzle-IX. Peer locally or haul your traffic to Frankfurt.'},
|
||
{id:'sto',name:'Stockholm',x:1110,y:160,land:'eu',reg:'EU',P:300,ix:'NodNod',dc:'Bunker-ish DC'},
|
||
{id:'mad',name:'Madrid',x:935,y:392,land:'eu',reg:'EU',P:600,ix:'Siesta-IX',dc:'Interaction MAD'},
|
||
{id:'lag',name:'Lagos',x:1010,y:565,land:'af',reg:'AF',P:500,ix:'Jollof-IX',dc:'Rack Centre-ish'},
|
||
{id:'jnb',name:'Johannesburg',x:1130,y:730,land:'af',reg:'AF',P:400,za:true,ix:'Braai-IX',dc:'Teraco-ish'},
|
||
{id:'bom',name:'Mumbai',x:1385,y:488,land:'eu',reg:'AS',P:1100,india:true,ix:'Mumb-IX',dc:'Nesco-ish'},
|
||
{id:'sin',name:'Singapore',x:1556,y:568,land:'eu',reg:'AS',P:450,ix:'Lah-IX',dc:'Equinox SG-ish',note:'Asia\'s hub. Expensive, humid, very well connected.'},
|
||
{id:'hkg',name:'Hong Kong',x:1645,y:440,land:'eu',reg:'AS',P:600,ix:'HK-Kicks',dc:'Mega-ish Plus'},
|
||
{id:'icn',name:'Seoul',x:1722,y:302,land:'eu',reg:'AS',P:900,ix:'Kimch-IX',dc:'Gasan-ish Digital Complex',note:'Some of the fastest home broadband on the planet. The eyeballs here expect a lot.'},
|
||
{id:'pek',name:'Beijing',x:1652,y:318,land:'eu',reg:'AS',P:1800,cn:true,arpu:0.6,ix:'',dc:'Zhongguancun-ish DC',note:'Mainland China. Behind the Great Firewall, with its own rules for foreign networks.'},
|
||
{id:'sha',name:'Shanghai',x:1680,y:388,land:'eu',reg:'AS',P:2200,cn:true,arpu:0.6,ix:'',dc:'Lujiazui-ish Data Center',note:'Mainland China. Enormous market, strict rules, and a famously congested border.'},
|
||
{id:'tok',name:'Tokyo',x:1795,y:320,land:'jp',reg:'AS',P:1400,ix:'JP-Naptime',dc:'Otemachi-ish'},
|
||
{id:'syd',name:'Sydney',x:1860,y:790,land:'oc',reg:'OC',P:500,ix:'Roo-IX',dc:'Global Swish'},
|
||
{id:'for',name:'Fortaleza',x:0,y:0,land:'sa',reg:'SA',P:250,br:true,andes:'e',ix:'IX.brrr Fortaleza',ixCheap:0.3,dc:'Praia Landing Station',note:'Where South America’s cables actually land. Europe, Africa and the US come ashore here, then ride a long backhaul south.'},
|
||
{id:'rio',name:'Rio de Janeiro',x:0,y:0,land:'sa',reg:'SA',P:600,br:true,andes:'e',ix:'IX.brrr Rio',ixCheap:0.3,dc:'Copacabana Colo',note:'Beaches, cable landings and a Carnival that melts traffic graphs every February.'},
|
||
{id:'bue',name:'Buenos Aires',x:0,y:0,land:'sa',reg:'SA',P:500,andes:'e',arpu:0.7,ix:'Asado-IX',dc:'Puerto Madero-ish DC',note:'Tango, steak and a currency that changes value while you read this.'},
|
||
{id:'scl',name:'Santiago',x:0,y:0,land:'sa',reg:'SA',P:350,andes:'w',ix:'Empanada-IX',dc:'Andes-view Bunker',note:'The Pacific gateway. The Andes sit between it and everything else, and the ground shakes now and then.'},
|
||
{id:'lim',name:'Lima',x:0,y:0,land:'sa',reg:'SA',P:400,andes:'w',ix:'Ceviche-IX',dc:'Fog-cooled DC',note:'It almost never rains, but the sea fog keeps the racks cool.'},
|
||
{id:'bog',name:'Bogotá',x:0,y:0,land:'sa',reg:'SA',P:400,andes:'m',ix:'Arepa-IX',dc:'2,600 m Above Sea Level DC',note:'High up in the Andes. No fiber crosses the Darién Gap jungle to Panama, so the way north is under the sea.'},
|
||
{id:'pan',name:'Panama City',x:0,y:0,land:'am',reg:'AM',P:80,ix:'Canal-IX',dc:'Isthmus Interconnect',note:'Every cable between the Americas squeezes past here. Nothing crosses the Darién Gap by land, so South America is always a subsea hop away.'},
|
||
{id:'del',name:'Delhi',x:0,y:0,land:'eu',reg:'AS',P:1600,arpu:0.4,india:true,ix:'Butter-Chicken-IX',dc:'Smog-filtered DC',note:'An enormous, very online city a long way from the sea. Every subsea byte rides a backhaul from Mumbai or Chennai.'},
|
||
{id:'maa',name:'Chennai',x:0,y:0,land:'eu',reg:'AS',P:500,arpu:0.5,india:true,ix:'Dosa-IX',dc:'Cyclone-rated Landing Bay',note:'India’s east-coast landing hub, with cables to Singapore. Cyclone season is a thing.'},
|
||
{id:'blr',name:'Bengaluru',x:0,y:0,land:'eu',reg:'AS',P:600,arpu:0.6,india:true,ix:'Filter-Kaapi-IX',dc:'Traffic-jam-adjacent Campus',note:'India’s tech capital. Packets move faster than the cars outside.'},
|
||
{id:'hyd',name:'Hyderabad',x:0,y:0,land:'eu',reg:'AS',P:400,arpu:0.5,india:true,ix:'Biryani-IX',dc:'Hyperscale Hills',note:'Every hyperscaler is building a region here. The land is cheap and the biryani is excellent.'},
|
||
{id:'tpe',name:'Taipei',x:0,y:0,land:'tw',reg:'AS',P:450,ix:'Bubble-Tea-IX',dc:'Typhoon-proof Tower',note:'Makes most of the world’s chips and hangs on a handful of subsea cables. Ships keep “accidentally” dragging their anchors over them.'},
|
||
{id:'auh',name:'Abu Dhabi',x:0,y:0,land:'eu',reg:'AS',P:200,arpu:1.4,uae:true,ix:'',dc:'Oasis-cooled Campus',note:'The capital. Sovereign AI money and very big data centers. Inside the UAE only the two licensed operators may run fiber.'},
|
||
{id:'fuj',name:'Fujairah',x:0,y:0,land:'eu',reg:'AS',P:20,uae:true,ix:'',dc:'Cable Landing Sandcastle',note:'Most UAE cables land on this coast, outside the Strait of Hormuz. Getting from here to Dubai means renting from the duopoly.'},
|
||
{id:'cpt',name:'Cape Town',x:0,y:0,land:'af',reg:'AF',P:250,za:true,ix:'Biltong-IX',dc:'Table Mountain Colo',note:'Where the Atlantic cables to Africa’s south land. Penguins on the beach, load shedding on the grid.'},
|
||
{id:'mel',name:'Melbourne',x:0,y:0,land:'oc',reg:'OC',P:450,ix:'Flat-White-IX',dc:'Four-Seasons-a-Day DC',note:'Four seasons in one day, and the racks feel every one of them.'},
|
||
{id:'bne',name:'Brisbane',x:0,y:0,land:'oc',reg:'OC',P:250,ix:'Bris-Vegas-IX',dc:'Sunshine State Shed',note:'Sunny, humid and closer to the Pacific cables than Sydney would like to admit.'},
|
||
{id:'drw',name:'Darwin',x:0,y:0,land:'oc',reg:'OC',P:15,ix:'',dc:'Crocodile-proof Landing Station',note:'Tiny, tropical and the closest Australian city to Asia. New cables to Singapore and Jakarta land here, next to the crocodiles.'},
|
||
{id:'osa',name:'Osaka',x:0,y:0,land:'jp',reg:'AS',P:700,ix:'Takoyaki-IX',dc:'Dojima-ish DC',note:'Japan’s second hub, and Tokyo’s disaster-recovery plan. Earthquakes rarely hit both.'},
|
||
{id:'kul',name:'Kuala Lumpur',x:0,y:0,land:'eu',reg:'AS',P:350,ix:'Satay-IX',dc:'Twin Towers Colo',note:'Cheaper than Singapore next door. The data center builders noticed, and so did the power grid.'},
|
||
{id:'bkk',name:'Bangkok',x:0,y:0,land:'eu',reg:'AS',P:600,ix:'Tom-Yum-IX',dc:'Floating Market DC',note:'Big, busy and flooded with traffic, sometimes literally.'},
|
||
{id:'sgn',name:'Ho Chi Minh City',x:0,y:0,land:'eu',reg:'AS',P:500,vn:true,ix:'Pho-IX',dc:'Scooter-cooled DC',note:'Very online and badly served by the sea: at least one of its subsea cables is broken at any given time.'},
|
||
{id:'khi',name:'Karachi',x:0,y:0,land:'eu',reg:'AS',P:500,arpu:0.4,ix:'Chai-IX',dc:'Seaview Landing Station',note:'Pakistan’s door to the sea. Every cable lands here, and so does every new firewall rule.'},
|
||
{id:'dac',name:'Dhaka',x:0,y:0,land:'eu',reg:'AS',P:700,arpu:0.3,ix:'Rickshaw-IX',dc:'Monsoon-mapped DC',note:'Huge, dense and hungry. Its international traffic squeezes through a couple of cables, or comes overland from India.'},
|
||
{id:'cbo',name:'Colombo',x:0,y:0,land:'lk',reg:'AS',P:120,ix:'Hopper-IX',dc:'Tea-cooled Landing Station',note:'A small island at the crossroads of every Indian Ocean cable.'},
|
||
{id:'waw',name:'Warsaw',x:0,y:0,land:'eu',reg:'EU',P:550,ix:'Pierogi-IX',dc:'Palace-of-Culture-adjacent DC',note:'Central Europe’s rising hub. More data centers every year and a fiercely competitive ISP scene.'},
|
||
{id:'prg',name:'Prague',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Pilsner-IX',dc:'Castle-view Colo',note:'Beer is cheaper than water here, and IX ports are cheaper than both.'},
|
||
{id:'vie',name:'Vienna',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Schnitzel-IX',dc:'Waltz-cooled DC',note:'The old gateway to Eastern Europe. Packets still bow politely on the way through.'},
|
||
{id:'bud',name:'Budapest',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Goulash-IX',dc:'Thermal Bath DC',note:'Waste heat goes straight into the spa next door.'},
|
||
{id:'buh',name:'Bucharest',x:0,y:0,land:'eu',reg:'EU',P:400,ix:'Sarmale-IX',dc:'Parliament-sized DC',note:'Gigabit home broadband for the price of a coffee. Customers here expect a lot for very little.'},
|
||
{id:'tll',name:'Tallinn',x:0,y:0,land:'eu',reg:'EU',P:80,ix:'E-Stonia-IX',dc:'Medieval Wall DC',note:'Digital everything, e-residency for anyone, and Baltic cables that ships keep dragging their anchors over.'},
|
||
{id:'ist',name:'Istanbul',x:0,y:0,land:'eu',reg:'EU',P:900,ix:'Baklava-IX',dc:'Bosphorus Bridge DC',note:'One foot in Europe, one in Asia. Every land route between them crosses here.'},
|
||
{id:'kyv',name:'Kyiv',x:0,y:0,land:'eu',reg:'EU',P:500,blackout:true,ix:'Varenyky-IX',dc:'Generator-backed Bunker DC',note:'Ukrainian network engineers kept the internet running through blackouts and much worse. Generators, spare fiber and redundant everything are standard here, and the peering scene is famously tough.'},
|
||
];
|
||
// Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat.
|
||
const CITY_NUDGE={stg:[30,6],fra:[-8,-8],auh:[-30,3],fuj:[8,30],dxb:[6,-8],rio:[14,-16],tll:[-4,22],osa:[-10,6],khi:[-2,-6]};
|
||
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]));
|
||
const CABLES=[
|
||
{"id":"marea","name":"Marea Carey","price":0.8,"age":"new","blurb":"Hits the high notes across the Atlantic. Huge capacity, cheap waves.","pairs":[["ash","mad",[[-74,36.5],[-50,40],[-25,43],[-10,44]]]]},
|
||
{"id":"grace","name":"Grace Hopscotch","price":0.85,"age":"new","blurb":"Hops from New York to the UK and Spain.","pairs":[["nyc","lon",[[-72,40],[-50,47],[-25,50],[-10,50.5]]],["nyc","mad",[[-72,39.8],[-50,42],[-25,43.2],[-10,43.8]]]]},
|
||
{"id":"dunant","name":"Dunno-ant","price":0.85,"age":"new","blurb":"Nobody remembers who it is named after.","pairs":[["ash","par",[[-74,36.8],[-50,42],[-25,46],[-5,47.3]]]]},
|
||
{"id":"amitie","name":"Amitié-ish","price":0.9,"age":"new","blurb":"A friendly cable with French manners.","pairs":[["nyc","lon",[[-70,41.5],[-50,46],[-25,49],[-8,50.3]]],["nyc","par",[[-70,41.3],[-50,45],[-25,47.5],[-5,47.6]]]]},
|
||
{"id":"hibx","name":"Hibernia Express-o","price":1.7,"age":"mid","blurb":"The straightest line across the Atlantic. Traders pay double to save a few milliseconds.","pairs":[["nyc","lon",[[-68,42],[-55,46.5],[-30,52.5],[-12,52.5]]]],"lat":0.9},
|
||
{"id":"tat","name":"TAT-14 Retirement Home","price":1.3,"age":"old","blurb":"Laid last century. Cuts often, costs more, still somehow running.","pairs":[["nyc","ams",[[-70,41],[-45,48],[-20,52],[0,54],[3,53.5]]]]},
|
||
{"id":"ella","name":"EllaLink-ing","price":1.0,"age":"new","blurb":"Brazil straight to Iberia, skipping the US entirely.","pairs":[["for","mad",[[-37,-2.2],[-32,5],[-22,20],[-14,33],[-10,37.5]]],["sao","mad",[[-44,-24.5],[-38,-14],[-34,-6],[-30,5],[-22,20],[-14,33],[-10,37.5]]]]},
|
||
{"id":"sacs","name":"SACS-y Cable","price":1.0,"age":"mid","blurb":"South Atlantic, cool and confident.","pairs":[["for","lag",[[-36,-3],[-20,0],[0,3]]],["sao","lag",[[-44,-24.5],[-35,-10],[-15,-3],[0,2],[3,5.5]]]]},
|
||
{"id":"col3","name":"Columbus III-and-a-half","price":1.4,"age":"old","blurb":"Discovered the Atlantic again. Old, pricey and fragile.","pairs":[["mia","mad",[[-79,26],[-60,30],[-30,35],[-10,36.5]]]]},
|
||
{"id":"twoaf","name":"2Africa-n-Back","price":0.75,"age":"new","blurb":"All the way around Africa and back. Cheapest capacity on the map.","pairs":[["lon","lag",[[-6,49],[-12,40],[-20,20],[-18,8],[-5,3],[3,5.5]]],["jnb","mrs",[[32,-30],[40,-20],[45,-5],[52,10],[45,12.3],[44,12.4],[41,15.1],[38,21.1],[35,26.1],[33,29.6],[32.4,31.3],[30,32.1],[20,34.1],[12,37.6],[6,42.5]]],["mrs","bom",[[6,42.5],[12,37.6],[20,34.1],[30,32.1],[32.4,31.3],[33,29.6],[35,26.1],[38,21.1],[41,15.1],[44,12.4],[52,13],[62,18],[70,19]]]]},
|
||
{"id":"equi","name":"Equi-yes","price":0.8,"age":"new","blurb":"Always agrees with you. Iberia to West Africa.","pairs":[["lag","cpt",[[4,3],[6,-5],[10,-20],[16,-33]]],["mad","lag",[[-10,38],[-15,28],[-18,15],[-14,5],[-2,3],[3,5.8]]]]},
|
||
{"id":"smw6","name":"SEE-ME-WAVE 6","price":0.95,"age":"new","blurb":"Sixth in a long-running series. Europe to India to Singapore.","pairs":[["mrs","bom",[[6.4,42.74],[12.4,37.84],[20.4,34.34],[30.4,32.34],[32.8,31.54],[33.4,29.84],[35.4,26.34],[38.4,21.34],[41.4,15.34],[44.4,12.64],[52,13.4],[62,18.4],[70,19.4]]],["bom","sin",[[72,17],[76,8],[80.5,5],[90,5],[96,5.5],[100,4],[103,1.5]]],["mrs","sin",[[6.4,42.74],[12.4,37.84],[20.4,34.34],[30.4,32.34],[32.8,31.54],[33.4,29.84],[35.4,26.34],[38.4,21.34],[41.4,15.34],[44.4,12.64],[52,12.8],[62,12.5],[75,6.8],[80.5,5.2],[92,5.8],[97,5.8],[100.5,4],[103,1.7]]]]},
|
||
{"id":"peace","name":"PEACE-out","price":0.85,"age":"new","blurb":"Marseille to Singapore, then it leaves the party.","pairs":[["mrs","sin",[[5.6,42.26],[11.6,37.36],[19.6,33.86],[29.6,31.860000000000003],[32.0,31.060000000000002],[32.6,29.360000000000003],[34.6,25.860000000000003],[37.6,20.860000000000003],[40.6,14.86],[43.6,12.16],[52,12.2],[62,11.8],[75,6.3],[80.5,4.6],[92,5.2],[97,5.3],[100.5,3.6],[103,1.4]]]]},
|
||
{"id":"aae","name":"AAE-1-ish","price":1.0,"age":"mid","blurb":"Asia, Africa, Europe, and one more thing.","pairs":[["khi","sin",[[66,22],[70,12],[78,5.5],[90,5.5],[97,6],[100,3.6],[102.6,2.1],[103.7,1.3]]],["mrs","hkg",[[6.8,42.98],[12.8,38.08],[20.8,34.58],[30.8,32.58],[33.199999999999996,31.78],[33.8,30.080000000000002],[35.8,26.580000000000002],[38.8,21.580000000000002],[41.8,15.58],[44.8,12.88],[52,11.8],[62,11.4],[75,6],[80.5,4.4],[92,5],[97,5],[100.5,3.3],[104.5,1.5],[107,5],[110,10],[113,18],[114.2,21.8]]],["sin","hkg",[[104.5,1.5],[108,6],[111,12],[114,20],[114.2,22]]]]},
|
||
{"id":"apg","name":"A Pretty Gateway","price":0.9,"age":"mid","blurb":"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,21.5],[122,24],[126,28],[132,32],[137,33.8],[139.8,35]]],["hkg","icn",[[116,22],[122,26],[125,32],[126,35],[126.2,36.8]]],["tok","icn",[[136,33.8],[130,33.5],[128,34.5],[126.5,35.5]]],["tok","sha",[[135,33.5],[128,31.5],[122.5,31.2]]]]},
|
||
{"id":"jup","name":"Jupiterrible","price":0.9,"age":"new","blurb":"Named after a planet, behaves like one: big and far away.","pairs":[["lax","osa",[[-121,33.3],[-145,31.5],[-175,31.5],[-200,32.5],[-222,33.8]]],["lax","tok",[[-121,33.5],[-145,32],[-175,32],[-200,33],[-218,34.5]]]]},
|
||
{"id":"fast","name":"FASTEST","price":0.85,"age":"mid","blurb":"Its predecessor was FASTER. Marketing had a good day.","pairs":[["sea","tok",[[-125,46],[-150,45],[-180,42],[-205,38],[-218,35]]]]},
|
||
{"id":"ncp","name":"New Cross Pacific-ish","price":1.0,"age":"mid","blurb":"Crosses the Pacific, mildly annoyed about it.","pairs":[["sea","tpe",[[-125,46],[-155,45],[-185,38],[-212,28],[-235,25.6]]],["sea","icn",[[-125,46.5],[-155,46.5],[-185,42],[-212,33],[-229,33.8],[-232,36]]],["sea","sha",[[-125,46.2],[-155,45.5],[-185,40],[-212,31],[-236,30.5]]]]},
|
||
{"id":"plcn","name":"Pacific Light-ish","price":1.1,"age":"mid","blurb":"Lighter on paperwork than its namesake. Still heavy on paperwork.","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]]]]},
|
||
{"id":"scx","name":"Southern Cross-ed Fingers","price":1.2,"age":"old","blurb":"Old Pacific workhorse. Everyone hopes it holds.","pairs":[["sjc","syd",[[-123,37],[-150,20],[-175,0],[-190,-20],[-200,-30],[-207,-33.5]]],["akl","syd",[[168,-37],[158,-35]]]]},
|
||
{"id":"hwk","name":"Hawaiki-wiki","price":0.95,"age":"new","blurb":"Quick Pacific crossing with a stop for snacks.","pairs":[["sea","syd",[[-125,45],[-150,20],[-170,-5],[-185,-25],[-200,-32],[-206,-33.8]]],["akl","sea",[[178,-34],[190,-20],[210,10],[230,40],[234.5,47]]]]},
|
||
{"id":"indigo","name":"Indigo-go","price":0.9,"age":"new","blurb":"Singapore to Sydney in one go, via Perth.","pairs":[["sin","syd",[[104.5,0],[107,-8],[113,-12],[112,-25],[114,-35],[130,-37],[145,-41],[152,-36]]],["sin","per",[[104.6,0],[107.2,-8],[113,-14],[112.5,-25],[115,-31.8]]]]},
|
||
{"id":"guam","name":"Guam-bling","price":1.1,"age":"mid","blurb":"A bet on a tiny island in the middle of the Pacific.","pairs":[["tok","syd",[[142,33],[146,15],[152,0],[156,-20],[152.5,-33]]]]},
|
||
{"id":"ohman","name":"Oh-Man Australia Cable","price":1.0,"age":"new","blurb":"Perth to the Gulf across the Indian Ocean. Oh man, it is long.","pairs":[["per","dxb",[[113,-31],[100,-25],[80,-10],[65,10],[59,20],[57,24.5]]]]},
|
||
{"id":"tasman","name":"Tasman Global Excess","price":0.95,"age":"new","blurb":"Sydney to Auckland with plenty to spare.","pairs":[["akl","syd",[[170,-36],[158,-34.5]]]]},
|
||
{"id":"bifrost","name":"Bi-Frosted","price":0.9,"age":"new","blurb":"A rainbow bridge from Singapore to California, via Jakarta and Manila.","pairs":[["sin","jkt",[[105,-1],[106,-4]]],["jkt","mnl",[[108,-5],[112,-3],[118,2],[122,6],[121,10],[120,13.5]]],["mnl","lax",[[123,15],[140,20],[180,25],[210,30],[235,33.5]]]]},
|
||
{"id":"sjcph","name":"Sushi-Jollibee Cable","price":0.9,"age":"mid","blurb":"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",[[122,19],[127,24],[133,30],[138.5,34.5]]]]},
|
||
{"id":"farice","name":"Far-Ice-1","price":1.2,"age":"old","blurb":"Iceland’s lifeline to Scotland. Lonely but determined.","pairs":[["rek","lon",[[-20,63],[-10,61],[-4,59],[-1.5,57]]]]},
|
||
{"id":"danice","name":"Dance-Ice","price":1.0,"age":"mid","blurb":"Iceland to Denmark, choreographed.","pairs":[["rek","cph",[[-18,63],[-5,62],[5,59],[8.5,57.5],[11,57]]]]},
|
||
{"id":"gcon","name":"Greenland Connect-the-Dots","price":1.4,"age":"old","blurb":"Hops via Greenland. Polar bears included.","pairs":[["rek","mtl",[[-26,63.5],[-42,60],[-55,53],[-60,48],[-66,47],[-70,46.5]]]]},
|
||
{"id":"iris","name":"IRIS-ish","price":0.9,"age":"new","blurb":"Iceland to Ireland, brand new and still smells like plastic.","pairs":[["rek","dub",[[-22,63],[-15,58],[-10.5,54.5],[-9,53.3]]]]},
|
||
{"id":"aec","name":"AEConnect-the-Dots","price":0.85,"age":"new","blurb":"New York to Ireland: the tech-tax express.","pairs":[["nyc","dub",[[-70,41],[-50,47],[-25,52],[-11,52.8]]]]},
|
||
{"id":"havf","name":"Havfun","price":0.8,"age":"new","blurb":"Danish for “sea fun”. Probably.","pairs":[["nyc","cph",[[-70,41.5],[-50,49],[-25,55],[-10,58],[0,58],[7,57.5],[10,57.6]]],["dub","cph",[[-10,54.5],[-8,57],[-2,59],[6,58],[10,57.6]]]]},
|
||
{"id":"celtix","name":"Celtix Connected","price":0.7,"age":"mid","blurb":"Dublin to London across the Irish Sea.","pairs":[["dub","lon",[[-5,53.4]]]]},
|
||
{"id":"falcon","name":"Falcon Punch","price":0.9,"age":"mid","blurb":"Dubai to Mumbai. Hits hard.","pairs":[["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":"Europe-India Gateway-ish, through the Red Sea.","pairs":[["dxb","mrs",[[57,25],[59,22],[55,16],[48,12.8],[43.2,11.92],[40.2,14.62],[37.2,20.62],[34.2,25.62],[32.2,29.12],[31.599999999999998,30.82],[29.2,31.62],[19.2,33.620000000000005],[11.2,37.120000000000005],[5.2,42.02]]]]},
|
||
{"id":"clion","name":"C-Lion King","price":1.0,"age":"new","blurb":"Helsinki to Germany under the Baltic. Anchors keep finding it.","pairs":[["hel","fra",[[24,59.8],[20,57.5],[15,55.2],[12.2,54.3]]]]},
|
||
{"id":"uly","name":"Ulysses-ish","price":0.8,"age":"old","blurb":"Short hop across the North Sea. An odyssey it is not.","pairs":[["lon","ams",[[2,51.8]]]]},
|
||
{"id":"chn","name":"Channel Hopper","price":0.7,"age":"mid","blurb":"London to Paris under the Channel. Cheaper than the train.","pairs":[["lon","par",[[1,50.5]]]]},
|
||
{"id":"medn","name":"Med-Nauti-lust","price":0.9,"age":"mid","blurb":"Across the Mediterranean, Egypt to France. Romantic, in a cable way.","pairs":[["ist","mrs",[[26.5,40],[25,37],[20,35.5],[12,38],[6.5,42.6]]],["cai","mrs",[[29.9,31.4],[28,32.5],[20,34.5],[12,38],[6.5,42.6]]]]},
|
||
{"id":"eassy","name":"EASSy Peasy","price":0.95,"age":"mid","blurb":"East Africa up to Europe via the Red Sea. Lemon squeezy.","pairs":[["nbo","mrs",[[39.7,-4],[42,-1],[45,2],[51,10.5],[45,12.3],[43.4,12.0],[40.4,14.7],[37.4,20.700000000000003],[34.4,25.700000000000003],[32.4,29.200000000000003],[31.799999999999997,30.900000000000002],[29.4,31.700000000000003],[19.4,33.7],[11.4,37.2],[5.4,42.1]]]]},
|
||
{"id":"teams","name":"TEAMS-work","price":0.9,"age":"mid","blurb":"Kenya to the Gulf. Makes the dream work.","pairs":[["nbo","dxb",[[39.7,-4],[44,0],[52,8],[58,18],[59,22.5],[57,25]]]]},
|
||
{"id":"monet","name":"Mo-Net-y","price":0.9,"age":"new","blurb":"Brazil to Florida. The invoice arrives just as fast.","pairs":[["sao","mia",[[-44,-25.5],[-36,-14],[-33,-4],[-45,4],[-62,16],[-76,25]]],["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":"Straight from São Paulo to New York, skipping the Miami hairpin.","pairs":[["sao","nyc",[[-44,-25.5],[-34,-10],[-33,0],[-50,18],[-66,33],[-72,39.5]]]]},
|
||
{"id":"sam1","name":"SAM-1-and-Done","price":1.2,"age":"old","blurb":"An old ring around the whole continent, the long way round Cape Horn.","pairs":[["mia","for",[[-75,24],[-62,16],[-45,4],[-37,-2.5]]],["for","rio",[[-36,-4],[-34,-9],[-37,-16],[-41,-23.6]]],["rio","sao",[[-44,-24.3]]],["sao","bue",[[-47,-27],[-52,-35],[-56,-36]]],["bue","scl",[[-56,-37.5],[-62,-45],[-65,-56],[-72,-56],[-77,-45],[-74,-34]]],["scl","lim",[[-73.5,-30],[-74,-20],[-78,-13]]],["lim","pan",[[-81,-6],[-82,0],[-80,7]]],["pan","mia",[[-79.5,10],[-77,15],[-74,19.5],[-75,23],[-79,25]]]]},
|
||
{"id":"curie","name":"Curie-osity","price":0.85,"age":"new","blurb":"Los Angeles to Chile, with a small detour for Panama.","pairs":[["lax","scl",[[-120,30],[-108,14],[-92,0],[-80,-20],[-73,-33]]],["lax","pan",[[-120,30],[-105,15],[-90,7],[-80,7.5]]]]},
|
||
{"id":"pccs","name":"Caribbean Crossing-ish","price":1.0,"age":"mid","blurb":"Hops the Caribbean so Bogotá can skip the jungle.","pairs":[["mia","bog",[[-80,24],[-77.5,19],[-76,12],[-75,10.5]]],["pan","bog",[[-79.6,9.6],[-77,9.9],[-75.5,10.5]]]]},
|
||
{"id":"tannat","name":"Tannat-ish","price":0.9,"age":"mid","blurb":"Named after a wine. São Paulo to Buenos Aires, past Uruguay.","pairs":[["sao","bue",[[-46,-26],[-50,-32],[-55,-35.5]]]]},
|
||
{"id":"humb","name":"Humboldt Penguin","price":1.3,"age":"new","blurb":"The first cable from South America to Oceania. 14,000 km of very lonely glass.","pairs":[["scl","syd",[[-75,-34],[-110,-38],[-150,-40],[-180,-38],[-200,-35],[-206,-34]]]]},
|
||
{"id":"wacs","name":"WACS-a-Mole","price":1.1,"age":"mid","blurb":"Up the west coast of Africa. Something on it is always down.","pairs":[["cpt","lag",[[16,-34],[10,-20],[6,-5],[4,3]]],["lag","lon",[[3,4],[-10,8],[-20,20],[-15,35],[-10,45],[-6,49.5]]]]},
|
||
{"id":"safe","name":"SAFE-ish (Not Very)","price":1.4,"age":"old","blurb":"An old cable from Cape Town round to India, via some very small islands.","pairs":[["cpt","bom",[[22,-36],[45,-30],[57,-20],[65,0],[70,15]]]]},
|
||
{"id":"bbg","name":"Bay of Bengal Gateway-ish","price":0.95,"age":"mid","blurb":"Fujairah to Mumbai, round the tip of India to Chennai, then on to Singapore.","pairs":[["fuj","bom",[[58,24.5],[63,22],[69.5,19.5]]],["bom","maa",[[72,15],[75,8],[78.5,6.6],[81.8,8],[81,12]]],["maa","sin",[[82,12],[90,8],[96.5,6],[100,3.5],[102.5,2],[103.6,1.25]]]]},
|
||
{"id":"i2i","name":"i2i-ish (Eye to Eye)","price":0.85,"age":"mid","blurb":"Chennai to Singapore, looking it straight in the eye.","pairs":[["maa","sin",[[82,13],[91,9.5],[97,6.6],[100.2,3.8],[102.6,2.2],[103.7,1.3]]]]},
|
||
{"id":"tse","name":"Strait-ish Express","price":1.5,"age":"old","blurb":"A short cable across a very tense strait.","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":"Leaves the Gulf from Fujairah and runs up the Red Sea to Europe.","pairs":[["fuj","mrs",[[57.5,23.5],[59.5,21.5],[55,15.5],[48,12.6],[43.2,11.8],[40.2,14.5],[37.2,20.5],[34.2,25.5],[32.2,29],[31.6,30.7],[29.2,31.5],[19.2,33.5],[11.2,37],[5.2,42]]]]},
|
||
{"id":"aagony","name":"AAG-ony","price":1.1,"age":"old","blurb":"An Asia–America gateway-ish cable that breaks so often it has its own support group.","pairs":[["sgn","hkg",[[109,12],[113,18],[114.2,21.5]]],["sgn","sin",[[106,7],[104.6,3]]]]},
|
||
{"id":"darwin","name":"Darwin Award Cable","price":1.0,"age":"new","blurb":"Darwin to Singapore via Jakarta. Survival of the fittest packets.","pairs":[["drw","jkt",[[129,-11.2],[122,-10],[114,-8.6],[108,-6.6]]],["drw","sin",[[129,-11.2],[120,-9],[114,-6],[108,-2],[105,0.6]]]]},
|
||
{"id":"jga","name":"JGA-ish (Japan–Guam–Aussie)","price":0.9,"age":"new","blurb":"Brisbane to Tokyo with a beach break in Guam.","pairs":[["bne","tok",[[155,-25],[156,-5],[146,13],[141,30]]]]},
|
||
{"id":"smw4","name":"SEE-ME-WAVE 4-ish","price":1.2,"age":"old","blurb":"The previous generation. Still carries most of Pakistan, Sri Lanka and Bangladesh, held together with hope.","pairs":[["khi","mrs",[[65,23.5],[60,22],[55,15.5],[48,12.6],[43.2,11.8],[40.2,14.5],[37.2,20.5],[34.2,25.5],[32.2,29],[31.6,30.7],[29.2,31.5],[19.2,33.5],[11.2,37],[5.2,42]]],["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",[[82,14],[87,17.5],[91.5,21.2]]],["dac","sin",[[92,21],[93,17],[95,10],[97,6.4],[100,3.6],[102.6,2.1],[103.7,1.3]]]]},
|
||
{"id":"balt","name":"Baltic Anchor Magnet","price":0.8,"age":"mid","blurb":"Short hops under the Baltic Sea. Every passing ship seems to find it.","pairs":[["tll","hel",[[24.8,59.8]]],["tll","sto",[[22,59.3],[19.5,59.3]]]]},
|
||
{"id":"bsea","name":"Black Sea-ish Cable","price":1.0,"age":"mid","blurb":"Istanbul to Bucharest's coast across the Black Sea.","pairs":[["ist","buh",[[29.5,42],[29.5,43.5],[28.8,44.2]]]]}
|
||
];
|
||
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;i<ll.length;i++)L+=hav(ll[i-1][0],ll[i-1][1],ll[i][0],ll[i][1]);
|
||
return {cid:c.id,a,b,pts,km:Math.round(L)};}));
|
||
function cablesOk(a,b){const ban=S&&S.ev&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city);if(ban)return [];const bp=S&&S.scn&&S.scn.rules&&S.scn.rules.banPairs;return bp?cablesFor(a,b).filter(c=>!bp.includes(c.cid+':'+c.a+'-'+c.b)&&!bp.includes(c.cid+':'+c.b+'-'+c.a)):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);
|
||
const ruCity=c=>!!CITY[c].ru;
|
||
const cnCity=c=>!!CITY[c].cn;
|
||
const BIGC=['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'];
|
||
const MIDC=['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'];
|
||
|
||
/* ================= NETWORKS ================= */
|
||
const NETS=[
|
||
{id:'lvl',name:'Level Tree',asn:3535,type:'t1',pol:'restrictive',share:.07,price:9,col:'#7B61FF',pops:['ber','zrh','dub','cph','osl','tor','lax','mex','mtl','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','rio','bue','scl','bog','lim','pan','waw','prg','vie','bud','buh','ist'],ix:[],blurb:'Grew from a seedling into a global backbone. Leaves no route behind.'},
|
||
{id:'ntt',name:'Not That Telecom',asn:2941,type:'t1',pol:'restrictive',share:.06,price:8,col:'#4B3FC4',pops:['jkt','mnl','per','lax','dxb','icn','sea','sjc','dal','ash','nyc','lon','ams','fra','sin','hkg','tok','syd','tpe','del','maa','blr','hyd','osa','kul','bkk','sgn'],ix:[],blurb:'Huge in Asia. "Which telecom?" "Not that one."'},
|
||
{id:'tly',name:'Tell-Ya Carrier',asn:1229,type:'t1',pol:'restrictive',share:.05,price:8,col:'#9D4EDD',pops:['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'],ix:[],blurb:'Nordic backbone that tells you exactly where your packets went.'},
|
||
{id:'cog',name:'Cogentle',asn:714,type:'t1',pol:'restrictive',share:.04,price:3,col:'#B35CF0',pops:['ber','zrh','dub','hel','sof','beg','tor','lax','mex','cph','icn','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','mrs','sto','sin','hkg','tok','rio','bue','scl','bog','lim','osa','waw','prg','vie','bud','buh','ist','kyv'],ix:[],blurb:'Cheapest transit on the map. Famously gentle, except during peering spats.'},
|
||
{id:'tat',name:'Ta-Ta Comms',asn:6543,type:'t1',pol:'restrictive',share:.04,price:9,col:'#6A4C93',pops:['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'],ix:[],blurb:'Waves goodbye to latency across the Indian Ocean.'},
|
||
{id:'drz',name:'Drizzle Electric',asn:9369,type:'t2',pol:'open',share:.04,price:4,col:'#1E90FF',pops:['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','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'],ix:'ALL',blurb:'Will peer with anyone, anywhere. Rumored to mail out IPv6 cakes.'},
|
||
{id:'tng',name:'Tangerine Telecom',asn:5115,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['cai','nbo','dxb','par','mrs','mad','lon','ams','lag','jnb','waw','buh'],ix:['par','mrs','mad','lon','ams','lag','jnb','waw'],blurb:'Juicy reach into Europe and Africa.'},
|
||
{id:'sgt',name:'SingTell',asn:7474,type:'t2',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'],ix:['sin','hkg','tok','syd','bom','tpe','maa','kul','bkk'],blurb:'Sings your packets across Asia-Pacific.'},
|
||
{id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#E63946',pops:['nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa','ist','prg','bud','buh'],ix:['lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa'],blurb:'Mobile giant. The signal is real, the name is not.'},
|
||
{id:'ctc',name:'China Telecomet',asn:4314,type:'t2',pol:'restrictive',share:.02,price:22,premium:2.5,cn:true,col:'#0B5CAD',pops:['pek','sha','hkg','sin','tok','lon','fra','nyc','sjc'],ix:[],blurb:'The biggest network in China. Its CN-Too premium route skips the congested border, for a price.'},
|
||
{id:'cun',name:'China Unicorn',asn:4837,type:'t2',pol:'restrictive',share:.015,price:16,cn:true,col:'#D7000F',pops:['pek','sha','hkg','fra','sjc','lon'],ix:[],blurb:'Number two in China, with a horn for every backbone.'},
|
||
{id:'cmb',name:'China Moble',asn:9880,type:'eye',pol:'paid',paidFee:12000,share:.01,cn:true,col:'#0085CA',pops:['pek','sha','hkg'],ix:[],blurb:'The largest mobile network on Earth. Paid peering only.'},
|
||
{id:'cmc',name:'Comecast',asn:7227,type:'eye',pol:'selective',minIx:10,minPni:30,share:.03,col:'#2C7A7B',pops:['ash','nyc','chi','sjc','sea','mia'],ix:['ash','nyc','chi','sjc','sea'],blurb:'Huge eyeball network. Come for the broadband, stay because there is no other choice.'},
|
||
{id:'dtk',name:'Doitsche Telekomm',asn:3203,type:'eye',pol:'paid',paidFee:9000,share:.03,col:'#E20074',pops:['fra','ams','lon'],ix:[],blurb:'Pink eyeball giant. Peering is available... for a monthly fee.'},
|
||
{id:'nfx',name:'NetChill',asn:2906,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.15,cache:{name:'Open Couch',min:12},col:'#C8102E',pops:ALLC,ix:'ALL',blurb:'Streams 40% of evening traffic. Hands out free caches if you send enough eyeballs.'},
|
||
{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',pops:ALLC,ix:'ALL',blurb:'Search, video and goggles. Mostly goggles.'},
|
||
{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',pops:BIGC,ix:'ALL',blurb:'Social media. Everyone keeps falling for it.'},
|
||
{id:'akm',name:'Akamaybe',asn:20490,type:'cdn',pol:'open',share:.07,cache:{name:'Akamaybe Box',min:6},col:'#0099CC',pops:ALLC,ix:'ALL',blurb:'The original CDN. Maybe it is already in your rack.'},
|
||
{id:'cfl',name:'Crowdflare',asn:13353,type:'cdn',pol:'open',share:.05,col:'#F48120',pops:BIGC,ix:'ALL',blurb:'Shields half the web from crowds of bots.'},
|
||
{id:'amz',name:"Amazin' Web Services",asn:16590,type:'cdn',pol:'selective',minIx:8,minPni:30,share:.05,col:'#FF9900',pops:MIDC,ix:'ALL',blurb:"The cloud. It's just someone else's Ashburn."},
|
||
{id:'msf',name:'Microsnoft',asn:8705,type:'cdn',pol:'selective',minIx:5,minPni:25,share:.04,col:'#00A4EF',pops:MIDC,ix:'ALL',blurb:'Updates. So many updates.'},
|
||
{id:'bdc',name:'BiteDance',asn:39669,type:'cdn',pol:'open',share:.03,col:'#111111',pops:MIDC.concat(['pek','sha']),ix:'ALL',blurb:'Short videos, very long traffic graphs.'},
|
||
{id:'slw',name:'Slowly',asn:54311,type:'cdn',pol:'open',share:.02,col:'#E5383B',pops:MIDC,ix:'ALL',blurb:'An edge cloud that is, despite the name, quite fast.'},
|
||
];
|
||
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:'Chat, games and payments. Every message costs ten cents.'},
|
||
{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:'Shopping festivals that melt traffic graphs.'},
|
||
{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:'Search, maps and a cheerful goodbye.'});
|
||
NETS.push(
|
||
{id:'rtc',name:'Rostelecomedy',asn:12389,type:'t2',pol:'selective',minIx:20,minPni:40,share:.01,price:6,col:'#7700FF',pops:['mos','hel','sto','fra','ams'],ix:['mos','fra','ams'],blurb:'The national carrier. Every punchline is pre-approved.'},
|
||
{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:'Search, taxis and maps. Slightly sleepy.'},
|
||
{id:'vkl',name:'VKontakt-lens',asn:47541,type:'cdn',pol:'open',share:.006,col:'#0077FF',pops:['mos','hel'],ix:['mos','hel'],blurb:'Social network with perfect vision.'},
|
||
{id:'ets',name:'Etis-a-lot',asn:5384,type:'eye',pol:'paid',paidFee:8000,share:.006,col:'#719E19',pops:['dxb','mrs','lon','fra','sin','auh','fuj'],ix:[],blurb:'Charges a lot. Paid peering only, and the name says it all.'},
|
||
{id:'tmx',name:'Tel-Mess',asn:8151,type:'eye',pol:'paid',paidFee:7000,share:.008,col:'#00A0DF',pops:['mex','dal','lax','mia'],ix:[],blurb:'Mexico’s giant. Paid peering only, and the pricing is a mess.'},
|
||
{id:'bcd',name:'Bell Canad-eh',asn:577,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#00549A',pops:['tor','mtl','nyc','chi'],ix:['tor','mtl'],blurb:'Polite, enormous, and sorry about the bill.'});
|
||
NETS.push(
|
||
{id:'tsf',name:'Telkom-selfie',asn:7713,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#E4002B',pops:['jkt','sin'],ix:['jkt','sin'],blurb:'Indonesia’s mobile giant. Every packet poses for a photo first.'},
|
||
{id:'pld',name:'PLDTea Time',asn:9299,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,col:'#D62027',pops:['mnl','hkg','sin'],ix:['mnl','hkg'],blurb:'Philippine giant. Peering requests are reviewed over a cup of tea.'},
|
||
{id:'spk',name:'Spark-le',asn:4771,type:'eye',pol:'open',share:.005,col:'#6A2C91',pops:['akl','syd'],ix:['akl','syd'],blurb:'New Zealand’s shiniest ISP.'},
|
||
{id:'tsy',name:'Telstraya',asn:1221,type:'t2',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['syd','per','sin','hkg','lax','tpe','mel','bne','drw'],ix:['syd','per','sin','hkg','mel','bne'],blurb:'Australia’s big one. G’day, that will be nine dollars a megabit. Sorry, gigabit.'});
|
||
NETS.push(
|
||
{id:'sfc',name:'Safari-Comic',asn:33771,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#4CB848',pops:['nbo'],ix:['nbo'],blurb:'Kenya’s mobile giant. Pays you in M-Pesos.'},
|
||
{id:'teg',name:'Tele-Comet Egypt',asn:8452,type:'t2',pol:'selective',minIx:15,minPni:40,share:.006,price:8,col:'#5B2D8E',pops:['cai','mrs','fra','lon'],ix:['cai','mrs'],blurb:'Owns the land crossing every Red Sea cable needs. Collects tolls like a pharaoh.'});
|
||
NETS.push(
|
||
{id:'clr',name:'Clarovision',asn:28537,type:'t2',pol:'selective',minIx:10,minPni:30,share:.012,price:5,col:'#DA291C',pops:['sao','rio','for','bue','scl','lim','bog','pan','mex','mia'],ix:['sao','rio','for','bue','scl','lim','bog'],blurb:'The big regional carrier. Sees everything clearly, especially your invoice.'},
|
||
{id:'viv',name:'Vivo-ish',asn:26959,type:'eye',pol:'selective',minIx:8,minPni:25,share:.01,col:'#660099',pops:['sao','rio','for'],ix:['sao','rio','for'],blurb:'Brazil’s mobile giant. Very much alive.'},
|
||
{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:'Ships parcels and packets, both overnight.'},
|
||
{id:'jio',name:'Jio-graphy',asn:55863,type:'eye',pol:'selective',minIx:10,minPni:30,share:.02,col:'#0F3CC9',pops:['bom','del','maa','blr','hyd'],ix:['bom','del','maa','blr','hyd'],blurb:'Gave a billion people cheap data. Knows exactly where every one of them is.'},
|
||
{id:'atl',name:'Airtel-tale',asn:9849,type:'t2',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:'India’s other giant. Every outage comes with a story.'},
|
||
{id:'cht',name:'Chunghwa Tele-calm',asn:3426,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#00A0E9',pops:['tpe','hkg','tok','lax','sin'],ix:['tpe','hkg'],blurb:'Taiwan’s incumbent. Stays calm while ships drag their anchors over its cables.'},
|
||
{id:'duu',name:'do-ish',asn:15820,type:'eye',pol:'paid',paidFee:6000,share:.004,col:'#00A9CE',pops:['dxb','auh','fuj'],ix:[],blurb:'The other half of the UAE duopoly. Does what Etis-a-lot does, in a different colour.'});
|
||
NETS.push(
|
||
{id:'kdi',name:'KD-DIY',asn:2561,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#E85D04',pops:['tok','osa','lax','sin','hkg'],ix:['tok','osa'],blurb:'Japanese carrier that builds everything itself. Even the cable ships.'},
|
||
{id:'opt',name:'Opt-Out-Us',asn:7745,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,col:'#00837E',pops:['syd','mel','bne','per'],ix:['syd','mel','bne'],blurb:'Australia’s number two. You can opt out of the marketing emails, eventually.'},
|
||
{id:'tru',name:'Mostly-True Move',asn:7740,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#E4002B',pops:['bkk'],ix:['bkk'],blurb:'Thailand’s mobile giant. Its coverage maps are mostly true.'},
|
||
{id:'vtl',name:'Viet-tell',asn:7525,type:'t2',pol:'selective',minIx:10,minPni:30,share:.005,price:7,col:'#EE0033',pops:['sgn','hkg','sin'],ix:['sgn'],blurb:'Vietnam’s giant. Will tell you which subsea cable is broken this week.'},
|
||
{id:'ptc',name:'PTC-hell',asn:17577,type:'t2',pol:'selective',minIx:10,minPni:30,share:.004,price:8,col:'#00843D',pops:['khi','dxb'],ix:['khi'],blurb:'Pakistan’s incumbent. Every session comes with a firewall rule.'},
|
||
{id:'tmy',name:'Telekom Ma-lazy-sia',asn:4877,type:'t2',pol:'selective',minIx:10,minPni:30,share:.004,price:6,col:'#1F2A6B',pops:['kul','sin'],ix:['kul'],blurb:'Malaysia’s incumbent. In no hurry whatsoever.'},
|
||
{id:'ttk',name:'Türk Tele-komik',asn:9211,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#1D3F8F',pops:['ist','fra','sof','lon'],ix:['ist'],blurb:'Bridges Europe and Asia, and occasionally your BGP table.'},
|
||
{id:'dgi',name:'Digi-tally Cheap',asn:8798,type:'eye',pol:'open',share:.006,col:'#2A5CAA',pops:['buh','bud','mad'],ix:['buh','bud','mad'],blurb:'Gigabit to every flat for the price of a coffee. Peers with anyone.'},
|
||
{id:'ups',name:'UPC-You-Later',asn:6380,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,col:'#D8001B',pops:['waw','prg','vie','bud','zrh','kyv'],ix:['waw','prg','vie','kyv'],blurb:'Cable broadband across Central Europe. See you later, in a support queue.'});
|
||
NETS.push({id:'kys',name:'KyivStar-ish',asn:15859,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#0055B8',pops:['kyv','waw','fra'],ix:['kyv'],blurb:'Ukraine’s biggest mobile network. Has kept working through things most networks never have to plan for.'});
|
||
const NET=Object.fromEntries(NETS.map(n=>[n.id,n]));
|
||
const NSH={}; {const t=NETS.reduce((a,n)=>a+n.share,0); NETS.forEach(n=>NSH[n.id]=n.share/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:'Tier 1',t2:'Tier 2',cdn:'CDN / content',eye:'Eyeballs'};
|
||
const initials=n=>n.name.replace(/[^A-Za-z ]/g,'').split(' ').filter(Boolean).map(w=>w[0]).join('').slice(0,3).toUpperCase();
|
||
|
||
/* ================= BUSINESSES ================= */
|
||
const BIZ_T={
|
||
dia:{l:'Enterprise DIA',opts:[1,2,5,10],rate:600},
|
||
game:{l:'Game servers',opts:[5,10,20,40],rate:120},
|
||
host:{l:'Hosting',opts:[10,20,40,80],rate:60},
|
||
isp:{l:'Downstream ISP (buys transit)',opts:[100,200,400,800],rate:15,lv:2},
|
||
l2vpn:{l:'L2VPN circuit',opts:[1,10,40,100],rate:0,l2:true,km:1,lv:1},
|
||
stream:{l:'Streaming startup',opts:[50,100,200],rate:80,lv:2},
|
||
edu:{l:'University network',opts:[20,50,100],rate:90,lv:2},
|
||
gpu:{l:'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:'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:'AI training interconnect',opts:[400,800,1600],rate:0,l2:true,div:true,km:0.9,lv:4,names:['Skynet-ish Compute','Galaxy Brain Training Run','Megawatt Minds','The Big Model Co.','Infinite Context Corp','Sentient Spreadsheet Inc.']},
|
||
hyper:{l:'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:'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:'Bulk backup transfer (latency does not matter)',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:'Event network',opts:[100,200,400,800,1600,3200],rate:0,event:true,lv:2,names:['Carnaval-ish Parade','Diwali-ish Streaming Night','The World Cup-ish Final','NANOG-ish 99','Burning Router Festival','Eurovisión-ish 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)','Gamescom-ish Expo','Oktoberfest-ish Livestream']},
|
||
sdwan:{l:'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:'Wholesale wave',opts:[1],rate:0,fiber:true,lv:2,names:['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','GTT (Got Tangled Twice)','A Hyperscaler Who Shall Not Be Named','Megapork','youNetworks']},
|
||
dfpair:{l:'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:'DDoS protection + DIA',opts:[1,5,10,20],rate:900},
|
||
aiwan:{l:'AI WAN between two AI factories',opts:[3200,6400,12800],rate:0,l2:true,div:true,mega:true,km:0.45,lv:4,names:['Fairwater-ish AI WAN','Planet-Scale Superfactory Link','Two Brains One Model Inc.','Distributed Godlike Compute','The Gigawatt Handshake']},
|
||
mtrain:{l:'Multi-site training run',opts:[1600,3200,6400],rate:0,l2:true,sdwan:true,mega:true,lv:4,names:['Gemini-ish Ultra Training Run','Frontier Model 9000','The Very Big Model','Checkpoint-Free Training Co.','Model Too Big For One Building']},
|
||
ingest:{l:'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:'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']},
|
||
provedor:{l:'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:'Local ISP',req:'Start here',unlock:'Enterprises, game servers, hosting, L2VPNs and DDoS protection.'},
|
||
{n:'Regional player',req:'peak 200 Gbps and 3 POPs',unlock:'Downstream ISPs, streaming startups and universities. Gear: Edge Lord 400 routers, dark fiber leases, Rainbow-in-a-Box DWDM, Ackackia 400ZR+ optics.'},
|
||
{n:'Serious backbone',req:'peak 1 Tbps and 6 POPs',unlock:'AI GPU data centers and cloud on-ramps. Gear: Chonk 800 routers, Sizzle 800ZR+ optics, ROADMaster 9000 line systems, building your own fiber.'},
|
||
{n:'Big league',req:'peak 3 Tbps, 10 POPs, 3 continents',unlock:'AI training interconnects and hyperscaler DCI deals in the terabits. Gear: Absolute Unit 1.6T routers, Sienna WaveMagic 1.6T transponders.'},
|
||
];
|
||
const lvl=()=>(S&&S.lvl)||1;
|
||
function custLevel(){const pops=Object.keys(S.pops).length,pk=S.stats.peak;if(pk>=3000&&pops>=10&®ionsCount()>=3)return 4;if(pk>=1000&&pops>=6)return 3;if(pk>=200&&pops>=3)return 2;return 1;}
|
||
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'];
|
||
|
||
/* ================= GOALS ================= */
|
||
const GOALS=[
|
||
{id:'bb',t:'Light up your first customers',d:'Open your home city and press “Launch broadband”. Eyeballs are people at home watching cat videos. They pay you every month.',r:5000,ok:()=>Object.values(S.pops).some(p=>p.bb)},
|
||
{id:'tr',t:'Reach the whole internet',d:'Your eyeballs want everything. Buy IP transit from a Tier 1 or Tier 2 in your city. Transit gives you the full routing table.',r:5000,ok:()=>S.transit.length>0},
|
||
{id:'ix',t:'Join an Internet Exchange',d:'Get a port at an IX: a big shared switch where networks swap traffic for free instead of paying transit.',r:7500,ok:()=>Object.keys(S.ixp).length>0},
|
||
{id:'p5',t:'Make 5 peering friends',d:'On the Peering tab, request sessions, or join the route server to peer with every open network at once.',r:10000,ok:()=>R.sessions>=5},
|
||
{id:'ln',t:'Lay your first fiber',d:'Drag from your pink router to another city. Short hops are cheap. Oceans are not.',r:10000,ok:()=>S.links.length>0},
|
||
{id:'bz',t:'Sign a business customer',d:'Businesses show up with a $ bubble. You need a POP in their city. Check the Deals tab.',r:12500,ok:()=>S.biz.length>0},
|
||
{id:'rd',t:'Survive a failure',d:'Things break all the time. Build a second path or a second upstream so traffic reroutes when something dies.',r:12500,ok:()=>S.stats.survived>0},
|
||
{id:'ca',t:'Host an embedded cache',d:'Big CDNs give you free cache boxes once you send them enough traffic. Free bandwidth, just add power.',r:12500,ok:()=>S.caches.length>0},
|
||
{id:'pn',t:'Set up a PNI',d:'A private cross-connect to one network in the same data center, for when traffic outgrows the IX.',r:15000,ok:()=>S.pni.length>0},
|
||
{id:'c3',t:'Go global',d:'Have POPs on 3 continents. Subsea cables cost a fortune, so plan the route.',r:50000,ok:()=>regionsCount()>=3},
|
||
{id:'t2',t:'Become a Tier 2',d:'5+ POPs, ports on 3+ IXs and 15+ peering sessions.',r:50000,ok:()=>isTier2()},
|
||
{id:'tb',t:'Serve 1 Tbps',d:'A terabit per second of happy traffic.',r:75000,ok:()=>R.served>=1000},
|
||
{id:'df',t:'Light your own dark fiber',d:'Lease or dig dark fiber, put a DWDM system on it and light a channel. Cheaper per bit than waves, once it works.',r:40000,ok:()=>S.links.some(l=>l.kind==='df'&&dfCap(l)>0)},
|
||
{id:'m2',t:'Be in two buildings at once',d:'Add a second site in a metro from the Infra tab, so one power cut no longer takes the whole city dark.',r:30000,ok:()=>Object.values(S.pops).some(p=>p.site2)},
|
||
{id:'c5',t:'Five continents',d:'POPs in five of the six regions on the map.',r:100000,ok:()=>regionsCount()>=5},
|
||
{id:'gi',t:'Sign a giant',d:'Land an AI WAN, a multi-site training run or a fiber-pairs deal with a hyperscaler. Customer level 4 and a POP near their campus required.',r:150000,ok:()=>S.biz.some(b=>BIZ_T[b.type]&&BIZ_T[b.type].mega&&!BIZ_T[b.type].event)},
|
||
{id:'t10',t:'Serve 10 Tbps',d:'Ten terabits per second of happy traffic. The giants will notice.',r:250000,ok:()=>R.served>=10000},
|
||
{id:'t1',t:'Go transit-free: Tier 1!',d:'Peer with all five Tier 1s over PNIs and cancel every transit port. Then nobody charges you to reach the internet.',r:0,win:true,ok:()=>isTier1()},
|
||
];
|
||
|
||
/* ================= 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};
|
||
let uidN=1; const uid=()=>'i'+(Date.now()%1e7).toString(36)+(uidN++);
|
||
function emptyR(){return {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:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{}};}
|
||
/* ================= 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:'A',apr:[.07,.11],amt:[4,9],term:[24,48],covs:['peer30','continents2','golf'],blurb:'Only lends to people who do not need it.'},
|
||
db:{name:'Deutsche Bankrupt',col:'#0018A8',min:'BBB',apr:[.08,.13],amt:[3,7],term:[18,36],covs:['nocog','gen','fax'],blurb:'Very solid. Mostly.'},
|
||
jpm:{name:'JP Morgain',col:'#5B4636',min:'BBB',apr:[.09,.14],amt:[3,6],term:[12,36],covs:['uptime','logo'],blurb:'Lends you money and also a little bit of their own.'},
|
||
cs:{name:'Credit Sweaty',col:'#7A9CC6',min:'BB',apr:[.11,.17],amt:[2,5],term:[12,30],covs:['cash50','nochina'],blurb:'Nervous, but enthusiastic.'},
|
||
wf:{name:'Wells Far-Gone',col:'#D71E28',min:'BB',apr:[.12,.18],amt:[2,4],term:[12,24],covs:['nosub','logo'],blurb:'Opened three accounts for you while you read this.'},
|
||
spk:{name:'Spätzle-Sparkasse',col:'#E30613',min:'B',apr:[.05,.08],amt:[1,3],term:[24,60],covs:['spaetzle','kehrwoche'],blurb:'Cheap, patient, and very particular about Stuttgart.'},
|
||
rev:{name:'Revoloot',col:'#191C1F',min:'B',apr:[.13,.2],amt:[1,3],term:[6,18],covs:['app'],blurb:'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:'Cheap state money for connecting the underserved. Bring a pen.'},
|
||
crypto:{name:'Crypto Bros Capital',col:'#F7931A',min:'CCC',apr:[.15,.25],amt:[2,6],term:[6,18],covs:['hodl'],crypto:true,blurb:'Pays out in TubeCoin. Value may vary. A lot.'},
|
||
vult:{name:'Venture Vultures',col:'#8E44AD',min:'CCC',amt:[6,12],share:[.1,.15],covs:['blitz'],equity:true,blurb:'No repayments, ever. Just a slice of your revenue, forever, and a lot of opinions.'},
|
||
shark:{name:'Loan Shark Telecom Finance',col:'#37474F',min:'C',apr:[.6,.9],amt:[1,2],term:[4,8],covs:[],shark:true,blurb:'Always open. Ask no questions. Do not be late.'},
|
||
};
|
||
const RATINGS=['C','CCC','B','BB','BBB','A','AA','AAA'];
|
||
const COVS={
|
||
peer30:{l:'Keep your peering ratio above 30%. The bank read a blog post about peering.',ok:()=>(R.peerShare||0)>=0.3},
|
||
continents2:{l:'Keep POPs on at least 2 continents. Diversification!',ok:()=>regionsCount()>=2},
|
||
golf:{l:'Your CEO plays golf with our CEO every Thursday.',ok:()=>true},
|
||
nocog:{l:'No Cogentle transit anywhere. Our CEO got de-peered once and has not recovered.',ok:()=>!S.transit.some(t=>t.net==='cog')},
|
||
gen:{l:'Every POP needs a backup generator. Our risk team saw one disaster movie.',ok:()=>Object.values(S.pops).every(p=>p.gen)},
|
||
fax:{l:'Send us your monthly report by fax.',ok:()=>true},
|
||
uptime:{l:'Deliver at least 95% of what your customers want.',ok:()=>!R.demand||R.served/R.demand>=0.95},
|
||
logo:{l:'Our logo goes on every router you own.',ok:()=>true},
|
||
cash50:{l:'Never let cash drop below $50k. It makes us sweat.',ok:()=>S.cash>=50000},
|
||
nochina:{l:'Stay out of mainland China. Compliance said so.',ok:()=>!Object.keys(S.pops).some(cnCity)},
|
||
nosub:{l:'No new subsea links while this loan runs. We are afraid of sharks.',ok:l=>S.links.filter(x=>x.sub).length<=(l.base&&l.base.sub||0)},
|
||
spaetzle:{l:'Peer at the Spätzle-IX in Stuttgart. Local money for local packets.',ok:()=>S.ixp.stg!==undefined},
|
||
kehrwoche:{l:'Do the Kehrwoche: keep your NOC free of incidents older than a week.',ok:()=>!S.inc.some(i=>S.day-i.start>7)},
|
||
app:{l:'Download our app and enable all notifications.',ok:()=>true},
|
||
rural:{l:'Run home broadband somewhere underserved (Asia, Africa, Oceania or South America).',ok:()=>Object.keys(S.pops).some(c=>S.pops[c].bb&&['AS','AF','OC','SA'].includes(CITY[c].reg))},
|
||
forms:{l:'Fill in form T-17b in triplicate, every month, forever.',ok:()=>true},
|
||
hodl:{l:'Never sell your TubeCoin. Diamond hands.',ok:()=>true},
|
||
blitz:{l:'Open a new POP at least every 90 days. Blitzscale or die.',ok:l=>S.day-Math.max(l.start,...Object.values(S.pops).map(p=>p.day||0))<=90},
|
||
};
|
||
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=3;
|
||
if(rev>50000)sc++;if(rev>250000)sc++;if(rev>1000000)sc++;if(R.revMo>R.costMo)sc++;else 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)));
|
||
let pool=emergency?keys.filter(k=>['shark','gov','crypto','vult','rev','spk'].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{o.apr=+ra(B.apr).toFixed(3);o.term=Math.round(ra(B.term)/6)*6||6;o.pay=Math.round(annuity(amount,o.apr,o.term));}
|
||
S.loanOffers.push(o);
|
||
toast(`<b>${esc(B.name)} would like to lend you ${fmt$(amount)}.</b><br>${emergency?'They heard you might be in a spot of bother.':'Terms apply. Several terms.'}`,emergency?'bad':'goal',[{l:'Open bank',act:'bank',args:{}}]);
|
||
}
|
||
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(`<b>${esc(B.name)} is unhappy.</b><br>You broke a loan condition: ${esc(COVS[broken[0]].l)} Fix it within 10 days or pay a penalty.`,'bad',[{l:'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(`<b>${esc(B.name)} are circling.</b><br>They now take ${pct(l.share)} of your revenue.`,'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(`<b>Penalty from ${esc(B.name)}: ${fmt$(fee)}</b><br>Added to what you owe. Your monthly payment is now ${fmt$(l.pay)}.`,'bad');}
|
||
sfx('err');}}
|
||
// monthly statement: payments already leave your cash daily as part of costs
|
||
for(const l of S.loans.slice()){if(BANKS[l.bank].equity||(d-l.start)%30!==0||d===l.start)continue;
|
||
l.bal=Math.max(0,l.bal*(1+l.apr/12)-l.pay);l.left--;
|
||
if(l.left<=0||l.bal<1){S.loans=S.loans.filter(x=>x!==l);track('loan_repaid');toast(`<b>Loan from ${esc(BANKS[l.bank].name)} paid off!</b><br>They sent a fruit basket. It is mostly bananas.`,'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);addInc({type:'shutdown',ref:c,until:d+1,msg:`Two very large gentlemen from Loan Shark Telecom Finance unplugged your router in ${CITY[c].name} "as a reminder".`,cost:0});toast(`<b>The loan shark sent a reminder.</b><br>Your POP in ${CITY[c].name} is dark until tomorrow.`,'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;
|
||
if(S.loanOffers.length<4&&(broke?Math.random()<0.25:(d>20&&Math.random()<1/40)))spawnLoanOffer(broke);
|
||
}
|
||
/* 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();};
|
||
function isoWeek(dt){const d=new Date(Date.UTC(dt.getFullYear(),dt.getMonth(),dt.getDate()));const n=d.getUTCDay()||7;d.setUTCDate(d.getUTCDate()+4-n);const y0=new Date(Date.UTC(d.getUTCFullYear(),0,1));return {y:d.getUTCFullYear(),w:Math.ceil(((d-y0)/864e5+1)/7)};}
|
||
function pathExists(a,b){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l))continue;(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 SCN=[
|
||
{id:'stg',n:'Only Spätzle-IX',city:'stg',cash:400000,days:730,rules:{noTransit:true},d:'Start in Stuttgart, where nobody sells transit. Reach the internet through peering, PNIs, caches and your own fiber only. No transit anywhere, ever.',goal:'Serve 200 Gbps',ok:()=>R.served>=200},
|
||
{id:'redsea',n:'Red Sea Crisis',city:'mrs',cash:2500000,days:540,rules:{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']},d:'Every cable through the Red Sea is cut, and so is the hop to Egypt. Get Marseille talking to Singapore anyway: round Africa, overland, or the other way round the planet.',goal:'A path from Marseille to Singapore, and 300 Gbps served',ok:()=>pathExists('mrs','sin')&&R.served>=300},
|
||
{id:'spat',n:'The Cogentle Spat',city:'nyc',cash:700000,days:540,rules:{spat:true},d:'Cogentle and Goggle are not speaking, and this time it is permanent. Buy the cheap transit if you dare.',goal:'99% reach and 150 Gbps served',ok:()=>R.reach>=0.99&&R.served>=150},
|
||
{id:'carnaval',n:'Carnaval',city:'rio',cash:600000,days:100,rules:{},setup:()=>{S.biz.push({id:uid(),city:'rio',city2:null,reqs:[],name:'Carnaval-ish Parade in Rio de Janeiro',type:'event',bw:400,rate:0,mood:100,since:0,start:90,dur:5,fee:400*5*70});},d:'Rio from scratch. Carnaval-ish starts in 90 days and wants 400 Gbps for five days straight. The whole world is watching.',goal:'Deliver Carnaval in full',ok:()=>(S.stats.evFull||0)>=1},
|
||
{id:'darien',n:'Mind the Gap',city:'pan',cash:900000,days:730,rules:{},d:'Start in Panama City. Nothing crosses the Darién Gap by land, and the Andes are in the way of everything else.',goal:'POPs in Bogotá, Lima, Santiago and São Paulo, and 150 Gbps served',ok:()=>['bog','lim','scl','sao'].every(c=>S.pops[c])&&R.served>=150},
|
||
{id:'baltic',n:'Anchors Away',city:'tll',cash:500000,days:540,rules:{anchors:3},d:'Tallinn. Ships drag their anchors over Baltic cables three times as often as usual.',goal:'90 days in a row with 99.5% of demand served',ok:()=>(S.stats.clean||0)>=90},
|
||
];
|
||
const WEEK_CITIES=['fra','ams','lon','nyc','ash','sjc','sin','tok','syd','sao','jnb','bom','waw','ist','mex','hkg'];
|
||
const WEEK_MODS=[{id:'pricey',n:'Everything costs 30% more'},{id:'chaos',n:'Twice the failures'},{id:'poor',n:'Start with only $200k'},{id:'boom',n:'Eyeballs grow 50% faster'},{id:'dk',n:'Every IX is run by DE-KICKS'},{id:'sharks',n:'Shark season: subsea cuts twice as likely'}];
|
||
function weekly(){const {y,w}=isoWeek(new Date());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={}){newGame(nm,city);S.mode=o.mode||'normal';
|
||
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=4;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||('Weekly challenge '+sc.key),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';
|
||
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=200000;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;}}
|
||
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
|
||
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${esc(o.scn.goal||'Serve as much traffic as you can in one year.')} You have ${S.scn.days} days.`:S.mode==='sandbox'?`<b>Sandbox mode</b><br>A billion dollars, every unlock, and nothing ever breaks. Build the internet you always wanted.`:`<b>Welcome, ${esc(nm)}!</b><br>The RIPE-ish NCC assigned you AS${S.asn}. Your first router is humming in ${CITY[city].name}.`,'goal');
|
||
renderAll();save();if(!S.scn&&S.mode!=='sandbox')tutorialStart();}
|
||
/* ---------- conference season ---------- */
|
||
const CONFS=[{n:'NANOG-ish',c:'chi',m:1},{n:'APRICOT-ish',c:'sin',m:1},{n:'Peering Days-ish',c:'waw',m:2},{n:'UKNOF-ish',c:'lon',m:3},{n:'MENOG-ish',c:'dxb',m:3},{n:'NZNOG-ish',c:'akl',m:3},{n:'RIPE-ish',c:'ams',m:4},{n:'NANOG-ish',c:'sea',m:5},{n:'IX Forum-ish',c:'tok',m:6},{n:'AfPIF-ish',c:'nbo',m:7},{n:'AusNOG-ish',c:'syd',m:8},{n:'LACNOG-ish',c:'sao',m:9},{n:'NANOG-ish',c:'ash',m:9},{n:'DENOG-ish',c:'fra',m:10},{n:'RIPE-ish',c:'ber',m:10},{n:'PTT Forum-ish',c:'sao',m:11}];
|
||
const CONF_COST=8000,CONF_DAYS=45;
|
||
const confDay=(cf,y)=>y*360+cf.m*30+9;
|
||
function confKey(cf,y){return cf.n+'@'+cf.c+'@'+y;}
|
||
function upcomingConfs(within){const y0=Math.floor(S.day/360),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;}
|
||
function confTick(d){S.confReg=S.confReg||{};
|
||
for(const cf of upcomingConfs(30)){if(cf.day-d===30&&!S.confReg[cf.key])toast(`<b>${esc(cf.n)} comes to ${esc(CITY[cf.c].name)} in 30 days.</b><br>Peering coordinators, hallway track, free stickers. Register in the Deals tab.`,'goal',[{l:'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;S.conf={until:d+CONF_DAYS,reg,name:cf.n};S.stats.confs=(S.stats.confs||0)+1;
|
||
const r=Math.random();let extra='';if(r<0.3){const cash=5000+Math.floor(Math.random()*4)*5000;S.cash+=cash;extra=` You also won the raffle: ${fmt$(cash)} worth of optics, sold on eBuy the same evening.`;}else if(r<0.5)extra=' Someone from Goggle bought you a beer. You did not get their name, only a sticker.';
|
||
toast(`<b>${esc(cf.n)} in ${esc(CITY[cf.c].name)}</b><br>You shook a lot of hands. For ${CONF_DAYS} days, selective networks with a presence in ${esc(REG[reg])} want half the usual traffic before they peer.${extra}`,'goal');sfx('coin');}}
|
||
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 `<h3 style="font-size:15px;margin:10px 0 4px">Conferences</h3>${cb?`<div class="inc" style="background:#EAF7EE"><div class="nm">${esc(cb.name)} glow: ${cb.until-S.day} days left</div><div class="meta">Selective networks in ${esc(REG[cb.reg])} need half the usual traffic to peer. Now is the time to ask for that PNI.</div></div>`:''}${up.map(cf=>{const reg=S.confReg&&S.confReg[cf.key];return `<div class="row"><div class="grow"><div class="nm">${esc(cf.n)} · ${esc(CITY[cf.c].name)}</div><div class="meta">${cf.day===S.day?'Today':`in ${cf.day-S.day} days`} · ${esc(REG[CITY[cf.c].reg])}</div></div>${reg?'<span class="tag st on">Registered</span>':btn(`Attend <small>${fmt$(CONF_COST)}</small>`,'confGo',{key:cf.key},'sm',S.cash<CONF_COST)}</div>`;}).join('')}`;}
|
||
|
||
/* ---------- guided first game ---------- */
|
||
const TUT=[
|
||
{t:'Your router is live. Press “Launch broadband” to sell internet to the people of your city.',sel:'[data-act="launchBB"]',ok:()=>S.pops[S.home]&&S.pops[S.home].bb},
|
||
{t:'Your customers want the whole internet. Open the Transit tab and buy a port from a carrier.',sel:'[data-act="tab"][data-args*=\'"up"\'],[data-act="buyTransit"]',ok:()=>S.transit.length>0,skip:()=>!NETS.some(n=>n.price&&n.pops.includes(S.home))},
|
||
{t:'Transit costs money per gigabit. Peering is free: open the Peering tab, buy an IX port, then join the route server.',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:'Start the clock with 1× and watch traffic and money flow. You can pause any time.',sel:'#sp1',ok:()=>S.day>=5},
|
||
{t:'Grow: drag from your pink router onto a nearby city to lay fiber and open a second POP.',sel:null,ok:()=>S.links.length>0},
|
||
{t:'Businesses pop up as $ bubbles on the map. Open Deals and sign your first customer.',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();}
|
||
function renderCoach(){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;}
|
||
while(S.tut<TUT.length){const st=TUT[S.tut];let ok=false;try{ok=st.ok()||(st.skip&&st.skip());}catch(e){}if(!ok)break;S.tut++;}
|
||
if(S.tut>=TUT.length){S.tut=null;el.hidden=true;try{localStorage.setItem('sot-tut','1');}catch(e){}toast('<b>You know the basics.</b><br>The goals on the left take it from here. Things will break. That is the fun part.','goal');return;}
|
||
const st=TUT[S.tut];el.innerHTML=`<div class="ct"><span class="cs">Step ${S.tut+1} of ${TUT.length}</span>${esc(st.t)}</div>${btn('Skip tutorial','tutSkip',{},'ghost sm')}`;el.hidden=false;
|
||
if(st.sel){const t=document.querySelector(st.sel);if(t)t.classList.add('coach-glow');}}
|
||
/* ---------- traceroute and looking glass ---------- */
|
||
const slug=t=>String(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x';
|
||
function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={};
|
||
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=(l.km+60)*MET[l.metric||'normal'].f;(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,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]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,l,w] of adj[u]||[]){const nd=ud+w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
|
||
const path=dst=>{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:NET[net].cache.name+' cache',used:R.useCache[x.id]||0,cap:CACHE_CAP});
|
||
for(const p of S.pni)if(p.net===net&&popUp(p.city)&&!siteDown(p.city,p.site||'a'))out.push({k:'p',rank:1,city:p.city,pref:p.pref||'normal',lab:'PNI with '+NET[net].name,used:R.usePni[p.id]||0,cap:lagCap(PORT[p.tier].g,p.n)});
|
||
for(const c in S.ixp)if(ixSessions(c).has(net)&&(popUp(c)||remoteCities().includes(c))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:2,city:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:ixName(c)+' peering',used:R.useIx[c]||0,cap:ixCap(c)});
|
||
for(const t of S.transit)if(popUp(t.city)&&!(t.down>day)&&!siteDown(t.city,t.site||'a')&&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',lab:NET[t.net].name+' transit',tnet:t.net,used:R.useT[t.id]||0,cap:lagCap(PORT[t.tier].g,t.n)});
|
||
return out;}
|
||
function traceroute(src,to){const P=trPaths(src),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,`${CITY[src].name}, your router`);
|
||
const walk=path=>{for(const h of path){const l=h.l,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'?'own dark fiber':l.kind==='vxc'?'fabric circuit':l.cable?CAB[l.cable].name:'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 * * * ← no working path between these POPs');return {text:lines.join('\n'),why:'No path: every route between these cities is down or missing.'};}walk(path);return {text:lines.join('\n'),why:`Internal path over ${path.length} link${path.length===1?'':'s'}, chosen by distance and link metrics${S.te&&S.te.on?'. Auto-TE may move overflow elsewhere when this is full':''}.`};}
|
||
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 * * * ← !N network unreachable');return {text:lines.join('\n'),why:`Nothing on your network reaches ${N.name}: no transit, IX session, PNI or cache with a working path from ${CITY[src].name}.`,asPath:null};}
|
||
ex.sort((a,b)=>(a.pref==='low'?4:a.rank)-(b.pref==='low'?4:b.rank)||(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||P.dist[a.city]-P.dist[b.city]);
|
||
const e=ex.find(x=>x.used<x.cap*0.999)||ex[0];walk(P.path(e.city));
|
||
let asPath=[S.asn];
|
||
if(e.k==='t'){const T=NET[e.tnet];asPath.push(T.asn);hop(`be-${S.asn}.${e.city}.${slug(T.name)}.net`,`203.0.113.${hstr(e.city)%250}`,0.4,`hand-off to ${T.name}`);
|
||
if(T.id!==N.id){const far=(N.pops&&N.pops.length?N.pops:[e.city]).reduce((a,c)=>kmBetween(e.city,c)<kmBetween(e.city,a)?c:a,(N.pops||[e.city])[0]);const km=CITY[far]?kmBetween(e.city,far):0;
|
||
hop(`ae-2.core.${far}.${slug(T.name)}.net`,`203.0.113.${(hstr(far)+7)%250}`,km*1.3/100+0.3,CITY[far]?`${T.name} carries it to ${CITY[far].name}`:'');
|
||
hop(`${slug(N.name)}-peer.${far}.${slug(T.name)}.net`,`198.51.100.${hstr(N.id)%250}`,0.4,`${T.name} hands it to ${N.name}`);}}
|
||
else if(e.k==='ix'){hop(`${slug(ixName(e.city))}.peering.${e.city}`,`185.0.${hstr(e.city)%250}.${hstr(N.id)%250}`,0.3,`across the ${ixName(e.city)} switch`);}
|
||
else if(e.k==='p'){hop(`pni-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),3),0.2,'private cross-connect');}
|
||
else{hop(`cache-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),4),0.1,'embedded cache in your rack');}
|
||
asPath.push(N.asn);if(e.k!=='c')hop(`www.${slug(N.name)}.example`,`198.51.100.${(hstr(N.id)+1)%250}`,0.5+(e.k==='t'?1:0.2),`${N.name}`);
|
||
const order={c:'caches beat PNIs',p:'PNIs beat IX peering',ix:'IX peering beats transit',t:'transit is the last resort'}[e.k];
|
||
const cn=cnCity(src)!==!!N.cn?` Crossing the Great Firewall here loses about ${S.ev.gfw>S.day?35:20}% of packets.`:'';
|
||
return {text:lines.join('\n'),why:`Exit: ${e.lab} in ${CITY[e.city].name}. ${order[0].toUpperCase()+order.slice(1)}, and closer exits win ties${e.pref!=='normal'?`; this one is set to ${e.pref==='high'?'Prefer':'Backup only'}`:''}.${e.used>=e.cap*0.999?' It is full, so some traffic overflows to the next exit.':''}${cn}`,asPath};}
|
||
function traceModal(src,to){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;
|
||
const r=t.startsWith('net:')?traceroute(src,{net:t.slice(4)}):traceroute(src,{city:t.slice(5)});
|
||
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Looking glass</div><h2 style="font-size:26px">Traceroute</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>
|
||
<div class="trsel"><label>From <select id="trFrom">${pops.map(c=>`<option value="${c}"${c===src?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label>
|
||
<label>To <select id="trTo"><optgroup label="Networks">${nets.map(n=>`<option value="net:${n.id}"${t==='net:'+n.id?' selected':''}>${esc(n.name)} (AS${n.asn})</option>`).join('')}</optgroup><optgroup label="Your POPs">${pops.filter(c=>c!==src).map(c=>`<option value="city:${c}"${t==='city:'+c?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</optgroup></select></label>${btn('Run','traceRun',{},'pink sm')}</div>
|
||
<pre class="term">${esc(r.text)}</pre>${r.asPath?`<p class="meta"><b>AS path:</b> ${r.asPath.map(a=>'AS'+a).join(' → ')}</p>`:''}<p class="note">${esc(r.why)}</p>
|
||
<div class="btns">${btn('Copy','traceCopy',{},'ghost sm')}</div>`);UI.trText=r.text;}
|
||
|
||
/* ---------- share card ---------- */
|
||
function shareCanvas(){const Wc=1200,Hc=630,cv=document.createElement('canvas');cv.width=Wc;cv.height=Hc;const g=cv.getContext&&cv.getContext('2d');if(!g)return null;
|
||
g.fillStyle='#57C4E5';g.fillRect(0,0,Wc,Hc);
|
||
// mini map
|
||
const mx=40,my=150,mw=700,mh=350,sx=mw/W,sy=mh/H;g.save();g.beginPath();g.rect(mx,my,mw,mh);g.clip();g.fillStyle='#3AA6CF';g.fillRect(mx,my,mw,mh);
|
||
g.fillStyle='#9BDA6C';g.strokeStyle='#1E2640';g.lineWidth=1.5;for(const L of LANDS){if(L.hide)continue;g.beginPath();L.pts.forEach((q,i)=>i?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 l of S.links){const A=CITY[l.a],B=CITY[l.b];let bx=B.x;if(Math.abs(bx-A.x)>W/2)bx+=bx<A.x?W:-W;g.beginPath();g.moveTo(mx+A.x*sx,my+A.y*sy);g.lineTo(mx+bx*sx,my+B.y*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)}${S.mode==='sandbox'?' · Sandbox':''}`,42,92);
|
||
// stats
|
||
const got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined),rk={l:0,e:1,r:2,c:3},top=got.slice().sort((a,b)=>rk[a.r]-rk[b.r]).slice(0,8);
|
||
const rows=[['Peak traffic',fmtG(S.stats.peak||0)],['Peered',pct(R.peerShare||0)],['POPs',`${Object.keys(S.pops).length} in ${regionsCount()} regions`],['Links',String(S.links.length)],['Customers',String(S.biz.length)],['Incidents survived',String(S.stats.survived||0)],['Shark bites',String(S.stats.sharks||0)],['Badges',`${got.length}/${BADGES.length}`]];
|
||
if(S.scn)rows.unshift([S.scn.id==='weekly'?'Weekly '+S.scn.key:S.scn.name,S.scn.done?(S.scn.id==='weekly'?'score '+fmtG(S.scn.score||S.stats.peak||0):`done in ${S.scn.done} days`):S.scn.failed?'not this time':'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;}
|
||
g.font='34px sans-serif';top.forEach((b,i)=>g.fillText(b.i,40+i*48,520));
|
||
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('Build the internet, one tube at a time',300,580);
|
||
return cv;}
|
||
function shareModal(){const cv=shareCanvas();if(!cv){toast('<b>Your browser cannot draw the card.</b>','bad');return;}let url='';try{url=cv.toDataURL('image/png');}catch(e){}
|
||
UI.shareCv=cv;openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Share</div><h2 style="font-size:26px">Your network card</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>${url?`<img src="${url}" alt="Stats card for ${esc(S.name)}" style="width:100%;border:3px solid var(--ink);border-radius:12px;margin-top:8px">`:''}<div class="btns" style="margin-top:10px">${navigator.share?btn('Share…','shareGo',{},'pink'):''}${btn('Download PNG','shareDl',{},navigator.share?'':'pink')}</div><p class="note">Post it wherever your peering friends hang out.</p>`);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');}
|
||
function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)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(`<div class="eyebrow">Weekly challenge ${esc(sc.key)}</div><h2 style="font-size:30px">Your score: ${fmtG(score)}</h2><p class="tagline">Peak traffic served in one year${best&&best>score?`. Your best this week is ${fmtG(best)}`:best?'. A new personal best for this week!':''}.</p><div class="btns">${btn('Share my result','share',{},'pink big')}${btn('Keep playing','closeModal',{},'ghost big')}</div>`);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(`<div class="eyebrow">Scenario complete</div><h2 style="font-size:30px">${esc(def.n)}: done in ${d} days</h2><p class="tagline">${esc(def.goal)}. ${d<def.days/2?'With time to spare.':'Just in time.'}</p><div class="btns">${btn('Share my result','share',{},'pink big')}${btn('Keep playing','closeModal',{},'ghost big')}${btn('More scenarios','scenarios',{},'ghost')}</div>`);sfx('coin');}
|
||
else if(d>=def.days){sc.failed=d;openModal(`<div class="eyebrow">Scenario over</div><h2 style="font-size:30px">Time's up</h2><p class="tagline">${esc(def.goal)} was not reached in ${def.days} days. Keep playing this network as free play, or try again.</p><div class="btns">${btn('Try again','startScn',{id:def.id},'pink big')}${btn('Keep playing','closeModal',{},'ghost big')}</div>`);}}
|
||
function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){}
|
||
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Scenarios</div><h2 style="font-size:28px">Pick a challenge</h2></div><button class="x" data-act="${UI.started?'closeModal':'helpClose'}" aria-label="Close">×</button></div>
|
||
<div class="scn wk"><div class="grow"><div class="nm">Weekly challenge ${esc(wk.key)}</div><div class="meta">Start in ${esc(CITY[wk.city].name)} · ${wk.mods.map(m=>esc(m.n)).join(' · ')} · one year, score = peak traffic. The same world for everyone this week.${best?` Your best: ${fmtG(best)}.`:''}</div></div>${btn('Play','startWeekly',{},'pink')}</div>
|
||
${SCN.map(x=>`<div class="scn"><div class="grow"><div class="nm">${esc(x.n)} ${h[x.id]?`<span class="tag open">done in ${h[x.id].days} days</span>`:''}</div><div class="meta">${esc(x.d)}</div><div class="meta"><b>Goal:</b> ${esc(x.goal)} · <b>Time:</b> ${x.days} days · start in ${esc(CITY[x.city].name)}</div></div>${btn('Play','startScn',{id:x.id},'')}</div>`).join('')}`);}
|
||
function newGame(name,home){
|
||
S={v:1,name,asn:200000+Math.floor(Math.random()*15000),home,day:0,cash:START_CASH,
|
||
pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},
|
||
done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubAt:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0};
|
||
}
|
||
|
||
/* ================= HELPERS ================= */
|
||
const fmt$=v=>{const a=Math.abs(v),s=v<0?'-':'';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>=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)+'%';
|
||
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
|
||
const pick=a=>a[Math.floor(Math.random()*a.length)];
|
||
const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||
function dateStr(d){const y=1+Math.floor(d/360),m=Math.floor(d/30)%12,dd=d%30+1;return `Y${y} · ${MONTHS[m]} ${dd}`;}
|
||
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)));}
|
||
const isSub=(a,b)=>CITY[a].land!==CITY[b].land;
|
||
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;
|
||
function ixName(c){return S.myIx[c]?S.myIx[c].name:CITY[c].ix;}
|
||
function ixMembers(c){if(S.myIx[c])return S.myIx[c].members.slice();if(!CITY[c].ix)return [];return NETS.filter(n=>n.ix==='ALL'||(Array.isArray(n.ix)&&n.ix.includes(c))).map(n=>n.id);}
|
||
// 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;
|
||
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`:`${PORT[tier].n} port`;}
|
||
function ixCap(c){return S.myIx[c]?400:lagCap(PORT[S.ixp[c]].g,(S.ixn||{})[c])*(isRemote(c)?REMOTE_CAP:1);}
|
||
function ixSessions(c){
|
||
const s=new Set(); if(S.ixp[c]===undefined)return s;
|
||
for(const id of ixMembers(c)){const n=NET[id];
|
||
if(S.peers[id+'@'+c]&&!snub(id,c)&&!(isRemote(c)&&noRemote(id)))s.add(id);
|
||
else if(S.rs[c]&&n.pol==='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('POPs on 3+ continents');
|
||
if(pops<10)miss.push(`10+ POPs (${pops})`);
|
||
if(R.served<1500)miss.push(`serve 1.5 Tbps (${fmtG(R.served)})`);
|
||
if(R.sessions<20)miss.push(`20+ peering sessions (${R.sessions})`);
|
||
return {ok:!miss.length,missing:miss};
|
||
}
|
||
/* 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. */
|
||
const SNUB_WIN=150,SNUB_P=0.22;
|
||
const SNUB_IX=['Only peers over PNIs in this metro. Order a cross-connect instead.','Their IX port here is full until the next upgrade. They promise it is soon.','Moved everything in this city to PNIs. Please read their PearingDB page, all 40 pages of it.','The peering coordinator for this city is on a six-month sabbatical.','Their policy here says "IX peering by invitation only". You were not invited.'];
|
||
const SNUB_ALL=['Not accepting new peers in this region right now.','Region frozen while they renegotiate with the local incumbent.','Their routers in this city are "at capacity". They are not.','Already reach you through your transit provider here and think that is fine.','Their lawyers are reviewing every peering agreement in this country. Again.','A new VP wants to "monetise interconnection" in this market.'];
|
||
function hstr(t){let h=2166136261;for(let i=0;i<t.length;i++){h^=t.charCodeAt(i);h=Math.imul(h,16777619);}return h>>>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])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=`<p class="note" style="color:var(--bad)"><b>Remote peering is a last resort.</b> Ports come through a reseller at 1.5× the price, only 80% of the port is really yours, latency rides the fabric, one fabric outage drops every session, and many selective networks refuse remote members. A POP here is better.</p>`;
|
||
const REMOTE_WHY=['Policy: no remote peers. Be in the building or be in the transit bill.','Saw your session come in over a fabric and said "we can smell the VXC from here".','Only peers with members they can reach without a 1,500 km hairpin.','Their PearingDB entry says "Remote peering: No (we mean it)".','Tried a remote peer once. It flapped during a product launch. Never again.'];
|
||
function isRemote(c){return S.ixp[c]!==undefined&&!S.pops[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);}
|
||
function ixPortMo(c,tier){return Math.round(PORT[tier].ix*(S.pops[c]?1:REMOTE_FEE)*dkMult(c)*(CITY[c].ixCheap||1));}
|
||
/* 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™','Like blackholing, but with a Plus.'],['Route Server Gold','The same route server, in a gold-coloured portal.'],['Premium Port LEDs','Your port light now blinks in brand colours.'],['Strategic Peering Insights','A monthly PDF of your own traffic graphs.'],['GlobePeer Ready™','Makes your port "ready" for a product you did not buy.'],['Cloud Exchange Readiness Fee','A fee for being ready for the cloud.'],['Account Manager Lunch Fund','Your account manager is hungry.']];
|
||
const DK_STALL=['Your account manager would love to "align on value" first. Strategic call booked for next week.','Pricing is reviewed by the Global Commercial Council, who meet on the next full moon.','They sent a 14-page NDA before they can even repeat the price. Lawyers estimate a week.','Your account manager is at a conference in Dubai. And then one in Madrid.'];
|
||
function dkMult(c){if(!S||!isDk(c)||!S.dk||!S.dk.m[c])return 1;const ret=S.dk.ret[c];return S.dk.m[c]*(ret&&ret>S.day?0.6:1);}
|
||
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);
|
||
openModal(`<div class="eyebrow">DE-KICKS Group · Sales</div><h2 style="font-size:26px">Your personalised ${PORT[q.tier].n} quote for ${esc(ixName(c))}</h2>
|
||
<p class="tagline">“Thanks for your interest! We don't publish prices, because every customer is unique.”</p>
|
||
<div class="kv"><span>Monthly price, just for you</span><b>${fmt$(mo)}/mo</b></div>
|
||
<div class="kv"><span>List price</span><b>Confidential</b></div>
|
||
<div class="kv"><span>What others pay</span><b>Covered by NDA</b></div>
|
||
<p class="note">Quotes go up with how big you look. ${q.h>=3?'Your account manager has stopped replying to haggling.':`Haggles left: ${3-q.h}.`}</p>
|
||
<div class="btns">${btn(`Sign <small>${fmt$(mo)}/mo</small>`,'dkAccept',{},'pink',S.cash<mo)}${btn('Haggle','dkHaggle',{},'',q.h>=3)}${btn('Walk away','dkWalk',{},'ghost')}</div>`);}
|
||
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){dk.m[c]=+(dk.m[c]*1.1).toFixed(3);toast(`<b>Your ${esc(ixName(c))} promo ended.</b><br>Price is back, plus 10% for "loyalty programme administration".`,'bad');}
|
||
if(dk.m[c]&&(d+hstr(c)%90)%365===0){const f=1.08+Math.random()*0.07;dk.m[c]=+(dk.m[c]*f).toFixed(3);toast(`<b>DE-KICKS has harmonised its prices.</b><br>Harmonised means up: ${esc(ixName(c))} now costs ${Math.round((f-1)*100)}% more. Thank you for your continued partnership.`,'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(`<b>Good news! You've been enrolled in ${esc(n)}.</b><br>${esc(blurb)} ${fmt$(mo)}/mo, added to your ${esc(ixName(c))} invoice. Opt out any time in the IX panel.`,'bad');}}}
|
||
}
|
||
|
||
function elephant(){S.phpDone=true;S.ev.php=S.day+4;
|
||
toast(`<b>🐘 BREAKING: CVE-2026-31337 just took down half the internet.</b><br>A bug in PHP turned every WordPress-ish site on Earth into a crypto miner. Eyeball traffic is down 30% for a few days while the world patches. Your hosting customers are doing it at 3 a.m.`,'bad');sfx('alert');renderMega();}
|
||
function snubWhy(sn){const d=Math.max(1,sn.until-S.day);return `${sn.why} They will reconsider in ${d} day${d===1?'':'s'}.`;}
|
||
function peerOk(id,via,city){
|
||
const n=NET[id],dem=R.demTo[id]||0;
|
||
const sn=snub(id,city);if(sn&&(via==='ix'||sn.all))return {ok:false,snub:true,why:snubWhy(sn)};
|
||
if(via==='ix'&&city&&isRemote(city)&&noRemote(id))return {ok:false,remote:true,why:REMOTE_WHY[hstr(id)%REMOTE_WHY.length]};
|
||
if(n.pol==='open')return {ok:true};
|
||
if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id));return dem>=need?{ok:true}:{ok:false,why:`Wants ≥ ${need} Gbps of traffic from you (you send ${dem.toFixed(1)})`};}
|
||
if(n.pol==='paid')return via==='pni'?{ok:true,fee:n.paidFee}:{ok:false,why:'Paid peering only, over a PNI'};
|
||
if(via!=='pni')return {ok:false,why:'Tier 1s never peer at IXs'};
|
||
const c=t1Club();return c.ok?{ok:true}:{ok:false,why:'Not big enough yet: '+c.missing.join(', ')};
|
||
}
|
||
// 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:`${NET[t.net].name} transit · ${lagName(t.tier,t.n)}`,u,tip:'Add a LAG member, upgrade the port or buy a second upstream.'});}
|
||
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:c,lab:`${ixName(c)} port`,u,tip:'Upgrade the IX port or add a LAG member.'});}
|
||
for(const p of S.pni){const cap=lagCap(PORT[p.tier].g,p.n),u=(R.usePni[p.id]||0)/cap;if(u>=HOT)out.push({k:'p',city:p.city,lab:`PNI with ${NET[p.net].name}`,u,tip:'Add a LAG member or upgrade the PNI.'});}
|
||
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});cc[k].used+=R.useCache[x.id]||0;cc[k].cap+=CACHE_CAP;}
|
||
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:`${NET[x.net].cache.name} cache${x.cap>CACHE_CAP?'s':''}`,u,tip:'Ask for another box. The overflow goes out over peering or transit.'});}
|
||
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:'Routers',u,tip:'Upgrade the router or add a second one in the Infra tab.'});}
|
||
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;}
|
||
function isTier1(){return NETS.filter(n=>n.type==='t1').every(n=>S.pni.some(p=>p.net===n.id))&&S.transit.length===0&&R.reach>0.999;}
|
||
function tierLabel(){return S.won?'Tier 1':isTier2()?'Tier 2':'Tier 3';}
|
||
|
||
/* ================= SIMULATION ================= */
|
||
function compute(){
|
||
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp);
|
||
const remote=remoteCities(),adj={}; pops.concat(remote).forEach(p=>adj[p]=[]);
|
||
const edges={};
|
||
for(const l of S.links){if(linkDown(l)||!adj[l.a]||!adj[l.b])continue;const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key];
|
||
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,km:l.km,cap:0,w:Infinity,lat:Infinity,links:[]};adj[l.a].push([l.b,e]);adj[l.b].push([l.a,e]);}e.cap+=capOf(l);e.links.push(l);e.w=Math.min(e.w,(l.km+60)*MET[l.metric||'normal'].f);e.lat=Math.min(e.lat,linkLat(l));}
|
||
const SP={};
|
||
for(const s of pops){const dist={[s]:0},prev={},done=new Set();
|
||
for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);
|
||
for(const [v,l] of adj[u]){const nd=ud+l.w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
|
||
SP[s]={dist,prev};}
|
||
const prevU=e=>{let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;return e.cap?ld/e.cap:0;};
|
||
const dijk=(s0,mode)=>{const dist={[s0]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,e] of adj[u]){const nd=ud+(mode==='fast'?e.lat+0.05:e.w*(1+10*prevU(e)));if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=e;}}}return {dist,prev};};
|
||
const E=[], ev=S.ev;
|
||
const depeer=ev.depeer>day||scnRule('spat'), leak=ev.leak&&ev.leak.until>day?ev.leak.net:null;
|
||
for(const t of S.transit){if(!popUp(t.city)||t.down>day||siteDown(t.city,t.site||'a'))continue;
|
||
E.push({k:'t',prem:!!t.premium&&t.city==='hkg',pref:t.pref||'normal',lab:NET[t.net].name+' transit',id:t.id,city:t.city,cap:lagCap(PORT[t.tier].g,t.n),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak});}
|
||
for(const c in S.ixp){if(!(popUp(c)||remote.includes(c))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||siteDown(c,(S.ixSite||{})[c]||'a'))continue;const set=ixSessions(c);R2.sessions+=set.size;
|
||
E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:ixName(c)+' peering',id:c,city:c,cap:ixCap(c),used:0,rank:2,ok:n=>set.has(n)});}
|
||
for(const p of S.pni){R2.sessions++;if(!popUp(p.city)||siteDown(p.city,p.site||'a'))continue;E.push({k:'p',pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:'PNI with '+NET[p.net].name,id:p.id,city:p.city,cap:lagCap(PORT[p.tier].g,p.n),used:0,rank:1,ok:n=>n===p.net});}
|
||
for(const c of S.caches){if(!popUp(c.city)||siteDown(c.city,'a'))continue;E.push({k:'c',pref:'normal',lab:NET[c.net].cache.name+' cache',id:c.id,city:c.city,cap:CACHE_CAP,used:0,rank:0,ok:n=>n===c.net});}
|
||
{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);}}
|
||
for(const n of NETS){R2.reachable[n.id]=E.some(e=>e.rank>0&&e.ok(n.id));if(R2.reachable[n.id])R2.reach+=NSH[n.id];}
|
||
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);
|
||
const flows=[];
|
||
for(const c of Object.keys(S.pops)){
|
||
const p=S.pops[c],SH=cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cnCity(c)&&ev.golden>day?1.4:1);const biz=S.biz.filter(b=>b.city===c&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&(!BIZ_T[b.type].event||eventLive(b))).reduce((a,b)=>a+b.bw,0);const d=eye+biz;
|
||
R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d;
|
||
for(const n of NETS)R2.demTo[n.id]=(R2.demTo[n.id]||0)+d*(SH[n.id]||0);
|
||
if(!popUp(c))continue;
|
||
const dd=ev.ddos&&ev.ddos.city===c&&ev.ddos.until>day?d*0.7*(S.scrubAt?0.15:1):0;
|
||
if(dd)for(const n of NETS)flows.push({c,n:n.id,rem:dd*NSH[n.id],junk:true});
|
||
R2.cityBlocked=R2.cityBlocked||{};
|
||
for(const n of NETS){const a=d*(SH[n.id]||0);if(a<=0)continue;
|
||
if(cacheNets.has(n.id)){flows.push({c,n:n.id,rem:a*0.85,cache:true});flows.push({c,n:n.id,rem:a*0.15});}
|
||
else flows.push({c,n:n.id,rem:a});}
|
||
}
|
||
const res={},eload={},nres={};for(const k in edges)res[k]=edges[k].cap;for(const c of pops){nres[c]=nodeCap(c);R2.nodeCap[c]=nres[c];}
|
||
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;
|
||
for(const [A,B] of pairs){let amt=0;
|
||
if(popUp(A)&&popUp(B)&&SP[A]&&SP[A].dist[B]!==undefined){
|
||
const sp=b.route&&b.route!=='normal'?dijk(A,b.route):SP[A],path=[],ns=[B];let v=B;while(v!==A){const l=sp.prev[v];path.push(l);v=l.a===v?l.b:l.a;ns.push(v);}
|
||
amt=b.bw;for(const l of path)amt=Math.min(amt,res[l.id]);for(const n of ns)if(nres[n]!==undefined)amt=Math.min(amt,nres[n]);amt=Math.max(0,amt);maxLat=Math.max(maxLat,path.reduce((x,e)=>x+e.lat,0)+path.length*0.05);
|
||
for(const n of ns)if(nres[n]!==undefined){nres[n]-=amt;R2.nodeLoad[n]=(R2.nodeLoad[n]||0)+amt;}
|
||
const ek='l2:'+b.id;R2.egDesc[ek]={lab:(b.sites?'SD-WAN for ':'L2VPN for ')+b.name,city:A,k:'l2'};
|
||
for(const l of path){res[l.id]-=amt;eload[l.id]=(eload[l.id]||0)+amt;const rec=R2.ef[l.id]||(R2.ef[l.id]={eg:{},net:{},dst:{}});rec.eg[ek]=(rec.eg[ek]||0)+amt;rec.net.l2vpn=(rec.net.l2vpn||0)+amt;rec.dst[B]=(rec.dst[B]||0)+amt;}}
|
||
minF=Math.min(minF,amt/b.bw);tot+=amt;}
|
||
R2.l2lat[b.id]=maxLat;R2.l2[b.id]=b.bw*minF;R2.egT.l2=(R2.egT.l2||0)+tot;if((b.reqs||[]).includes('diverse'))R2.div[b.id]=diversePaths(b.city,b.city2);}
|
||
const TE=!!(S.te&&S.te.on);R2.teMoved=0;const teCache={};
|
||
const spPath=(sp,src,dst)=>{const path=[],ns=[dst];let v=dst;while(v!==src){const l=sp.prev[v];path.push(l);v=l.a===v?l.b:l.a;ns.push(v);}return {path,ns};};
|
||
const altPath=(src,dst,base)=>{const key=src+'>'+dst,c0=teCache[key];
|
||
if(c0===false)return null;if(c0&&c0.path.every(l=>res[l.id]>1e-3)&&c0.ns.every(n=>nres[n]===undefined||nres[n]>1e-3))return c0;
|
||
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]<ud){u=k;ud=dist[k];}if(u===null||u===dst)break;done.add(u);
|
||
for(const [v,e] of adj[u]){if(res[e.id]<=1e-3||(nres[v]!==undefined&&nres[v]<=1e-3))continue;const nd=ud+e.w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=e;}}}
|
||
if(dist[dst]===undefined||dist[dst]>2*base+60){teCache[key]=false;return null;}
|
||
const P=spPath({prev},src,dst);teCache[key]=P;return P;};
|
||
for(let rank=0;rank<5;rank++){
|
||
const Er=E.filter(e=>(e.pref==='low'?4:e.rank)===rank);if(!Er.length)continue;const sorted={};
|
||
for(const f of flows){
|
||
if(f.rem<=1e-6||(rank===0&&!f.cache))continue;
|
||
const sp=SP[f.c];
|
||
const srt=sorted[f.c]||(sorted[f.c]=Er.filter(e=>sp.dist[e.city]!==undefined).sort((a,b)=>(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||sp.dist[a.city]-sp.dist[b.city]));
|
||
const cands=srt.filter(e=>e.used<e.cap&&e.ok(f.n));
|
||
// 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.
|
||
// Push up to `want` along one path to exit e; returns what fitted.
|
||
const push=(e,P,want)=>{const path=P.path,ns=P.ns;let amt=want;
|
||
for(const l of path)amt=Math.min(amt,res[l.id]);for(const n of ns)if(nres[n]!==undefined)amt=Math.min(amt,nres[n]);
|
||
if(amt<=1e-6)return 0;
|
||
for(const n of ns)if(nres[n]!==undefined){nres[n]-=amt;R2.nodeLoad[n]=(R2.nodeLoad[n]||0)+amt;}
|
||
const ek=e.k+':'+e.id;R2.egDesc[ek]={lab:e.lab,city:e.city,k:e.k};
|
||
for(const l of path){res[l.id]-=amt;eload[l.id]=(eload[l.id]||0)+amt;const rec=R2.ef[l.id]||(R2.ef[l.id]={eg:{},net:{},dst:{}});rec.eg[ek]=(rec.eg[ek]||0)+amt;const nk=f.junk?'junk':f.n;rec.net[nk]=(rec.net[nk]||0)+amt;rec.dst[f.c]=(rec.dst[f.c]||0)+amt;}
|
||
e.used+=amt;f.rem-=amt;
|
||
if(!f.junk){let ok=amt;const fc=cnCity(f.c),ec=cnCity(e.city),nc=!!NET[f.n].cn;
|
||
if(fc!==ec||(fc&&!nc)||(!fc&&nc&&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);}
|
||
if(f.n==='ggl'&&ruCity(f.c))ok*=0.5;
|
||
R2.citySrv[f.c]+=ok;R2.served+=ok;if(e.rank<=2)R2.peered+=ok;R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=R2.netEg[f.n]||(R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=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=(e,want)=>{
|
||
let room=Math.min(want,f.rem,e.cap-e.used);if(room<=1e-6)return;
|
||
room-=push(e,spPath(sp,f.c,e.city),room);
|
||
if(TE&&room>1e-6&&f.rem>1e-6&&e.used<e.cap&&e.city!==f.c)for(let k=0;k<2&&room>1e-6;k++){const P=altPath(f.c,e.city,sp.dist[e.city]);if(!P)break;const m=push(e,P,Math.min(room,e.cap-e.used));if(m<=1e-6)break;room-=m;R2.teMoved+=m;}
|
||
};
|
||
const gk=e=>(e.pref==='high'?0:1);
|
||
for(let i=0;i<cands.length&&f.rem>1e-6;){
|
||
let j=i+1;while(j<cands.length&&gk(cands[j])===gk(cands[i])&&Math.abs(sp.dist[cands[j].city]-sp.dist[cands[i].city])<1e-6)j++;
|
||
const g=cands.slice(i,j);i=j;
|
||
if(g.length>1){const room=g.map(e=>Math.max(0,e.cap-e.used)),tot=room.reduce((a,b)=>a+b,0),want=f.rem;if(tot>1e-6)g.forEach((e,k)=>send(e,want*room[k]/tot));}
|
||
for(const e of g){if(f.rem<=1e-6)break;send(e,f.rem);}
|
||
}
|
||
}
|
||
}
|
||
for(const k in edges){const e=edges[k],ld=eload[k]||0;for(const l of e.links)R2.load[l.id]=ld*capOf(l)/e.cap;}
|
||
R2.peerShare=R2.served>0?R2.peered/R2.served:0;
|
||
for(const e of E){if(e.k==='t')R2.useT[e.id]=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;}
|
||
// money
|
||
const C=R2.cost,V=R2.rev,pm=S.priceMul;
|
||
C.pops=Object.values(S.pops).reduce((a,p)=>a+POP_MO+((p.routers||1)-1)*ROUTER_MO+(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.spares?Math.round(150+(l.ch||[]).length*80):0),0);
|
||
C.links=S.links.reduce((a,l)=>a+(l.mo||0),0);
|
||
C.nni=(S.nni||[]).reduce((a,x)=>a+NNI[x.tier].mo,0);
|
||
C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0);R2.p95[t.id]=q;const n=t.n||1;return a+Math.max(q,PORT[t.tier].g*n*0.2)*NET[t.net].price*(t.premium&&t.city==='hkg'?NET[t.net].premium:1)*pm*regionMult(t.city)+PORT[t.tier].tmo*n;},0);
|
||
C.ix=Object.keys(S.ixp).reduce((a,c)=>a+(S.myIx[c]?MYIX_MO:ixPortMo(c,S.ixp[c])*((S.ixn||{})[c]||1)+dkAddonMo(c)),0);
|
||
C.pni=S.pni.reduce((a,p)=>a+PORT[p.tier].pni*(p.n||1)+(NET[p.net].pol==='paid'?NET[p.net].paidFee:0),0);
|
||
C.caches=S.caches.length*CACHE_MO;
|
||
C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.pay),0);
|
||
C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+(S.scrubAt?SCRUB_MO:0)+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);
|
||
V.eyeballs=0;V.business=0;V.ix=0;
|
||
for(const c in S.pops){const sf=sfOf(R2,c);V.eyeballs+=R2.cityEye[c]*sf*EYE_RATE*(CITY[c].arpu||1);}
|
||
for(const b of S.biz){const sf=BIZ_T[b.type].fiber?(fiberOk(b)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city);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;
|
||
C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?l.share:0),0)*(V.eyeballs+V.business+V.ix);
|
||
R2.costMo=Object.values(C).reduce((a,b)=>a+b,0);
|
||
R2.revMo=V.eyeballs+V.business+V.ix;
|
||
R=R2;UI.hotMap=hotByCity();
|
||
}
|
||
function p95(t,cur){const h=(t.hist||[]).slice(-29).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];}
|
||
function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0);}
|
||
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);}
|
||
function nniPort(c,prov){return (S.nni||[]).find(x=>x.city===c&&x.prov===prov);}
|
||
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);}
|
||
const own=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
|
||
const isCity=c=>typeof c==='string'&&own(CITY,c),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){
|
||
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'].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.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,4,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'){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);
|
||
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,4,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);else p.bb=null;}
|
||
if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra';
|
||
const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,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);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))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.metric&&!own(MET,l.metric))l.metric='normal';return l;});
|
||
s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t));
|
||
s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.id=sid(x.id),x.tier=tier(x.tier),x.n=lag(x.n),x));
|
||
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));
|
||
for(const c of Object.keys(s.ixp)){if(!isCity(c))delete s.ixp[c];else s.ixp[c]=tier(s.ixp[c]);}
|
||
for(const k of ['rs','ixn','ixPref','ixSite'])for(const c of Object.keys(s[k]))if(!isCity(c))delete s[k][c];
|
||
for(const c of Object.keys(s.ixn))s.ixn[c]=lag(s.ixn[c]);
|
||
for(const k of Object.keys(s.peers)){const [n,c]=k.split('@');if(!isNet(n)||!isCity(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||'Your IX').slice(0,40);m.next=num(m.next,s.day);}
|
||
const okBiz=b=>b&&own(BIZ_T,b.type)&&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||'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(!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.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';return b;};
|
||
s.biz=s.biz.filter(okBiz).map(fixBiz);s.offers=s.offers.filter(okBiz).map(fixBiz);
|
||
s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(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));
|
||
s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank));
|
||
s.usedNames=s.usedNames.filter(x=>typeof x==='string');s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,30);
|
||
if(s.scrubAt&&!isCity(s.scrubAt))s.scrubAt=null;
|
||
return s;}
|
||
function migrate(s){sanitize(s);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=s.nni||[];s.cnLic=s.cnLic||{state:'none'};if(s.scrubAt===undefined)s.scrubAt=null;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;}return s;}
|
||
const REQS={
|
||
lat:{only:true,l2:true,bonus:0,l:o=>`One-way latency within ${o.latMax} ms (best now: ${(()=>{const v=R.l2lat[o.id]!==undefined?R.l2lat[o.id]:bestLat(o.city,o.city2);return isFinite(v)?v.toFixed(1)+' ms':'no path'})()})`,ok:b=>(R.l2lat[b.id]!==undefined?R.l2lat[b.id]:bestLat(b.city,b.city2))<=b.latMax},
|
||
diverse:{l:'Two paths that share no trench or fabric',bonus:.25,l2:true,ok:b=>R.div[b.id]!==undefined?!!R.div[b.id]:diversePaths(b.city,b.city2)},
|
||
sharks:{l:'Afraid of sharks: needs a path with no subsea cable',bonus:.2,l2:true,ok:b=>terrestrialPath(b.city,b.city2)},
|
||
nocog:{l:'Refuses Cogentle transit anywhere on your network (long story)',bonus:.15,ok:()=>!S.transit.some(t=>t.net==='cog')},
|
||
ipv6:{l:'IPv6 or bust: you must peer with Drizzle Electric',bonus:.1,ok:()=>Object.keys(S.ixp).some(c=>ixSessions(c).has('drz'))||S.pni.some(p=>p.net==='drz')},
|
||
netchill:{l:'Wants NetChill on-net: a cache or a PNI',bonus:.15,ok:()=>S.caches.some(c=>c.net==='nfx')||S.pni.some(p=>p.net==='nfx')},
|
||
gen:{l:'Backup generator in every city they touch',bonus:.15,ok:b=>[b.city,b.city2].filter(Boolean).every(c=>S.pops[c]&&S.pops[c].gen)},
|
||
routers:{l:'Insists on two routers in their city',bonus:.15,ok:b=>((S.pops[b.city]&&S.pops[b.city].routers)||1)>=2},
|
||
local:{l:'Local breakout: transit or an IX port in their own city',bonus:.2,ip:true,ok:b=>S.transit.some(t=>t.city===b.city)||S.ixp[b.city]!==undefined},
|
||
metro:{l:'Two data centers in every metro they touch',bonus:.2,only:true,ok:b=>[b.city,b.city2].filter(Boolean).every(c=>S.pops[c]&&S.pops[c].site2)},
|
||
twoup:{l:'Wants two different transit providers (or none at all)',bonus:.15,ip:true,ok:()=>new Set(S.transit.map(t=>t.net)).size>=2||S.transit.length===0},
|
||
china:{l:'Needs low-loss reach into China',bonus:.3,ip:true,ok:()=>S.transit.some(t=>t.premium&&t.city==='hkg')||S.links.some(l=>l.premium)||S.pni.some(p=>NET[p.net].cn)},
|
||
scrubbed:{l:'Will only sign with a network that runs a DDoS scrubbing center',bonus:.15,ok:()=>!!S.scrubAt},
|
||
puns:{l:'Their CEO hates puns. Please do not mention the network names.',bonus:.05,ok:()=>true},
|
||
};
|
||
function terrestrialPath(a,b){const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);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));
|
||
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 `<div class="meta"><b style="color:${ok?'var(--eye)':'var(--bad)'}">${ok?'✓':'✗'}</b> ${esc(lab)}</div>`;}).join('');}
|
||
function diversePaths(a,b){
|
||
const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);
|
||
const live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
|
||
const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);}
|
||
const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}}
|
||
if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;};
|
||
const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));}
|
||
function fiberOk(b){const l=S.links.find(x=>x.id===b.link);if(!l)return false;if(b.type==='dfpair'||b.type==='pairs')return l.ready<=S.day&&!(l.cut>S.day);return !linkDown(l);}
|
||
function soldSlots(l){return S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);}
|
||
function bizSf(b){const T=BIZ_T[b.type];return T.fiber?(fiberOk(b)?1:0):T.l2?clamp((R.l2[b.id]||0)/b.bw,0,1):sfOf(R,b.city);}
|
||
function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);}
|
||
function bHas(o){return bCities(o).every(c=>S.pops[c]);}
|
||
function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day<b.start+b.dur;}
|
||
function bTerms(o){const T=BIZ_T[o.type];
|
||
if(T.event){const live=S.day>=o.start;return `${fmtG(o.bw)} extra for ${o.dur} days, ${live?`day ${S.day-o.start+1} of ${o.dur}`:`starting in ${o.start-S.day}d`} · pays ${fmt$(o.fee)} when it is over`;}
|
||
if(T.sdwan)return `${o.sites.length} sites: ${o.sites.map(c=>CITY[c].name).join(', ')} · ${fmtG(o.bw)} per site · ${fmt$(o.bw*o.rate)}/mo`;
|
||
if(T.fiber)return `${esc(o.what)} · ${fmt$(o.rate)}/mo`;
|
||
return `${fmtG(o.bw)} · ${fmt$(o.bw*o.rate)}/mo`;}
|
||
// 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<b.start)return true;
|
||
if(d<b.start+b.dur){b.srv=(b.srv||0)+sfOf(R,b.city);b.srvDays=(b.srvDays||0)+1;if(d===b.start)toast(`<b>${esc(b.name)} starts today!</b><br>${fmtG(b.bw)} of extra demand in ${CITY[b.city].name} for ${b.dur} days.`,'goal',[{l:'Show me',act:'focusCity',args:{city:b.city}}]);return true;}
|
||
const avg=b.srvDays?b.srv/b.srvDays:0;if(avg>=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?`<b>${esc(b.name)} is over: +${fmt$(pay)}</b><br>You delivered ${pct(avg)} of what the crowd wanted.${avg>=0.95?' Flawless.':''}`:`<b>${esc(b.name)} was a disaster.</b><br>Only ${pct(avg)} delivered, and it trended on social media. Penalty: ${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. */
|
||
const MEGA=[{c:'ash',n:'Data Center Alley-ish'},{c:'ash',n:'Prometheus-ish Ohio'},{c:'dal',n:'Star-Gait Abilene'},{c:'dal',n:'Hyperion-ish Louisiana'},{c:'dal',n:'Colossal Ego Memphis'},{c:'chi',n:'Fairwater-ish Wisconsin'},{c:'chi',n:'Project Rainier-ish Indiana'},{c:'chi',n:'Cornfield Cluster Iowa'},{c:'nyc',n:'Neocloud New Jersey'},{c:'sto',n:'Star-Gait Fjord-way'},{c:'mad',n:'Aragón Mega-shed'},{c:'dub',n:'Bring-Your-Own-Power Dublin'},{c:'auh',n:'Star-Gait UAE'},{c:'dxb',n:'Desert Kingdom AI Campus'},{c:'kul',n:'Johor-ish Overflow'},{c:'hyd',n:'Vizag-ish AI Hub'},{c:'icn',n:'Ulsan-ish AI Campus'},{c:'tok',n:'Hokkaido-ish Snow DC'},{c:'syd',n:'Star-Gait Down Under'},{c:'mex',n:'Querétaro-ish Cluster'},{c:'for',n:'Short-Video Ceará Campus'},{c:'scl',n:'Quilicura-ish Region'}];
|
||
function spawnMega(t,T,nm,mine){
|
||
const megaMine=MEGA.filter(m=>mine.includes(m.c));if(!megaMine.length)return;
|
||
if(t==='ingest'){const m=pick(megaMine),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:`${nm()} at ${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'){const a=pick(megaMine),others=MEGA.filter(m=>m.c!==a.c&&(Math.random()<0.7?mine.includes(m.c):true));if(!others.length)return;const b=pick(others),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=pick(megaMine),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.length<Math.min(4,pool.length+1)&&pool.length)sites.push(pool.splice(Math.floor(Math.random()*pool.length),1)[0]);
|
||
const avg=sites.slice(1).reduce((x,c)=>x+kmBetween(hub.c,c),0)/(sites.length-1),bw=pick(T.opts);
|
||
S.offers.push({id:uid(),city:hub.c,city2:null,sites,name:`${nm()} (hub: ${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.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:`${n} fiber pairs in your ${CITY[l.a].name}–${CITY[l.b].name} trench. Trenching was the expensive part, so they want all of it`,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),lv=S.lvl||1;
|
||
const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n));const n=list.length?pick(list):pick(T.names);S.usedNames.push(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(ALLC);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:nm()+' in '+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:ALLC).filter(c=>c!==hub),sites=[hub];
|
||
while(sites.length<n&&pool.length)sites.push(pool.splice(Math.floor(Math.random()*pool.length),1)[0]);if(sites.length<3)return;
|
||
S.offers.push({id:uid(),city:hub,city2:null,sites,name:nm(),type:t,bw:pick(T.opts),rate:700*sites.length,reqs:[],exp:S.day+40});return;}
|
||
const ready=S.links.filter(l=>l.kind==='df'&&l.ready<=S.day);
|
||
if(t==='wwave'){const free=l=>DF_SYS[l.sys].max-(l.ch||[]).length-soldSlots(l);const ls=ready.filter(l=>free(l)>=1&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;const l=pick(ls),slots=1+Math.floor(Math.random()*Math.min(4,free(l)));
|
||
S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,slots,what:`${slots}× 400G alien wave${slots>1?'s':''} on your ${CITY[l.a].name}–${CITY[l.b].name} fiber`,name:nm(),type:t,bw:1,rate:Math.round(waveMo(l.km,false,2)*0.55*slots),reqs:[],exp:S.day+30});return;}
|
||
if(t==='dfpair'){const ls=ready.filter(l=>l.own&&S.biz.filter(b=>b.type==='dfpair'&&b.link===l.id).length<2&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;const l=pick(ls);
|
||
S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,what:`a spare fiber pair in your ${CITY[l.a].name}–${CITY[l.b].name} trench`,name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*0.9),reqs:[],exp:S.day+30});}
|
||
}
|
||
function cnOk(){return S.cnLic&&S.cnLic.state==='ok';}
|
||
function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;return C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;}
|
||
const uaePair=(a,b)=>!!CITY[a].uae&&!!CITY[b].uae;
|
||
const andesPair=(a,b)=>!!CITY[a].andes&&!!CITY[b].andes&&CITY[a].andes!==CITY[b].andes;
|
||
function landMult(a,b){if(isSub(a,b))return 1;if(uaePair(a,b))return 3;return (CITY[a].reg!==CITY[b].reg?2.5:1)*(andesPair(a,b)?2:1);}
|
||
function landWhy(a,b){if(isSub(a,b))return '';if(uaePair(a,b))return 'Inside the UAE only the two licensed operators, Etis-a-lot and do-ish, may run fiber. No dark fiber, no digging your own, and waves cost 3×.';
|
||
const r=[];if(CITY[a].reg!==CITY[b].reg)r.push('Overland between continents crosses a dozen borders: 2.5× the price.');if(andesPair(a,b))r.push('This route crosses the Andes: 2× the price, and landslides and snow cut it far more often than flat fiber.');return r.join(' ');}
|
||
function linkLat(l){const f=l.kind==='df'?(l.own?1.1:1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;}
|
||
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)};
|
||
const c=cabs.find(x=>x.cid===via);return {via,cabs,cab:via,km:c.km,sub:true,wm:bf*CAB[via].price};}
|
||
function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)return landMult(a,b)>1?`<p class="note">${landWhy(a,b)}</p>`:'';const wr=waveRoute(a,b,1,false);
|
||
const opts=(sub?[]:[{v:'land',l:`Overland <small>${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms</small>`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} <small>${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · old, cuts often':''}</small>`})));
|
||
return `<h4 class="sub4">Route</h4><div class="seg">${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}</div>${wr&&wr.cab?`<p class="note">${esc(CAB[wr.cab].blurb)} All your waves on one cable share its fate when it is cut.</p>`:''}`;}
|
||
function bestLat(a,b){const ls=S.links.filter(l=>!linkDown(l));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;}
|
||
const RT={normal:'Follow metrics',fast:'Lowest latency',scenic:'Scenic (quietest links)'};
|
||
function routeCtl(b){const lt=R.l2lat[b.id];return `<div class="btns"><span class="meta" style="align-self:center">Route:</span>${Object.keys(RT).map(m=>btn(RT[m],'setRoute',{id:b.id,m},(b.route||'normal')===m?'pink sm':'ghost sm')).join('')}</div><div class="meta">Path latency: <b>${lt!==undefined?lt.toFixed(1)+' ms one-way':'no path yet'}</b>${b.latMax?` · budget ${b.latMax} ms`:''}</div>`;}
|
||
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*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(p.sdown&&p.sdown.until>S.day&&p.sdown.s===s)return true;return s==='b'&&p.ringcut>S.day;}
|
||
function siteCtl(k,id,c,cur){const p=S.pops[c];if(!p||!p.site2)return '';cur=cur||'a';return `<div class="seg site"><span class="meta">Site:</span>${['a','b'].map(x=>btn(`${x.toUpperCase()} <small>${esc(siteName(c,x))}</small>`,'siteSet',{k,id,s:x},cur===x?'pink sm':'ghost sm')).join('')}</div>`;}
|
||
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?g.n:'?';}
|
||
function portNote(c){const p=S.pops[c];if(!p)return '';const g=p.rgen||0;return g<RG.length-1&&RG[g].maxP<PORT.length-1?`<p class="note" style="margin-top:0">Your ${esc(RG[g].n)} here tops out at ${RG[g].pn} ports. Bigger ports need a router upgrade (Infra tab).</p>`:'';}
|
||
function sfOf(r,c){const d=r.cityDem[c]||0;return d<=1e-6?1:clamp(r.citySrv[c]/d,0,1);}
|
||
|
||
/* ---------- failures & events ---------- */
|
||
function addInc(o){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(o.msg||''))S.stats.sharks=(S.stats.sharks||0)+1;const f=S.stats.f=S.stats.f||{};if(/anchor/i.test(o.msg||''))f.anchor=1;if(/crocodile/i.test(o.msg||''))f.croc=1;if(/llama/i.test(o.msg||''))f.llama=1;}
|
||
const HARMLESS=[
|
||
['Certificate expired','The TLS certificate on your NOC dashboard expired. Nobody can see any graphs, so technically there are no problems.'],
|
||
['It was DNS','Someone deleted the DNS record for the internal wiki. The runbook for fixing DNS was on the wiki.'],
|
||
['Leap second','A leap second convinced one of your routers it is 1970. Uptime now reads minus 56 years. Traffic is fine.'],
|
||
['Change freeze','Management declared a change freeze. Someone made a change to announce the change freeze.'],
|
||
['Ticket of the week','A customer opened a P1 ticket: “the internet is slow”. Attached was a photo of their router, unplugged.'],
|
||
['Monitoring','Your monitoring system went down. You found out because nothing alerted. Very peaceful week.'],
|
||
['Load-bearing typo','Someone named a VLAN “prodcution”. It is now load-bearing and can never be renamed.'],
|
||
['IPv6 milestone','Your IPv6 traffic grew 400%. From one packet to five.'],
|
||
['Mystery link','You found a 10G link in the inventory that nobody ordered, nobody pays for, and that carries 3 Gbps of something.'],
|
||
['Spreadsheet IPAM','Your IP address spreadsheet hit 1,048,576 rows. Excel has opinions.'],
|
||
['Goose incident','A goose attacked the technician on the way to your amp hut. The goose won. Repair rescheduled, nothing broke.'],
|
||
['Latency test','A carrier pigeon beat one of your links in an informal latency test. Morale is low. Throughput is fine.'],
|
||
['Zombie route','A route you withdrew in Year 1 is still visible somewhere in the internet. Nobody knows where. It is fine. Probably.'],
|
||
['Auditor visit','An auditor asked for a network diagram. You sent the game map. They approved it.'],
|
||
['Open to work','Your peering coordinator updated their profile to “open to work”. Three Tier 1s suddenly want to chat. Nothing happened, but it felt nice.'],
|
||
['Hold music','Your upstream support line plays the same 11 seconds of hold music. Your on-call engineer can now hum it in four keys.'],
|
||
['Naming committee','A two-hour meeting about router hostnames ended with a vote for “router-final-v2-NEW”.'],
|
||
['Vendor TAC','Vendor support asked you to “try turning it off and on again”. For the router you already rebooted. Ticket closed.'],
|
||
];
|
||
function fireFailure(){
|
||
const opts=[];
|
||
const live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))];
|
||
if(live.length){opts.push(['cut',2+Math.min(6,live.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&&S.day>60)opts.push(['leak',2]);
|
||
if(S.day>40)opts.push(['ddos',2]);
|
||
if(fabsUsed.length)opts.push(['fabric',1.5]);
|
||
const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0);if(lit.length)opts.push(['amp',1.5+lit.length*0.3],['optic',1.5+lit.length*0.3]);
|
||
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(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label');if(Object.keys(S.ixp).length)f.push('maxpfx');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(lit.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(`<b>${m[0]}</b><br>${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([`A backhoe cut the metro ring between your two sites in ${CITY[c].name}. Turns out both fiber routes ran down the same street.`,`Someone pulled the wrong cross-connect at the meet-me room in ${CITY[c].name}, and ${siteName(c,'b')} is cut off from ${siteName(c,'a')}.`,`A tram line construction project in ${CITY[c].name} found your metro ring. Both halves of it.`]),cost:3000,fix:'Splice it tonight'});return;}
|
||
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:pick([`The A/C at ${CITY[c].dc} died on the hottest day of the year. Your routers in ${CITY[c].name} throttled to half capacity.`,`Someone set the data center thermostat in ${CITY[c].name} to Fahrenheit thinking it was Celsius. Routers are cooking at half speed.`,`The cooling contractor in ${CITY[c].name} replaced the chillers with a very confident fan. Half capacity for two days.`]),cost:2000,fix:'Buy 40 desk fans'});
|
||
}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([`Someone in ${CITY[l.a].dc} labeled every patch cable “DO NOT UNPLUG”. Someone else unplugged one anyway: your ${A}–${B} link.`,`A remote-hands tech in ${A} was asked to clean the fiber on port 1. They cleaned it with a sandwich. ${A}–${B} is down.`,`A new tech in ${A} “tidied up” the cable mess. Your ${A}–${B} link was part of the mess.`])
|
||
:l.kind==='df'?pick([`The landlord in ${A} re-routed the building riser and pinched your dark fiber to ${B}.`,`A splicer fusing someone else’s cable in a manhole near ${B} fused yours instead.`])
|
||
:pick([`${W} fat-fingered a cross-connect and patched your ${A}–${B} wave into a pizza oven.`,`${W} did “quick maintenance” on the wrong wavelength. Your ${A}–${B} wave is now carrying someone else's cat videos.`,`${W} scheduled maintenance in UTC. Your team read it as local time. ${A}–${B} went dark at peak.`,`An engineer at ${W} swapped Tx and Rx on your ${A}–${B} wave. Light goes in, confusion comes out.`,`${W} decommissioned your ${A}–${B} wave because the ticket said “decom” instead of “docs”.`]);
|
||
addInc({type,ref:l.id,until:l.cut,msg,cost:1500,fix:'Bribe their NOC with donuts'});
|
||
}else if(type==='mtu'){
|
||
const l=pick(live);l.deg=S.day+3;addInc({type,ref:l.id,until:l.deg,msg:`MTU mismatch on ${CITY[l.a].name}–${CITY[l.b].name}: jumbo frames keep getting stuck in the tube. Usable capacity halved.`,cost:800,fix:'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.incidents++;S.stats.survived++;pp.sdown={until:S.day+1,s:'a'};toast(`<b>Vacuum incident in ${C}</b><br>The cleaner unplugged everything at ${esc(siteName(c,'a'))}. ${esc(siteName(c,'b'))} kept the city online at half capacity.`,'good');sfx('alert');return;}
|
||
if(type==='cleaner'&&(pp.routers||1)>=2){S.stats.incidents++;S.stats.survived++;toast(`<b>Vacuum incident in ${C}</b><br>The cleaner at ${CITY[c].dc} unplugged one of your routers to plug in a vacuum. The other one kept going. The floor is spotless.`,'good');sfx('alert');return;}
|
||
pp.down=Math.max(pp.down||0,S.day+1);
|
||
const msg=type==='cleaner'?`The cleaner at ${CITY[c].dc} unplugged your router to plug in a vacuum. The floor is spotless.`:pick([`Your on-call engineer typed “clear bgp *” in production in ${C} at 3am. It cleared.`,`An intern pushed an ACL in ${C} that denies 0.0.0.0/0. Very secure. Very offline.`,`Someone ran “reload” on the ${C} router, thinking it was their laptop terminal.`,`A config template rendered “{{ router_id }}” literally in ${C}. The router took it personally.`,`Someone committed a config in ${C} with “commit confirmed 1” and went to lunch.`,`Someone deployed to ${C} on a Friday at 16:59.`,`A cosmic ray flipped a bit in your ${C} router. It now believes 10.0.0.0/8 lives in Antarctica.`,`An automation script in ${C} ran “sed” on the whole config instead of one line. Every interface is now named “TODO”.`]);
|
||
addInc({type,ref:c,until:pp.down,msg:msg+(type==='oops'&&(pp.routers||1)>=2?' Automation pushed it to every router, so redundancy did not help.':''),cost:1500,fix:type==='oops'?'Roll back the config':'Hide the vacuum'});
|
||
}else if(type==='maxpfx'){
|
||
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+1+Math.floor(Math.random()*2));
|
||
addInc({type,ref:c,until:S.ev.ixdown[c],msg:`A member at ${ixName(c)} leaked the full routing table into the route server. Max-prefix limits tripped everywhere. Peering in ${CITY[c].name} is down.`,cost:0});
|
||
}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:`${NET[t.net].name} fat-fingered a route-map and prepended your AS ${30+Math.floor(Math.random()*60)} times in ${CITY[t.city].name}. Nobody wants that path.`,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:'Your ROA expired over the weekend. Your prefixes are RPKI-invalid and about half the internet is dropping them.',cost:1000,fix:'Renew the ROA'});
|
||
}else if(type==='amp'||type==='roadmff'){
|
||
const l=pick(lit),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'?`You fat-fingered the channel plan on ${A}–${B} and lit a new channel right on top of every existing one.`:pick([`An in-line amplifier hut between ${A} and ${B} lost power. A family of mice had moved in.`,`Someone stole the copper grounding from an amp hut on ${A}–${B}. All channels dark.`,`A firmware bug in the ${DF_SYS[l.sys].n} at ${A} set every channel to “maintenance”.`,`Lightning hit an amp site on ${A}–${B}. The surge protector was decorative.`]);
|
||
addInc({type,ref:l.id,until:l.eqDown,msg:msg+(type==='amp'&&l.spares?' Your spares kit gets it back tomorrow.':''),cost:type==='amp'&&!l.spares?AMP_COST:0,fix:'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([`A ${OPT[o].n} on ${A}–${B} overheated and is now a very expensive keychain.`,`The laser in a ${OPT[o].n} on ${A}–${B} died. One channel dark.`,`A ${OPT[o].n} on ${A}–${B} started reporting a temperature of 900°C. It was wrong, but it shut down anyway.`])+(l.spares?' Swapped from your spares kit by tomorrow.':''),cost:l.spares?0:OPT[o].cost,fix:'Buy a replacement'});
|
||
}else if(type==='cut'){
|
||
const mon=Math.floor((S.day%365)/30.42),monsoon=mon>=5&&mon<=8,tw=x=>x.sub&&(x.a==='tpe'||x.b==='tpe'||['clion','balt'].includes(x.cable)),vn=x=>x.sub&&(x.a==='sgn'||x.b==='sgn'),inl=x=>!x.sub&&(CITY[x.a].india||CITY[x.b].india);
|
||
const l=pick(live.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?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);return Array(w).fill(x);})),dur=10+Math.floor(Math.random()*8),tr=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===tr);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));
|
||
const A=CITY[l.a].name,B=CITY[l.b].name;
|
||
const msg=vn(l)&&Math.random()<0.8?pick([`Another of Vietnam’s subsea cables is broken: your ${A}–${B} link. The repair ship will come after the holidays. Which holidays is unclear.`,`Your ${A}–${B} cable broke in the same spot as last time. The repair crew recognised it.`]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([`A crocodile took a bite out of your ${A}–${B} fiber. It was not impressed.`,`Termites ate the duct on ${A}–${B}. Then the fiber. Then the replacement duct.`]):tw(l)&&Math.random()<0.8?pick([`A cargo ship “forgot” to raise its anchor and dragged it across your ${A}–${B} cable. The owners are very sorry, and somewhat hard to reach.`,`Another anchor, another cut: your ${A}–${B} cable. The ship’s flag changed twice during the investigation.`,`A fishing boat with an unusually heavy anchor cut ${A}–${B}. It was not fishing.`]):!l.sub&&andesPair(l.a,l.b)?pick([`A landslide in the Andes buried your ${A}–${B} fiber.`,`Snow closed the mountain pass, and the repair crew with it: ${A}–${B} is down.`,`An earthquake shook your ${A}–${B} fiber loose somewhere above 4,000 metres.`,`A llama herd trampled the fiber marker on ${A}–${B}. Then a backhoe found the fiber.`]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([`Road widening near ${A} cut your fiber to ${B}. It is always road widening.`,`The monsoon flooded a manhole on ${A}–${B}. The fiber is now underwater, as is the manhole.`,`A JCB-ish digger found your ${A}–${B} fiber. A different JCB-ish digger is coming to fix it.`]):l.sub?pick([`A curious shark bit your subsea cable ${A}–${B}.`,`A ship dragged its anchor across your ${A}–${B} cable.`,`An undersea landslide snapped ${A}–${B}.`]):pick([`A backhoe found your fiber between ${A} and ${B}.`,`Squirrels chewed through ${A}–${B}. They regret nothing.`,`Road works cut ${A}–${B}. Nobody called before digging.`]);
|
||
addInc({type,ref:tr,until:S.day+dur,msg:msg+(hit.length>1?` All ${hit.length} links in that trench went down with it.`:''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))});
|
||
}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]:[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(`<b>Router crash in ${CITY[c].name}</b><br>One router panicked and its twin took over.${slow?` The crashed one ${esc(pick(SLOW_BOOT))}.`:''} Capacity there is down one router for ${dur} days.`,'good');sfx('alert');return;}
|
||
if(type==='power'&&!pp.gen&&pp.site2){const sd=Math.random()<0.5?'a':'b';pp.sdown={until:S.day+dur,s:sd};addInc({type:'site',ref:c,until:S.day+dur,msg:`${CITY[c].za?'Load shedding':'A power cut'} took out ${siteName(c,sd)} in ${CITY[c].name}. ${siteName(c,sd==='a'?'b':'a')} kept going, so the POP runs at half capacity. Anything plugged in only at the dark site is offline.`,cost:5000,fix:'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(`<b>Blackout in ${CITY[c].name}</b><br>The grid went dark again. Your generator started on the first try, like it always does here.`,'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?`<b>Load shedding in ${CITY[c].name}</b><br>Stage ${2+Math.floor(Math.random()*5)} today. Your generator coughed, then kept the lights on.`:`<b>Power cut in ${CITY[c].name}</b><br>Your backup generator kicked in. Lights stayed on.`,'good');sfx('alert');return;}
|
||
pp.down=Math.max(pp.down||0,S.day+dur);
|
||
const msg=type==='crash'?(slow?`Your router in ${CITY[c].name} crashed and is rebooting. It ${pick(SLOW_BOOT)}. Boot time on this one: about ${bootMin(c)} minutes per attempt, and it is on attempt ${2+Math.floor(Math.random()*5)}.`:pick([`Your router in ${CITY[c].name} crashed. Kernel panic, packet panic.`,`A firmware update bricked your router in ${CITY[c].name}.`])):CITY[c].blackout?`A blackout hit ${CITY[c].name} and your POP has no generator. Every other network here has one. Buy one.`:CITY[c].za?`Load shedding stage ${3+Math.floor(Math.random()*4)} in ${CITY[c].name}, and you have no generator. Buy one: here it is not optional.`:`Power outage at ${CITY[c].dc} in ${CITY[c].name}. The generator did not start.`;
|
||
addInc({type,ref:c,until:S.pops[c].down,msg,slow:type==='crash'&&slow,cost:type==='crash'?2500:7000,fix:type==='crash'?(slow?'Turn it off and on again (it will take a while)':'Turn it off and on again'):'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:`${NET[t.net].name} is having an outage in ${CITY[t.city].name}. Your transit port there is dark.`,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:`Someone plugged a loop into the ${ixName(c)} fabric. Broadcast storm! All peering there is down.`,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:`BGP route leak: a small ISP is announcing ${NET[n].name}'s prefixes. Traffic to them over transit is black-holed. Direct peering still works.`,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:`${FAB[f].name} is having a bad day. Every virtual circuit on their fabric is down.`,cost:0});
|
||
}else if(type==='ddos'){
|
||
const c=pick(Object.keys(S.pops));S.ev.ddos={city:c,until:S.day+4};
|
||
if(S.scrubAt){S.stats.survived++;toast(`<b>DDoS on ${CITY[c].name}</b><br>A botnet of smart toasters tried. Your scrubbing center in ${CITY[S.scrubAt].name} ate most of it.`,'good');sfx('alert');addInc({type,ref:c,until:S.day+4,msg:'Mostly absorbed by scrubbing.',cost:0});return;}
|
||
addInc({type,ref:c,until:S.day+4,msg:`A botnet of smart toasters is DDoSing ${CITY[c].name}. Junk traffic is eating your capacity.`,cost:6000,fix:'Buy scrubbing'});
|
||
}
|
||
compute();
|
||
const last=S.inc[S.inc.length-1];
|
||
last.impact=Math.max(0,before-R.served);
|
||
if(before>1&&last.impact<before*0.03&&type!=='ddos'){S.stats.survived++;toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)} Traffic rerouted, customers barely noticed.`,'good');}
|
||
else toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}`,'bad',last.cost?[{l:`${last.fix||'Rush repair'} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]);
|
||
sfx('alert');
|
||
}
|
||
function incTitle(t){return {ring:'Metro ring cut',site:'Site outage',cut:'Fiber cut',crash:'Router crash',power:'Power outage',transit:'Upstream outage',ixloop:'IX meltdown',leak:'Route leak',ddos:'DDoS attack',fabric:'Fabric outage',depeer:'Peering spat',fatwave:'Fat-fingered wave',label:'Patch panel mishap',mtu:'MTU mismatch',oops:'Oops',cleaner:'Vacuum incident',maxpfx:'Max-prefix meltdown',prepend:'Prepend-ageddon',rpki:'RPKI invalid',amp:'Amplifier failure',roadmff:'Fat-fingered ROADM',optic:'Dead optic',maint:'Maintenance window',ac:'Cooling failure',hijack:'BGP hijack',shutdown:'Government shutdown',redsea:'Geopolitical cable cut'}[t]||'Incident';}
|
||
const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop','maxpfx'],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'){S.ev.ddos=null;}
|
||
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==='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==='ring'){if(S.pops[i.ref])S.pops[i.ref].ringcut=remainUntil(x=>x.type==='ring'&&x.ref===i.ref);}
|
||
else if(T==='site'){if(S.pops[i.ref])S.pops[i.ref].sdown=null;}
|
||
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==='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];return true;});}
|
||
function fireEvent(){
|
||
const opts=['viral','price','grant'];
|
||
if(S.day>50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic');
|
||
if(Object.keys(S.pops).some(ruCity))opts.push('runet','runet');
|
||
if(['mnl','hkg','tok','icn','sha','jkt'].some(c=>S.pops[c]))opts.push('typhoon');
|
||
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==='sanction'){S.ev.sanction=S.day+60;toast('<b>Sanctions!</b><br>The Republic of Paperworkistan sanctioned your router vendor’s favorite screw supplier. Spare parts are slow: router crashes take twice as long to fix for 60 days.','bad');sfx('alert');return;}
|
||
if(e==='tariff'){S.ev.tariff=S.day+90;toast('<b>Trade war on optics</b><br>Two governments slapped tariffs on each other’s lasers. Optics cost 40% more for 90 days.','bad');sfx('alert');return;}
|
||
if(e==='hijack'){S.ev.rpki={until:S.day+1,nets:NETS.map(n=>n.id).filter(()=>Math.random()<0.6)};addInc({type:'hijack',ref:'rpki',until:S.day+1,msg:'A state-owned ISP “accidentally” announced your prefixes for 18 minutes. Their apology press release was suspiciously well written. Many networks are still routing your traffic into the void.',cost:1500,fix:'Call everyone you know'});toast('<b>BGP hijack</b><br>Someone else is announcing your prefixes. Reach is down until it is cleaned up.','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(`<b>Landing permit dispute in ${CITY[c].name}</b><br>Two ministries both claim the beach. No new subsea links can land there for 45 days.`,'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:`Regulators ordered every network in ${CITY[c].name} to switch off for a day during national school exams. Yes, this really happens.`,cost:0});toast(`<b>Ordered offline in ${CITY[c].name}</b><br>A government exam-day shutdown. Your POP there is dark for a day.`,'bad');sfx('alert');return;}
|
||
if(e==='typhoon'){const c=pick(['mnl','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick(['Typhoon Bandwidth','Typhoon Latency','Typhoon Jitter','Typhoon Packet-Loss']);
|
||
if(p.gen){S.stats.survived++;toast(`<b>${nm} hits ${CITY[c].name}</b><br>The grid is down, but your backup generator kept the routers running.`,'good');sfx('alert');return;}
|
||
p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:`${nm} knocked out power in ${CITY[c].name}. Your POP has no generator.`,cost:7000,fix:'Rent a generator'});toast(`<b>${nm} hits ${CITY[c].name}</b><br>Power is out and your POP is dark for two days. A generator would have saved it.`,'bad');sfx('alert');compute();return;}
|
||
if(e==='runet'){S.ev.runet=S.day+1;toast('<b>Sovereign internet drill</b><br>Moscow unplugged itself from the rest of the internet for a day to see what happens. Everything leaving Russia is dark until tomorrow.','bad');sfx('alert');compute();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('<b>Baltic cable damaged</b><br>A cargo ship dragged its anchor for 100 km and swears it noticed nothing. You have no links on those cables.','goal');return;}
|
||
const dur=15+Math.floor(Math.random()*15);for(const tr of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tr).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tr,until:S.day+dur,msg:'A cargo ship dragged its anchor along the Baltic seabed for 100 km and swears it noticed nothing. Investigators are “looking into it”.',cost:0});}
|
||
toast(`<b>Baltic cable damaged</b><br>${hit.length} of your links are down for about ${dur} days.`,'bad');sfx('alert');compute();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('<b>Cables cut in the Red Sea</b><br>A ship dragged its anchor across several cables. Everyone blames everyone. Luckily you do not use those cables.','goal');return;}
|
||
const dur=20+Math.floor(Math.random()*15);for(const tr of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tr).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tr,until:S.day+dur,msg:`A ship drifting without power dragged its anchor through the Red Sea cables. Everyone blames everyone. Repair ships need permits from three governments.`,cost:0});}
|
||
toast(`<b>Cables cut in the Red Sea</b><br>${hit.length} of your subsea links are down for about ${dur} days while the diplomats argue about repair ships.`,'bad');sfx('alert');compute();return;}
|
||
if(e==='golden'){S.ev.golden=S.day+7;toast('<b>Golden Week!</b><br>Demand in mainland China is up 40% for a week.','goal');return;}
|
||
if(e==='gfw'){S.ev.gfw=S.day+10;toast('<b>The border got stricter.</b><br>Cross-border packet loss rises to 35% for 10 days. Premium routes are barely affected.','bad');sfx('alert');return;}
|
||
if(e==='viral'){S.ev.viral=S.day+8;toast('<b>New season of “Stranger Pings” just dropped!</b><br>Eyeball demand is up 25% for a week. Got headroom?','goal');}
|
||
else if(e==='price'){S.priceMul*=0.92;toast('<b>Transit prices fell 8%.</b><br>They do this every year. Nobody knows where the bottom is.','good');}
|
||
else if(e==='grant'){S.cash+=30000;toast('<b>Rural broadband grant: +$30k</b><br>The Ministry of Tubes likes what you are doing.','good');sfx('coin');}
|
||
else if(e==='depeer'){S.ev.depeer=S.day+20;addInc({type:'depeer',ref:'cog',until:S.day+20,msg:'Cogentle and Goggle are in a peering spat. Goggle is unreachable through Cogentle transit.',cost:0});toast('<b>Peering spat!</b><br>Cogentle de-peered Goggle for 20 days. Goggle traffic over Cogentle transit is gone. Peer with Goggle directly or use another upstream.','bad');sfx('alert');}
|
||
else if(e==='cake'){S.cash+=8000;toast('<b>Drizzle Electric sent you an IPv6 cake.</b><br>You sold it for $8k.','good');sfx('coin');}
|
||
}
|
||
|
||
/* ---------- daily tick ---------- */
|
||
function dayTick(){
|
||
if(!S||S.lost)return;
|
||
S.day++;
|
||
const d=S.day;
|
||
dkTick(d);
|
||
if(!S.phpDone&&d>45&&Math.random()<1/400)elephant();
|
||
if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved);
|
||
if(R&&R.demand>0)S.stats.clean=R.served/R.demand>=0.995?(S.stats.clean||0)+1:0;
|
||
if(S.ev.php===d)toast('<b>The internet is back.</b><br>Half of it, anyway. Everything was patched in a hurry and nobody learned anything.','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;
|
||
toast(`<b>${esc(NET[id].name)} de-peered you in ${esc(CITY[c].name)}.</b><br>${esc(sn.why)} Traffic falls back to your next best path.`,'bad');}
|
||
if(S.cnLic&&S.cnLic.state==='pending'&&d>=S.cnLic.ready){S.cnLic.state='ok';toast('<b>License granted!</b><br>Your joint venture can now build POPs in mainland China.','goal');sfx('coin');}
|
||
// resolve incidents
|
||
for(const i of S.inc.slice())if(i.until<=d){clearInc(i);toast(`<b>Resolved:</b> ${incTitle(i.type).toLowerCase()} is fixed.`,'good');}
|
||
// 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),P=CITY[c].P;
|
||
if(sf>=0.9){const g=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(3,p.bb.d*(1-(0.9-sf)*0.04));}
|
||
compute();
|
||
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)/30;
|
||
S.stats.peak=Math.max(S.stats.peak,R.served);
|
||
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 lv=custLevel();if(lv>(S.lvl||1)){S.lvl=lv;track('level_'+lv);toast(`<b>Customer level ${lv}: ${LEVELS[lv-1].n}</b><br>New customers unlocked: ${LEVELS[lv-1].unlock}`,'goal');sfx('coin');}}
|
||
for(const l of S.links){if(l.kind!=='df')continue;
|
||
if(l.ready===d){toast(`<b>${l.own?'Your fiber is finished':'Dark fiber handed over'}: ${CITY[l.a].name}–${CITY[l.b].name}</b><br>${(l.ch||[]).length?'Channels are lighting up now.':'It is dark. Add optics to light it up.'}`,'goal',[{l:'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);l.ready+=extra;toast(`<b>Construction delay: +${extra} days</b><br>${pick(['Archaeologists found a Roman bathhouse on your route.','A protected hamster species lives along the right-of-way.','The railway changed its mind about the easement.','The drilling crew hit a granite boulder the size of a bus.','A town council wants a public hearing. About the color of the manhole covers.','Somebody else’s gas main was exactly where the map said it was not.','The permit office lost your permit. And then the replacement.'])} (${CITY[l.a].name}–${CITY[l.b].name})`,'bad');}}
|
||
// businesses mood
|
||
for(const b of S.biz.slice()){if(eventTick(b,d))continue;const sf=bizSf(b),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99,scrubOk=b.type!=='scrub'||!!S.scrubAt,divOk=reqOk(b);
|
||
if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2);
|
||
else if(S.day-(b.since||0)<15){}
|
||
else{b.mood-=(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));
|
||
if(b.mood<=0){S.biz=S.biz.filter(x=>x!==b);toast(`<b>${esc(b.name)} cancelled.</b><br>Too many outages and too little bandwidth in ${CITY[b.city].name}.`,'bad');sfx('err');}
|
||
else if(b.mood<30&&!b.warned){b.warned=true;toast(`<b>${esc(b.name)} is furious.</b><br>Fix service in ${CITY[b.city].name} or they leave.`,'bad',[{l:'Show me',act:'focusCity',args:{city:b.city}}]);}}
|
||
if(b.mood>60)b.warned=false;}
|
||
// own IX members join
|
||
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.length<12){
|
||
const cands=NETS.filter(n=>n.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(`<b>${esc(n.name)} joined ${esc(m.name)}!</b><br>Another member paying ${fmt$(MYIX_FEE)}/mo for a port.`,'good');sfx('coin');}
|
||
m.next=d+8+Math.floor(Math.random()*10);}}
|
||
loanTick(d);
|
||
if(S.mode==='sandbox'&&S.cash<1e8)S.cash=1e9;
|
||
// offers
|
||
S.offers=S.offers.filter(o=>o.exp>d);
|
||
if(S.offers.length<5&&Math.random()<0.05+0.01*(S.lvl||1))spawnOffer();
|
||
// failures & events
|
||
if(d>=S.nextFail){fireFailure();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));}
|
||
if(d>=S.nextEvent){fireEvent();S.nextEvent=d+45+Math.floor(Math.random()*45);}
|
||
compute();
|
||
// payday floaters
|
||
if(d%30===0){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-(CITY[c].arpu||1));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');}
|
||
checkGoals();
|
||
scnTick(d);
|
||
confTick(d);
|
||
// money trouble
|
||
if(S.cash<0){S.neg++;if(S.neg===1)toast('<b>You are in the red.</b><br>Cancel something expensive, wait for revenue, or check the bank for a loan. At −$100k the bank takes your routers.','bad');}
|
||
else S.neg=0;
|
||
if(S.cash<-100000){S.lost=true;track('bankrupt');showLose();return;}
|
||
if(d%360===0&&[1,2,4].includes(d/360))track('game_year_'+(d/360+1),true);
|
||
if(d%10===0)save();
|
||
}
|
||
function spawnOffer(){
|
||
const mine=Object.keys(S.pops),lv=S.lvl||1;
|
||
const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>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');
|
||
if(S.links.some(l=>l.kind==='df'&&l.ready<=S.day))types.push('wwave','wwave');if(S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('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&&S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('pairs');
|
||
const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor');
|
||
const t=pick(types),T=BIZ_T[t];
|
||
if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;}
|
||
let city=(Math.random()<0.65&&mine.length)?pick(mine):pick(ALLC.concat(cnOk()?['pek','sha']:[])),city2=null;
|
||
if(T.l2){city=pick(mine);const pool=(Math.random()<(T.lv>=3?0.8:0.6)?mine:ALLC).filter(c=>c!==city);city2=pick(pool.length?pool:ALLC.filter(c=>c!==city));}
|
||
const 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));
|
||
S.usedNames.push(name);
|
||
if(t==='provedor')city=pick(br);
|
||
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));}
|
||
const rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate;
|
||
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));
|
||
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)));
|
||
S.offers.push({id:uid(),city,city2,name,type:t,bw,rate:r2,reqs,latMax:T.lat?+(kmBetween(city,city2)/200*1.35).toFixed(1):null,exp:S.day+40});
|
||
}
|
||
/* 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:'Common',col:'#16A866'},r:{n:'Rare',col:'#3A7BEA'},e:{n:'Epic',col:'#9D4EDD'},l:{n:'Legendary',col:'#FF8A3D'}};
|
||
const st=()=>S.stats||{};
|
||
const BADGES=[
|
||
{id:'hello',i:'👋',t:'Hello, Neighbour',d:'Bring up your first peering session.',r:'c',ok:()=>R.sessions>=1},
|
||
{id:'backhoe',i:'🚜',t:'Met the Backhoe',d:'Have a fiber cut.',r:'c',ok:()=>(st().by||{}).cut>=1},
|
||
{id:'debt',i:'🏦',t:'In Debt We Trust',d:'Take out a loan.',r:'c',ok:()=>(st().loans||0)>=1||(S.loans||[]).length>0},
|
||
{id:'twins',i:'👯',t:'Twins',d:'Run two routers in one POP.',r:'c',ok:()=>Object.values(S.pops).some(p=>(p.routers||1)>=2)},
|
||
{id:'shark',i:'🦈',t:'Shark Week',d:'Get a subsea cable bitten by a shark.',r:'r',ok:()=>(st().sharks||0)>=1},
|
||
{id:'ixc',i:'🔀',t:'IX Collector',d:'Have ports on 10 internet exchanges.',r:'r',ok:()=>Object.keys(S.ixp).length>=10},
|
||
{id:'haggle',i:'🤝',t:'Never Paid List Price',d:'Haggle a DE-KICKS quote down.',r:'r',ok:()=>!!st().haggleWin},
|
||
{id:'unsub',i:'📭',t:'Unsubscribed',d:'Opt out of 3 auto-enrolled add-ons.',r:'r',ok:()=>(st().optouts||0)>=3},
|
||
{id:'read',i:'💔',t:'Left on Read',d:'Get de-peered by a big network.',r:'r',ok:()=>(st().depeered||0)>=1},
|
||
{id:'couch',i:'🛋️',t:'Peering From the Couch',d:'Peer at an IX remotely.',r:'r',ok:()=>Object.keys(S.ixp).some(c=>isRemote(c)&&ixSessions(c).size>0)},
|
||
{id:'oink',i:'🐖',t:'Pig Whisperer',d:'Run a slow-booting PacketOinker chassis.',r:'r',ok:()=>Object.keys(S.pops).some(c=>(S.pops[c].rgen||0)>=2&&slowBoot(c))},
|
||
{id:'gap',i:'🌴',t:'Mind the Gap',d:'Link Panama City and Bogotá.',r:'r',ok:()=>S.links.some(l=>[l.a,l.b].includes('pan')&&[l.a,l.b].includes('bog'))},
|
||
{id:'andes',i:'🏔️',t:'Over the Mountains',d:'Build fiber across the Andes.',r:'r',ok:()=>S.links.some(l=>!l.sub&&andesPair(l.a,l.b))},
|
||
{id:'duo',i:'🏜️',t:'Duopoly Customer',d:'Buy a wave inside the UAE.',r:'r',ok:()=>S.links.some(l=>uaePair(l.a,l.b))},
|
||
{id:'shed',i:'🔌',t:'Stage Six',d:'Ride out load shedding on your own generator.',r:'r',ok:()=>(st().shed||0)>=1},
|
||
{id:'metro3',i:'🏢',t:'Two Buildings, Three Cities',d:'Have a second site in 3 metros.',r:'r',ok:()=>Object.values(S.pops).filter(p=>p.site2).length>=3},
|
||
{id:'penguin',i:'🐧',t:'Lonely Penguin',d:'Light a wave on the Humboldt cable to Sydney.',r:'e',ok:()=>S.links.some(l=>l.cable==='humb')},
|
||
{id:'horn',i:'⛵',t:'The Long Way Round',d:'Run a link round Cape Horn.',r:'e',ok:()=>S.links.some(l=>l.cable==='sam1'&&[l.a,l.b].includes('bue')&&[l.a,l.b].includes('scl'))},
|
||
{id:'six',i:'🌍',t:'Six Continents',d:'POPs in every region on the map.',r:'e',ok:()=>regionsCount()>=6},
|
||
{id:'giants',i:'🏭',t:'Friend of Giants',d:'Hold deals at 3 different AI campuses at once.',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:'Trench Landlord',d:'Lease hundreds of fiber pairs to a hyperscaler.',r:'e',ok:()=>S.biz.some(b=>b.type==='pairs')},
|
||
{id:'t1',i:'👑',t:'Tier 1',d:'Go transit-free.',r:'e',ok:()=>!!S.won},
|
||
{id:'bait',i:'🎣',t:'Shark Bait',d:'Get bitten by sharks 3 times in one game.',r:'l',ok:()=>(st().sharks||0)>=3},
|
||
{id:'nines',i:'💎',t:'Five Nines',d:'Serve 99.5% of demand every single day for a whole year.',r:'l',ok:()=>(st().clean||0)>=365},
|
||
{id:'fifty',i:'🗺️',t:'Everywhere at Once',d:'Have POPs in 50 cities.',r:'l',ok:()=>Object.keys(S.pops).length>=50},
|
||
{id:'unicorn',i:'🦄',t:'Unicorn',d:'Hold a billion dollars in cash.',r:'l',ok:()=>S.cash>=1e9},
|
||
{id:'clean',i:'🧼',t:'Debt-Free Tier 1',d:'Win without ever taking a loan.',r:'l',ok:()=>!!S.won&&!(st().loans||0)&&!(S.loans||[]).length},
|
||
{id:'speed',i:'⚡',t:'Speedrun',d:'Reach Tier 1 within three years.',r:'l',ok:()=>!!S.won&&S.day<=1095},
|
||
{id:'te',i:'🧭',t:'Traffic Whisperer',d:'Have Auto-TE move 100 Gbps onto alternate paths at once.',r:'r',ok:()=>(st().teMax||0)>=100},
|
||
{id:'street',i:'🚧',t:'Same Street',d:'Lose a metro ring to one backhoe.',r:'r',ok:()=>(st().by||{}).ring>=1},
|
||
{id:'anchor',i:'⚓',t:'Anchors Aweigh',d:'Have a cable cut by a dragged anchor.',r:'r',ok:()=>!!(st().f||{}).anchor},
|
||
{id:'retained',i:'🎁',t:'Customer Success Story',d:'Take a DE-KICKS retention offer.',r:'r',ok:()=>!!st().retained},
|
||
{id:'brrr',i:'🇧🇷',t:'Samba Peering',d:'Ports on all three IX.brrr exchanges.',r:'e',ok:()=>['sao','rio','for'].every(c=>S.ixp[c]!==undefined)},
|
||
{id:'bingo',i:'🎰',t:'DE-KICKS Bingo',d:'Ports at all six DE-KICKS exchanges. They thank you for your continued partnership.',r:'e',ok:()=>DK_CITIES.filter(c=>CITY[c]&&CITY[c].ix).every(c=>S.ixp[c]!==undefined)},
|
||
{id:'fire',i:'🌋',t:'Ring of Fire',d:'POPs all the way round the Pacific: Los Angeles, Tokyo, Taipei, Manila, Jakarta, Sydney, Auckland and Santiago.',r:'e',ok:()=>['lax','tok','tpe','mnl','jkt','syd','akl','scl'].every(c=>S.pops[c])},
|
||
{id:'curtain',i:'🎭',t:'Iron Curtain Call',d:'POPs in Warsaw, Prague, Vienna, Budapest, Bucharest, Sofia, Belgrade and Tallinn.',r:'e',ok:()=>['waw','prg','vie','bud','buh','sof','beg','tll'].every(c=>S.pops[c])},
|
||
{id:'islands',i:'🏝️',t:'Island Hopper',d:'POPs in Reykjavik, Dublin, London, Colombo, Taipei, Manila, Tokyo and Auckland.',r:'e',ok:()=>['rek','dub','lon','cbo','tpe','mnl','tok','akl'].every(c=>S.pops[c])},
|
||
{id:'wall',i:'🧱',t:'Through the Wall',d:'Run a licensed POP in mainland China.',r:'e',ok:()=>cnOk()&&Object.keys(S.pops).some(cnCity)},
|
||
{id:'croc',i:'🐊',t:'Darwin Award',d:'Have your fiber bitten by a crocodile.',r:'l',ok:()=>!!(st().f||{}).croc},
|
||
{id:'unbreak',i:'🛡️',t:'Unbreakable',d:'Survive 100 incidents without customer impact.',r:'l',ok:()=>(st().survived||0)>=100},
|
||
{id:'gigawatt',i:'⚛️',t:'Gigawatt Landlord',d:'Hold an AI WAN, a training run, an ingest and a fiber-pairs deal at the same time.',r:'l',ok:()=>['aiwan','mtrain','ingest','pairs'].every(t=>S.biz.some(b=>b.type===t))},
|
||
{id:'blitz',i:'🚀',t:'Blitz',d:'Reach Tier 1 within two years.',r:'l',ok:()=>!!S.won&&S.day<=730},
|
||
{id:'peta',i:'🌌',t:'Hundred Terabits',d:'Serve 100 Tbps.',r:'l',ok:()=>R.served>=100000},
|
||
{id:'llama',i:'🦙',t:'Llama Drama',d:'Lose fiber to a llama herd.',r:'l',secret:true,ok:()=>!!(st().f||{}).llama},
|
||
{id:'hallway',i:'🎤',t:'Hallway Track',d:'Attend a conference.',r:'r',ok:()=>(st().confs||0)>=1},
|
||
{id:'beer',i:'🍺',t:'Peering Over Beer',d:'Set up a PNI while the conference glow lasts.',r:'e',ok:()=>!!st().beerPni},
|
||
{id:'circuit',i:'✈️',t:'Conference Circuit',d:'Attend six conferences in one game.',r:'l',ok:()=>(st().confs||0)>=6},
|
||
{id:'scen1',i:'🎯',t:'Scenario Solver',d:'Complete any scenario.',r:'r',ok:()=>Object.keys(scnHof()).some(k=>k!=='weekly')},
|
||
{id:'weekly',i:'📅',t:'Weekly Regular',d:'Finish a weekly challenge.',r:'r',ok:()=>!!scnHof().weekly},
|
||
{id:'scen3',i:'🏅',t:'Scenario Specialist',d:'Complete three different scenarios.',r:'e',ok:()=>Object.keys(scnHof()).filter(k=>k!=='weekly').length>=3},
|
||
{id:'scenall',i:'🏆',t:'Scenario Grandmaster',d:'Complete every scenario.',r:'l',ok:()=>SCN.every(x=>scnHof()[x.id])},
|
||
{id:'elephant',i:'🐘',t:'I Survived the Elephant',d:'Live through the day half the internet went down.',r:'l',secret:true,ok:()=>!!S.phpDone&&!(S.ev.php>S.day)},
|
||
{id:'zero',i:'🕳️',t:'Zero Peers Given',d:'Reach Tier 2 with every single session over the route server.',r:'l',secret:true,ok:()=>isTier2()&&!Object.keys(S.peers).length&&!S.pni.length},
|
||
];
|
||
function hof(){try{return JSON.parse(localStorage.getItem('sot-badges')||'{}')||{};}catch(e){return {};}}
|
||
function checkBadges(){S.ach=S.ach||{};if(S.mode==='sandbox')return;let h=null;
|
||
for(const b of BADGES){if(S.ach[b.id]!==undefined)continue;let ok=false;try{ok=b.ok();}catch(e){}
|
||
if(!ok)continue;S.ach[b.id]=S.day;const R0=RARITY[b.r];
|
||
if(!h)h=hof();if(!h[b.id])h[b.id]={d:new Date().toISOString().slice(0,10),n:S.name};
|
||
toast(`<b>${b.i} Badge unlocked: ${esc(b.t)}</b><br><span style="color:${R0.col};font-weight:900">${R0.n}</span> · ${esc(b.d)}`,'goal');sfx('coin');track('badge_'+b.id);}
|
||
if(h)try{localStorage.setItem('sot-badges',JSON.stringify(h));}catch(e){}}
|
||
function badgeGrid(){const h=hof(),got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined).length;
|
||
return `<h3 style="font-size:15px;margin:14px 0 6px">Badges <span class="meta">${got}/${BADGES.length} this game · ${Object.keys(h).filter(k=>BADGES.some(b=>b.id===k)).length} ever</span></h3><div class="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;
|
||
return `<div class="bdg ${on?'on':ever?'ever':''}" style="--rc:${R0.col}" title="${esc(hide?'A secret badge':b.t+': '+b.d)}"><span class="bi">${hide?'❔':b.i}</span><span class="bt">${esc(hide?'???':b.t)}</span><span class="br">${R0.n}${ever&&!on?' · earned before':''}</span>${hide?'':`<span class="bd">${esc(b.d)}</span>`}</div>`;}).join('')}</div>`;}
|
||
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(`<b>Goal complete: ${esc(g.t)}</b>${g.r?`<br>Reward: +${fmt$(g.r)}`:''}`,'goal');sfx('coin');
|
||
track('goal_'+g.id);if(g.win&&!S.won){S.won=true;track('win_tier1');showWin();}}}
|
||
}
|
||
|
||
/* ================= ACTIONS ================= */
|
||
function spend(c){if(S.cash<c){toast('<b>Not enough cash.</b><br>Wait for revenue, or speed up time.','bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;}
|
||
const ACT={
|
||
speed:({v})=>{v=+v;if(![0,0.5,1,2,4,8].includes(v))return;UI.speed=v;renderHUD();},
|
||
help:()=>showHelp(),
|
||
dash:()=>{if(!S)return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();},
|
||
dashClose:()=>{$('dash').hidden=true;},
|
||
bank:()=>{if(!S)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=` TubeCoin moved ${f>=1?'up':'down'} ${Math.round(Math.abs(f-1)*100)}% on the way to your account.`;}
|
||
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.amount,apr:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,covs:o.covs,base:{sub:S.links.filter(x=>x.sub).length}});
|
||
track('loan_taken');toast(`<b>${fmt$(got)} from ${esc(B.name)} has landed.</b><br>${B.equity?`They now own ${pct(o.share)} of your revenue.`:`${fmt$(o.pay)}/mo for ${o.term} months.`}${note}`,'good');sfx('coin');after();renderBank();},
|
||
declineLoan:({id})=>{S.loanOffers=S.loanOffers.filter(x=>x.id!==id);sfx('click');renderBank();},
|
||
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?`<b>You bought out ${esc(B.name)}.</b><br>They flew off to find another startup.`:`<b>Loan from ${esc(B.name)} repaid early.</b>`,'good');after();renderBank();},
|
||
dashLink:({id})=>{$('dash').hidden=true;UI.confirm=null;UI.sel={type:'link',id};renderPanel();},
|
||
animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();const m=$('modalCard'),r=m&&m.querySelector('.setrow');if(r)r.outerHTML=settingsRow();},
|
||
soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();const m=$('modalCard'),r=m&&m.querySelector('.setrow');if(r)r.outerHTML=settingsRow();},
|
||
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();},
|
||
closeModal:()=>closeModal(),
|
||
tab:({t})=>{UI.tab=t;UI.confirm=null;renderPanel();},
|
||
leftTab:({t})=>{UI.left=t;UI.leftOpen=true;renderLeft();},
|
||
toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();},
|
||
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();},
|
||
selLink:({id})=>{UI.sel={type:'link',id};UI.confirm=null;renderPanel();},
|
||
buildPop:({city})=>{if(S.pops[city])return;if(cnCity(city)&&!cnOk()){toast('<b>You need a license first.</b><br>Foreign networks need a joint venture to build in mainland China.','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};floater(CITY[city].x,CITY[city].y-30,'New POP!','#FF4F9A');UI.tab='cust';after();},
|
||
launchBB:({city})=>{const p=S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:Math.max(8,C.P*0.03)};floater(C.x,C.y-30,'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,'Ad campaign!','#FF8A3D');after();},
|
||
buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast('<b>No transit in this scenario.</b><br>Peering, PNIs, caches and your own fiber only.','bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!NET[net].price||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(`<b>Your router can't take a ${PORT[tier].n} port.</b><br>Upgrade it in the Infra tab.`,'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.transit.push({id:uid(),city,net,tier,down:0});toast(`<b>${esc(NET[net].name)} transit is live in ${CITY[city].name}.</b><br>Full table received: ~1,000,000 routes.`,'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))return;if(!spend(PORT[t.tier].setup))return;}t.n=n;toast(+d>0?`<b>LAG member added.</b><br>${esc(NET[t.net].name)} in ${CITY[t.city].name} is now ${lagName(t.tier,n)}.`:`<b>LAG member removed.</b>`,'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>LAG_MAX)return;if(+d>0&&!spend(1500+PORT[p.tier].setup/2))return;p.n=n;sfx('build');after();},
|
||
lagIx:({city,d})=>{d=+d;if(d!==1&&d!==-1)return;if(!isCity(city)||S.ixp[city]===undefined||S.myIx[city]||!S.pops[city])return;S.ixn=S.ixn||{};const n=(S.ixn[city]||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0&&!spend(ixPortMo(city,S.ixp[city])))return;S.ixn[city]=n;sfx('build');after();},
|
||
cancelTransit:({id})=>{if(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[city]&&(!remoteCities().includes(city)||tier>1))||(S.ixp[city]!==undefined&&tier<=S.ixp[city]))return;if(S.pops[city]&&!portOk(city,tier)){toast(`<b>Your router can't take a ${PORT[tier].n} port.</b><br>Upgrade it in the Infra tab.`,'bad');sfx('err');return;}
|
||
if(isDk(city)&&S.ixp[city]===undefined&&!signed){const dk=dkState();if(dk.stall>S.day){toast(`<b>DE-KICKS sales is still "aligning".</b><br>They will get back to you in ${dk.stall-S.day} days.`,'bad');sfx('err');return;}dk.q={city,tier,m:dkQuoteMult(),h:0};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[city]?`<b>Port up at ${esc(ixName(city))}!</b><br>Now request peering, or join the route server.`:`<b>Remote port up at ${esc(ixName(city))}.</b><br>It came through a reseller, so expect a markup, a crowded port and some networks that won't talk to you. The route server is your friend here.`,'good');after();},
|
||
cancelIx:({city,sure})=>{if(UI.confirm!=='ix'+city){UI.confirm='ix'+city;renderPanel();return;}
|
||
if(isDk(city)&&!sure){const dk=dkState();if(!dk.retUsed[city]){openModal(`<div class="eyebrow">DE-KICKS Group · Customer Success</div><h2 style="font-size:26px">Wait! Before you go…</h2><p class="tagline">We value our partnership too much to let a little thing like price get in the way.</p><div class="kv"><span>Retention offer</span><b>40% off for 6 months</b></div><p class="note">After that, the normal price returns, plus a small loyalty administration fee.</p><div class="btns">${btn('Stay, take the discount','dkStay',{city},'pink')}${btn('Leave anyway','cancelIx',{city,sure:1},'ghost')}</div>`);return;}}
|
||
closeModal();if(S.dk){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(!isCity(city)||S.ixp[city]===undefined)return;S.rs[city]=!S.rs[city];if(S.rs[city])toast('<b>Route server session up.</b><br>You now peer with every open network on this IX, in one go.','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(`<b>Signed with DE-KICKS.</b><br>Welcome to the family. Please don't tell anyone what you pay.`,'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('<b>"Just this once."</b><br>Your account manager found a special discount. Do not tell the others.','good');}
|
||
else if(r<0.75){q.m=+(q.m*1.1).toFixed(2);dkQuoteModal();toast('<b>"After consulting with management…"</b><br>The price went up. Management was consulted.','bad');}
|
||
else{dk.stall=S.day+5+Math.floor(Math.random()*6);dk.q=null;closeModal();toast(`<b>Haggling paused.</b><br>${esc(pick(DK_STALL))}`,'bad');}},
|
||
dkWalk:()=>{const dk=dkState();dk.q=null;closeModal();toast('<b>DE-KICKS will "circle back".</b><br>Expect an email titled "Quick question 🙂" within the hour.','');},
|
||
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(`<b>Opted out of ${esc(n)}.</b><br>It took four clicks, a survey and a "we're sad to see you go" page.`,'good');after();},
|
||
dkStay:({city})=>{S.stats.retained=1;const dk=dkState();dk.ret[city]=S.day+180;dk.retUsed[city]=true;UI.confirm=null;closeModal();toast(`<b>40% off ${esc(ixName(city))} for 6 months.</b><br>Your account manager is relieved. Read the small print later.`,'good');after();},
|
||
buyTE:()=>{if(S.te)return;if(lvl()<3){toast('<b>Auto-TE unlocks at customer level 3.</b>','bad');sfx('err');return;}if(!spend(TE_COST))return;S.te={on:true,day:S.day};toast('<b>Auto-TE is live.</b><br>The controller now pushes overflow onto alternate paths whenever the shortest one is full.','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);},
|
||
traceCopy:()=>{try{navigator.clipboard.writeText(UI.trText||'');toast('<b>Copied.</b> Paste it into your favourite NOC chat.','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:`${S.name} (AS${S.asn}): ${tierLabel()}, ${fmtG(S.stats.peak||0)} peak. Build your own internet at`,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;if(!spend(CONF_COST))return;S.confReg[key]=true;toast('<b>Registered.</b><br>Flights booked, badge printed, business cards ordered in the wrong font.','good');after();},
|
||
tutSkip:()=>{S.tut=null;try{localStorage.setItem('sot-tut','1');}catch(e){}renderCoach();},
|
||
addSite:({city})=>{const p=S.pops[city];if(!p||p.site2)return;if(!spend(SITE2_COST))return;p.site2=true;p.site2Day=S.day;toast(`<b>Second site live in ${CITY[city].name}.</b><br>${esc(siteName(city,'b'))} is joined to ${esc(siteName(city,'a'))} by your own metro ring. Move some uplinks there from the Transit and Peering tabs.`,'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';if(S.ixSite)delete S.ixSite[city];after();},
|
||
siteSet:({k,id,s})=>{if(s!=='a'&&s!=='b')return;if(k==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.site=s;}else if(k==='p'){const x=S.pni.find(x=>x.id===id);if(x)x.site=s;}else if(k==='ix'&&S.ixp[id]!==undefined){S.ixSite=S.ixSite||{};S.ixSite[id]=s;}after();},
|
||
peer:({city,net})=>{if(!isCity(city)||!isNet(net)||S.ixp[city]===undefined||!ixMembers(city).includes(net))return;const r=peerOk(net,'ix',city);if(!r.ok){toast(`<b>${esc(NET[net].name)} declined.</b><br>${esc(r.why)}`,'bad');sfx('err');return;}S.peers[net+'@'+city]=true;
|
||
toast(`<b>${esc(NET[net].name)} accepted!</b><br>${NET[net].pol==='selective'?'They checked your PearingDB page and liked the traffic numbers.':'BGP session established.'}`,'good');sfx('build');after();},
|
||
unpeer:({city,net})=>{delete S.peers[net+'@'+city];after();},
|
||
pni:({city,net,tier})=>{tier=+tier;if(!S.pops[city]||!NET[net]||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(`<b>Your router can't take a ${PORT[tier].n} port.</b><br>Upgrade it in the Infra tab.`,'bad');sfx('err');return;}const r=peerOk(net,'pni',city);if(!r.ok){toast(`<b>${esc(NET[net].name)} declined the PNI.</b><br>${esc(r.why)}`,'bad');sfx('err');return;}if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
|
||
const ex=S.pni.find(p=>p.city===city&&p.net===net);if(ex&&tier<=ex.tier)return;if(!spend((1500+PORT[tier].setup/2)*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.pni.push({id:uid(),city,net,tier});
|
||
toast(`<b>PNI with ${esc(NET[net].name)} is up.</b><br>A cross-connect in ${esc(CITY[city].dc)}. Private and fast.`,'good');after();},
|
||
cancelPni:({id})=>{if(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]||S.caches.filter(x=>x.city===city&&x.net===net).length>=4)return;if((R.demTo[net]||0)<n.cache.min){toast(`<b>${esc(n.name)} says not yet.</b><br>Send them ${n.cache.min}+ Gbps first.`,'bad');sfx('err');return;}
|
||
S.caches.push({id:uid(),city,net});toast(`<b>${esc(n.cache.name)} installed in ${CITY[city].name}!</b><br>${esc(n.name)} shipped it for free. You pay ${fmt$(CACHE_MO)}/mo power.`,'good');sfx('build');after();},
|
||
rmCache:({id})=>{S.caches=S.caches.filter(c=>c.id!==id);after();},
|
||
accept:({id})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!bHas(o)){toast('<b>You need a POP in every city on the contract first.</b>','bad');return;}
|
||
if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||DF_SYS[l.sys].max-(l.ch||[]).length-soldSlots(l)<o.slots){toast('<b>Not enough free channels on that fiber any more.</b>','bad');return;}}
|
||
if(BIZ_T[o.type].event&&S.day>=o.start){toast('<b>Too late: the event has already started.</b>','bad');return;}
|
||
S.offers=S.offers.filter(x=>x!==o);S.biz.push({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});
|
||
floater(CITY[o.city].x,CITY[o.city].y-30,'Signed!','#16A866');sfx('coin');after();},
|
||
decline:({id})=>{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('<b>The event is already running.</b><br>The organisers will not let you walk out now.','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();},
|
||
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;if(!waveOk(l.a,l.b,tier)){toast(`<b>A ${LT[tier].n} wave needs ${esc(waveNeed(tier))} routers at both ends.</b>`,'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();},
|
||
rmLink:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);UI.sel=null;UI.confirm=null;after();},
|
||
fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))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(`<b>Power-cycled.</b><br>The router in ${esc(CITY[i.ref].name)} is booting again. It will be up tomorrow, the ${esc(RG[(p&&p.rgen)||0].chip)} willing.`,'good');after();return;}clearInc(i);toast(`<b>Fixed.</b> ${incTitle(i.type)} resolved early.`,'good');after();},
|
||
foundIx:({city})=>{if(!S.pops[city]||S.myIx[city]||CITY[city].ix||CITY[city].cn)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};S.ixp[city]=2;toast(`<b>You founded ${esc(nm)}!</b><br>Networks will join over time and pay you for ports. Open members peer with you for free.`,'goal');after();},
|
||
buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p)return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),same=sib.length>0&&UI.route==='same',border=cnCity(a)!==cnCity(b),mult=(sib.length&&!same?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
|
||
if((cnCity(a)||cnCity(b))&&!cnOk())return;
|
||
if(!waveOk(a,b,tier)){toast(`<b>A ${LT[tier].n} wave needs ${esc(waveNeed(tier))} routers at both ends.</b>`,'bad');sfx('err');return;}
|
||
const wr=waveRoute(a,b,mult,border);if(!wr){toast('<b>No cable available for that route right now.</b>','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(!spend(cost))return;if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};
|
||
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:(same?(sib[0].trench||sib[0].id):id),cut:0,day:S.day};S.links.push(l);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,`${LT[tier].n} lit!`,'#FF4F9A');after();},
|
||
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);if(ex&&tier<=ex.tier)return;if(ex&&nniUsed(city,prov)>NNI[tier].g){toast('<b>Too many circuits</b> for a smaller port.','bad');return;}if(!spend(NNI[tier].mo))return;if(ex)ex.tier=tier;else S.nni.push({id:uid(),city,prov,tier});toast(`<b>${esc(FAB[prov].name)} port is up in ${CITY[city].name}.</b><br>Now order virtual circuits to other cities on their fabric.`,'good');after();},
|
||
rmNni:({city,prov})=>{if(nniUsed(city,prov)>0){toast('<b>Cancel the circuits on this port first.</b>','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;const g=VXC[t].g,pa=nniPort(a,prov);if(!pa||nniUsed(a,prov)+g>NNI[pa.tier].g){toast('<b>Not enough room on your fabric port.</b> Upgrade it first.','bad');sfx('err');return;}
|
||
if(S.pops[b]){const pb=nniPort(b,prov);if(!pb||nniUsed(b,prov)+g>NNI[pb.tier].g){toast(`<b>Not enough room on your ${esc(FAB[prov].name)} port in ${CITY[b].name}.</b>`,'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});closeModal();
|
||
toast(`<b>Circuit up in 59 seconds.</b><br>${VXC[t].n} over ${esc(FAB[prov].name)}: ${CITY[a].name} → ${CITY[b].name}.${S.pops[b]?'':' Now grab an IX port there for remote peering.'}`,'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>NNI[pt.tier].g){toast(`<b>Fabric port in ${CITY[c].name} is full.</b>`,'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);const rem=remoteCities();for(const c in S.ixp){if(!S.pops[c]&&!rem.includes(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'&&!(isCity(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(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();},
|
||
goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':'peer';renderPanel();},
|
||
applyCn:()=>{if(S.cnLic.state!=='none')return;if(!spend(CN_LIC))return;S.cnLic={state:'pending',ready:S.day+45};toast('<b>Application filed.</b><br>Your local partner says about 45 days. Probably.','goal');after();},
|
||
togglePrem:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.premium=!t.premium;sfx('click');after();},
|
||
scrub:({city})=>{if(S.scrubAt){if(UI.confirm!=='scrub'){UI.confirm='scrub';renderAll();return;}S.scrubAt=null;UI.confirm=null;after();return;}if(!spend(SCRUB_COST))return;S.scrubAt=city;toast(`<b>Scrubbing center online in ${CITY[city].name}.</b><br>DDoS attacks are now absorbed, and you can sell DDoS protection to businesses.`,'good');after();},
|
||
cnPrem:({v})=>{UI.cnPrem=!!+v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
|
||
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;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);},
|
||
addRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)>=4)return;if(!spend(routerCost(p.rgen||0)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,'Router added','#FF4F9A');after();},
|
||
rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;p.routers--;after();},
|
||
upRouter:({city})=>{const p=S.pops[city];if(!p)return;const g=(p.rgen||0)+1;if(!RG[g])return;if(RG[g].lvl>lvl()){toast(`<b>${esc(RG[g].n)} unlocks at customer level ${RG[g].lvl}.</b>`,'bad');sfx('err');return;}
|
||
const rt=p.routers||1;if(!spend(RG[g].cost*rt))return;p.rgen=g;
|
||
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?`Swapping the only router in ${CITY[city].name} for a ${RG[g].n}. The new one ${pick(SLOW_BOOT)}. Back in ${dd} days.`:`Swapping the only router in ${CITY[city].name} for a ${RG[g].n}. Maintenance window: back tomorrow.`,cost:0});toast(`<b>Maintenance window in ${CITY[city].name}</b><br>${sl?`One router, and this one takes forever to boot. Back in ${dd} days.`:'One router means downtime during the swap. Back tomorrow.'}`,'bad');}
|
||
else toast(`<b>Rolling upgrade in ${CITY[city].name}</b><br>${rt} × ${esc(RG[g].n)}, swapped one at a time. Zero downtime.`,'good');
|
||
floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');after();},
|
||
dfMode:({m})=>{UI.lmode=m;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);},
|
||
orderDf:()=>{const p=UI.pending;if(!p)return;const {a,b}=p,km=kmBetween(a,b);if(isSub(a,b)||!dfAllowed(a,b))return;
|
||
const own=UI.dfSrc==='build'&&lvl()>=3,sys=DF_SYS[UI.dfSys]&&DF_SYS[UI.dfSys].lvl<=lvl()?UI.dfSys:'lite';if(lvl()<2)return;
|
||
const up=(own?dfBuildCost(km):0)+DF_SYS[sys].cost+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};
|
||
const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),id=uid();
|
||
const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:false,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):30),spares:false};
|
||
S.links.push(l);closeModal();UI.sel={type:'link',id};
|
||
toast(own?`<b>Groundbreaking!</b><br>Your own fiber from ${CITY[a].name} to ${CITY[b].name}. Permits and digging take about ${dfBuildDays(km)} days.`:`<b>Dark fiber IRU signed.</b><br>${CITY[a].name}–${CITY[b].name} will be spliced and handed over in about 30 days.`,'goal');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(`<b>Can't add ${O.n}.</b><br>${esc(why)}`,'bad');sfx('err');return;}if(!spend(optCost(o)))return;(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)return;const i=(l.ch||[]).lastIndexOf(o);if(i>=0)l.ch.splice(i,1);after();},
|
||
upSys:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.sys==='roadm'||lvl()<3)return;if(!spend(DF_SYS.roadm.cost))return;l.sys='roadm';if(l.ready<=S.day){l.eqDown=S.day+1;toast('<b>Line system swap</b><br>All channels are dark for a day while the ROADMs go in.','bad');}after();},
|
||
spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();},
|
||
crews:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.ready<=S.day)return;const c=Math.round(15000+l.km*6);if(!spend(c))return;l.ready=Math.max(S.day+1,l.ready-30);toast('<b>More crews on site.</b><br>Construction is 30 days ahead.','good');after();},
|
||
addGen:({city})=>{const p=S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,'Generator!','#FF8A3D');after();},
|
||
start:()=>{const nm=(($('nmIn')&&$('nmIn').value)||'Packet Pals').slice(0,24);beginGame(nm,UI.startCity,{mode:UI.mode==='sandbox'?'sandbox':'normal'});},
|
||
modeSet:({m})=>{UI.mode=m;document.querySelectorAll('.modeb').forEach(b=>b.classList.toggle('pink',b.dataset.m===m));document.querySelectorAll('.modeb').forEach(b=>b.classList.toggle('ghost',b.dataset.m!==m));},
|
||
scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||'Packet Pals').slice(0,24);scenarioModal();},
|
||
startScn:({id,sure})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`<h2 style="font-size:26px">Start ${esc(sc.n)}?</h2><p class="tagline">${esc(S.name)} will be replaced. Export it from the menu first if you want to keep it.</p><div class="btns">${btn('Start the scenario','startScn',{id,sure:1},'pink big')}${btn('Keep playing','closeModal',{},'ghost big')}</div>`);return;}beginGame(UI.nm||(S&&S.name)||'Packet Pals',sc.city,{scn:sc});},
|
||
startWeekly:({sure}={})=>{if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`<h2 style="font-size:26px">Start the weekly challenge?</h2><p class="tagline">${esc(S.name)} will be replaced. Export it from the menu first if you want to keep it.</p><div class="btns">${btn('Start the challenge','startWeekly',{sure:1},'pink big')}${btn('Keep playing','closeModal',{},'ghost big')}</div>`);return;}const wk=weekly();beginGame(UI.nm||(S&&S.name)||'Packet Pals',wk.city,{scn:wk,seed:wk.seed});},
|
||
pickStart:({city})=>{UI.startCity=city;document.querySelectorAll('.start').forEach(b=>b.classList.toggle('on',b.dataset.city===city));},
|
||
cont:()=>{migrate(S);track('game_continue',true);UI.started=true;closeModal();renderAll();},
|
||
newgame:()=>{try{localStorage.removeItem('sot-save-v1');}catch(e){}S=null;UI.started=false;UI.sel=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();},
|
||
keepPlaying:()=>{closeModal();},
|
||
exportSave:()=>exportSave(),
|
||
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';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;try{S=migrate(JSON.parse(JSON.stringify(s0)));compute();checkGoals();renderAll();}catch(e){S=prev;if(S)compute();renderAll();toast('<b>Import failed.</b><br>That save is damaged and could not be loaded. Your current game is untouched.','bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=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;compute();renderAll();save();toast(`<b>Welcome back, ${esc(S.name)}.</b><br>Imported and saved on this device.`,'good');sfx('coin');track('game_import');},
|
||
menu:()=>{if(!S||!UI.started){showTitle();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)}</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>
|
||
<p class="tagline">Your game saves itself every few seconds on this device.</p>
|
||
<div class="menu-list">
|
||
${btn('Back to the map','closeModal',{},'pink big')}
|
||
${btn('Export save <small>download a file</small>','exportSave',{},'')}
|
||
${btn('Import a save <small>from a file</small>','importPick',{},'')}
|
||
${btn('Share your network <small>image card</small>','share',{},'')}
|
||
${btn('Scenarios & weekly challenge','scenarios',{},'ghost')}
|
||
${btn('How to play','help',{},'ghost')}
|
||
${RELEASE_NOTES.length?btn(`What’s new in ${esc(APP_VERSION)}`,'whatsNewShow',{},'ghost'):''}
|
||
${btn('Start a new network','resetAsk',{},'red')}
|
||
</div>${settingsRow()}`);},
|
||
resetAsk:()=>openModal(`<h2 style="font-size:26px">Start a new network?</h2><p class="tagline">${esc(S?S.name:'Your network')} and everything it owns will be deleted. This cannot be undone.</p><div class="btns">${btn('Delete and start over','newgame',{},'red big')}${btn('Keep playing','closeModal',{},'ghost big')}</div>`),
|
||
whatsNewShow:()=>whatsNew(true,true),
|
||
updateNow:()=>{save();location.reload();},
|
||
updateLater:()=>{$('update').hidden=true;UI.updLater=Date.now();},
|
||
helpClose:()=>{if(UI.started)closeModal();else showTitle();},
|
||
};
|
||
function pairLinks(a,b){return S.links.filter(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));}
|
||
function dfAllowed(a,b){return !isSub(a,b)&&cnCity(a)===cnCity(b)&&!uaePair(a,b);}
|
||
function optCost(o){return Math.round(OPT[o].cost*(S&&S.ev&&S.ev.tariff>S.day?1.4:1));}
|
||
function chWhy(l,o){const O=OPT[o];if(O.lvl>lvl())return `Unlocks at customer level ${O.lvl}.`;if(O.sys==='roadm'&&l.sys!=='roadm')return 'Needs a ROADMaster 9000 line system.';if(l.km>O.reach)return `Reach is ${O.reach.toLocaleString()} km; this route is ${l.km.toLocaleString()} km.`;
|
||
if((l.ch||[]).length+soldSlots(l)>=DF_SYS[l.sys].max)return `${DF_SYS[l.sys].n} is full (${DF_SYS[l.sys].max} channels${soldSlots(l)?`, ${soldSlots(l)} sold to customers`:''}).`;
|
||
for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&(p.rgen||0)<O.rg)return `Needs ${RG[O.rg].n} routers at both ends (${CITY[c].name}).`;}return '';}
|
||
function bbCost(c){return 15000+CITY[c].P*20;}
|
||
function after(){if(S)purgeInc();compute();checkGoals();renderAll();save();}
|
||
function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;if(!S.pops[c])UI.tab='cust';renderPanel();}
|
||
|
||
/* ================= SAVE ================= */
|
||
function save(){if(!S||S.lost)return;S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};try{localStorage.setItem('sot-save-v1',JSON.stringify(S));}catch(e){}UI.lastSave=performance.now();}
|
||
// Save whenever the player might be leaving: tab hidden, page closing or reloading.
|
||
addEventListener('pagehide',()=>save());
|
||
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden')save();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(){const d=new Date().toISOString().slice(0,10),n=(S&&S.name||'network').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'network';return `series-of-tubes-${n}-${d}.json`;}
|
||
function exportSave(){if(!S)return;save();const blob=new Blob([JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S},null,1)],{type:'application/json'});
|
||
const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=saveFileName();document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);
|
||
toast(`<b>Save exported.</b><br>${esc(saveFileName())} is in your downloads. Open it on another device with “Import a save”.`,'good');}
|
||
function parseSave(txt){if(typeof txt!=='string')return {err:'That file is not valid JSON.'};let j;try{j=JSON.parse(txt);}catch(e){return {err:'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:'That does not look like a Series of Tubes save.'};
|
||
if(s.lost)return {err:'That network went bankrupt. It cannot be brought back, only mourned.'};
|
||
for(const c of Object.keys(s.pops))if(!isCity(c))return {err:`That save has a POP in a city this version does not know (${esc(String(c).slice(0,12))}).`};
|
||
return {s,ver:j.version||'?',name:String(s.name||'Unnamed network')};}
|
||
function importFile(file){if(!file)return;if(file.size>8e6){toast('<b>That file is too big to be a save.</b>','bad');return;}
|
||
const rd=new FileReader();rd.onload=()=>{const r=parseSave(String(rd.result));if(r.err){toast(`<b>Import failed.</b><br>${esc(r.err)}`,'bad');sfx('err');return;}
|
||
UI.importing=r.s;openModal(`<div class="eyebrow">Import a save</div><h2 style="font-size:26px">Load ${esc(r.name)}?</h2><p class="tagline">${esc(dateStr(r.s.day))} · ${fmt$(r.s.cash)} in the bank · ${Object.keys(r.s.pops).length} POP${Object.keys(r.s.pops).length===1?'':'s'} · saved by v${esc(r.ver)}</p>${S&&UI.started&&!S.lost?`<p class="note" style="color:var(--bad)">This replaces ${esc(S.name)}. Export it first if you want to keep it.</p>`:''}<div class="btns">${btn('Load this network','importGo',{},'pink big')}${btn('Cancel',UI.started?'closeModal':'helpClose',{},'ghost big')}</div>`);};
|
||
rd.readAsText(file);}
|
||
function loadSave(){try{const t=localStorage.getItem('sot-save-v1');if(t){const s=JSON.parse(t);if(s&&s.v===1&&!s.lost)return s;}}catch(e){}return null;}
|
||
|
||
/* ================= 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==='click'){tone(660,0,.04,'triangle',.05);}
|
||
}catch(e){}}
|
||
|
||
/* ================= DOM RENDER ================= */
|
||
const $=id=>document.getElementById(id);
|
||
const btn=(label,act,args={},cls='',dis=false,title='')=>`<button class="b ${cls}" data-act="${act}" data-args="${esc(JSON.stringify(args))}"${dis?' disabled':''}${title?` title="${esc(title)}"`:''}>${label}</button>`;
|
||
const logo=n=>`<span class="logo" style="--c:${n.col}">${initials(n)}</span>`;
|
||
const barCls=u=>u>=0.9?'bad':u>=0.65?'warn':'';
|
||
function renderAll(){renderHUD();renderLeft();renderPanel();renderHint();renderMega();renderCoach();}
|
||
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;}
|
||
function renderHUD(){
|
||
for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b)b.classList.toggle('on',UI.speed===v);}
|
||
$('muteBtn').style.opacity=UI.muted?.4:1;
|
||
if(!S)return;
|
||
$('hName').textContent=S.name;$('hAsn').textContent='AS'+S.asn+(S.mode==='sandbox'?' · Sandbox':S.scn?' · '+(S.scn.id==='weekly'?'Weekly '+S.scn.key:S.scn.name)+(S.scn.done||S.scn.failed?'':` · ${Math.max(0,S.scn.days-S.day)}d left`):'');
|
||
$('hCash').textContent=fmt$(S.cash);$('hCash').style.color=S.cash<0?'var(--bad)':'';
|
||
const net=R.revMo-R.costMo;$('hRate').innerHTML=`<span class="${net>=0?'up':'down'}">${net>=0?'▲':'▼'} ${fmt$(Math.abs(net))}/mo</span>`;
|
||
$('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=pct(R.reach);$('hReach').style.color=R.reach<0.99?'var(--bad)':'var(--eye)';
|
||
$('hTier').textContent=tierLabel();
|
||
$('hDate').textContent=dateStr(S.day);
|
||
{const bo=(S.loanOffers||[]).length,hb=$('hBank');hb.hidden=!bo;hb.textContent=bo;}
|
||
const n=S.inc.length;$('hNoc').classList.toggle('hot',n>0);$('hNocVal').textContent=n?`${n} incident${n>1?'s':''}`:'All quiet';
|
||
}
|
||
function renderLeft(){
|
||
const L=$('left');L.classList.toggle('closed',!UI.leftOpen);
|
||
if(!S){L.hidden=true;return;}L.hidden=false;
|
||
const ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length;
|
||
const tabs=[['goals',`Goals<span class="cnt">${ndone}/${GOALS.length}</span>`],['deals',`Deals${S.offers.length?`<span class="cnt">${S.offers.length}</span>`:''}`],['noc',`NOC${S.inc.length?`<span class="cnt red">${S.inc.length}</span>`:''}`],['nets','Networks']];
|
||
$('leftTabs').innerHTML=tabs.map(([k,l])=>`<button class="${UI.left===k?'on':''}" data-act="leftTab" data-args='{"t":"${k}"}'>${l}</button>`).join('')+(innerWidth<760?`<button data-act="toggleLeft" style="margin-left:auto" aria-label="Close">×</button>`:'');
|
||
let h='';
|
||
if(UI.left==='goals'){
|
||
const cur=GOALS.find(g=>S.done[g.id]===undefined);
|
||
h+=GOALS.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `<div class="goal ${d?'done':''} ${c?'cur':''}"><div class="ck">${d?'✓':''}</div><div><div class="gt">${esc(g.t)}</div>${c||!d?`<div class="gd">${esc(g.d)}</div>`:''}${!d&&g.r?`<div class="gr">Reward ${fmt$(g.r)}</div>`:''}</div></div>`;}).join('');
|
||
h+=badgeGrid();
|
||
}else if(UI.left==='deals'){
|
||
h+=confSection();
|
||
{const lv=S.lvl||1,nx=LEVELS[lv];h+=`<div class="inc" style="background:#FFF6CF"><div class="nm">Customer level ${lv}: ${LEVELS[lv-1].n}</div><div class="meta">${nx?`Next: ${nx.req} unlocks ${nx.unlock.toLowerCase()}`:'Every customer type is unlocked. Go get those terabits.'}</div></div>`;}
|
||
if(!S.offers.length)h+=`<p class="empty">No open offers right now. Businesses look for networks with POPs in their city. New ones pop up every few weeks.</p>`;
|
||
for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o);
|
||
h+=`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · <b>${bTerms(o)}</b> · ${o.exp-S.day}d left${(o.reqs||[]).length?` · ${o.reqs.length} special requirement${o.reqs.length>1?'s':''}`:''}</div>${reqList(o)}
|
||
<div class="btns">${has?btn('Accept','accept',{id:o.id},'green sm'):btn('Go there','focusCity',{city:o.city},'ghost sm')}${btn('Decline','decline',{id:o.id},'ghost sm')}</div>${has?'':`<div class="why">Needs a POP in ${bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')}</div>`}</div></div>`;}
|
||
}else if(UI.left==='noc'){
|
||
h+=`<div class="btns" style="margin-bottom:8px">${btn('Open NOC dashboard','dash',{},'pink')}${btn('Traceroute','trace',{},'')}</div>`;
|
||
h+=`<p class="lead">Your Network Operations Center. Every notification also lands here. Things fail all the time on the internet. Redundant links and multiple upstreams let traffic reroute by itself.</p>`;
|
||
h+=`<div class="kv"><span>DDoS scrubbing</span><b>${S.scrubAt?'On · '+CITY[S.scrubAt].name:'None (build one from a POP\'s Infra tab)'}</b></div>`;
|
||
h+=S.te?`<div class="kv"><span>Auto-TE</span><b>${S.te.on?`On · moving ${fmtG(R.teMoved||0)} onto alternate paths`:'Off'}</b></div><div class="btns">${btn(S.te.on?'Turn Auto-TE off':'Turn Auto-TE on','teToggle',{},'ghost sm')}</div>`
|
||
:`<div class="kv"><span>Auto-TE</span><b>${lvl()<3?'Unlocks at customer level 3':'Not installed'}</b></div><p class="meta" style="margin:2px 0 6px">Traffic takes the shortest path, even when it is full. A traffic-engineering controller spills the overflow onto the next-best paths with room.</p><div class="btns">${btn(`Install Auto-TE <small>${fmt$(TE_COST)} + ${fmt$(TE_MO)}/mo</small>`,'buyTE',{},'pink sm',lvl()<3||S.cash<TE_COST)}</div>`;
|
||
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+=`<h3 style="font-size:15px;margin:4px 0">Congested links</h3>${S.te&&S.te.on?'':'<p class="meta" style="margin:0 0 4px">Raise a full link’s metric so traffic prefers another path, upgrade it, or install Auto-TE.</p>'}`+hot.map(l=>`<div class="row"><div class="grow"><div class="nm">${CITY[l.a].name} ⇄ ${CITY[l.b].name}</div><div class="meta">${capName(l)} · ${pct((R.load[l.id]||0)/capOf(l))} full</div></div>${btn('Inspect','selLink',{id:l.id},'pink sm')}</div>`).join('');}
|
||
const hotR=hotPorts();
|
||
if(hotR.length)h+=`<h3 style="font-size:15px;margin:4px 0">Ports, caches and routers running hot</h3>`+hotR.map(x=>`<div class="row"><span class="hotk hk-${x.k}">${HOTL[x.k]}</span><div class="grow"><div class="nm">${CITY[x.city].name} · ${esc(x.lab)}</div><div class="meta">${pct(Math.min(1,x.u))} full${x.u>=0.995?' · dropping or overflowing':''} · ${esc(x.tip)}</div></div>${btn('Inspect','focusCity',{city:x.city},'pink sm')}</div>`).join('');
|
||
if(!S.inc.length&&!hot.length&&!hotR.length)h+=`<p class="empty">All systems green. Enjoy it while it lasts.</p>`;
|
||
for(const i of S.inc){h+=`<div class="inc"><div class="nm">${incTitle(i.type)}</div><div class="meta">${esc(i.msg)}</div><div class="meta">Auto-fix in ${i.until-S.day} day${i.until-S.day===1?'':'s'}${i.impact?` · ${fmtG(i.impact)} lost`:''}</div>${i.cost?`<div class="btns">${btn(`${esc(i.fix||'Rush repair')} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash<i.cost)}</div>`:''}</div>`;}
|
||
if(S.log&&S.log.length){h+=`<h3 style="font-size:15px;margin:12px 0 4px">Recent events</h3>`+S.log.slice(0,15).map(e=>`<div class="row"><div class="grow"><div class="meta"><b class="tag ${e.k==='bad'?'restrictive':e.k==='good'?'open':'st'}">${dateStr(e.d)}</b> ${esc(e.t)}</div></div></div>`).join('');}
|
||
h+=`<div class="kv" style="margin-top:8px"><span>Incidents so far</span><b>${S.stats.incidents}</b></div><div class="kv"><span>Survived with no impact</span><b>${S.stats.survived}</b></div>`;
|
||
}else{
|
||
h+=`<p class="lead">Every network on the map. Traffic share is how much of your users' traffic goes to them.</p>`;
|
||
for(const n of NETS){const st=[];if(S.transit.some(t=>t.net===n.id))st.push('Transit');if(Object.keys(S.ixp).some(c=>ixSessions(c).has(n.id)))st.push('Peered');if(S.pni.some(p=>p.net===n.id))st.push('PNI');if(S.caches.some(c=>c.net===n.id))st.push('Cache');
|
||
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="meta">AS${n.asn}</span></div><div class="meta"><span class="tag ${n.type}">${TYPE_L[n.type]}</span> <span class="tag ${n.pol}">${n.pol}</span> · ${(NSH[n.id]*100).toFixed(1)}% of traffic${n.price?` · transit $${(n.price*S.priceMul).toFixed(2)}/Gbps`:''}</div><div class="meta">${esc(n.blurb)}</div>${st.length?`<div class="btns">${st.map(s=>`<span class="tag st on">${s}</span>`).join('')}</div>`:''}</div></div>`;}
|
||
}
|
||
if(h!==UI._lh){UI._lh=h;$('leftBody').innerHTML=h;}
|
||
}
|
||
function renderPanel(){
|
||
const P=$('panel');
|
||
if(!S||!UI.sel){P.hidden=true;return;}
|
||
P.hidden=false;
|
||
const scrollEl=$('panelBody').querySelector('.scroll');const st=scrollEl?scrollEl.scrollTop:0;
|
||
const html=UI.sel.type==='city'?cityPanel(UI.sel.id):linkPanel(UI.sel.id);if(html===UI._ph&&!P.hidden&&$('panelBody').firstChild)return;UI._ph=html;$('panelBody').innerHTML=html;
|
||
const ns=$('panelBody').querySelector('.scroll');if(ns)ns.scrollTop=st;
|
||
}
|
||
function cityPanel(c){
|
||
const C=CITY[c],p=S.pops[c],ix=ixName(c),down=p&&p.down>S.day;
|
||
let h=`<div class="ph"><div style="min-width:0"><div class="eyebrow">${REG[C.reg]} · ${esc(C.dc)}</div><h2>${C.name}</h2>
|
||
<div class="facts"><span class="fact">${fmtG(C.P)} of eyeballs</span>${regionMult(c)>1?`<span class="fact">Transit ${regionMult(c)}× pricier</span>`:''}${C.reg==='AS'&&!C.cn?'<span class="fact ixf">Underserved: users grow 60% faster</span>':''}${ix?`<span class="fact ixf">IX: <b>${esc(ix)}</b></span>`:''}${p?`<span class="fact mine">Your POP</span><button class="fact trb" data-act="trace" data-args='{"city":"${c}"}'>🔍 Traceroute</button>`:''}${down?`<span class="fact down">DOWN</span>`:''}</div></div>
|
||
<button class="x" data-act="closePanel" aria-label="Close">×</button></div>`;
|
||
if(!p){
|
||
h+=`<div class="scroll">${C.note?`<p class="note" style="margin-top:0">${esc(C.note)}</p>`:''}
|
||
${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`<section><h3>Open a POP here</h3><p class="lead">A POP (point of presence) is your router in a rack here. Then connect it: lay fiber from one of your POPs, or buy transit right here.</p>
|
||
${C.ru?`<p class="why">Includes the mandatory government box in your rack: ${fmt$(RU_BOX)} + ${fmt$(RU_BOX_MO)}/mo. It comes with its own listener.</p>`:''}${btn(`Build POP <small>${fmt$(popCost(c))} + ${fmt$(POP_MO)}/mo</small>`,'buildPop',{city:c},'pink big',S.cash<popCost(c))}
|
||
<p class="note">Or drag from one of your routers to this city to lay fiber and build the POP in one go.</p></section>`}`;
|
||
h+=offersHere(c);
|
||
const tr=NETS.filter(n=>n.price&&n.pops.includes(c));
|
||
const fh=FABS.filter(f=>f.cities.includes(c));
|
||
if(ix&&fh.length){if(remoteCities().includes(c))h+=ixSection(c).replace('<h3>Internet Exchange</h3>','<h3>Remote peering at the IX</h3>');
|
||
else h+=`<section><h3>Remote peering</h3><p class="lead">Peer at ${esc(ix)} without building a POP. Order a virtual circuit here from one of your POPs over ${fh.map(f=>esc(f.name)).join(' or ')}.</p>${REMOTE_WARN}${btn('Order circuit anyway','openVxc',{to:c},'ghost sm')}</section>`;}
|
||
h+=`<section><h3>Who's here</h3><div class="meta" style="font-size:12.5px;line-height:1.6">${MEGA.filter(m=>m.c===c).length?`AI and cloud campuses nearby: ${MEGA.filter(m=>m.c===c).map(m=>`<b>${esc(m.n)}</b>`).join(', ')}<br>`:''}Transit sellers: ${tr.map(n=>`<b>${esc(n.name)}</b>`).join(', ')||'none'}<br>Fabrics: ${fh.map(f=>`<b>${esc(f.name)}</b>`).join(', ')||'none'}<br>${ix?`IX members on ${esc(ix)}: ${ixMembers(c).length}`:'No IX here yet. You could found one later.'}</div></section></div>`;
|
||
return h;
|
||
}
|
||
const tabs=[['cust','Customers'],['up','Transit'],['peer','Peering'],['links','Infra']];
|
||
h+=`<nav class="tabs">${tabs.map(([k,l])=>`<button class="${UI.tab===k?'on':''}" data-act="tab" data-args='{"t":"${k}"}'>${l}</button>`).join('')}</nav><div class="scroll">`;
|
||
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+=`<section><h3 style="color:var(--bad)">This POP is down</h3><p class="lead">${i?esc(i.msg):''} Customers here get nothing until it's back.</p>${i&&i.cost?btn(`${i.fix} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red'):''}</section>`;}
|
||
if(UI.tab==='cust'){
|
||
{const nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||1;if(nl>=nc*0.95)h+=`<section><h3 style="color:var(--bad)">Router maxed out</h3><p class="lead">Your routers here are forwarding ${fmtG(nl)} of ${fmtG(nc)}. Traffic is being dropped. Upgrade or add a router in the Infra tab.</p>${btn('Open Infra','tab',{t:'links'},'pink sm')}</section>`;}
|
||
h+=`<section><h3>Home broadband</h3>`;
|
||
if(!p.bb){const s=Math.max(8,C.P*0.03);h+=`<p class="lead">Sell internet to homes here. Starts around ${fmtG(s)} and grows toward ${fmtG(C.P)} while service is good. Pays ${fmt$(EYE_RATE)} per Gbps served, every month.</p>${btn(`Launch broadband <small>${fmt$(bbCost(c))}</small>`,'launchBB',{city:c},'pink big',S.cash<bbCost(c))}`;}
|
||
else{const eye=R.cityEye[c]||0;
|
||
h+=`<div class="kv"><span>Eyeball demand</span><b>${fmtG(eye)} of ${fmtG(C.P)}</b></div><div class="bar me"><i style="width:${eye/C.P*100}%"></i></div>
|
||
<div class="kv"><span>Served in ${C.name}</span><b style="color:${sf<0.9?'var(--bad)':'var(--eye)'}">${pct(sf)}</b></div><div class="bar ${sf<0.9?'bad':''}"><i style="width:${sf*100}%"></i></div>
|
||
<div class="kv"><span>Revenue</span><b>${fmt$(eye*sf*EYE_RATE)}/mo</b></div>
|
||
<div class="kv"><span>Network-wide peering ratio</span><b>${pct(R.peerShare||0)}</b></div><p class="note">More traffic over peering, PNIs and caches means lower latency, and happier users grow faster.</p>
|
||
${sf<0.9?`<p class="why">Customers are unhappy and leaving. Add upstream capacity, peering, or a bigger link.</p>`:''}
|
||
<div class="btns">${p.boost>S.day?`<span class="tag st on">Ad campaign: ${p.boost-S.day}d left</span>`:btn('Run ad campaign <small>$8k · 2× growth 30d</small>','ad',{city:c},'',S.cash<8000)}</div>`;}
|
||
h+=`</section><section><h3>Business customers</h3>`;
|
||
const bz=S.biz.filter(b=>bCities(b).includes(c));
|
||
if(!bz.length)h+=`<p class="empty">No businesses yet. Offers pop up as $ bubbles on the map.</p>`;
|
||
for(const b of bz)h+=`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · carrying ${fmtG(R.l2[b.id]||0)}${b.sites?' per site':''}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · <b style="color:var(--bad)">fiber is down</b>':''}${BIZ_T[b.type].event&&eventLive(b)?` · <b>serving ${pct(sfOf(R,b.city))}</b>`:''}${b.type==='scrub'&&!S.scrubAt?' · <b style="color:var(--bad)">needs a scrubbing center</b>':''}${S.day-(b.since||0)<15?` · <b>provisioning, ${15-(S.day-(b.since||0))}d grace</b>`:''}</div>${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}<div class="bar ${b.mood<30?'bad':b.mood<65?'warn':''}"><i style="width:${b.mood}%"></i></div><div class="meta">Happiness ${Math.round(b.mood)}%</div></div>${btn(UI.confirm===b.id?'Really drop?':'Drop','dropBiz',{id:b.id},'ghost sm')}</div>`;
|
||
h+=`</section>`+offersHere(c);
|
||
}else if(UI.tab==='up'){
|
||
h+=portNote(c);
|
||
h+=`<section><h3>IP transit</h3><p class="lead">Pay a bigger network per Gbps and it carries your traffic to the whole internet. Billed on the 95th percentile of the last 30 days, with a 20% commit and a port fee. Spikes like DDoS raise your bill.</p>`;
|
||
const prov=NETS.filter(n=>n.price&&n.pops.includes(c)).sort((a,b)=>a.price-b.price);
|
||
if(!prov.length)h+=`<p class="empty">Nobody sells transit here. Haul your traffic over fiber to a city that has it.</p>`;
|
||
for(const n of prov){const t=S.transit.find(x=>x.city===c&&x.net===n.id);const pr=n.price*S.priceMul*(t&&t.premium&&c==='hkg'?n.premium:1)*regionMult(c);
|
||
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="tag ${n.type}">${TYPE_L[n.type]}</span></div><div class="meta">$${pr.toFixed(2)} per Gbps / month · billed on 95th percentile</div>`;
|
||
if(t){const u=R.useT[t.id]||0,cap=lagCap(PORT[t.tier].g,t.n),tdown=t.down>S.day;
|
||
h+=`<div class="kv"><span>${lagName(t.tier,t.n)}${tdown?' · <b style="color:var(--bad)">OUTAGE</b>':''}</span><b>${fmtG(u)}</b></div><div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('t',t.id,t.pref)}${siteCtl('t',t.id,c,t.site)}${n.premium&&c==='hkg'?`<div class="btns">${btn(t.premium?'CN-Too premium on ✓':`Switch to CN-Too premium <small>${n.premium}× price · ~3% loss into China</small>`,'togglePrem',{id:t.id},t.premium?'green sm':'sm')}</div>`:''}<div class="meta">95th pct ${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))}/mo</div>
|
||
<div class="btns">${PORT.map((P2,i)=>i>t.tier?btn(`Upgrade ${(t.n||1)>1?'all to ':''}${P2.n} <small>${fmt$(P2.setup*(t.n||1))} + ${fmt$(P2.tmo*(t.n||1))}/mo</small>`,'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash<P2.setup*(t.n||1)||!portOk(c,i)):'').join('')}${(t.n||1)<LAG_MAX?btn(`+ LAG member <small>${fmt$(PORT[t.tier].setup)} + ${fmt$(PORT[t.tier].tmo)}/mo</small>`,'lagT',{id:t.id,d:1},'sm',S.cash<PORT[t.tier].setup||!portOk(c,t.tier)):''}${(t.n||1)>1?btn('− member','lagT',{id:t.id,d:-1},'ghost sm'):''}${btn(UI.confirm===t.id?'Really cancel?':'Cancel','cancelTransit',{id:t.id},'ghost sm')}</div>`;}
|
||
else h+=`<div class="btns">${PORT.map((P2,i)=>btn(`${P2.n} <small>${fmt$(P2.setup)} + ${fmt$(P2.tmo)}/mo</small>`,'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash<P2.setup||!portOk(c,i))).join('')}</div>`;
|
||
h+=`</div></div>`;}
|
||
h+=`</section>`;
|
||
}else if(UI.tab==='peer'){
|
||
h+=portNote(c);
|
||
h+=ixSection(c);
|
||
h+=`<section><h3>Private interconnects (PNI)</h3><p class="lead">A dedicated cross-connect to one network in ${esc(C.dc)}. Needs more traffic than IX peering, but has its own capacity.</p>`;
|
||
const here=NETS.filter(n=>n.pops.includes(c));
|
||
for(const n of here){const pn=S.pni.find(x=>x.city===c&&x.net===n.id),chk=peerOk(n.id,'pni',c);
|
||
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="tag ${n.pol}">${n.pol}</span></div>`;
|
||
if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(PORT[pn.tier].g,pn.n);h+=`<div class="kv"><span>${(pn.n||1)>1?`${pn.n}×${PORT[pn.tier].n} LAG`:PORT[pn.tier].n} PNI</span><b>${fmtG(u)}</b></div><div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('p',pn.id,pn.pref)}${siteCtl('p',pn.id,c,pn.site)}<div class="btns">${PORT.map((P2,i)=>i>pn.tier?btn(`Upgrade ${(pn.n||1)>1?'all to ':''}${P2.n} <small>${fmt$((1500+P2.setup/2)*(pn.n||1))}</small>`,'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)||S.cash<(1500+P2.setup/2)*(pn.n||1)):'').join('')}${(pn.n||1)<LAG_MAX?btn(`+ LAG member <small>${fmt$(1500+PORT[pn.tier].setup/2)} + ${fmt$(PORT[pn.tier].pni)}/mo</small>`,'lagP',{id:pn.id,d:1},'sm',S.cash<1500+PORT[pn.tier].setup/2):''}${(pn.n||1)>1?btn('− member','lagP',{id:pn.id,d:-1},'ghost sm'):''}${btn(UI.confirm===pn.id?'Really remove?':'Remove','cancelPni',{id:pn.id},'ghost sm')}</div>`;}
|
||
else{h+=chk.ok?`<div class="btns">${PORT.map((P2,i)=>btn(`${P2.n} <small>${fmt$(1500+P2.setup/2)}</small>`,'pni',{city:c,net:n.id,tier:i},'sm',S.cash<1500+P2.setup/2||!portOk(c,i))).join('')}</div>${chk.fee?`<div class="meta">Paid peering: ${fmt$(chk.fee)}/mo on top</div>`:''}`:`<div class="why">${esc(chk.why)}</div>`;}
|
||
h+=`</div></div>`;}
|
||
h+=`</section><section><h3>Embedded caches</h3><p class="lead">CDNs put free cache servers inside your POP. Most of their traffic is then served right here, with no transit and no IX port.</p>`;
|
||
for(const n of NETS.filter(n=>n.cache)){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+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.cache.name)}</div><div class="meta">from ${esc(n.name)} · ${have.length?`${have.length} box${have.length>1?'es':''} · serving ${fmtG(have.reduce((a,x)=>a+(R.useCache[x.id]||0),0))}`:`100G per box`}</div>${!ok?`<div class="why">Needs ${n.cache.min} Gbps of traffic to ${esc(n.name)} (now ${dem.toFixed(1)})</div>`:''}</div>
|
||
${have.length?btn('Remove','rmCache',{id:have[0].id},'ghost sm'):''}${have.length<4?btn(have.length?'+ box':'Request','cache',{city:c,net:n.id},'sm',!ok):''}</div>`;}
|
||
h+=`</section>`;
|
||
}else{
|
||
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),N=RG[g+1];
|
||
h+=`<section><h3>Routers</h3><p class="lead">The model sets your fastest interface and how much this POP can forward. More routers add capacity and survive crashes.</p>
|
||
<div class="row"><span class="logo" style="--c:#FF4F9A">R${g+1}</span><div class="grow"><div class="nm">${rt} × ${esc(G.n)}</div><div class="meta">Up to ${G.pn} interfaces · ${fmtG(G.cap)} per router · ${esc(G.blurb)}</div></div></div>
|
||
<div class="kv"><span>Forwarding chip</span><b>${esc(G.chip)}</b></div><div class="kv"><span>Boot time</span><b>${slowBoot(c)?`<span style="color:var(--bad)">~${bootMin(c)} min · a slow one</span>`:`~${bootMin(c)} min`}</b></div>${slowBoot(c)?`<p class="note">This chassis takes forever to boot: crashes last longer, and swapping the only router here takes 3 days. A second router hides it.</p>`:''}
|
||
<div class="kv"><span>Forwarding load</span><b>${fmtG(nl)} / ${fmtG(nc)}</b></div><div class="bar ${barCls(nl/nc)}"><i style="width:${Math.min(100,nl/nc*100)}%"></i></div>
|
||
${nl>=nc*0.95?`<p class="why">Maxed out. Traffic here is being dropped.</p>`:''}
|
||
<div class="btns">${N?btn(N.lvl>lvl()?`${esc(N.n)} <small>level ${N.lvl}</small>`:`Upgrade to ${esc(N.n)} <small>${fmt$(N.cost*rt)} + ${fmt$(N.mo*rt)}/mo</small>`,'upRouter',{city:c},'pink',N.lvl>lvl()||S.cash<N.cost*rt):''}${rt<4?btn(`Add router <small>${fmt$(routerCost(g))} + ${fmt$(ROUTER_MO+G.mo)}/mo</small>`,'addRouter',{city:c},'',S.cash<routerCost(g)):''}${rt>1?btn('Remove one','rmRouter',{city:c},'ghost sm'):''}</div>
|
||
${N?`<p class="note">${rt>1?'Rolling upgrade: one router at a time, no downtime.':'With one router, the upgrade needs a maintenance window: this POP goes dark for a day.'}</p>`:''}
|
||
<p class="note">${rt>=2?'A crash here only costs one router’s capacity for a few days.':'One router is a single point of failure.'}</p></section>
|
||
<section><h3>Metro diversity</h3>${p.site2?(()=>{const up=s=>[...S.transit.filter(t=>t.city===c&&(t.site||'a')===s).map(t=>NET[t.net].name+' transit'),...S.pni.filter(x=>x.city===c&&(x.site||'a')===s).map(x=>'PNI '+NET[x.net].name),...(S.ixp[c]!==undefined&&((S.ixSite||{})[c]||'a')===s?[ixName(c)+' port']:[]),...(s==='a'?S.caches.filter(x=>x.city===c).map(x=>NET[x.net].cache.name):[])];
|
||
const row=s=>{const dn=siteDown(c,s),u=up(s);return `<div class="row"><span class="logo" style="--c:${s==='a'?'#FF4F9A':'#7B61FF'}">${s.toUpperCase()}</span><div class="grow"><div class="nm">${esc(siteName(c,s))}${dn?' <span class="tag restrictive">DOWN</span>':''}</div><div class="meta">${u.length?esc(u.join(', ')):'Nothing plugged in here yet'}</div></div></div>`;};
|
||
return `<p class="lead">Two buildings joined by your own metro ring. A power cut or cleaner in one leaves the other running at half capacity. Uplinks only work while their site is up.</p>${row('a')}${row('b')}${up('b').length&&up('a').length?'':`<p class="why">Everything is in one building. Move some uplinks to the other site from the Transit and Peering tabs.</p>`}<div class="kv"><span>Second site and metro ring</span><b>${fmt$(SITE2_MO)}/mo</b></div><div class="btns">${btn(UI.confirm==='site'+c?'Really close it?':'Close site B','rmSite',{city:c},'ghost sm')}</div>`;})()
|
||
:`<p class="lead">Right now ${esc(CITY[c].name)} is one building. A power cut, an A/C failure or a cleaner with a vacuum takes the whole city dark, and a second router does not help with that. A second data center across town, joined by your own metro ring, keeps half the POP up.</p><div class="btns">${btn(`Add a second site <small>${fmt$(SITE2_COST)} + ${fmt$(SITE2_MO)}/mo</small>`,'addSite',{city:c},'pink',S.cash<SITE2_COST)}</div>`}</section>
|
||
<section><h3>Power</h3><div class="kv"><span>Backup generator</span><b>${p.gen?'Installed':'None'}</b></div>${p.gen?'<p class="note">Power cuts are covered.</p>':`<div class="btns">${btn(`Install generator <small>${fmt$(GEN_COST)} + ${fmt$(GEN_MO)}/mo</small>`,'addGen',{city:c},'',S.cash<GEN_COST)}</div>`}</section>`;
|
||
h+=`<section><h3>DDoS scrubbing center</h3>${S.scrubAt===c?`<p class="lead">Online here. Attack traffic anywhere on your network is cleaned before it hurts, and you can sell DDoS protection to businesses.</p>${btn(UI.confirm==='scrub'?'Really shut it down?':'Shut down','scrub',{city:c},'ghost sm')}`:S.scrubAt?`<p class="lead">You already run one in ${CITY[S.scrubAt].name}.</p>`:`<p class="lead">Absorbs DDoS attacks for your whole network and unlocks DDoS protection contracts for businesses.</p>${btn(`Build scrubbing center <small>${fmt$(SCRUB_COST)} + ${fmt$(SCRUB_MO)}/mo</small>`,'scrub',{city:c},'',S.cash<SCRUB_COST)}`}</section>`;
|
||
const fabs=FABS.filter(f=>f.cities.includes(c));
|
||
if(fabs.length){h+=`<section><h3>Interconnection fabrics (NNI)</h3><p class="lead">Buy a port on a fabric, then order virtual circuits to your other POPs or to a remote IX. Fast and flexible, but you share their fabric.</p>`;
|
||
for(const f of fabs){const pt=nniPort(c,f.id),used=nniUsed(c,f.id);
|
||
h+=`<div class="row"><span class="logo" style="--c:${f.col}">${initials(f)}</span><div class="grow"><div class="nm">${esc(f.name)}</div><div class="meta">${esc(f.blurb)}</div>`;
|
||
if(pt){const cap=NNI[pt.tier].g;h+=`<div class="kv"><span>${NNI[pt.tier].n} port · ${fmt$(NNI[pt.tier].mo)}/mo</span><b>${fmtG(used)} of circuits</b></div><div class="bar ${barCls(used/cap)}"><i style="width:${used/cap*100}%"></i></div><div class="btns">${btn('New circuit','openVxc',{from:c,prov:f.id},'pink sm')}${pt.tier<1?btn(`Upgrade 100G <small>${fmt$(NNI[1].mo)}/mo</small>`,'buyNni',{city:c,prov:f.id,tier:1},'sm'):''}${btn('Remove port','rmNni',{city:c,prov:f.id},'ghost sm')}</div>`;}
|
||
else h+=`<div class="btns">${NNI.map((N,i)=>btn(`${N.n} port <small>${fmt$(N.mo)}/mo</small>`,'buyNni',{city:c,prov:f.id,tier:i},'sm',S.cash<N.mo)).join('')}</div>`;
|
||
h+=`</div></div>`;}
|
||
h+=`</section>`;}
|
||
h+=`<section><h3>Fiber from ${C.name}</h3><p class="lead">Drag from this router to any city on the map to lay a new link. Two paths to every POP means a backhoe can't take you offline.</p>`;
|
||
if(!ls.length)h+=`<p class="empty">No links yet.</p>`;
|
||
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+=`<div class="row"><div class="grow"><div class="nm">→ ${CITY[o].name}${l.mult>1?' · diverse':''} ${cut?'<span class="tag restrictive">CUT</span>':''}</div><div class="meta">${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?'virtual circuit via '+esc(FAB[l.prov].name):l.kind==='df'?(l.own?'own dark fiber':'dark fiber IRU')+(l.ready>S.day?` · ready in ${l.ready-S.day}d`:''):l.sub?'subsea':'terrestrial'} · ${fmt$(l.mo)}/mo</div><div class="bar ${barCls(u)}"><i style="width:${u*100}%"></i></div></div>${btn('Open','selLink',{id:l.id},'ghost sm')}</div>`;}
|
||
h+=`</section>`;
|
||
}
|
||
return h+`</div>`;
|
||
}
|
||
function ixSection(c){const C=CITY[c],ix=ixName(c);let h='';
|
||
h+=`<section><h3>Internet Exchange</h3>`;
|
||
if(!ix&&C.cn){h+=`<p class="lead">Running an exchange in mainland China takes a different license entirely. Peer with Chinese networks over PNIs, or meet them in Hong Kong.</p>`;}
|
||
else if(!ix){h+=`<p class="lead">There's no IX in ${C.name} yet. Found one: networks join over time, pay you for ports, and peer with you for free.</p>${S.pops[c]?btn(`Found your own IX <small>${fmt$(MYIX_COST)} + ${fmt$(MYIX_MO)}/mo</small>`,'foundIx',{city:c},'pink',S.cash<MYIX_COST):'<p class="note">Build a POP here first.</p>'}`;}
|
||
else if(S.ixp[c]===undefined){h+=`<p class="lead">${esc(ix)} is a shared switch. One port lets you peer with every member for free. Members: ${ixMembers(c).map(id=>esc(NET[id].name)).join(', ')||'nobody yet'}.</p>${S.pops[c]?'':REMOTE_WARN}${CITY[c].ixCheap?`<p class="note"><b>Run by a nonprofit.</b> Public prices at a fraction of what other exchanges charge, and almost everyone is here.</p>`:''}${isDk(c)?`<p class="note"><b>Run by DE-KICKS Group.</b> No public price list. Ask sales for a personalised quote and bring your haggling face.</p>`:''}<div class="btns">${PORT.map((P2,i)=>btn(`${P2.n} port <small>${isDk(c)?'Price on request ☎':fmt$(ixPortMo(c,i))+'/mo'}</small>`,'buyIx',{city:c,tier:i},'',(!isDk(c)&&S.cash<ixPortMo(c,i))||(!!S.pops[c]&&!portOk(c,i))||(!S.pops[c]&&i>1))).join('')}</div>`;}
|
||
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+=`<div class="kv"><span>${mine?'Your own fabric · 400G':lagName(S.ixp[c],(S.ixn||{})[c])}${xdown?' · <b style="color:var(--bad)">FABRIC DOWN</b>':''}</span><b>${fmtG(u)}</b></div><div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('ix',c,S.ixPref&&S.ixPref[c])}${S.pops[c]?siteCtl('ix',c,c,(S.ixSite||{})[c]):''}`;
|
||
if(isDk(c)&&S.dk){const ad=S.dk.add[c]||[],rt=S.dk.ret[c];h+=`<p class="note">DE-KICKS personalised pricing: ${Math.round(dkMult(c)*100)}% of what a normal IX would charge${rt&&rt>S.day?` (promo, ${rt-S.day} days left)`:''}.</p>`;
|
||
for(const x of ad)h+=`<div class="row"><div class="grow"><div class="nm">${esc(x.n)} <span class="tag paid">auto-enrolled</span></div><div class="meta">${esc(x.blurb)} · ${fmt$(x.mo)}/mo</div></div>${btn(UI.confirm==='dk'+c+x.n?'Lose exclusive benefits?':'Opt out','dkOptOut',{city:c,n:x.n},'ghost sm')}</div>`;}
|
||
if(isRemote(c))h+=`<p class="note">Remote port via a reseller: 1.5× price, 80% usable, and ${ixMembers(c).filter(noRemote).length} member${ixMembers(c).filter(noRemote).length===1?'':'s'} here refuse remote peers.</p>`;
|
||
if(mine)h+=`<div class="kv"><span>Members paying you</span><b>${S.myIx[c].members.length} · ${fmt$(S.myIx[c].members.length*MYIX_FEE)}/mo</b></div>`;
|
||
else h+=`<div class="btns">${PORT.map((P2,i)=>i>S.ixp[c]?btn(`Upgrade ${P2.n} <small>${fmt$(ixPortMo(c,i)*((S.ixn||{})[c]||1))}/mo</small>`,'buyIx',{city:c,tier:i},'sm',(!!S.pops[c]&&!portOk(c,i))||(!S.pops[c]&&i>1)):'').join('')}${S.pops[c]&&((S.ixn||{})[c]||1)<LAG_MAX?btn(`+ LAG member <small>${fmt$(ixPortMo(c,S.ixp[c]))}/mo</small>`,'lagIx',{city:c,d:1},'sm',S.cash<ixPortMo(c,S.ixp[c])):''}${((S.ixn||{})[c]||1)>1?btn('− member','lagIx',{city:c,d:-1},'ghost sm'):''}${btn(S.rs[c]?'Leave route server':'Join route server','rs',{city:c},S.rs[c]?'ghost sm':'pink sm')}${btn(UI.confirm==='ix'+c?'Really leave?':'Leave IX','cancelIx',{city:c},'ghost sm')}</div>`;
|
||
h+=`<div style="margin-top:8px">`;
|
||
for(const id of ixMembers(c)){const n=NET[id],on=set.has(id),viaRs=on&&!S.peers[id+'@'+c]&&!mine,chk=peerOk(id,'ix',c);
|
||
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)}</div><div class="meta"><span class="tag ${n.type}">${TYPE_L[n.type]}</span> <span class="tag ${n.pol}">${n.pol}</span> · ${(NSH[id]*100).toFixed(0)}%</div>${!on&&!chk.ok?`<div class="why">${esc(chk.why)}</div>`:''}</div>
|
||
${on?(viaRs||mine?`<span class="tag st on">${mine?'Member':'via RS'}</span>`:btn('Peered ✓','unpeer',{city:c,net:id},'green sm',false,'Click to tear down')):btn('Request','peer',{city:c,net:id},'sm',!chk.ok)}</div>`;}
|
||
h+=`</div>`;}
|
||
h+=`</section>`;return h;
|
||
}
|
||
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=`<div class="ph"><div><div class="eyebrow">Virtual circuit · ${esc(f.name)} · ${l.km.toLocaleString()} km</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="Close">×</button></div><div class="scroll">`;
|
||
if(down)h+=`<section><h3 style="color:var(--bad)">Fabric outage</h3><p class="lead">${esc(f.name)} is down. Nothing you can do but wait, or have another path.</p></section>`;
|
||
h+=`<section><h3>Capacity</h3><div class="kv"><span>${VXC[l.vt].n} circuit</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
|
||
<div class="kv"><span>Monthly</span><b>${fmt$(l.mo)}/mo</b></div>${!S.pops[l.b]?`<p class="note">Remote peering leg into ${esc(CITY[l.b].ix)}.</p>`:''}
|
||
<div class="btns">${VXC.map((V,t)=>t>l.vt?btn(`${V.n} <small>${fmt$(vxcMo(l.km,l.sub,t))}/mo</small>`,'upVxc',{id:l.id,t},'sm'):'').join('')}</div></section>
|
||
${trafficSection(l)}${metricSection(l)}
|
||
<section>${btn(UI.confirm===l.id?'Really cancel?':'Cancel circuit','cancelVxc',{id:l.id},'ghost sm')}</section></div>`;
|
||
return h;
|
||
}
|
||
function prefCtl(kind,id,cur){cur=cur||'normal';return `<div class="btns"><span class="meta" style="align-self:center">Egress:</span>${Object.keys(PREF).map(v=>btn(PREF[v],'setPref',{kind,id,v},cur===v?'pink sm':'ghost sm')).join('')}</div>`;}
|
||
function trafficSection(l){
|
||
const rec=R.ef[edgeKey(l)],n=pairLinks(l.a,l.b).length;
|
||
let h=`<section><h3>What's on this link</h3>`;
|
||
if(!rec){return h+`<p class="empty">No traffic right now.</p></section>`;}
|
||
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':NET[id].col,nm=id=>id==='junk'?'DDoS junk':id==='l2vpn'?'L2VPN customers':NET[id].name;
|
||
h+=`${n>1?`<p class="note" style="margin-top:0">Totals for all ${n} links between these cities.</p>`:''}<div class="stack">${nets.map(([id,v])=>`<i style="width:${v/tot*100}%;background:${col(id)}" title="${esc(nm(id))}"></i>`).join('')}</div>`;
|
||
h+=`<h4 class="sub4">Content from</h4>`+nets.slice(0,6).map(([id,v])=>`<div class="kv"><span><span class="dot" style="background:${col(id)}"></span>${esc(nm(id))}</span><b>${fmtG(v)} · ${pct(v/tot)}</b></div>`).join('');
|
||
const egs=Object.entries(rec.eg).sort((a,b)=>b[1]-a[1]);
|
||
h+=`<h4 class="sub4">Enters your network at</h4>`+egs.slice(0,6).map(([k,v])=>{const d=R.egDesc[k];return `<div class="row"><div class="grow"><div class="nm">${esc(d.lab)}</div><div class="meta">${CITY[d.city].name} · ${fmtG(v)} · ${pct(v/tot)}</div></div>${btn('Open','goEgress',{city:d.city,k:d.k},'ghost sm')}</div>`;}).join('');
|
||
const dst=Object.entries(rec.dst).sort((a,b)=>b[1]-a[1]);
|
||
h+=`<h4 class="sub4">Going to customers in</h4>`+dst.slice(0,6).map(([c,v])=>`<div class="kv"><span>${CITY[c].name}</span><b>${fmtG(v)} · ${pct(v/tot)}</b></div>`).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+=`<p class="why">Biggest feeder: ${esc(d.lab)} in ${CITY[d.city].name}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.</p>`;}
|
||
return h+`</section>`;
|
||
}
|
||
function metricSection(l){const cur=l.metric||'normal';
|
||
return `<section><h3>Routing metric</h3><p class="lead">Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.</p><div class="btns">${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},cur===k?'pink sm':'ghost sm')).join('')}</div></section>`;}
|
||
function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2;
|
||
let h=`<section><h3>Behind the Great Firewall</h3><p class="lead">Mainland China plays by its own rules. ${CN_BLOCKED.slice(0,4).map(esc).join(', ')} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about ${pct(loss)} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.</p>`;
|
||
if(st==='none')h+=`<p class="lead">Foreign networks need a local joint venture and an operating license to build infrastructure here.</p>${btn(`Apply for a license <small>${fmt$(CN_LIC)} + ${fmt$(CN_JV_MO)}/mo · ~45 days</small>`,'applyCn',{},'pink',S.cash<CN_LIC)}`;
|
||
else if(st==='pending')h+=`<p class="note">License paperwork in progress: ${Math.max(0,S.cnLic.ready-S.day)} days left.</p>`;
|
||
else h+=`<p class="note">Your joint venture holds an operating license.</p>`;
|
||
if(R.gfwCross>0.5)h+=`<div class="kv"><span>Your traffic crossing the border</span><b>${fmtG(R.gfwCross)}</b></div><div class="kv"><span>Lost on the way</span><b style="color:var(--bad)">${fmtG(R.gfwLost)}</b></div>`;
|
||
return h+`</section>`;}
|
||
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=`<div class="ph"><div><div class="eyebrow">Dark fiber · ${l.own?'your own build':'leased IRU'} · ${l.km.toLocaleString()} km</div><h2>${A} ⇄ ${B}</h2></div><button class="x" data-act="closePanel" aria-label="Close">×</button></div><div class="scroll">`;
|
||
if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1);
|
||
h+=`<section><h3>${l.own?'Under construction':'Being spliced'}</h3><div class="kv"><span>${l.own?'Permits, trenching, splicing':'IRU handover'}</span><b>${l.ready-S.day} days left</b></div><div class="bar me"><i style="width:${done*100}%"></i></div>${l.own?btn(`Hire extra crews <small>${fmt$(Math.round(15000+l.km*6))} · −30 days</small>`,'crews',{id:l.id},'sm',S.cash<15000+l.km*6):''}<p class="note">You can pre-install optics now so it lights up the day it's ready.</p></section>`;}
|
||
else if(inc&&linkDown(l))h+=`<section><h3 style="color:var(--bad)">Dark!</h3><p class="lead">${esc(inc.msg)}</p>${inc.cost?btn(`${esc(inc.fix||'Rush repair')} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
|
||
h+=`<section><h3>Capacity</h3><div class="kv"><span>${(l.ch||[]).length} of ${sysD.max} channels lit${soldSlots(l)?` · ${soldSlots(l)} sold as alien waves`:''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
|
||
<div class="kv"><span>Latency</span><b>${linkLat(l).toFixed(1)} ms one-way</b></div><div class="kv"><span>${l.own?'Right-of-way upkeep':'IRU lease'}</span><b>${fmt$(l.mo)}/mo</b></div><div class="kv"><span>${amps} amp huts</span><b>${fmt$(amps*AMP_MO)}/mo</b></div>${!bld&&!(l.ch||[]).length?`<p class="why">This fiber is dark. Add optics below to carry traffic.</p>`:''}</section>`;
|
||
h+=`<section><h3>Optics</h3><p class="lead">Each channel is a pair of optics, one per end. ZR+ optics plug straight into your routers. Transponders sit on a shelf.</p>`;
|
||
for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k);
|
||
h+=`<div class="row"><div class="grow"><div class="nm">${O.n} <span class="meta">${fmtG(O.g)} · reach ${O.reach.toLocaleString()} km</span></div><div class="meta">${esc(O.blurb)}${n?` · <b>${n} lit</b>`:''}</div>${why?`<div class="why">${esc(why)}</div>`:''}</div>${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(`+ <small>${fmt$(optCost(k))}</small>`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash<optCost(k))}</div>`;}
|
||
h+=`</section><section><h3>Line system</h3><div class="kv"><span>${esc(sysD.n)}</span><b>${amps} amplifiers</b></div><p class="note">${esc(sysD.blurb)}</p><div class="btns">${l.sys!=='roadm'?btn(lvl()>=3?`Upgrade to ROADMaster 9000 <small>${fmt$(DF_SYS.roadm.cost)}</small>`:'ROADMaster 9000 <small>level 3</small>','upSys',{id:l.id},'sm',lvl()<3||S.cash<DF_SYS.roadm.cost):''}${btn(l.spares?'Spares kit on ✓':`Keep a spares kit <small>${fmt$(Math.round(150+(l.ch||[]).length*80))}/mo</small>`,'spares',{id:l.id},l.spares?'green sm':'sm')}</div><p class="note">Spare optics and amplifier cards on the shelf turn multi-day hardware failures into one-day swaps.</p></section>`;
|
||
h+=`${trafficSection(l)}${metricSection(l)}<section>${btn(UI.confirm===l.id?'Really give it up?':(l.own?'Abandon the fiber':'Cancel the IRU'),'rmLink',{id:l.id},'ghost sm')}</section></div>`;
|
||
return h;
|
||
}
|
||
function offersHere(c){
|
||
const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return '';
|
||
return `<section><h3>Offers here</h3>${os.map(o=>`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${o.exp-S.day}d left</div>${R.reach<0.99&&!BIZ_T[o.type].l2?`<div class="why">They need the full internet. Your reach is ${pct(R.reach)}.</div>`:''}${o.type==='scrub'&&!S.scrubAt?`<div class="why">Needs your own scrubbing center (Infra tab).</div>`:''}${reqList(o)}${bHas(o)?'':`<div class="why">Needs a POP in ${bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')} too.</div>`}</div>${bHas(o)?btn('Accept','accept',{id:o.id},'green sm'):''}${btn('No','decline',{id:o.id},'ghost sm')}</div>`).join('')}</section>`;
|
||
}
|
||
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==='df')return dfPanel(l);
|
||
const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,tr=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===tr)||((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)===tr);
|
||
let h=`<div class="ph"><div><div class="eyebrow">${l.cable?esc(CAB[l.cable].name):l.sub?'Subsea cable':'Terrestrial fiber'} · ${l.km.toLocaleString()} km</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="Close">×</button></div><div class="scroll">`;
|
||
if(cut)h+=`<section><h3 style="color:var(--bad)">Cut!</h3><p class="lead">${inc?esc(inc.msg):''} Back in ${l.cut-S.day} days.</p>${inc&&inc.cost?btn(`${esc(inc.fix||'Rush repair')} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
|
||
h+=`<section><h3>Capacity</h3><div class="kv"><span>${LT[l.tier].n} wave</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
|
||
<div class="kv"><span>Latency</span><b>${linkLat(l).toFixed(1)} ms one-way</b></div>${l.cable?`<div class="kv"><span>Cable system</span><b>${esc(CAB[l.cable].name)}</b></div>`:''}
|
||
<div class="kv"><span>Wave lease</span><b>${fmt$(l.mo)}/mo</b></div>${u>=0.9?`<p class="why">Congested. Upgrade it or add a parallel path.</p>`:''}
|
||
<div class="btns">${LT.map((T,i)=>{const d=Math.round(waveMo(l.km,l.sub,i)*(l.mult||1)),ok=waveOk(l.a,l.b,i);return i>l.tier?btn(`${T.n} <small>${ok?fmt$(d)+'/mo':'needs '+esc(waveNeed(i))}</small>`,'upLink',{id:l.id,tier:i},'sm',S.cash<d||!ok):'';}).join('')}</div></section>
|
||
<section><h3>Redundancy</h3><p class="lead">${mates.length?`Shares a trench with ${mates.length} other link${mates.length>1?'s':''}. One cut takes them all down.`:sib.length?'Runs on its own route. A cut here leaves the other links up.':'This is the only link between these cities. Add a parallel one, or a path through another city.'}</p>
|
||
${sib.map(x=>`<div class="row"><div class="grow"><div class="nm">${capName(x)} parallel link ${x.cut>S.day?'<span class="tag restrictive">CUT</span>':''}</div><div class="meta">${(x.trench||x.id)===tr?'same trench':'diverse route'}</div></div>${btn('Open','selLink',{id:x.id},'ghost sm')}</div>`).join('')}
|
||
<div class="btns">${btn('Add parallel link','addParallel',{id:l.id},'pink sm')}</div></section>
|
||
${trafficSection(l)}${metricSection(l)}
|
||
<section>${btn(UI.confirm===l.id?'Really decommission?':'Decommission link','rmLink',{id:l.id},'ghost sm')}</section></div>`;
|
||
return h;
|
||
}
|
||
const EGC={c:['Caches','#16A866'],p:['PNIs','#7B61FF'],ix:['IX peering','#FFD23F'],t:['Transit','#FF8A3D'],l2:['L2 circuits','#2F8CFF']};
|
||
function svgChart(rows,stackKeys,lines,fmtY){
|
||
const W=600,H=180,L=50,B=20,T=8,Rr=8;if(rows.length<2)return `<p class="empty">Collecting data. Check back in a few days.</p>`;
|
||
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+=`<line x1="${L}" x2="${W-Rr}" y1="${yy}" y2="${yy}" stroke="#D5DEEC" stroke-width="1"/><text x="${L-6}" y="${yy+3}" text-anchor="end" font-size="10" fill="#55608A" font-weight="700">${fmtY(v)}</text>`;}
|
||
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<rows.length;i++)d+=`L${x(i)},${y(top[i])}`;for(let i=rows.length-1;i>=0;i--)d+=`L${x(i)},${y(base[i])}`;g+=`<path d="${d}Z" fill="${EGC[k][1]}" fill-opacity=".85" stroke="#1E2640" stroke-width=".8"/>`;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+=`<path d="${d}" fill="none" stroke="${ln.col}" stroke-width="2.5" ${ln.dash?'stroke-dasharray="5 4"':''} stroke-linejoin="round"/>`;const last=rows[rows.length-1][ln.k]||0;g+=`<circle cx="${x(rows.length-1)}" cy="${y(last)}" r="3.5" fill="${ln.col}" stroke="#1E2640" stroke-width="1.5"/>`;}
|
||
g+=`<text x="${L}" y="${H-5}" font-size="10" fill="#55608A" font-weight="700">${dateStr(rows[0].d)}</text><text x="${W-Rr}" y="${H-5}" text-anchor="end" font-size="10" fill="#55608A" font-weight="700">${dateStr(rows[rows.length-1].d)}</text>`;
|
||
return `<svg class="chart" viewBox="0 0 ${W} ${H}" role="img">${g}</svg>`;}
|
||
function renderDash(){
|
||
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)=>`<div class="tile"><div class="lbl">${l}</div><div class="val">${v}</div>${sub?`<div class="sub">${sub}</div>`:''}</div>`;
|
||
let h=`<div style="display:flex;align-items:center;gap:10px"><div><div class="eyebrow">AS${S.asn} · ${esc(S.name)} · ${tierLabel()}</div><h2 style="font-size:28px">NOC dashboard</h2></div><button class="x" data-act="dashClose" aria-label="Close">×</button></div>
|
||
<div class="dgrid">${tile('Traffic now',fmtG(R.served),`of ${fmtG(R.demand)} wanted`)}${tile('Peak',fmtG(S.stats.peak))}${tile('Delivered, 30 days',(up*100).toFixed(1)+'%',up>=0.999?'five nines-ish':up>=0.99?'two nines and change':'customers are upset')}${tile('Peering ratio',pct(R.peerShare||0),'caches, PNIs and IX')}${tile('Monthly P&L',`<span style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</span>`,`${fmt$(R.revMo)} in · ${fmt$(R.costMo)} out`)}${tile('Incidents',S.stats.incidents,`${S.stats.survived} shrugged off`)}</div>
|
||
<div class="dcols"><div class="panel2"><h3>Traffic by way out</h3>${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)))}<div class="legend">${Object.keys(EGC).map(k=>`<span><i style="background:${EGC[k][1]}"></i>${EGC[k][0]} ${pct((R.egT[k]||0)/tot)}</span>`).join('')}<span><i style="background:#fff;border-style:dashed"></i>Demand</span></div></div>
|
||
<div class="panel2"><h3>Money per month</h3>${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v))}<div class="legend"><span><i style="background:#16A866"></i>Revenue</span><span><i style="background:#FF4D5E"></i>Costs</span></div>
|
||
<h3 style="margin-top:8px">Where the money goes</h3>${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`<div class="kv"><span>${{pops:'POPs and routers',links:'Waves and fiber',transit:'Transit',ix:'IX ports',pni:'PNIs',caches:'Cache power',nni:'Fabric ports',optical:'Amp huts and spares',loans:'Loan repayments',revshare:'Investor revenue share',extras:'Licenses and scrubbing'}[k]||k}</span><b>${fmt$(v)}/mo</b></div>`).join('')}</div></div>`;
|
||
const nets=NETS.map(n=>{const e=R.netEg[n.id]||{c:0,p:0,ix:0,t:0};const t=e.c+e.p+e.ix+e.t;return {n,e,t};}).filter(x=>x.t>0.01||R.demTo[x.n.id]>0.01).sort((a,b)=>b.t-a.t);
|
||
const tT=(R.egT.t||0)||1;
|
||
h+=`<div class="panel2" style="margin-top:12px"><h3>Traffic by network (ASN)</h3><p class="note" style="margin-top:0">Where your users' traffic comes from, and how it gets to you. Red in the mix is paid transit; everything else is free or cheap.</p><div class="tscroll"><table class="tbl"><thead><tr><th>Network</th><th>AS</th><th>Type</th><th class="r">Traffic</th><th>How it arrives</th><th class="r">Transit cost</th><th class="r">Lost</th></tr></thead><tbody>
|
||
${nets.map(({n,e,t})=>{const want=R.demTo[n.id]||0;return `<tr><td><span style="display:inline-flex;align-items:center;gap:6px">${logo(n)}<b>${esc(n.name)}</b></span></td><td>${n.asn}</td><td><span class="tag ${n.type}">${TYPE_L[n.type]}</span></td><td class="r">${fmtG(t)}</td><td><div class="mix">${['c','p','ix','t'].map(k=>`<i style="width:${t?e[k]/t*100:0}%;background:${k==='t'?'#FF4D5E':EGC[k][1]}"></i>`).join('')}</div></td><td class="r">${e.t>0.01?fmt$((R.cost.transit||0)*e.t/tT)+'/mo':'—'}</td><td class="r" style="color:${want-t>want*0.05?'var(--bad)':'inherit'}">${want>0.01?pct(Math.max(0,1-t/want)):'—'}</td></tr>`;}).join('')}</tbody></table></div></div>`;
|
||
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);
|
||
h+=`<div class="dcols" style="margin-top:12px"><div class="panel2"><h3>Busiest links</h3>${ls.length?ls.map(({l,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[l.a].name} ⇄ ${CITY[l.b].name} <span class="meta">${capName(l)} · ${linkLat(l).toFixed(1)} ms</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b>${btn('Open','dashLink',{id:l.id},'ghost sm')}</div>`).join(''):'<p class="empty">No links yet.</p>'}</div>
|
||
<div class="panel2"><h3>Router load</h3>${rs.map(({c,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[c].name} <span class="meta">${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b></div>`).join('')}
|
||
<h3 style="margin-top:10px">Your AS</h3><div class="kv"><span>AS number</span><b>AS${S.asn}</b></div><div class="kv"><span>Prefixes</span><b>${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6</b></div><div class="kv"><span>BGP sessions</span><b>${R.sessions}</b></div><div class="kv"><span>Upstreams</span><b>${new Set(S.transit.map(t=>t.net)).size}</b></div><div class="kv"><span>Reach</span><b>${pct(R.reach)}</b></div><div class="kv"><span>Customers</span><b>${S.biz.length} businesses</b></div></div></div>`;
|
||
if(h!==UI._dh){UI._dh=h;$('dashCard').innerHTML=h;}
|
||
}
|
||
function renderBank(){
|
||
if(!S||$('bankBox').hidden)return;const rt=rating(),net=R.revMo-R.costMo;
|
||
const terms=(o)=>{const B=BANKS[o.bank];return B.equity?`<span class="tag st on">No repayments</span><span class="tag st">${pct(o.share)} of revenue, forever</span><span class="tag st">Buy-out ${fmt$(o.amount*3)}</span>`:`<span class="tag st on">${(o.apr*100).toFixed(1)}% APR</span><span class="tag st">${o.term} months</span><span class="tag st">${fmt$(o.pay)}/mo</span>${B.crypto?'<span class="tag selective">Paid in TubeCoin</span>':''}`;};
|
||
const covList=(l)=>l.covs.length?l.covs.map(c=>{const ok=COVS[c].ok(l);return `<div class="meta"><b style="color:${ok?'var(--eye)':'var(--bad)'}">${ok?'✓':'✗'}</b> ${esc(COVS[c].l)}</div>`;}).join(''):'<div class="meta">No conditions. That is the scary part.</div>';
|
||
let h=`<div style="display:flex;align-items:center;gap:12px"><div><div class="eyebrow">AS${S.asn} · ${esc(S.name)}</div><h2 style="font-size:28px">Bank</h2></div><button class="x" data-act="bankClose" aria-label="Close">×</button></div>
|
||
<div class="dgrid"><div class="tile"><div class="lbl">Cash</div><div class="val" style="color:${S.cash<0?'var(--bad)':'inherit'}">${fmt$(S.cash)}</div><div class="sub">${S.cash<0?'Bankrupt at −$100k':'in the vault'}</div></div>
|
||
<div class="tile"><div class="lbl">Monthly P&L</div><div class="val" style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</div><div class="sub">after loan payments</div></div>
|
||
<div class="tile"><div class="lbl">Credit rating</div><div class="val">${rt}</div><div class="sub">${rIdx(rt)>=5?'Bankers return your calls':rIdx(rt)>=3?'Bankers return your emails':'Bankers pretend to be out'}</div></div>
|
||
<div class="tile"><div class="lbl">Debt</div><div class="val">${fmt$(S.loans.reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.bal),0))}</div><div class="sub">${S.loans.length} loan${S.loans.length===1?'':'s'}</div></div></div>`;
|
||
h+=`<h3 style="font-size:18px;margin-top:6px">Offers</h3>`;
|
||
if(!S.loanOffers.length)h+=`<p class="empty">No offers right now. Banks get in touch now and then, and much faster when you are in trouble. A better credit rating brings better banks.</p>`;
|
||
for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`<div class="loan"><span class="logo" style="--c:${B.col}">${initials(B)}</span><div class="grow"><div class="nm">${esc(B.name)} offers <b>${fmt$(o.amount)}</b></div><div class="meta">${esc(B.blurb)} · offer ends in ${o.exp-S.day}d</div><div class="terms">${terms(o)}</div>${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(x=>x.sub).length}})}<div class="btns" style="margin-top:6px">${btn('Take the money','takeLoan',{id:o.id},'pink')}${btn('No thanks','declineLoan',{id:o.id},'ghost sm')}</div></div></div>`;}
|
||
h+=`<h3 style="font-size:18px;margin-top:14px">Your loans</h3>`;
|
||
if(!S.loans.length)h+=`<p class="empty">Debt-free. Your accountant is suspicious.</p>`;
|
||
for(const l of S.loans){const B=BANKS[l.bank];const cost=repayCost(l,B);
|
||
h+=`<div class="loan"><span class="logo" style="--c:${B.col}">${initials(B)}</span><div class="grow"><div class="nm">${esc(B.name)} · ${fmt$(l.amount)}</div>
|
||
${B.equity?`<div class="meta">Taking ${pct(l.share)} of your revenue every month.</div>`:`<div class="kv"><span>Still owed</span><b>${fmt$(l.bal)}</b></div><div class="bar me"><i style="width:${Math.min(100,(1-l.bal/l.amount)*100)}%"></i></div><div class="meta">${fmt$(l.pay)}/mo · ${l.left} months left · ${(l.apr*100).toFixed(1)}% APR</div>`}
|
||
${covList(l)}${l.breach>=1?`<div class="why">Condition broken for ${l.breach} day${l.breach===1?'':'s'}. ${l.breach<10?`Penalty in ${10-l.breach} days.`:'Penalties are running.'}</div>`:''}
|
||
<div class="btns" style="margin-top:6px">${btn(UI.confirm===l.id?`Really pay ${fmt$(cost)}?`:B.equity?`Buy them out <small>${fmt$(cost)}</small>`:`Repay early <small>${fmt$(cost)} incl. 2% fee</small>`,'repayLoan',{id:l.id},UI.confirm===l.id?'red sm':'sm',S.cash<cost)}</div></div></div>`;}
|
||
if(h!==UI._bh){UI._bh=h;$('bankCard').innerHTML=h;}
|
||
}
|
||
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(UI.drag&&UI.drag.mode==='link')t=UI.snap?'Release to plan a link':'Drag onto another city';
|
||
else if(!S.links.length&&S.done.tr)t='Tip: drag from your pink router to another city to lay fiber';
|
||
else if(!S.done.bb)t='Tap your city, then Launch broadband';
|
||
hn.textContent=t;hn.hidden=!t;
|
||
}
|
||
|
||
/* ---------- toasts & modals ---------- */
|
||
function toast(html,kind='',actions=[]){
|
||
if(S){S.log=S.log||[];const tmp=document.createElement('div');tmp.innerHTML=html.replace(/<br>/g,' ');S.log.unshift({d:S.day,t:tmp.textContent,k:kind});if(S.log.length>30)S.log.length=30;}
|
||
const el=document.createElement('div');el.className='toast '+kind;
|
||
el.innerHTML=`<div class="tx">${html}</div>${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);
|
||
}
|
||
function openModal(html){$('modalCard').innerHTML=html;$('modal').hidden=false;}
|
||
function closeModal(){$('modal').hidden=true;UI.pending=null;}
|
||
function showTitle(){
|
||
const sv=loadSave();
|
||
const starts=[['fra','Crossroads of Europe. DE-KICKS IX, cheap transit.'],['nyc','Huge eyeball market. Pricey neighbours.'],['sin','Asia hub. Great peering, far from home.'],['sao','Big hungry market, few providers.']];
|
||
openModal(`<div class="title-art"><svg width="74" height="74" viewBox="0 0 74 74" aria-hidden="true"><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#1E2640" stroke-width="16" stroke-linecap="round"/><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#FFD23F" stroke-width="9" stroke-linecap="round"/><circle cx="58" cy="16" r="11" fill="#FF4F9A" stroke="#1E2640" stroke-width="4"/><circle cx="21" cy="44" r="3" fill="#fff"/><circle cx="30" cy="27" r="3" fill="#fff"/></svg>
|
||
<h1>Series<br>of <span>Tubes</span></h1></div>
|
||
<p class="tagline">Build an internet. Lay fiber between cities, buy transit, peer at exchanges, sign up businesses, and keep the eyeballs happy while backhoes, sharks and route leaks do their best to stop you.</p>
|
||
${sv?`<div class="btns" style="margin-bottom:6px">${btn(`Continue ${esc(sv.name)} · ${dateStr(sv.day)}`,'cont',{},'pink big')}</div>`:''}
|
||
<label class="f" for="nmIn">Name your network</label><input class="t" id="nmIn" maxlength="24" value="Packet Pals" autocomplete="off">
|
||
<label class="f">Pick your home city</label><div class="starts">${starts.map(([c,d])=>`<button class="start ${UI.startCity===c?'on':''}" data-city="${c}" data-act="pickStart" data-args='{"city":"${c}"}'><b>${CITY[c].name}</b><span>${d}</span></button>`).join('')}</div>
|
||
<label class="f">Mode</label><div class="btns">${[['normal','Normal'],['sandbox','Sandbox']].map(([m,l])=>`<button class="b sm modeb ${(UI.mode||'normal')===m?'pink':'ghost'}" data-m="${m}" data-act="modeSet" data-args='{"m":"${m}"}'>${l}</button>`).join('')}${btn('Scenarios & weekly challenge →','scenarios',{},'sm')}</div>
|
||
<div class="btns" style="margin-top:16px;justify-content:space-between;align-items:center">${btn(sv?'Start a new network':'Start building','start',{},'big')}${btn('How to play','help',{},'ghost')}${btn('Import a save','importPick',{},'ghost sm')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">Source on GitHub</a> · Cookieless stats, no tracking</p>`);
|
||
if(sv){S=migrate(sv);compute();}
|
||
}
|
||
// "What's new": shown once to returning players after an update, or on demand.
|
||
function whatsNew(returning,force){
|
||
if(IS_DEV||!RELEASE_NOTES.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(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Release notes</div><h2 style="font-size:28px">New in Series of Tubes ${esc(APP_VERSION)}</h2></div><button class="x" data-act="${UI.started?'closeModal':'helpClose'}" aria-label="Close">×</button></div>
|
||
<ul class="notes">${RELEASE_NOTES.map(n=>`<li>${esc(n)}</li>`).join('')}</ul>
|
||
${returning&&S?`<p class="note">Your network ${esc(S.name)} was saved and is waiting for you.</p>`:''}
|
||
<div class="btns" style="margin-top:12px">${btn(UI.started?'Back to my network':'Got it',UI.started?'closeModal':'helpClose',{},'pink big')}<a class="b ghost" href="https://github.com/fjaeckel/seriesoftubes/blob/main/CHANGELOG.md" target="_blank" rel="noopener">Full changelog</a></div>`);
|
||
return true;}
|
||
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=`<div class="tx"><b>Series of Tubes ${esc(j.version)} is out!</b>${top?`<br>${esc(top.length>120?top.slice(0,117)+'…':top)}`:''}<br><span class="meta">Your game is saved automatically.</span></div>${btn('Reload now','updateNow',{},'pink sm')}${btn('Later','updateLater',{},'ghost sm')}`;$('update').hidden=false;
|
||
}).catch(()=>{});
|
||
}
|
||
function showHelp(){
|
||
openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:28px">How the internet works here</h2><button class="x" data-act="helpClose" aria-label="Close">×</button></div>
|
||
<p class="tagline" style="margin:6px 0 4px"><b>Controls:</b> drag the map to pan, scroll or pinch to zoom, tap a city to open it. <b>Drag from your pink router to another city</b> to lay fiber. <span class="kbd">Space</span> pauses, <span class="kbd">0</span> is half speed, <span class="kbd">1</span> <span class="kbd">2</span> <span class="kbd">3</span> <span class="kbd">4</span> set speed. At 1× a day lasts 2.5 seconds.</p>
|
||
<dl class="gl">
|
||
<dt>Eyeballs</dt><dd>Home broadband users. They mostly download from CDNs and pay you per Gbps you deliver. Serve them well and they multiply.</dd>
|
||
<dt>POP</dt><dd>Point of presence: your router in a data center. Everything starts at a POP.</dd>
|
||
<dt>IP transit</dt><dd>You pay a bigger network per Gbps and it delivers your traffic anywhere. Easy, full reach, never free.</dd>
|
||
<dt>Tier 1 / Tier 2</dt><dd>Tier 1s reach the whole internet without paying anyone, because they all peer with each other. Tier 2s peer a lot but still buy some transit.</dd>
|
||
<dt>CDN</dt><dd>Content networks like NetChill and Goggle. Most of your traffic comes from them. Peer with them and that traffic is free.</dd>
|
||
<dt>IX (Internet Exchange)</dt><dd>A shared switch in a city. One port, many free peering sessions. The route server peers you with every open member at once.</dd>
|
||
<dt>PNI</dt><dd>Private network interconnect: a cable straight to one network in the same building. For big traffic.</dd>
|
||
<dt>Embedded cache</dt><dd>A CDN's server in your rack. Serves most of that CDN's traffic locally, for the price of power.</dd>
|
||
<dt>DE-KICKS</dt><dd>The group behind several big exchanges (Frankfurt, Madrid, Marseille, Dubai, Mumbai, New York) treats price lists as a state secret. Ports are quoted per customer and go up the bigger you look. Haggling can work, backfire or stall for a week. Prices get "harmonised" upwards once a year, add-ons appear on your invoice until you opt out, and trying to leave earns you a retention discount that ends with a fee.</dd><dt>Remote peering</dt><dd>Reach an IX over a fabric circuit without a POP there. It works, and the route server still gets you every open network, but it is discouraged: the reseller charges 1.5× for the port and oversubscribes it to 80%, latency rides the fabric, one fabric outage drops every session, and many selective networks refuse remote members outright.</dd><dt>Peering policy</dt><dd>Open peers with anyone. Selective wants to see traffic first. Restrictive (Tier 1s) only peers with giants, over PNIs. Paid means exactly that. Big selective networks also have moods: in some cities they refuse new peers for a few months, or only take PNIs, and now and then they tear down a session you already had. Try another city or a PNI, and ask again later.</dd>
|
||
<dt>Waves</dt><dd>Your fiber links are leased waves at a flat monthly rate. Longer and bigger costs more (10G → 6.4T), and subsea is 1.8× the price.</dd><dt>95th percentile</dt><dd>Transit bills sample your usage every day and charge the 95th percentile of the last 30 days, so short spikes are forgiven but long ones are not.</dd><dt>Routers</dt><dd>Each POP's router model caps its fastest port (100G, 400G, 800G, 1.6T) and how much it can forward. Bigger waves and ports need better routers at both ends. Better models unlock with your customer level. With one router, upgrades mean a day of downtime.</dd><dt>Dark fiber</dt><dd>Lease an IRU or build your own (slow, with delays), then buy a line system with amplifiers and light channels with 400ZR+, 800ZR+ or 1.6T transponders. Much cheaper than waves at scale, but the gear can fail. A spares kit speeds up repairs.</dd><dt>Subsea cables</dt><dd>Subsea waves can only follow real-ish cable systems, drawn faintly on the map (tap a city to highlight its cables). Teal ones are new and cheap, purple ones pricey, dashed ones old and cut-prone. All your waves on one cable die together when it is cut. Between continents on land, you can often choose overland (2.5×, many borders) or a cable.</dd><dt>Latency</dt><dd>Every link has latency. High-frequency traders pay a fortune for a circuit within their latency budget; route them “Lowest latency”. Bulk backup customers do not care, so route them “Scenic” over your quiet links to keep busy ones free.</dd><dt>NOC dashboard</dt><dd>The chart button at the top opens traffic graphs by exit (caches, PNIs, IX, transit), money over time, per-ASN traffic with how it reaches you and what its transit costs, plus your busiest links and routers.</dd><dt>Asia</dt><dd>A weird, underserved market. Transit costs 2.5× what it does in Europe (Africa 2×, Oceania 1.8×), local incumbents mostly peer only for pay, and IXs are fragmented. But demand is enormous and users sign up 60% faster than anywhere else. Peering and caches pay off most here.</dd><dt>Russia</dt><dd>Moscow needs a mandatory government box in every POP, Western CDNs are mostly gone, Goggle video is throttled to half speed, and the sovereign internet drills now and then cut Moscow off for a day.</dd><dt>Events, chains and wholesale</dt><dd>Event networks (a final, a festival, a keynote) need a burst of capacity in one city for a few days and pay once at the end, prorated by how much of the crowd you served; below 70% you pay a penalty. SD-WAN chains connect 3–6 of your POPs hub-and-spoke, so one broken spoke upsets the whole contract. Once you run your own dark fiber, carriers want to rent spare channels as alien waves, and on fiber you built yourself, a spare pair.</dd><dt>Bank</dt><dd>Tap your cash to open the bank. Lenders make offers now and then, and much more often when you are in the red. Each loan has a monthly payment and some odd conditions; break one and you pay a penalty. Your credit rating decides which banks talk to you. The loan shark is always there. Do not be late.</dd><dt>LAGs</dt><dd>Out of port speed? Bundle up to 8 identical ports to the same transit provider, IX or PNI into a LAG. Each member costs a full port; flow hashing is never perfectly even, so a bundle carries about 95% of the sum.</dd><dt>Traffic engineering</dt><dd>Tap a link to see which networks, which entry points and which customer cities fill it. Raise a link's metric to steer traffic around it, or set an egress (transit, IX, PNI) to Prefer or Backup only.</dd><dt>China</dt><dd>Mainland China needs a license and a local joint venture. Many foreign services are blocked there, and traffic crossing the border loses packets unless you pay for premium routes.</dd><dt>Weird requirements</dt><dd>Some customers come with conditions: no Cogentle anywhere, no subsea cables because of sharks, two routers, a generator, NetChill on-net, low-loss China reach and more. Each pays a bonus. Unmet ones make them grumpy until you fix it or they leave.</dd><dt>Customer levels</dt><dd>As your peak traffic and footprint grow, bigger customers show up: streaming startups and universities, then AI GPU data centers and cloud on-ramps, then AI training interconnects and hyperscaler DCI deals measured in terabits. Pink $$ bubbles mark the big ones.</dd><dt>L2VPN & DDoS protection</dt><dd>Businesses may want a private circuit between two of your POPs (it rides your backbone), or DDoS protection (needs your own scrubbing center).</dd><dt>NNI fabrics</dt><dd>Megapork, PocketFabric and Consolation Connect sell a port plus virtual circuits between cities. Great for small links and remote peering at an IX where you have no POP.</dd>
|
||
<dt>Conferences</dt><dd>NANOG-ish, RIPE-ish, DENOG-ish and friends come round every year. Register in the Deals tab for $8k. For 45 days after, selective networks with a presence in that region need only half the usual traffic before they peer with you. Sometimes you also win the raffle.</dd><dt>Modes</dt><dd>Sandbox gives you a billion dollars, every unlock and no failures, but no badges. Scenarios are hand-built challenges with a goal and a deadline, and the weekly challenge gives everyone the same world for a week. Share your result with the card in the menu.</dd><dt>Traceroute</dt><dd>Tap 🔍 Traceroute on any of your cities, or open it from the NOC tab, to see the exact path to a network or POP, hop by hop, with latency, the exit and the AS path.</dd><dt>Badges</dt><dd>Below your goals sits a wall of badges, from common to legendary. Some take luck, some take years, and a couple are secret. Badges you earned in earlier games stay on this device with a dashed outline.</dd><dt>The giants</dt><dd>At customer level 3 and 4, hyperscalers and AI clouds show up with deals only they would ask for: terabit AI WANs between gigawatt campuses, training runs spread over several sites, week-long dataset ingests, and hundreds of fiber pairs in a trench you dug yourself. They pay like nobody else, and they want diverse paths, two sites per metro and zero excuses. Cities near their campuses list them under “Who’s here”.</dd><dt>Auto-TE</dt><dd>Traffic follows the shortest path by distance and link metric, and reroutes by itself when links fail. When a path is merely full, the overflow is dropped, just like a real IGP. From customer level 3 you can install Auto-TE in the NOC tab: it spills overflow onto up to two alternate paths with free capacity, as long as they are no more than twice as long.</dd><dt>Metro diversity</dt><dd>A POP is one building until you add a second site in the Infra tab. Then a power cut, cleaner or A/C failure only takes out half the city, and you choose which site each transit, PNI and IX port plugs into. Spread them out, or both halves of your redundancy will sit in the same dark room. Watch out for metro ring cuts, which cut site B off.</dd><dt>Regional quirks</dt><dd>South America hangs off Miami: transit is pricier, nothing crosses the Darién Gap by land, and fiber over the Andes costs double and breaks often. IX.brrr in Brazil is run by a nonprofit with cheap public prices, and small Brazilian provedores buy transit in bulk. Inside the UAE only the duopoly may run fiber, so no dark fiber and 3× waves. Taiwan’s cables meet a lot of anchors, Indian fiber meets road widening and the monsoon, and South Africa has load shedding: bring a generator.</dd><dt>Boot times</dt><dd>Some routers take forever to boot. The Infra tab shows how long yours takes. Slow booters make crashes last longer and turn a one-router swap into a three-day outage. Bigger chassis, especially anything with a PacketOinker™ inside, are slow more often. Twin routers make it someone else’s problem.</dd><dt>Failures</dt><dd>Things break all the time: fiber cuts, router crashes, power cuts, IX loops, fabric outages, route leaks, DDoS, fat fingers, cooling failures, and geopolitics: sanctions, tariffs, BGP hijacks, landing permit disputes, exam-day shutdowns and Red Sea cable cuts. Traffic reroutes automatically over other paths and upstreams. Parallel links on diverse routes, a second router and a backup generator all help. Or pay to rush repairs.</dd>
|
||
</dl><div class="btns" style="margin-top:14px">${btn(UI.started?'Back to the map':'Got it','helpClose',{},'big')}${RELEASE_NOTES.length?btn(`What’s new in ${esc(APP_VERSION)}`,'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn('Start a new network','resetAsk',{},'ghost sm'):''}</div><div class="btns" style="margin-top:6px">${UI.started&&S&&!S.lost?btn('Export save','exportSave',{},'ghost sm'):''}${btn('Import a save','importPick',{},'ghost sm')}</div>${settingsRow()}`);
|
||
}
|
||
function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`<div class="btns" style="margin-top:8px">${btn('Share my network','share',{},'pink')}</div>`);},0);openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">You're a <span style="color:var(--me)">Tier 1</span>!</h1><p class="tagline">${esc(S.name)} (AS${S.asn}) is transit-free. You peer with every giant on the planet and pay nobody to reach the internet. Took you ${S.day} days and ${S.stats.incidents} incidents.</p>${btn('Keep building','keepPlaying',{},'pink big')}`);sfx('coin');}
|
||
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">Bankrupt</h1><p class="tagline">The bank repossessed your routers and sold them on eBuy. ${esc(S.name)} lasted ${S.day} days and peaked at ${fmtG(S.stats.peak)}.</p>${btn('Try again','newgame',{},'pink big')}`);try{localStorage.removeItem('sot-save-v1');}catch(e){}}
|
||
function openLinkModal(a,b){
|
||
if([a,b].includes('kyv')&&[a,b].includes('mos')){openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:24px">Not happening</h2><button class="x" data-act="closeModal" aria-label="Close">×</button></div><p class="lead" style="margin-top:8px">Nobody sells capacity between Kyiv and Moscow, and nobody is going to. Route through Warsaw, Bucharest or Helsinki instead.</p>`);return;}
|
||
if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:24px">Not without a license</h2><button class="x" data-act="closeModal" aria-label="Close">×</button></div><p class="lead" style="margin-top:8px">Building into mainland China needs a joint venture and an operating license. Open ${CITY[cnCity(a)?a:b].name} to apply.</p>`);return;}
|
||
let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:popCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc');
|
||
if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),same=sib.length>0&&UI.route==='same',mult=(sib.length&&!same?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
|
||
if(border)route+=`<p class="lead" style="margin-top:8px">Cross-border circuits into mainland China are sold only by licensed carriers, at 3× the price. Regular ones lose about 20% of traffic at the border.</p>${a==='hkg'||b==='hkg'?`<div class="seg">${btn('Regular crossing','cnPrem',{v:0},!UI.cnPrem?'pink':'ghost')}${btn('Premium crossing <small>+60% · ~3% loss</small>','cnPrem',{v:1},UI.cnPrem?'pink':'ghost')}</div>`:`<p class="note">Premium crossings are only sold in Hong Kong.</p>`}`;
|
||
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+=`<p class="lead" style="margin-top:8px">You already have ${sib.length} link${sib.length>1?'s':''} here (${sib.map(l=>capName(l)).join(', ')}). Parallel links add capacity. How should this one be routed?</p>
|
||
<div class="seg">${btn('Diverse route <small>+40% · survives cuts alone</small>','route',{r:'diverse'},UI.route!=='same'?'pink':'ghost')}${btn('Same trench <small>cheaper · one backhoe cuts all</small>','route',{r:'same'},UI.route==='same'?'pink':'ghost')}</div>`;}
|
||
const mode=UI.lmode==='df'?'df':'wave',tabs=`<div class="seg" style="margin-top:8px">${btn('Lease a wave','dfMode',{m:'wave'},mode==='wave'?'pink':'ghost')}${btn('Dark fiber','dfMode',{m:'df'},mode==='df'?'pink':'ghost')}</div>`;
|
||
const head=`<div style="display:flex;align-items:center"><div><div class="eyebrow">${sub?'Subsea':'Terrestrial'} · ${km.toLocaleString()} km</div><h2 style="font-size:26px">${CITY[a].name} → ${CITY[b].name}</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>${tabs}`;
|
||
if(mode==='df'){openModal(head+dfModalBody(a,b,km,pop));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))];openModal(head+`<p class="lead" style="margin-top:10px">No subsea cable lands in both ${CITY[a].name} and ${CITY[b].name}. Cables from ${CITY[a].name} reach ${fr.join(', ')||'nowhere'}. Hop through one of those.</p>`);return;}
|
||
if(isSub(a,b)&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city)){openModal(head+`<p class="lead" style="margin-top:10px">The landing permit dispute in ${CITY[S.ev.landban.city].name} blocks new subsea links for ${S.ev.landban.until-S.day} more days.</p>`);return;}
|
||
if(uaePair(a,b)||andesPair(a,b))route+=`<p class="note" style="margin-top:8px">${landWhy(a,b)}</p>`;
|
||
const wr=waveRoute(a,b,mult,border);
|
||
openModal(`${head}
|
||
<p class="lead" style="margin-top:8px">Waves are leased at a flat monthly rate. Bigger and longer costs more, and subsea is 1.8×. First month is due now.</p>
|
||
${pop?`<p class="lead" style="margin-top:8px">Includes a new POP in ${CITY[b].name} (${fmt$(popCost(b))}${ruCity(b)?', government box included':CITY[b].uae?', free-zone license included':''}).</p>`:''}${route}${viaSeg(a,b)}
|
||
<div class="tiers">${LT.map((T,i)=>{const lc=Math.round(waveMo(wr.km,wr.sub,i)*wr.wm),c=lc+pop,ok=waveOk(a,b,i);return `<button class="tierbtn" data-act="buildLink" data-args='{"tier":${i}}'${S.cash<c||!ok?' disabled':''}><span class="sz">${T.n}</span><span class="grow meta">${!ok?`needs ${esc(waveNeed(i))} at both ends`:pop?`due now ${fmt$(c)}`:'flat rate'}</span><span class="pr num">${fmt$(lc)}/mo</span></button>`;}).join('')}</div>`);
|
||
}
|
||
function dfModalBody(a,b,km,pop){
|
||
if(isSub(a,b))return `<p class="lead" style="margin-top:10px">Nobody sells dark fiber on a subsea cable here. Subsea capacity comes as leased waves.</p>`;
|
||
if(uaePair(a,b))return `<p class="lead" style="margin-top:10px">No dark fiber inside the UAE. Only the two licensed operators may run fiber here, and they only sell waves.</p>`;
|
||
if(!dfAllowed(a,b))return `<p class="lead" style="margin-top:10px">Dark fiber across the Chinese border is not for sale. Buy a cross-border wave instead.</p>`;
|
||
if(lvl()<2)return `<p class="lead" style="margin-top:10px">Dark fiber unlocks at customer level 2. You need the scale to justify buying your own optical gear.</p>`;
|
||
const src=UI.dfSrc==='build'&&lvl()>=3?'build':'lease',sys=DF_SYS[UI.dfSys]&&DF_SYS[UI.dfSys].lvl<=lvl()?UI.dfSys:'lite',amps=ampCount(km);
|
||
const up=(src==='build'?dfBuildCost(km):0)+DF_SYS[sys].cost+amps*AMP_COST+pop,mo=(src==='build'?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO;
|
||
const w=Math.round(waveMo(km,false,3));
|
||
return `<p class="lead" style="margin-top:8px">A fiber pair of your own. The glass is cheap, the gear is not: you buy a line system with an amplifier every ${AMP_EVERY} km, then optics for each channel. Your gear can fail, and you fix it.</p>
|
||
<h4 class="sub4">The glass</h4><div class="seg">${btn(`Lease an IRU <small>${fmt$(dfLeaseMo(km))}/mo · ready in 30 days</small>`,'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${btn(lvl()>=3?`Build your own <small>${fmt$(dfBuildCost(km))} · ~${dfBuildDays(km)} days</small>`:'Build your own <small>level 3</small>','dfSrc',{v:'build'},src==='build'?'pink':'ghost',lvl()<3)}</div>
|
||
${src==='build'?`<p class="note">Your own trench: almost no rent, but permits and digging take forever, and delays happen.</p>`:''}
|
||
<h4 class="sub4">Line system</h4><div class="seg">${Object.keys(DF_SYS).map(k=>btn(`${DF_SYS[k].n} <small>${DF_SYS[k].lvl>lvl()?'level '+DF_SYS[k].lvl:fmt$(DF_SYS[k].cost)}</small>`,'dfSys',{v:k},sys===k?'pink':'ghost',DF_SYS[k].lvl>lvl())).join('')}</div>
|
||
<p class="note">${esc(DF_SYS[sys].blurb)} Plus ${amps} in-line amplifier${amps===1?'':'s'} (${fmt$(AMP_COST)} each, ${fmt$(AMP_MO)}/mo for hut rent and power).</p>
|
||
<div class="kv" style="margin-top:10px"><span>Due now</span><b>${fmt$(up)}</b></div><div class="kv"><span>Monthly</span><b>${fmt$(mo)}/mo</b></div>
|
||
<p class="note">For comparison, a leased 1.6T wave on this route is ${fmt$(w)}/mo. Optics come next, from the link panel.</p>
|
||
<div class="btns" style="margin-top:10px">${btn(`${src==='build'?'Start construction':'Sign the IRU'} <small>${fmt$(up)}</small>`,'orderDf',{},'pink big',S.cash<up)}</div>`;
|
||
}
|
||
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?`Remote peering at ${esc(CITY[b].ix)} · discouraged`:pb?'Your POP':'Your POP · needs a fabric port there';
|
||
const freeA=nniPort(a,f.id)?NNI[nniPort(a,f.id).tier].g-nniUsed(a,f.id):0,freeB=remote?1e9:pb?NNI[pb.tier].g-nniUsed(b,f.id):0;
|
||
return `<div class="row"><span class="logo" style="--c:${f.col}">${initials(f)}</span><div class="grow"><div class="nm">${CITY[a].name} → ${CITY[b].name}</div><div class="meta">${label} · ${km.toLocaleString()} km${sub?' subsea':''}</div>
|
||
<div class="btns">${VXC.map((V,t)=>btn(`${V.n} <small>${fmt$(vxcMo(km,sub,t))}/mo</small>`,'buyVxc',{a,b,prov:f.id,t},'sm',(!remote&&!pb)||V.g>freeA||V.g>freeB||S.cash<vxcMo(km,sub,t))).join('')}</div></div></div>`;};
|
||
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=`<p class="empty">You need a fabric port at one of your POPs first. Open a POP's Infra tab and buy a port on ${fs.map(f=>`<b>${esc(f.name)}</b> (${f.cities.filter(c=>S.pops[c]).map(c=>CITY[c].name).join(', ')||'no POP of yours on it yet'})`).join(', ')}.</p>`;}
|
||
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">Virtual circuit over an NNI fabric</div><h2 style="font-size:26px">${from?`From ${CITY[from].name}`:`To ${CITY[to].name}`}</h2></div><button class="x" data-act="closeModal" aria-label="Close">×</button></div>
|
||
<p class="lead" style="margin-top:8px">No install fee, live in minutes, billed monthly. Cheaper than a wave for small capacity, but it rides someone else's fabric, and that fabric can fail.</p>${rows}`);
|
||
}
|
||
|
||
/* ================= CANVAS ================= */
|
||
const cv=$('map'),ctx=cv.getContext('2d');
|
||
const cam={x:1050,y:330,z:0.8};
|
||
let CW=0,CH=0,DPR=1;
|
||
function resize(){DPR=Math.min(2,window.devicePixelRatio||1);CW=innerWidth;CH=innerHeight;cv.width=CW*DPR;cv.height=CH*DPR;}
|
||
addEventListener('resize',()=>{resize();WL.key=null;renderLeft();});resize();
|
||
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;};}
|
||
function inPoly(x,y,pts){let ins=false;for(let i=0,j=pts.length-1;i<pts.length;j=i++){const [xi,yi]=pts[i],[xj,yj]=pts[j];if(((yi>y)!==(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<n;i++){const nx=pts[(i+1)%n];m=mid(pts[i],nx);p.quadraticCurveTo(pts[i][0],pts[i][1],m[0],m[1]);}p.closePath();return p;}
|
||
const LANDP=LANDS.filter(l=>!l.hide).map(l=>smoothPath(l.pts)).concat(DECOR.map(smoothPath));
|
||
const ALLPOLY=LANDS.filter(l=>!l.hide).map(l=>l.pts).concat(DECOR);
|
||
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(LANDS.some(l=>inPoly(x,y,l.pts))&&!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=[];
|
||
function floater(x,y,text,col){if(!animOn())return;FLOATS.push({x,y,text,col,t:performance.now()});}
|
||
/* Animation setting: auto follows the system's reduced-motion preference, or force it on or off. */
|
||
function settingsRow(){const seg=(lab,act,cur,opts)=>`<div class="setline"><span>${lab}</span><div class="seg">${opts.map(([v,l])=>btn(l,act,{v},cur===v?'pink sm':'ghost sm')).join('')}</div></div>`;
|
||
return `<div class="setrow"><h3 style="font-size:15px;margin:12px 0 4px">Settings</h3>${seg('Animations','animSet',UI.anim||'auto',[['auto','Auto'],['on','On'],['off','Off']])}${seg('Sound','soundSet',UI.muted?'off':'on',[['on','On'],['off','Off']])}<p class="meta" style="margin:2px 0 0">Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.</p></div>`;}
|
||
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);
|
||
function rr(x,y,w,h,r){ctx.beginPath();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();}
|
||
function visibleKs(){const ks=[];for(const k of [-1,0,1]){const a=toS(0,0,k)[0],b=toS(W,0,k)[0];if(b>-200&&a<CW+200)ks.push(k);}return ks;}
|
||
const GEO=new Map();
|
||
function linkGeom(l){const i=pairLinks(l.a,l.b).indexOf(l);const key=l.id+'|'+i+'|'+(l.cable||'');const h=GEO.get(key);if(h)return h;
|
||
let pts=null;if(l.cable){const cp=cablePair(l.cable,l.a,l.b);if(cp){pts=cp.pts.map(p=>p.slice());const same=pairLinks(l.a,l.b).filter(x=>x.cable===l.cable).indexOf(l);if(same>0)for(let j=1;j<pts.length-1;j++){pts[j][1]+=same*5;}}}
|
||
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;j<pts.length;j++){L+=Math.hypot(pts[j][0]-pts[j-1][0],pts[j][1]-pts[j-1][1]);cum.push(L);}for(let j=0;j<cum.length;j++)cum[j]/=L||1;
|
||
const g={pts,cum,len:L};GEO.set(key,g);return g;}
|
||
function polyAt(sp,cum,t){let i=1;while(i<cum.length-1&&cum[i]<t)i++;const t0=cum[i-1],t1=cum[i],f=t1>t0?(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];}
|
||
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);}
|
||
function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!worldLayer(z);
|
||
if(!selC&&z<1.7&&cached)return;
|
||
ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';
|
||
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;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]<mn)mn=q[0];if(q[0]>mx)mx=q[0];}if(mx<-20||mn>CW+20)continue;
|
||
if(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<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);ctx.stroke();ctx.setLineDash([]);}
|
||
if(hot||z>=1.7){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);}
|
||
ctx.globalAlpha=1;}}}
|
||
function bezGeom(l){const A=CITY[l.a],B=CITY[l.b];const i=pairLinks(l.a,l.b).indexOf(l);const key=l.id+'|'+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;}
|
||
const base=Math.max(10,Math.min(len*0.13,110)),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?0.2:1)+Math.ceil(i/2)*16);
|
||
const mx=(A.x+bx)/2,my=(A.y+by)/2;
|
||
const obs=CITIES.filter(c=>c.id!==l.a&&c.id!==l.b).map(c=>[mx+wrapDx(mx,c.x),c.y]);
|
||
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<m)m=d;}}return m;};
|
||
const sg=Math.sign(off0)||1,mag=Math.abs(off0);
|
||
const cand=[1,1.5,2.1,2.9,3.8].map(k=>sg*mag*k).concat([1,1.5,2.1,2.9,3.8].map(k=>-sg*Math.max(mag,base)*k));
|
||
let best=null,bc=-1;
|
||
for(const off of cand){const cx=mx+nx*off,cy=my+ny*off,c=clear(cx,cy);if(c>=24){best=[cx,cy];break;}if(c>bc){bc=c;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';
|
||
|
||
function draw(now){
|
||
if(!ctx)return;
|
||
ctx.setTransform(DPR,0,0,DPR,0,0);
|
||
// sea
|
||
const g=ctx.createLinearGradient(0,0,0,CH);g.addColorStop(0,'#62CBEA');g.addColorStop(1,'#43AED6');ctx.fillStyle=g;ctx.fillRect(0,0,CW,CH);
|
||
const ks=visibleKs(),z=cam.z;
|
||
const wl=worldLayer(z);
|
||
for(const k of ks){
|
||
ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2));
|
||
// waves: one path, one stroke
|
||
ctx.strokeStyle='rgba(255,255,255,.45)';ctx.lineWidth=2/z;ctx.lineCap='round';ctx.beginPath();
|
||
const ph0=now/900;for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;ctx.moveTo(x-9+o,y);ctx.quadraticCurveTo(x-4.5+o,y-4,x+o,y);ctx.quadraticCurveTo(x+4.5+o,y+4,x+9+o,y);}ctx.stroke();
|
||
if(wl){ctx.setTransform(1,0,0,1,0,0);ctx.drawImage(wl.cv,Math.round(DPR*((k*W-cam.x)*z+CW/2)),Math.round(DPR*((-cam.y)*z+CH/2)));ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2));}else paintWorld(ctx,z,true);
|
||
// clouds
|
||
ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath();
|
||
for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100,y=c.y;ctx.moveTo(x+16*c.s,y);ctx.arc(x,y,16*c.s,0,7);ctx.moveTo(x+38*c.s,y-8*c.s);ctx.arc(x+18*c.s,y-8*c.s,20*c.s,0,7);ctx.moveTo(x+55*c.s,y);ctx.arc(x+40*c.s,y,15*c.s,0,7);}ctx.fill();
|
||
}
|
||
ctx.setTransform(DPR,0,0,DPR,0,0);
|
||
if(!S)return;
|
||
const sc=iconScale(),day=S.day;
|
||
// cable systems
|
||
drawCables(ks);
|
||
// links
|
||
for(const l of S.links){
|
||
const gm=linkGeom(l),cap=capOf(l),load=R.load[l.id]||0,u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&linkDown(l)&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc';
|
||
const sel=UI.sel&&UI.sel.type==='link'&&UI.sel.id===l.id;
|
||
const w=(vx?2.2:(2.5+tierW(l)*1.8))*sc;
|
||
for(const k of ks){
|
||
const sp=gm.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]<mn)mn=q[0];if(q[0]>mx)mx=q[0];}
|
||
if(mx<-40||mn>CW+40)continue;
|
||
const path=()=>{ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);};
|
||
ctx.lineCap='round';ctx.lineJoin='round';
|
||
if(sel){ctx.strokeStyle='rgba(255,79,154,.35)';ctx.lineWidth=w+14;path();ctx.stroke();}
|
||
ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(cut?[8,8]:vx?[2,7]:bld?[10,8]:[]);path();ctx.stroke();
|
||
ctx.strokeStyle=bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]);
|
||
if(df&&!bld&&!dark){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);path();ctx.stroke();ctx.setLineDash([]);}
|
||
const at=t=>polyAt(sp,gm.cum,t);
|
||
if(!cut&&load>0.01){const n=clamp(Math.round(2+u*10),2,12),len=gm.len*z,spd=90;
|
||
ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;
|
||
const rr2=Math.max(2.2,w*.42),base=now/1000*spd/Math.max(len,40);ctx.beginPath();for(let i=0;i<n;i++){let t=(base+i/n)%1;if(i%2)t=1-t;const [px,py]=at(t);ctx.moveTo(px+rr2,py);ctx.arc(px,py,rr2,0,7);}ctx.fill();ctx.stroke();}
|
||
const [mx2,my]=at(.5);const mxx=mx2;
|
||
if(bld){drawCone(mxx,my,now);}
|
||
else if(cut&&!vx){drawBackhoe(mxx,my,now,l.sub);}
|
||
else if(z>0.9||sel){const t=capName(l);ctx.font='800 11px "Baloo 2", sans-serif';const tw=ctx.measureText(t).width+10;ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);}
|
||
}
|
||
}
|
||
// drag preview
|
||
if(UI.drag&&UI.drag.mode==='link'){
|
||
const A=CITY[UI.drag.from];let tx=UI.drag.cx,ty=UI.drag.cy;
|
||
if(UI.snap){const sv=UI.snap;tx=sv.sx;ty=sv.sy;}
|
||
let [ax,ay]=toS(A.x,A.y,0);if(UI.snap){const B=CITY[UI.snap.id];const bxw=A.x+wrapDx(A.x,B.x);[tx,ty]=toS(bxw,B.y,0);}else{/* nearest copy of origin to cursor */for(const k of [-1,1]){const [px,py]=toS(A.x,A.y,k);if(Math.abs(px-tx)<Math.abs(ax-tx)){ax=px;ay=py;}}}
|
||
if(UI.snap){const B=CITY[UI.snap.id];const wx=A.x+wrapDx(A.x,B.x);for(const k of [-1,1]){const [px,py]=toS(A.x,A.y,k),[qx]=toS(wx,B.y,k);if(Math.abs(qx-CW/2)<Math.abs(tx-CW/2)){ax=px;ay=py;tx=qx;}}}
|
||
ctx.strokeStyle='#1E2640';ctx.lineWidth=7;ctx.lineCap='round';ctx.setLineDash([2,12]);ctx.beginPath();ctx.moveTo(ax,ay);ctx.lineTo(tx,ty);ctx.stroke();
|
||
ctx.strokeStyle='#FF4F9A';ctx.lineWidth=4;ctx.lineDashOffset=-now/30;ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;
|
||
if(UI.snap&&UI.snap.id!==UI.drag.from){const b=UI.snap.id,km=kmBetween(UI.drag.from,b),sub=isSub(UI.drag.from,b);
|
||
const t=`${km.toLocaleString()} km${sub?' · subsea':''} · ${sub&&!cablesFor(UI.drag.from,b).length?'no cable lands here':'from '+fmt$(waveMo(km,sub,0))+'/mo'}`;
|
||
ctx.font='800 13px "Baloo 2", sans-serif';const tw=ctx.measureText(t).width+18;const lx=(ax+tx)/2,ly=(ay+ty)/2-22;
|
||
ctx.fillStyle='#1E2640';rr(lx-tw/2,ly-12,tw,24,12);ctx.fill();ctx.fillStyle='#fff';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,lx,ly+1);}
|
||
}
|
||
// cities
|
||
UI.feed=null;if(UI.sel&&UI.sel.type==='link'){const sl=S.links.find(x=>x.id===UI.sel.id);const rec=sl&&R.ef[edgeKey(sl)];if(rec){UI.feed=new Set(Object.keys(rec.eg).map(k=>R.egDesc[k].city));UI.dest=new Set(Object.keys(rec.dst));}}
|
||
// Place labels: your POPs and the selected city first, then others; a label that would overlap moves above its city or hides.
|
||
const vis=[];for(const C of CITIES)for(const k of ks){const [sx,sy]=toS(C.x,C.y,k);if(sx<-60||sx>CW+60||sy<-60||sy>CH+60)continue;vis.push({C,sx,sy});}
|
||
const prio=v=>(UI.sel&&UI.sel.type==='city'&&UI.sel.id===v.C.id?0:S.pops[v.C.id]?1:2);vis.sort((a,b)=>prio(a)-prio(b)||b.C.P-a.C.P);
|
||
const rects=[],hit=(r)=>rects.some(q=>r.x<q.x+q.w&&q.x<r.x+r.w&&r.y<q.y+q.h&&q.y<r.y+r.h);
|
||
for(const v of vis){const h=(12+Math.sqrt(v.C.P)*0.75)*sc;rects.push({x:v.sx-18*sc,y:v.sy-h-4*sc,w:40*sc,h:h+14*sc});}
|
||
for(const v of vis){const p=S.pops[v.C.id];ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const tw=(LBLW[v.C.id+(p?1:0)]||(LBLW[v.C.id+(p?1:0)]=ctx.measureText(v.C.name).width+14));
|
||
const h=12+Math.sqrt(v.C.P)*0.75;const below=v.sy+16*sc+8,above=v.sy-h*sc-17*sc;let ly=null;
|
||
for(const y of [below,above]){const r={x:v.sx-tw/2-2,y:y-10,w:tw+4,h:21};if(!hit(r)){ly=y;rects.push(r);break;}}
|
||
if(ly===null&&prio(v)<2){ly=below;rects.push({x:v.sx-tw/2,y:below-10,w:tw,h:21});}
|
||
v.ly=ly;}
|
||
for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly);
|
||
// floaters
|
||
for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;}
|
||
for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}}
|
||
}
|
||
function drawCone(x,y,now){const b=Math.sin(now/300)*1.5;ctx.save();ctx.translate(x,y-12+b);ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();ctx.restore();}
|
||
// Static land + cable map, rendered once per zoom bucket into an offscreen canvas.
|
||
function paintWorld(c,z,withCables){
|
||
for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle='rgba(20,90,130,.35)';for(const p of LANDP)c.fill(p);c.restore();}
|
||
c.strokeStyle='#F8E6A8';c.lineWidth=10/z;c.lineJoin='round';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();}
|
||
c.fillStyle='#9BDA6C';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.fill(p);c.restore();}
|
||
c.fillStyle='#86CB5B';c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x+r*1.4,y);c.ellipse(x,y,r*1.4,r*.8,0,0,Math.PI*2);}c.fill();
|
||
c.fillStyle='rgba(255,255,255,.18)';c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x-r*.3+r*.6,y-r*.25);c.ellipse(x-r*.3,y-r*.25,r*.6,r*.3,0,0,Math.PI*2);}c.fill();
|
||
c.strokeStyle='#1E2640';c.lineWidth=2.5/z;for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();}
|
||
if(withCables)for(const off of [0,W,-W]){c.save();c.translate(off,0);for(const cp of CABLE_PAIRS){const C=CAB[cp.cid];c.globalAlpha=0.4;c.strokeStyle=cableCol(C);c.lineWidth=1.6/z;c.lineJoin='round';c.setLineDash(C.age==='old'?[6/z,5/z]:[]);c.beginPath();c.moveTo(cp.pts[0][0],cp.pts[0][1]);for(let i=1;i<cp.pts.length;i++)c.lineTo(cp.pts[i][0],cp.pts[i][1]);c.stroke();}c.restore();}
|
||
c.globalAlpha=1;c.setLineDash([]);
|
||
}
|
||
const WL={key:null,cv:null,zAt:0,lastZ:0};const MAXPX=4096;
|
||
// Cache at the exact on-screen scale, so drawing it is a plain copy. While the zoom is changing we draw vectors instead.
|
||
function worldLayer(z){
|
||
const now=performance.now();if(z!==WL.lastZ){WL.lastZ=z;WL.zAt=now;}
|
||
const sc=z*DPR,key=sc.toFixed(4);if(WL.key===key)return WL;
|
||
if(W*sc>MAXPX||now-WL.zAt<250)return null;
|
||
const cv2=WL.cv||document.createElement('canvas');cv2.width=Math.ceil(W*sc)+2;cv2.height=Math.ceil(H*sc)+2;
|
||
const c=cv2.getContext('2d');if(!c)return null;c.setTransform(sc,0,0,sc,0,0);paintWorld(c,z,true);WL.cv=cv2;WL.key=key;return WL;
|
||
}
|
||
function cableCol(C){return C.price<=0.85?'#14A88C':C.price<=1.1?'#2F7BEA':'#A05AE0';}
|
||
function drawBackhoe(x,y,now,sub){
|
||
const b=Math.sin(now/180)*2;ctx.save();ctx.translate(x,y-14+b);
|
||
ctx.strokeStyle='#1E2640';ctx.lineWidth=2.2;
|
||
if(sub){ // shark fin
|
||
ctx.fillStyle='#6B7C99';ctx.beginPath();ctx.moveTo(-12,8);ctx.quadraticCurveTo(-2,-14,10,-12);ctx.quadraticCurveTo(4,-2,12,8);ctx.closePath();ctx.fill();ctx.stroke();
|
||
}else{
|
||
ctx.fillStyle='#FFD23F';rr(-12,-4,18,12,3);ctx.fill();ctx.stroke();rr(-8,-12,10,9,2);ctx.fillStyle='#BDE8FF';ctx.fill();ctx.stroke();
|
||
ctx.beginPath();ctx.moveTo(6,0);ctx.lineTo(14,-10);ctx.lineTo(19,2);ctx.stroke();ctx.fillStyle='#1E2640';ctx.beginPath();ctx.arc(-7,10,3,0,7);ctx.arc(2,10,3,0,7);ctx.fill();
|
||
}
|
||
ctx.restore();
|
||
}
|
||
const LBLW={};
|
||
function drawCity(C,sx,sy,sc,now,lyOverride){
|
||
const hot=(UI.hotMap||{})[C.id];
|
||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||
const k=sc*(hov?1.15:1);
|
||
ctx.save();ctx.translate(sx,sy);
|
||
if(UI.feed&&UI.feed.has(C.id)){ctx.strokeStyle='#FF8A3D';ctx.lineWidth=4;ctx.setLineDash([3,5]);ctx.beginPath();ctx.arc(0,-6*k,36*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||
if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=3;ctx.setLineDash([6,6]);ctx.lineDashOffset=-now/40;ctx.beginPath();ctx.arc(0,-6*k,30*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||
if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9){const a=.35+.25*Math.sin(now/200);ctx.fillStyle=`rgba(255,77,94,${a})`;ctx.beginPath();ctx.arc(0,-6*k,26*k,0,7);ctx.fill();}
|
||
ctx.scale(k,k);
|
||
ctx.fillStyle='rgba(30,38,64,.2)';ctx.beginPath();ctx.ellipse(0,9,20,5,0,0,7);ctx.fill();
|
||
const h=12+Math.sqrt(C.P)*0.75;
|
||
const bl=[[-15,h*.65,'#FFFFFF'],[-5,h,'#FFE7A1'],[5,h*.5,'#BDE8FF']];
|
||
ctx.strokeStyle='#1E2640';ctx.lineWidth=2.2;
|
||
for(const [x,hh,col] of bl){ctx.fillStyle=col;rr(x,8-hh,10,hh,2);ctx.fill();ctx.stroke();}
|
||
ctx.fillStyle='rgba(30,38,64,.35)';ctx.beginPath();for(const [x,hh] of bl)for(let yy=8-hh+4;yy<5;yy+=5){ctx.rect(x+2.5,yy,2,2);ctx.rect(x+5.5,yy,2,2);}ctx.fill();
|
||
if(p){
|
||
ctx.translate(0,2);
|
||
ctx.lineWidth=2.4;ctx.beginPath();ctx.moveTo(-10,-6);ctx.lineTo(-13,-17);ctx.moveTo(10,-6);ctx.lineTo(13,-17);ctx.stroke();
|
||
ctx.fillStyle=down?'#FF4D5E':'#FFD23F';ctx.beginPath();ctx.arc(-13,-18,2.6,0,7);ctx.arc(13,-18,2.6,0,7);ctx.fill();ctx.stroke();
|
||
if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-13,-13,34,16,6);ctx.fill();ctx.stroke();}
|
||
if(p.gen){ctx.fillStyle='#FFD23F';rr(-27,-1,9,11,2);ctx.fill();ctx.stroke();}
|
||
ctx.fillStyle=down?'#8A91A8':'#FF4F9A';rr(-17,-7,34,16,6);ctx.fill();ctx.stroke();
|
||
if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const t=(now/700+i/3)%1;ctx.fillStyle=`rgba(90,98,130,${0.55*(1-t)})`;ctx.beginPath();ctx.arc(6+i*3,-12-t*18,3+t*4,0,7);ctx.fill();}}
|
||
if((p.rgen||0)>0){ctx.fillStyle='#FFD23F';ctx.beginPath();ctx.arc(17,-7,6,0,7);ctx.fill();ctx.lineWidth=1.8;ctx.stroke();ctx.fillStyle='#1E2640';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(String((p.rgen||0)+1),17,-6.5);ctx.lineWidth=2.2;}
|
||
const sf=sfOf(R,C.id);
|
||
for(let i=0;i<4;i++){const on=down?false:(((now/(160+i*37))|0)+i)%3!==0;ctx.fillStyle=down?'#3B4260':on?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';ctx.beginPath();ctx.arc(-10+i*6.6,1,2.1,0,7);ctx.fill();}
|
||
if(down){ctx.fillStyle='#fff';ctx.font='900 14px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.fillText('zzz',20,-14);}
|
||
ctx.translate(0,-2);
|
||
}
|
||
const ixn=ixName(C.id);
|
||
if(ixn){const mine=!!S.myIx[C.id],joined=S.ixp[C.id]!==undefined;const ixHot=hot&&hot.ix;ctx.fillStyle=ixHot?(Math.sin(now/180)>0?'#FF4D5E':'#FF8A3D'):mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(19+8.5*Math.cos(a),-h+2+8.5*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=2;ctx.stroke();
|
||
ctx.fillStyle=mine||ixHot?'#fff':'#1E2640';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',19,-h+2.5);}
|
||
if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const k of ['r','t','p','c']){if(!hot[k])continue;ctx.globalAlpha=pulse;ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-29,y,6.5,0,7);ctx.fill();ctx.globalAlpha=1;ctx.lineWidth=2;ctx.strokeStyle='#1E2640';ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(HOTL[k],-29,y+0.5);y+=14;}}
|
||
const off=S.offers.some(o=>bCities(o).includes(C.id));
|
||
if(off){const by=-h-16+Math.sin(now/250)*3;ctx.fillStyle='#fff';ctx.lineWidth=2.2;ctx.beginPath();ctx.ellipse(-2,by,11,9,0,0,7);ctx.fill();ctx.stroke();ctx.beginPath();ctx.moveTo(-5,by+8);ctx.lineTo(-7,by+14);ctx.lineTo(0,by+8);ctx.fillStyle='#fff';ctx.fill();const big=S.offers.some(o=>bCities(o).includes(C.id)&&(BIZ_T[o.type].lv>=3||BIZ_T[o.type].event));ctx.fillStyle=big?'#FF4F9A':'#16A866';ctx.font='900 13px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(big?'$$':'$',-2,by+1);}
|
||
const inc=S.inc.some(i=>i.ref===C.id&&i.type!=='leak');
|
||
if(inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);}
|
||
ctx.restore();
|
||
// label
|
||
if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){
|
||
ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=ctx.measureText(t).width+14,ly=lyOverride==null?sy+16*sc+8:lyOverride;
|
||
ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(sx-tw/2,ly-9,tw,19,9);ctx.fill();ctx.stroke();
|
||
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);
|
||
}
|
||
}
|
||
|
||
/* ---------- hit tests & input ---------- */
|
||
function hitCity(x,y,r=28){let best=null,bd=r*iconScale();for(const C of CITIES)for(const k of [-1,0,1]){const [sx,sy]=toS(C.x,C.y,k);const d=Math.hypot(sx-x,sy+4-y);if(d<bd){bd=d;best={id:C.id,sx,sy};}}return best;}
|
||
function hitLink(x,y){if(!S)return null;let best=null,bd=12;for(const l of S.links){const g=linkGeom(l);for(const k of [-1,0,1]){let prev=null;for(const p of g.pts){const q=toS(p[0],p[1],k);if(prev){const d=segDist(x,y,prev,q);if(d<bd){bd=d;best=l.id;}}prev=q;}}}return best;}
|
||
function wrapCam(){cam.x=((cam.x%W)+W)%W;cam.y=clamp(cam.y,0,H);}
|
||
const ptrs=new Map();
|
||
cv.addEventListener('pointerdown',e=>{audioInit();cv.setPointerCapture(e.pointerId);ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
|
||
if(ptrs.size===2){const [a,b]=[...ptrs.values()];UI.drag={mode:'pinch',d0:Math.hypot(a.x-b.x,a.y-b.y)||1,z0:cam.z};return;}
|
||
const hit=S&&hitCity(e.clientX,e.clientY);
|
||
if(hit&&S.pops[hit.id])UI.drag={mode:'maybeLink',from:hit.id,sx:e.clientX,sy:e.clientY,camx:cam.x,camy:cam.y,moved:false};
|
||
else UI.drag={mode:'pan',sx:e.clientX,sy:e.clientY,camx:cam.x,camy:cam.y,moved:false};
|
||
});
|
||
cv.addEventListener('pointermove',e=>{
|
||
if(ptrs.has(e.pointerId))ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
|
||
const d=UI.drag;
|
||
if(!d){const h=S&&hitCity(e.clientX,e.clientY);UI.hover=h?h.id:null;cv.style.cursor=h?(S.pops[h.id]?'crosshair':'pointer'):(hitLink(e.clientX,e.clientY)?'pointer':'grab');return;}
|
||
if(d.mode==='pinch'&&ptrs.size===2){const [a,b]=[...ptrs.values()];const mx=(a.x+b.x)/2,my=(a.y+b.y)/2;zoomAt(mx,my,clamp(d.z0*Math.hypot(a.x-b.x,a.y-b.y)/d.d0,0.35,3)/cam.z);return;}
|
||
const dx=e.clientX-d.sx,dy=e.clientY-d.sy;if(Math.hypot(dx,dy)>6)d.moved=true;
|
||
if(d.mode==='maybeLink'&&d.moved){d.mode='link';cv.classList.add('linking');}
|
||
if(d.mode==='link'){d.cx=e.clientX;d.cy=e.clientY;const h=hitCity(e.clientX,e.clientY,40);UI.snap=h&&h.id!==d.from?h:null;renderHint();}
|
||
else if(d.mode==='pan'&&d.moved){cam.x=d.camx-dx/cam.z;cam.y=d.camy-dy/cam.z;wrapCam();cv.style.cursor='grabbing';}
|
||
});
|
||
function endPtr(e){
|
||
ptrs.delete(e.pointerId);const d=UI.drag;if(!d)return;
|
||
if(d.mode==='pinch'){if(ptrs.size===0)UI.drag=null;return;}
|
||
if(d.mode==='link'){if(UI.snap&&UI.snap.id!==d.from){openLinkModal(d.from,UI.snap.id);sfx('click');}}
|
||
else if(!d.moved&&S){const h=hitCity(e.clientX,e.clientY);
|
||
if(h){selectCity(h.id);sfx('click');}
|
||
else{const l=hitLink(e.clientX,e.clientY);if(l){UI.sel={type:'link',id:l};UI.confirm=null;renderPanel();sfx('click');}else{UI.sel=null;renderPanel();}}}
|
||
UI.drag=null;UI.snap=null;cv.classList.remove('linking');cv.style.cursor='grab';renderHint();
|
||
}
|
||
cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',endPtr);
|
||
function zoomAt(mx,my,f){const wx=cam.x+(mx-CW/2)/cam.z,wy=cam.y+(my-CH/2)/cam.z;cam.z=clamp(cam.z*f,0.35,6);cam.x=wx-(mx-CW/2)/cam.z;cam.y=wy-(my-CH/2)/cam.z;wrapCam();}
|
||
cv.addEventListener('wheel',e=>{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false});
|
||
addEventListener('keydown',e=>{if(e.target.tagName==='INPUT')return;if(e.code==='Space'){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}});
|
||
|
||
/* ---------- click delegation ---------- */
|
||
let pressing=false;
|
||
document.addEventListener('pointerdown',e=>{if(e.target.closest('#panel,#left'))pressing=true;});
|
||
addEventListener('pointerup',()=>setTimeout(()=>pressing=false,0));
|
||
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','scenarios','startScn','startWeekly'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
|
||
|
||
/* ================= LOOP ================= */
|
||
let last=performance.now(),acc=0,hudT=0;
|
||
function frame(now){
|
||
const dt=Math.min(250,now-last);last=now;
|
||
if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);}
|
||
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
|
||
if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4){acc-=DAY_MS;dayTick();n++;}
|
||
if(n){renderHUD();if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}}
|
||
draw(animOn()?now:0);
|
||
if(!window.__TUBES_TEST__)requestAnimationFrame(frame);
|
||
}
|
||
function boot(data){
|
||
try{UI.muted=localStorage.getItem('sot-mute')==='1';UI.anim=localStorage.getItem('sot-anim')||'auto';}catch(e){}
|
||
applyAnim();
|
||
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
|
||
else{const sv=loadSave();
|
||
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){S=null;UI.started=false;try{localStorage.setItem('sot-save-broken',JSON.stringify(sv));localStorage.removeItem('sot-save-v1');}catch(e2){}}}
|
||
if(okSave){UI.started=true;UI.speed=[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;}}
|
||
renderAll();if(!whatsNew(true))toast(`<b>Welcome back, ${esc(S.name)}.</b><br>Your network is right where you left it: ${dateStr(S.day)}.`,'good');}
|
||
else{showTitle();whatsNew(false);if(sv)toast('<b>Your saved game could not be loaded.</b><br>It was damaged, so a backup was kept and you can start fresh.','bad');}}
|
||
renderHUD();renderLeft();
|
||
window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}}));
|
||
if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);}
|
||
}
|
||
window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {});
|
||
</script>
|
||
|
||
</body>
|
||
</html>
|