shipbuilding.ts 12 KB

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