shipbuilding.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import {cachedFetchJSON} from './cache';
  2. import {setupPopover} from './popover';
  3. const BUY = new Set([
  4. // definitely buy
  5. 'C', 'FLX', 'H', 'H2O', 'HAL', 'HCP', 'HE', 'LST', 'MG', 'N', 'NA', 'NCS', 'NS', 'O', 'PE', 'PG', 'S', 'TCL', 'THF',
  6. // maybe buy
  7. 'AIR', 'AU', 'BE', 'BRM', 'BOR', 'BTS', 'CU', 'FAN', 'FC', 'FE', 'HCC', 'HD', 'LDI', 'LI', 'MFK', 'MWF',
  8. 'REA', 'RG', 'RGO', 'ROM', 'SFK', 'SI', 'STL', 'TCO', 'TPU',
  9. // import
  10. 'AAR', 'AWF', 'CAP', 'CF', 'RAD',
  11. // skip
  12. 'LFE', 'LHP', 'MFE', 'SFE', 'SSC',
  13. ])
  14. const blueprint = {
  15. 'FFC': 1,
  16. 'FSE': 1,
  17. 'LFE': 2,
  18. 'MFE': 2,
  19. 'RCT': 1,
  20. 'SFE': 1,
  21. 'LCB': 1,
  22. 'MFL': 1,
  23. 'MSL': 1,
  24. 'LHP': 94,
  25. 'SSC': 128,
  26. 'BR1': 1,
  27. 'CQM': 1,
  28. }
  29. const shipbuilders = [
  30. 'CraftsmanThirteen',
  31. 'EvoV',
  32. 'MapReduce',
  33. 'SurvivorBob',
  34. 'TRUEnterprises',
  35. ];
  36. const main = document.querySelector('main.shipbuilding')!;
  37. (async () => {
  38. setupPopover();
  39. main.innerHTML = 'loading...';
  40. try {
  41. await render();
  42. } catch (e) {
  43. main.innerHTML = e instanceof Error ? e.message : String(e);
  44. }
  45. })();
  46. async function render() {
  47. const [allPrices, recipes, buildingList, knownCompanies, companyProductionById] = await Promise.all([
  48. cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
  49. recipeForMats(),
  50. cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
  51. cachedFetchJSON('https://pmmg-products.github.io/reports/data/knownCompanies.json') as Promise<Record<string, {Username: string}>>,
  52. pmmgMonthlyReport(),
  53. ]);
  54. const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === 'IC1')
  55. .map((price) => [price.MaterialTicker, price]));
  56. const buildings = Object.fromEntries(buildingList.map((b) => [b.building_ticker, b]));
  57. const production: Production = {};
  58. const extract: Record<string, number> = {};
  59. const buy: Record<string, number> = {};
  60. const analysisNodes: AnalysisNode[] = [];
  61. let cost = 0;
  62. for (const [mat, amount] of Object.entries(blueprint)) {
  63. const { cost: matCost, node } = analyzeMat(mat, amount, production, extract, buy, prices, recipes);
  64. cost += matCost;
  65. analysisNodes.push(node);
  66. }
  67. // requiredMats = buy + production
  68. const requiredMats: Record<string, number> = {...buy};
  69. for (const buildingProduction of Object.values(production))
  70. for (const [mat, amount] of Object.entries(buildingProduction))
  71. requiredMats[mat] = (requiredMats[mat] ?? 0) + amount;
  72. const expertiseGroups: Record<string, string[]> = {};
  73. for (const building of buildingList) {
  74. if (!(building.building_ticker in production))
  75. continue;
  76. if (!expertiseGroups[building.expertise])
  77. expertiseGroups[building.expertise] = [];
  78. expertiseGroups[building.expertise].push(building.building_ticker);
  79. }
  80. main.innerHTML = '';
  81. main.append(
  82. renderAnalysis(analysisNodes),
  83. element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
  84. renderProduction(expertiseGroups, production, prices, recipes, buildings),
  85. renderMatList('extract', extract),
  86. renderMatList('buy', buy),
  87. renderShipbuilders(requiredMats, knownCompanies, companyProductionById),
  88. );
  89. }
  90. function renderMatList(header: string, mats: Record<string, number>): HTMLElement {
  91. const section = element('section');
  92. section.append(element('h2', {textContent: header}));
  93. const matsSorted = Object.entries(mats).sort(([a], [b]) => a.localeCompare(b));
  94. section.append(element('p', {
  95. textContent: matsSorted.map(([mat, amount]) => `${formatAmount(amount)}x${mat}`).join(', '),
  96. }));
  97. return section;
  98. }
  99. async function pmmgMonthlyReport(): Promise<PMMGCompanyProduction> {
  100. const constants = await fetch('https://raw.githubusercontent.com/PMMG-Products/pmmg-products.github.io/main/reports/src/staticData/constants.ts')
  101. .then((res) => res.text());
  102. const match = constants.match(/export const months = \[(.*?)\];/s);
  103. if (!match)
  104. throw new Error('failed to parse PMMG months');
  105. const months = match[1].split(',').map((m) => m.trim().replace(/^"|"$/g, ''));
  106. const latestMonth = months.at(-1);
  107. if (!latestMonth)
  108. throw new Error('missing PMMG month');
  109. const report = await cachedFetchJSON(`https://pmmg-products.github.io/reports/data/company-data-${latestMonth}.json`);
  110. return report['individual'];
  111. }
  112. function renderShipbuilders(requiredMats: Record<string, number>,
  113. knownCompanies: Record<string, {Username: string}>, companyProductionById: PMMGCompanyProduction): HTMLElement {
  114. const matTickers = Object.keys(requiredMats).sort();
  115. const shipbuilderSet = new Set(shipbuilders);
  116. const shipbuildersById: Record<string, string> = {};
  117. for (const [companyId, company] of Object.entries(knownCompanies))
  118. if (shipbuilderSet.has(company.Username))
  119. shipbuildersById[companyId] = company.Username;
  120. const missingShipbuilders = shipbuilders
  121. .filter((username) => !Object.values(shipbuildersById).includes(username));
  122. if (missingShipbuilders.length > 0)
  123. return element('h3', {textContent: `missing shipbuilders in PMMG report: ${missingShipbuilders.join(', ')}`});
  124. const section = element('section');
  125. section.append(element('h2', {textContent: 'shipbuilders'}));
  126. const table = element('table');
  127. const header = element('tr');
  128. header.append(element('th', {textContent: 'mat'}));
  129. header.append(element('th', {textContent: 'amount'}));
  130. for (const username of Object.values(shipbuildersById))
  131. header.append(element('th', {textContent: username}));
  132. table.append(header);
  133. for (const mat of matTickers) {
  134. const row = element('tr');
  135. row.append(element('td', {textContent: mat}));
  136. row.append(element('td', {textContent: formatAmount(requiredMats[mat])}));
  137. for (const companyId of Object.keys(shipbuildersById)) {
  138. const makes = mat in companyProductionById[companyId];
  139. row.append(element('td', {textContent: makes ? '' : 'x'}));
  140. }
  141. table.append(row);
  142. }
  143. section.append(table);
  144. return section;
  145. }
  146. async function recipeForMats(): Promise<Record<string, Recipe>> {
  147. const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
  148. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  149. for (const recipe of allRecipes)
  150. for (const output of recipe.outputs) {
  151. const recipes = matRecipes[output.material_ticker];
  152. if (recipes)
  153. recipes.push(recipe);
  154. else
  155. matRecipes[output.material_ticker] = [recipe];
  156. }
  157. const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
  158. for (const [mat, recipes] of Object.entries(matRecipes))
  159. if (recipes.length === 1)
  160. matRecipe[mat] = recipes[0];
  161. return matRecipe;
  162. }
  163. function analyzeMat(mat: string, amount: number, production: Production, extract: Record<string, number>, buy: Record<string, number>,
  164. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): { cost: number, node: AnalysisNode } {
  165. const price = prices[mat];
  166. if (!price)
  167. throw new Error(`missing price for ${mat}`);
  168. const traded = price.AverageTraded30D ?? 0;
  169. if (BUY.has(mat)) {
  170. const matPrice = price.VWAP30D ?? price.Ask;
  171. if (matPrice == null) throw new Error(`missing ask price for ${mat}`);
  172. buy[mat] = (buy[mat] ?? 0) + amount;
  173. return {
  174. cost: matPrice * amount,
  175. node: { text: `${formatAmount(amount)}x${mat} buy: ${formatAmount(matPrice)}, daily traded ${formatFixed(traded, 1)}`, children: [] },
  176. };
  177. }
  178. const recipe = recipes[mat];
  179. if (!recipe) {
  180. extract[mat] = (extract[mat] ?? 0) + amount;
  181. return { cost: 0, node: { text: `${formatAmount(amount)}x${mat} extract`, children: [] } };
  182. }
  183. const building = recipe.building_ticker;
  184. if (!production[building])
  185. production[building] = {};
  186. production[building][mat] = (production[building][mat] ?? 0) + amount;
  187. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  188. let totalCost = 0;
  189. const children: AnalysisNode[] = [];
  190. for (const inputMat of recipe.inputs) {
  191. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  192. const {cost, node} = analyzeMat(inputMat.material_ticker, inputAmount, production, extract, buy, prices, recipes);
  193. totalCost += cost;
  194. children.push(node);
  195. }
  196. children.push({ text: `cost: ${formatWhole(totalCost)}`, children: [] });
  197. return {
  198. cost: totalCost,
  199. node: { text: `${formatAmount(amount)}x${mat} make (${building}, ${liquid})`, children },
  200. };
  201. }
  202. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  203. const section = element('section');
  204. for (const node of nodes)
  205. section.append(renderAnalysisNode(node));
  206. return section;
  207. }
  208. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  209. let el;
  210. if (node.children.length === 0) {
  211. el = element('div', {textContent: node.text, className: 'analysis-node'});
  212. } else {
  213. el = element('details', {className: 'analysis-node', open: level > 0});
  214. el.append(element('summary', {textContent: node.text}));
  215. for (const child of node.children)
  216. el.append(renderAnalysisNode(child, level + 1));
  217. }
  218. if (level === 0)
  219. el.classList.add('root');
  220. return el;
  221. }
  222. const WORKER_CONSUMPTION: Record<'pioneers' | 'settlers' | 'technicians' | 'engineers' | 'scientists', Record<string, number>> = {
  223. pioneers: {'COF': 0.5, 'DW': 4, 'RAT': 4, 'OVE': 0.5, 'PWO': 0.2},
  224. settlers: {'DW': 5, 'RAT': 6, 'KOM': 1, 'EXO': 0.5, 'REP': 0.2, 'PT': 0.5},
  225. technicians: {'DW': 7.5, 'RAT': 7, 'ALE': 1, 'MED': 0.5, 'SC': 0.1, 'HMS': 0.5, 'SCN': 0.1},
  226. engineers: {'DW': 10, 'MED': 0.5, 'GIN': 1, 'FIM': 7, 'VG': 0.2, 'HSS': 0.2, 'PDA': 0.1},
  227. scientists: {'DW': 10, 'MED': 0.5, 'WIN': 1, 'MEA': 7, 'NST': 0.1, 'LC': 0.2, 'WS': 0.05},
  228. };
  229. function buildingDailyCost(building: Building, prices: Record<string, RawPrice>): number {
  230. let cost = 0;
  231. for (const [workerType, mats] of Object.entries(WORKER_CONSUMPTION)) {
  232. const workers = building[workerType as keyof typeof WORKER_CONSUMPTION];
  233. for (const [mat, per100] of Object.entries(mats)) {
  234. const price = prices[mat].VWAP30D;
  235. if (price == null) throw new Error(`no price for ${mat}`);
  236. cost += price * workers * per100 / 100;
  237. }
  238. }
  239. return cost;
  240. }
  241. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production, prices: Record<string, RawPrice>,
  242. recipes: Record<string, Recipe>, buildings: Record<string, Building>): HTMLElement {
  243. const section = element('section');
  244. section.append(element('h2', {textContent: 'production'}));
  245. // mat → list of {outputMat, expertise, amount} that consume it as an input
  246. const matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]> = {};
  247. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  248. for (const building of productionBuildings) {
  249. for (const [mat, totalAmount] of Object.entries(production[building])) {
  250. const recipe = recipes[mat];
  251. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  252. for (const input of recipe.inputs) {
  253. const ticker = input.material_ticker;
  254. if (!matConsumers[ticker])
  255. matConsumers[ticker] = [];
  256. const amount = input.material_amount * totalAmount / outputPerRun;
  257. matConsumers[ticker].push({downstreamMat: mat, expertise, amount});
  258. }
  259. }
  260. }
  261. }
  262. let totalConsumablesCost = 0;
  263. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  264. section.append(element('h3', {textContent: expertise.toLocaleLowerCase()}));
  265. const shipTo: Record<string, Record<string, number>> = {};
  266. for (const building of productionBuildings) {
  267. const buildingMats = element('div');
  268. const mats = Object.entries(production[building]);
  269. let buildingMins = 0;
  270. for (const [index, [mat, amount]] of mats.entries()) {
  271. const traded = prices[mat]?.AverageTraded30D ?? 0;
  272. const span = element('span', {textContent: `${formatAmount(amount)}x${mat}`});
  273. span.style.color = traded > amount * 2 ? '#0cc' : '#c70';
  274. const consumers = matConsumers[mat];
  275. if (consumers) {
  276. span.dataset.tooltip = consumers
  277. .map((c) => `${formatAmount(c.amount)}x${mat} → ${c.downstreamMat} (${c.expertise.toLocaleLowerCase()})`)
  278. .join('\n');
  279. for (const consumer of consumers) {
  280. if (consumer.expertise == expertise) // we aren't shipping it anywhere
  281. continue;
  282. if (!shipTo[consumer.expertise])
  283. shipTo[consumer.expertise] = {};
  284. shipTo[consumer.expertise][mat] = (shipTo[consumer.expertise][mat] ?? 0) + consumer.amount;
  285. }
  286. }
  287. buildingMats.append(span);
  288. if (index < mats.length - 1)
  289. buildingMats.append(document.createTextNode(' '));
  290. const recipe = recipes[mat];
  291. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  292. buildingMins += amount / outputPerRun * (recipe.time_ms / 1000 / 60);
  293. }
  294. const numBuildings = buildingMins / (24*60) / 5 / 1.605; // one ship every 5 days, 160.5% efficiency
  295. const consumablesCost = buildingDailyCost(buildings[building], prices) * Math.round(Math.max(1, numBuildings));
  296. totalConsumablesCost += consumablesCost;
  297. const buildingRow = element('div', {className: 'building-row',
  298. textContent: `${formatFixed(numBuildings, 1)}x${building} (${formatWhole(consumablesCost)}/d)`});
  299. buildingRow.append(buildingMats);
  300. section.append(buildingRow);
  301. }
  302. const shipToDetails = element('details');
  303. shipToDetails.append(element('summary', {textContent: 'ship to'}));
  304. for (const [expertise, mats] of Object.entries(shipTo)) {
  305. const shipToRow = element('div', {textContent: expertise.toLocaleLowerCase() + ': '});
  306. shipToRow.textContent += Object.entries(mats).map(([mat, amount]) => `${amount}x${mat}`).join(' ');
  307. shipToDetails.append(shipToRow);
  308. }
  309. section.append(shipToDetails);
  310. }
  311. section.append(element('h4', {textContent: `total consumables cost: ${formatWhole(totalConsumablesCost)}/day,
  312. ${formatWhole(totalConsumablesCost * 5)}/ship`}));
  313. return section;
  314. }
  315. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  316. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  317. const node = document.createElement(tagName);
  318. Object.assign(node, properties);
  319. return node;
  320. }
  321. function formatAmount(n: number): string {
  322. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  323. }
  324. function formatFixed(n: number, digits: number): string {
  325. return n.toLocaleString(undefined, {
  326. minimumFractionDigits: digits,
  327. maximumFractionDigits: digits,
  328. });
  329. }
  330. function formatWhole(n: number): string {
  331. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  332. }
  333. interface AnalysisNode {
  334. text: string
  335. children: AnalysisNode[]
  336. }
  337. interface Recipe {
  338. recipe_name: string
  339. building_ticker: string
  340. inputs: RecipeMat[]
  341. outputs: RecipeMat[]
  342. time_ms: number
  343. }
  344. interface RecipeMat {
  345. material_ticker: string
  346. material_amount: number
  347. }
  348. interface RawPrice {
  349. MaterialTicker: string
  350. ExchangeCode: string
  351. Ask: number | null
  352. AverageTraded30D: number | null
  353. VWAP30D: number | null
  354. Supply: number
  355. }
  356. interface Building {
  357. building_ticker: string
  358. expertise: string
  359. pioneers: number
  360. settlers: number
  361. technicians: number
  362. engineers: number
  363. scientists: number
  364. }
  365. type PMMGCompanyProduction = Record<string, Record<string, {amount: number}>>;
  366. type Production = Record<string, Record<string, number>>;