shipbuilding.ts 13 KB

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