gov.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import {cachedFetchJSON} from './cache';
  2. const renderTarget = document.querySelector('#gov')!;
  3. const planetInput = document.querySelector('#planet') as HTMLInputElement;
  4. const popSelect = document.querySelector('#pop') as HTMLSelectElement;
  5. function serializeToHash(planet: string, pop: Pop): void {
  6. const params = new URLSearchParams({'planet': planet, 'pop': pop});
  7. document.location.hash = params.toString();
  8. }
  9. function deserializeFromHash(): {planet: string, pop: Pop} | null {
  10. const params = new URLSearchParams(document.location.hash.substring(1));
  11. const planet = params.get('planet');
  12. const pop = params.get('pop');
  13. if (planet && pop && ['pio', 'set', 'tec', 'eng', 'sci'].includes(pop)) {
  14. planetInput.value = planet;
  15. popSelect.value = pop;
  16. return {planet, pop: pop as Pop};
  17. } else
  18. return null;
  19. }
  20. document.querySelector('form')!.addEventListener('submit', async (event) => {
  21. event.preventDefault();
  22. const planet = planetInput.value;
  23. const pop = popSelect.value as Pop;
  24. if (planet && pop) {
  25. await render(planet, pop);
  26. serializeToHash(planet, pop);
  27. }
  28. });
  29. {
  30. const deserialized = deserializeFromHash();
  31. if (deserialized)
  32. void render(deserialized.planet, deserialized.pop);
  33. }
  34. async function render(planetName: string, pop: Pop) {
  35. const loader = document.querySelector('#loader') as HTMLElement;
  36. loader.style.display = 'block';
  37. renderTarget.innerHTML = '';
  38. try {
  39. await _render(planetName, pop);
  40. } catch (e) {
  41. renderTarget.textContent = (e as Error).message;
  42. }
  43. loader.style.display = 'none';
  44. }
  45. async function _render(planetName: string, pop: Pop) {
  46. const encodedPlanetName = encodeURIComponent(planetName);
  47. const [planet, siteCounts, infras]: [Planet, SiteCount[], Infrastructure[]] = await Promise.all([
  48. cachedFetchJSON(`https://api.fnar.net/planet/${encodedPlanetName}?include_population_reports=true`),
  49. cachedFetchJSON(`https://api.fnar.net/planet/sitecount?planet=${encodedPlanetName}`),
  50. cachedFetchJSON(`https://api.fnar.net/infrastructure?infrastructure=${encodedPlanetName}&include_upkeeps=true`)
  51. ]);
  52. let lastPOPR = null;
  53. for (const report of planet.PopulationReports) {
  54. if (!lastPOPR || report.SimulationPeriod > lastPOPR.SimulationPeriod)
  55. lastPOPR = report;
  56. }
  57. if (lastPOPR === null) {
  58. renderTarget.textContent = `no POPR for ${planetName}`;
  59. return;
  60. }
  61. const lastPOPRts = Math.floor(new Date(lastPOPR.ReportTimestamp).getTime() / 1000);
  62. const nextPOPRts = lastPOPRts + 7 * 24 * 60 * 60;
  63. const siteCount = siteCounts[0].Count;
  64. const totalNeeds: Record<Need, number> = {
  65. 'safety': calcTotalNeeds(lastPOPR, 'safety'),
  66. 'health': calcTotalNeeds(lastPOPR, 'health'),
  67. 'comfort': calcTotalNeeds(lastPOPR, 'comfort'),
  68. 'culture': calcTotalNeeds(lastPOPR, 'culture'),
  69. 'education': calcTotalNeeds(lastPOPR, 'education'),
  70. };
  71. const currentPOPIFilled: POPIFill = new Map();
  72. for (const infra of infras) {
  73. const filled = calcPOPIFilled(infra);
  74. if (filled !== null)
  75. currentPOPIFilled.set(infra.Type, {tier: infra.CurrentLevel, numMats: filled});
  76. }
  77. // gen
  78. renderTarget.innerHTML = `last POPR: ${lastPOPR.ReportTimestamp} (${lastPOPRts})
  79. <br>next POPR: ${new Date(nextPOPRts * 1000).toISOString()} (${nextPOPRts})
  80. <table>
  81. <tr>
  82. <th></th>
  83. <th>pio</th>
  84. <th>set</th>
  85. <th>tec</th>
  86. <th>eng</th>
  87. <th>sci</th>
  88. </tr>
  89. <tr>
  90. <th>population</th>
  91. <td>${lastPOPR.NextPopulationPioneer}<br>${formatDelta(lastPOPR.PopulationDifferencePioneer)}</td>
  92. <td>${lastPOPR.NextPopulationSettler}<br>${formatDelta(lastPOPR.PopulationDifferenceSettler)}</td>
  93. <td>${lastPOPR.NextPopulationTechnician}<br>${formatDelta(lastPOPR.PopulationDifferenceTechnician)}</td>
  94. <td>${lastPOPR.NextPopulationEngineer}<br>${formatDelta(lastPOPR.PopulationDifferenceEngineer)}</td>
  95. <td>${lastPOPR.NextPopulationScientist}<br>${formatDelta(lastPOPR.PopulationDifferenceScientist)}</td>
  96. </tr>
  97. <tr>
  98. <th>unemployed</th>
  99. <td>${unemployed(lastPOPR.NextPopulationPioneer, lastPOPR.PopulationDifferencePioneer, lastPOPR.OpenJobsPioneer, lastPOPR.UnemploymentRatePioneer)}</td>
  100. <td>${unemployed(lastPOPR.NextPopulationSettler, lastPOPR.PopulationDifferenceSettler, lastPOPR.OpenJobsSettler, lastPOPR.UnemploymentRateSettler)}</td>
  101. <td>${unemployed(lastPOPR.NextPopulationTechnician, lastPOPR.PopulationDifferenceTechnician, lastPOPR.OpenJobsTechnician, lastPOPR.UnemploymentRateTechnician)}</td>
  102. <td>${unemployed(lastPOPR.NextPopulationEngineer, lastPOPR.PopulationDifferenceEngineer, lastPOPR.OpenJobsEngineer, lastPOPR.UnemploymentRateEngineer)}</td>
  103. <td>${unemployed(lastPOPR.NextPopulationScientist, lastPOPR.PopulationDifferenceScientist, lastPOPR.OpenJobsScientist, lastPOPR.UnemploymentRateScientist)}</td>
  104. </tr>
  105. </table>
  106. <h2>needs</h2>
  107. ${siteCount} bases
  108. <table>
  109. <tr>
  110. <th></th>
  111. <th>safety</th>
  112. <th>health</th>
  113. <th>comfort</th>
  114. <th>culture</th>
  115. <th>education</th>
  116. </tr>
  117. <tr>
  118. <td>last POPR</td>
  119. <td>${formatPct(lastPOPR.NeedFulfillmentSafety)}</td>
  120. <td>${formatPct(lastPOPR.NeedFulfillmentHealth)}</td>
  121. <td>${formatPct(lastPOPR.NeedFulfillmentComfort)}</td>
  122. <td>${formatPct(lastPOPR.NeedFulfillmentCulture)}</td>
  123. <td>${formatPct(lastPOPR.NeedFulfillmentEducation)}</td>
  124. </tr>
  125. <tr>
  126. <td>total needed</td>
  127. <td>${formatNum(totalNeeds['safety'])}</td>
  128. <td>${formatNum(totalNeeds['health'])}</td>
  129. <td>${formatNum(totalNeeds['comfort'])}</td>
  130. <td>${formatNum(totalNeeds['culture'])}</td>
  131. <td>${formatNum(totalNeeds['education'])}</td>
  132. </tr>
  133. </table>
  134. <h2>POPI</h2>
  135. <table>
  136. <tr>
  137. ${infras.map((infra) => {
  138. if (infra.CurrentLevel === 0)
  139. return '';
  140. const fill = currentPOPIFilled.get(infra.Type)!;
  141. return `<tr>
  142. <td>${infra.Type} T${infra.CurrentLevel}</td>
  143. <td>${fill.numMats}/${infra.Upkeeps.length}</td>
  144. </tr>`;
  145. }).join('')}
  146. </tr>
  147. </table>
  148. <h2>options</h2>
  149. current projected ${pop} happiness: ${formatPct(projectedHappiness(pop, totalNeeds, siteCount, currentPOPIFilled))}
  150. <table>
  151. ${paretoFront(pop, totalNeeds, siteCount, currentPOPIFilled).map((result) => {
  152. return `<tr>
  153. <td>${[...result.config.entries()].map(([building, fill]) => `${building}: ${fill.numMats}`).join(', ')}</td>
  154. <td>${formatPct(result.happiness)}</td>
  155. </tr>`;
  156. }).join('')}
  157. </table>
  158. `;
  159. }
  160. const formatNum = new Intl.NumberFormat(undefined, {maximumFractionDigits: 2}).format;
  161. const formatPct = new Intl.NumberFormat(undefined, {style: 'percent', maximumFractionDigits: 2}).format;
  162. function formatDelta(n: number, withPlus: boolean = true): string {
  163. if (n > 0)
  164. return `<span class="positive">${withPlus ? '+' : ''}${n}</span>`;
  165. else if (n < 0)
  166. return `<span class="negative">${n}</span>`;
  167. else
  168. return n.toString();
  169. }
  170. function unemployed(people: number, change: number, openJobs: number, unemploymentRate: number): string {
  171. let nextUnemployed;
  172. if (openJobs <= people + change) {
  173. let prevUnemploymentRate = unemploymentRate;
  174. if (openJobs > 0)
  175. if (people - change > 0)
  176. prevUnemploymentRate = -openJobs / (people - change);
  177. else
  178. prevUnemploymentRate = -1
  179. const prevUnemployed = prevUnemploymentRate * (people - change);
  180. nextUnemployed = prevUnemployed + change;
  181. } else
  182. nextUnemployed = -openJobs + change;
  183. return formatDelta(Math.round(nextUnemployed), false);
  184. }
  185. function calcTotalNeeds(popReport: POPR, need: Need): number {
  186. return popReport.NextPopulationPioneer * NEEDS.pio[need]
  187. + popReport.NextPopulationSettler * NEEDS.set[need]
  188. + popReport.NextPopulationTechnician * NEEDS.tec[need]
  189. + popReport.NextPopulationEngineer * NEEDS.eng[need]
  190. + popReport.NextPopulationScientist * NEEDS.sci[need];
  191. }
  192. function calcPOPIFilled(infra: Infrastructure): number | null {
  193. if (infra.CurrentLevel === 0)
  194. return null;
  195. let filled = 0;
  196. for (const upkeep of infra.Upkeeps) {
  197. const nextConsumptionAmount = upkeep.StoreCapacity / 30 * upkeep.Duration; // # capacity is always 30 days
  198. if (upkeep.Stored >= nextConsumptionAmount)
  199. filled++;
  200. }
  201. return filled;
  202. }
  203. function paretoFront(pop: Pop, totalNeeds: Record<Need, number>, siteCount: number, currentPOPIFilled: POPIFill):
  204. {config: POPIFill, happiness: number, cost: number}[] {
  205. const results: {config: POPIFill, happiness: number, cost: number}[] = [];
  206. for (const config of popiFillCombinations(currentPOPIFilled)) {
  207. const happiness = projectedHappiness(pop, totalNeeds, siteCount, config);
  208. let cost = config.values().reduce((sum, fill) => sum + fill.numMats * fill.tier, 0); // TODO
  209. // is any result better than this one?
  210. if (results.some((result) => (result.happiness >= happiness && result.cost < cost) ||
  211. (result.happiness > happiness && result.cost <= cost)))
  212. continue;
  213. // are any results worse than this one?
  214. for (let i = results.length - 1; i >= 0; i--)
  215. if ((results[i].happiness <= happiness && results[i].cost > cost) ||
  216. (results[i].happiness < happiness && results[i].cost >= cost))
  217. results.splice(i, 1);
  218. results.push({config, happiness, cost});
  219. }
  220. return results;
  221. }
  222. function* popiFillCombinations(currentPOPIFilled: POPIFill): Generator<POPIFill> {
  223. const entries = [...currentPOPIFilled.keys()];
  224. function* helper(index: number, current: POPIFill): Generator<POPIFill> {
  225. if (index === entries.length) {
  226. yield new Map(current);
  227. return;
  228. }
  229. const building = entries[index];
  230. const tier = currentPOPIFilled.get(building)!.tier;
  231. for (let i = 0; i <= POPI[building].max; i++) {
  232. current.set(building, {tier, numMats: i});
  233. yield* helper(index + 1, current);
  234. }
  235. }
  236. yield* helper(0, new Map());
  237. }
  238. function projectedHappiness(pop: Pop, totalNeeds: Record<Need, number>, siteCount: number, popiFilled: POPIFill): number {
  239. let totalProvided: Record<Need, number> = {'safety': 50 * siteCount, 'health': 50 * siteCount,
  240. 'comfort': 0, 'culture': 0, 'education': 0};
  241. for (const [building, fill] of popiFilled.entries()) {
  242. const {max, needs} = POPI[building];
  243. for (const {need, supplied} of needs) {
  244. const provided = fill.numMats / max * fill.tier * supplied;
  245. totalProvided[need] += provided;
  246. }
  247. }
  248. const satisfaction: Map<Need, number> = new Map(); // percentage of needs fulfilled
  249. for (const _need in totalProvided) {
  250. const need = _need as Need;
  251. satisfaction.set(need, Math.min(totalProvided[need] / totalNeeds[need], 1));
  252. }
  253. const safetyHealthCap = Math.min(satisfaction.get('safety')!, satisfaction.get('health')!);
  254. if (satisfaction.get('comfort')! > safetyHealthCap)
  255. satisfaction.set('comfort', safetyHealthCap);
  256. if (satisfaction.get('culture')! > safetyHealthCap)
  257. satisfaction.set('culture', safetyHealthCap);
  258. const comfortCultureCap = Math.min(satisfaction.get('comfort')!, satisfaction.get('culture')!);
  259. if (satisfaction.get('education')! > comfortCultureCap)
  260. satisfaction.set('education', comfortCultureCap);
  261. const weights = NEEDS[pop];
  262. let happiness = 1 - Object.values(weights).reduce((sum, weight) => sum + weight, 0); // assume 100% life support
  263. for (const [need, s] of satisfaction.entries())
  264. happiness += weights[need] * s;
  265. return happiness;
  266. }
  267. const NEEDS: Record<Pop, Record<Need, number>> = {
  268. 'pio': {'safety': 0.25, 'health': 0.15, 'comfort': 0.03, 'culture': 0.02, 'education': 0.01},
  269. 'set': {'safety': 0.30, 'health': 0.20, 'comfort': 0.03, 'culture': 0.03, 'education': 0.03},
  270. 'tec': {'safety': 0.20, 'health': 0.30, 'comfort': 0.20, 'culture': 0.10, 'education': 0.05},
  271. 'eng': {'safety': 0.10, 'health': 0.15, 'comfort': 0.35, 'culture': 0.20, 'education': 0.10},
  272. 'sci': {'safety': 0.10, 'health': 0.10, 'comfort': 0.20, 'culture': 0.25, 'education': 0.30},
  273. }
  274. const POPI: Record<POPIBuilding, {max: number, needs: {need: Need, supplied: number}[]}> = {
  275. 'SAFETY_STATION': {max: 3, needs: [{need: 'safety', supplied: 2500}]},
  276. 'SECURITY_DRONE_POST': {max: 4, needs: [{need: 'safety', supplied: 5000}]},
  277. 'EMERGENCY_CENTER': {max: 5, needs: [{need: 'safety', supplied: 1000}, {need: 'health', supplied: 1000}]},
  278. 'INFIRMARY': {max: 3, needs: [{need: 'health', supplied: 2500}]},
  279. 'HOSPITAL': {max: 6, needs: [{need: 'health', supplied: 5000}]},
  280. 'WELLNESS_CENTER': {max: 6, needs: [{need: 'health', supplied: 1000}, {need: 'comfort', supplied: 1000}]},
  281. 'WILDLIFE_PARK': {max: 5, needs: [{need: 'comfort', supplied: 2500}]},
  282. 'ARCADES': {max: 6, needs: [{need: 'comfort', supplied: 5000}]},
  283. 'ART_CAFE': {max: 6, needs: [{need: 'comfort', supplied: 1000}, {need: 'culture', supplied: 1000}]},
  284. 'ART_GALLERY': {max: 4, needs: [{need: 'culture', supplied: 2500}]},
  285. 'THEATER': {max: 6, needs: [{need: 'culture', supplied: 5000}]},
  286. 'PLANETARY_BROADCASTING_HUB': {max: 6, needs: [{need: 'culture', supplied: 1000}, {need: 'education', supplied: 1000}]},
  287. 'LIBRARY': {max: 5, needs: [{need: 'education', supplied: 2500}]},
  288. 'UNIVERSITY': {max: 6, needs: [{need: 'education', supplied: 5000}]},
  289. };
  290. type Pop = 'pio' | 'set' | 'tec' | 'eng' | 'sci';
  291. type Need = 'safety' | 'health' | 'comfort' | 'culture' | 'education';
  292. type POPIBuilding = 'SAFETY_STATION' | 'SECURITY_DRONE_POST' | 'EMERGENCY_CENTER' | 'INFIRMARY' | 'HOSPITAL' |
  293. 'WELLNESS_CENTER' | 'WILDLIFE_PARK' | 'ARCADES' | 'ART_CAFE' | 'ART_GALLERY' | 'THEATER' |
  294. 'PLANETARY_BROADCASTING_HUB' | 'LIBRARY' | 'UNIVERSITY';
  295. type POPIFill = Map<POPIBuilding, {tier: number, numMats: number}>;
  296. interface Planet {
  297. PopulationReports: POPR[]
  298. }
  299. interface POPR {
  300. SimulationPeriod: number;
  301. ReportTimestamp: string;
  302. NeedFulfillmentSafety: number;
  303. NeedFulfillmentHealth: number;
  304. NeedFulfillmentComfort: number;
  305. NeedFulfillmentCulture: number;
  306. NeedFulfillmentEducation: number;
  307. NextPopulationPioneer: number;
  308. NextPopulationSettler: number;
  309. NextPopulationTechnician: number;
  310. NextPopulationEngineer: number;
  311. NextPopulationScientist: number;
  312. PopulationDifferencePioneer: number;
  313. PopulationDifferenceSettler: number;
  314. PopulationDifferenceTechnician: number;
  315. PopulationDifferenceEngineer: number;
  316. PopulationDifferenceScientist: number;
  317. OpenJobsPioneer: number;
  318. OpenJobsSettler: number;
  319. OpenJobsTechnician: number;
  320. OpenJobsEngineer: number;
  321. OpenJobsScientist: number;
  322. UnemploymentRatePioneer: number;
  323. UnemploymentRateSettler: number;
  324. UnemploymentRateTechnician: number;
  325. UnemploymentRateEngineer: number;
  326. UnemploymentRateScientist: number;
  327. }
  328. interface SiteCount {
  329. Count: number;
  330. }
  331. interface Infrastructure {
  332. Type: POPIBuilding;
  333. CurrentLevel: number;
  334. Upkeeps: {Stored: number, StoreCapacity: number, 'Duration': number}[];
  335. }