shipbuilding.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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', 'CU', 'FAN', 'FC', 'FE', 'HCC', 'HD', 'LDI', 'LI', 'MFK', 'MWF', 'REA', 'RG', 'RGO', 'ROM', 'SFK', 'SI', 'STL', 'TI', 'TPU',
  7. // import
  8. 'AAR', 'AWF', 'CAP', 'CF',
  9. // skip
  10. 'LFE', 'LHP', 'MFE', 'SFE', 'SSC',
  11. ])
  12. const blueprint = {
  13. 'FFC': 1,
  14. 'FSE': 1,
  15. 'LFE': 2,
  16. 'MFE': 2,
  17. 'RCT': 1,
  18. 'SFE': 1,
  19. 'LCB': 1,
  20. 'MFL': 1,
  21. 'MSL': 1,
  22. 'LHP': 94,
  23. 'SSC': 128,
  24. 'BR1': 1,
  25. 'CQM': 1,
  26. }
  27. const shipbuilders = [
  28. 'CraftsmanThirteen',
  29. 'EvoV',
  30. 'SurvivorBob',
  31. 'TRUEnterprises',
  32. ];
  33. render();
  34. async function render() {
  35. const main = document.querySelector('main.shipbuilding');
  36. if (!main)
  37. throw new Error('missing shipbuilding container');
  38. main.innerHTML = '<p>Loading...</p>';
  39. const [allPrices, recipes, buildings, knownCompanies, companyProductionById] = await Promise.all([
  40. cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
  41. recipeForMats(),
  42. cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
  43. cachedFetchJSON('https://pmmg-products.github.io/reports/data/knownCompanies.json') as Promise<Record<string, {Username: string}>>,
  44. pmmgMonthlyReport(),
  45. ]);
  46. const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === 'IC1')
  47. .map((price) => [price.MaterialTicker, price]));
  48. const production: Production = {};
  49. const buy: Record<string, number> = {};
  50. const analysisNodes: AnalysisNode[] = [];
  51. let cost = 0;
  52. for (const [mat, amount] of Object.entries(blueprint)) {
  53. const { cost: matCost, node } = analyzeMat(mat, amount, production, buy, prices, recipes);
  54. cost += matCost;
  55. analysisNodes.push(node);
  56. }
  57. // requiredMats = buy + production
  58. const requiredMats: Record<string, number> = {...buy};
  59. for (const buildingProduction of Object.values(production))
  60. for (const [mat, amount] of Object.entries(buildingProduction))
  61. requiredMats[mat] = (requiredMats[mat] ?? 0) + amount;
  62. const expertiseGroups: Record<string, string[]> = {};
  63. for (const building of buildings) {
  64. if (!(building.building_ticker in production))
  65. continue;
  66. if (!expertiseGroups[building.expertise])
  67. expertiseGroups[building.expertise] = [];
  68. expertiseGroups[building.expertise].push(building.building_ticker);
  69. }
  70. main.innerHTML = '';
  71. main.append(
  72. renderAnalysis(analysisNodes),
  73. element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
  74. renderProduction(expertiseGroups, production, prices, recipes),
  75. renderBuyMaterials(buy),
  76. renderShipbuilders(requiredMats, knownCompanies, companyProductionById),
  77. );
  78. }
  79. function renderBuyMaterials(buy: Record<string, number>): HTMLElement {
  80. const section = element('section');
  81. section.append(element('h2', {textContent: 'buy'}));
  82. const mats = Object.entries(buy).sort(([a], [b]) => a.localeCompare(b));
  83. section.append(element('p', {
  84. textContent: mats.map(([mat, amount]) => `${formatAmount(amount)}x${mat}`).join(', '),
  85. }));
  86. return section;
  87. }
  88. async function pmmgMonthlyReport(): Promise<PMMGCompanyProduction> {
  89. const constants = await fetch('https://raw.githubusercontent.com/PMMG-Products/pmmg-products.github.io/main/reports/src/staticData/constants.ts')
  90. .then((res) => res.text());
  91. const match = constants.match(/export const months = \[(.*?)\];/s);
  92. if (!match)
  93. throw new Error('failed to parse PMMG months');
  94. const months = match[1].split(',').map((m) => m.trim().replace(/^"|"$/g, ''));
  95. const latestMonth = months.at(-1);
  96. if (!latestMonth)
  97. throw new Error('missing PMMG month');
  98. const report = await cachedFetchJSON(`https://pmmg-products.github.io/reports/data/company-data-${latestMonth}.json`);
  99. return report['individual'];
  100. }
  101. function renderShipbuilders(requiredMats: Record<string, number>,
  102. knownCompanies: Record<string, {Username: string}>, companyProductionById: PMMGCompanyProduction): HTMLElement {
  103. const matTickers = Object.keys(requiredMats).sort();
  104. const shipbuilderSet = new Set(shipbuilders);
  105. const shipbuildersById: Record<string, string> = {};
  106. for (const [companyId, company] of Object.entries(knownCompanies))
  107. if (shipbuilderSet.has(company.Username))
  108. shipbuildersById[companyId] = company.Username;
  109. const missingShipbuilders = shipbuilders
  110. .filter((username) => !Object.values(shipbuildersById).includes(username));
  111. if (missingShipbuilders.length > 0)
  112. return element('h3', {textContent: `missing shipbuilders in PMMG report: ${missingShipbuilders.join(', ')}`});
  113. const section = element('section');
  114. section.append(element('h2', {textContent: 'shipbuilders'}));
  115. const table = element('table');
  116. const header = element('tr');
  117. header.append(element('th', {textContent: 'mat'}));
  118. header.append(element('th', {textContent: 'amount'}));
  119. for (const username of Object.values(shipbuildersById))
  120. header.append(element('th', {textContent: username}));
  121. table.append(header);
  122. for (const mat of matTickers) {
  123. const row = element('tr');
  124. row.append(element('td', {textContent: mat}));
  125. row.append(element('td', {textContent: formatAmount(requiredMats[mat])}));
  126. for (const companyId of Object.keys(shipbuildersById)) {
  127. const makes = mat in companyProductionById[companyId];
  128. row.append(element('td', {textContent: makes ? '' : 'x'}));
  129. }
  130. table.append(row);
  131. }
  132. section.append(table);
  133. return section;
  134. }
  135. async function recipeForMats(): Promise<Record<string, Recipe>> {
  136. const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
  137. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  138. for (const recipe of allRecipes)
  139. for (const output of recipe.outputs) {
  140. const recipes = matRecipes[output.material_ticker];
  141. if (recipes)
  142. recipes.push(recipe);
  143. else
  144. matRecipes[output.material_ticker] = [recipe];
  145. }
  146. const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
  147. for (const [mat, recipes] of Object.entries(matRecipes))
  148. if (recipes.length === 1)
  149. matRecipe[mat] = recipes[0];
  150. return matRecipe;
  151. }
  152. function analyzeMat(mat: string, amount: number, production: Production, buy: Record<string, number>,
  153. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): { cost: number, node: AnalysisNode } {
  154. const price = prices[mat];
  155. if (!price)
  156. throw new Error(`missing price for ${mat}`);
  157. const traded = price.AverageTraded30D ?? 0;
  158. if (BUY.has(mat)) {
  159. if (price.Ask == null)
  160. throw new Error(`missing ask price for ${mat}`);
  161. buy[mat] = (buy[mat] ?? 0) + amount;
  162. return {
  163. cost: price.Ask * amount,
  164. node: { text: `${formatAmount(amount)}x${mat} buy: ${formatAmount(price.Ask)}, daily traded ${formatFixed(traded, 1)}`, children: [] },
  165. };
  166. }
  167. const recipe = recipes[mat];
  168. if (!recipe)
  169. return { cost: 0, node: { text: `${formatAmount(amount)}x${mat} make (unknown recipe)`, children: [] } };
  170. const building = recipe.building_ticker;
  171. if (!production[building])
  172. production[building] = {};
  173. production[building][mat] = (production[building][mat] ?? 0) + amount;
  174. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  175. let totalCost = 0;
  176. const children: AnalysisNode[] = [];
  177. for (const inputMat of recipe.inputs) {
  178. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  179. const {cost, node} = analyzeMat(inputMat.material_ticker, inputAmount, production, buy, prices, recipes);
  180. totalCost += cost;
  181. children.push(node);
  182. }
  183. children.push({ text: `cost: ${formatWhole(totalCost)}`, children: [] });
  184. return {
  185. cost: totalCost,
  186. node: { text: `${formatAmount(amount)}x${mat} make (${building}, ${liquid})`, children },
  187. };
  188. }
  189. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  190. const section = element('section');
  191. for (const node of nodes)
  192. section.append(renderAnalysisNode(node));
  193. return section;
  194. }
  195. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  196. let el;
  197. if (node.children.length === 0) {
  198. el = element('div', {textContent: node.text, className: 'analysis-node'});
  199. } else {
  200. el = element('details', {className: 'analysis-node', open: true});
  201. el.append(element('summary', {textContent: node.text}));
  202. for (const child of node.children)
  203. el.append(renderAnalysisNode(child, level + 1));
  204. }
  205. if (level === 0)
  206. el.classList.add('root');
  207. return el;
  208. }
  209. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production,
  210. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): HTMLElement {
  211. const section = element('section');
  212. section.append(element('h2', {textContent: 'production'}));
  213. for (const [expertise, buildings] of Object.entries(expertiseGroups)) {
  214. section.append(element('h3', {textContent: expertise}));
  215. for (const building of buildings) {
  216. const buildingMats = element('div');
  217. const mats = Object.entries(production[building]);
  218. let buildingMins = 0;
  219. for (const [index, [mat, amount]] of mats.entries()) {
  220. const traded = prices[mat]?.AverageTraded30D ?? 0;
  221. const span = element('span', {
  222. textContent: `${formatAmount(amount)}x${mat}`,
  223. });
  224. span.style.color = traded > amount * 2 ? '#0cc' : '#c70';
  225. buildingMats.append(span);
  226. if (index < mats.length - 1)
  227. buildingMats.append(document.createTextNode(' '));
  228. const recipe = recipes[mat];
  229. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  230. buildingMins += amount / outputPerRun * (recipe.time_ms / 1000 / 60);
  231. }
  232. const numBuildings = buildingMins / (24*60) / 5 / 1.605; // one ship every 5 days, 160.5% efficiency
  233. const buildingRow = element('div', {className: 'building-row', textContent: `${formatFixed(numBuildings, 1)}x${building}`});
  234. buildingRow.append(buildingMats);
  235. section.append(buildingRow);
  236. }
  237. }
  238. return section;
  239. }
  240. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  241. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  242. const node = document.createElement(tagName);
  243. Object.assign(node, properties);
  244. return node;
  245. }
  246. function formatAmount(n: number): string {
  247. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  248. }
  249. function formatFixed(n: number, digits: number): string {
  250. return n.toLocaleString(undefined, {
  251. minimumFractionDigits: digits,
  252. maximumFractionDigits: digits,
  253. });
  254. }
  255. function formatWhole(n: number): string {
  256. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  257. }
  258. interface AnalysisNode {
  259. text: string
  260. children: AnalysisNode[]
  261. }
  262. interface Recipe {
  263. recipe_name: string
  264. building_ticker: string
  265. inputs: RecipeMat[]
  266. outputs: RecipeMat[]
  267. time_ms: number
  268. }
  269. interface RecipeMat {
  270. material_ticker: string
  271. material_amount: number
  272. }
  273. interface RawPrice {
  274. MaterialTicker: string
  275. ExchangeCode: string
  276. Ask: number | null
  277. AverageTraded30D: number | null
  278. Supply: number
  279. }
  280. interface Building {
  281. building_ticker: string
  282. expertise: string
  283. }
  284. type PMMGCompanyProduction = Record<string, Record<string, {amount: number}>>;
  285. type Production = Record<string, Record<string, number>>;