shipbuilding.ts 13 KB

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