bitburner-src/src/SaveObject.ts

874 lines
28 KiB
TypeScript
Raw Normal View History

import { Skills } from "@nsdefs";
2021-09-09 05:47:34 +02:00
import { loadAliases, loadGlobalAliases, Aliases, GlobalAliases } from "./Alias";
import { Companies, loadCompanies } from "./Company/Companies";
import { CONSTANTS } from "./Constants";
import { Factions, loadFactions } from "./Faction/Factions";
import { loadAllGangs, AllGangs } from "./Gang/AllGangs";
import { Player, setPlayer, loadPlayer } from "./Player";
2022-05-19 08:09:00 +02:00
import {
saveAllServers,
loadAllServers,
GetAllServers,
createUniqueRandomIp,
AddToAllServers,
GetServer,
} from "./Server/AllServers";
import { Settings } from "./Settings/Settings";
import { loadStockMarket, StockMarket } from "./StockMarket/StockMarket";
2021-09-25 23:21:50 +02:00
import { staneksGift, loadStaneksGift } from "./CotMG/Helper";
2019-02-20 09:42:27 +01:00
import { SnackbarEvents } from "./ui/React/Snackbar";
2021-05-18 05:59:45 +02:00
import * as ExportBonus from "./ExportBonus";
2021-09-25 20:42:57 +02:00
import { dialogBoxCreate } from "./ui/React/DialogBox";
import { Reviver, constructorsForReviver, Generic_toJSON, Generic_fromJSON, IReviverValue } from "./utils/JSONReviver";
2021-09-21 22:49:38 +02:00
import { save } from "./db";
2022-07-19 20:21:12 +02:00
import { AwardNFG, v1APIBreak } from "./utils/v1APIBreak";
import { AugmentationName, FactionName, LocationName, ToastVariant } from "@enums";
2021-11-10 05:42:36 +01:00
import { PlayerOwnedAugmentation } from "./Augmentation/PlayerOwnedAugmentation";
import { pushGameSaved } from "./Electron";
2022-04-18 18:44:00 +02:00
import { defaultMonacoTheme } from "./ScriptEditor/ui/themes";
2022-04-22 21:30:49 +02:00
import { Faction } from "./Faction/Faction";
2022-10-09 07:25:31 +02:00
import { safelyCreateUniqueServer } from "./Server/ServerHelpers";
2022-05-19 08:09:00 +02:00
import { SpecialServers } from "./Server/data/SpecialServers";
2022-07-26 21:09:11 +02:00
import { v2APIBreak } from "./utils/v2APIBreak";
import { Corporation } from "./Corporation/Corporation";
import { Terminal } from "./Terminal";
import { getRecordValues } from "./Types/Record";
import { ExportMaterial } from "./Corporation/Actions";
import { getGoSave, loadGo } from "./Go/SaveLoad";
/* SaveObject.js
* Defines the object used to save/load games
*/
export interface SaveData {
playerIdentifier: string;
fileName: string;
save: string;
savedOn: number;
}
export interface ImportData {
base64: string;
playerData?: ImportPlayerData;
}
export interface ImportPlayerData {
identifier: string;
lastSave: number;
totalPlaytime: number;
money: number;
skills: Skills;
augmentations: number;
factions: number;
achievements: number;
bitNode: number;
bitNodeLevel: number;
sourceFiles: number;
exploits: number;
}
2021-09-25 00:40:17 +02:00
class BitburnerSaveObject {
PlayerSave = "";
AllServersSave = "";
CompaniesSave = "";
FactionsSave = "";
AliasesSave = "";
GlobalAliasesSave = "";
StockMarketSave = "";
SettingsSave = "";
VersionSave = "";
AllGangsSave = "";
LastExportBonus = "0";
2021-09-25 23:21:50 +02:00
StaneksGiftSave = "";
GoSave = "";
2021-09-25 00:40:17 +02:00
getSaveString(forceExcludeRunningScripts = false): string {
2021-09-25 00:40:17 +02:00
this.PlayerSave = JSON.stringify(Player);
// For the servers save, overwrite the ExcludeRunningScripts setting if forced
const originalExcludeSetting = Settings.ExcludeRunningScriptsFromSave;
if (forceExcludeRunningScripts) Settings.ExcludeRunningScriptsFromSave = true;
this.AllServersSave = saveAllServers();
Settings.ExcludeRunningScriptsFromSave = originalExcludeSetting;
2021-09-25 00:40:17 +02:00
this.CompaniesSave = JSON.stringify(Companies);
this.FactionsSave = JSON.stringify(Factions);
this.AliasesSave = JSON.stringify(Object.fromEntries(Aliases.entries()));
this.GlobalAliasesSave = JSON.stringify(Object.fromEntries(GlobalAliases.entries()));
2021-09-25 00:40:17 +02:00
this.StockMarketSave = JSON.stringify(StockMarket);
this.SettingsSave = JSON.stringify(Settings);
2021-11-03 03:49:46 +01:00
this.VersionSave = JSON.stringify(CONSTANTS.VersionNumber);
2021-09-25 00:40:17 +02:00
this.LastExportBonus = JSON.stringify(ExportBonus.LastExportBonus);
2021-09-25 23:21:50 +02:00
this.StaneksGiftSave = JSON.stringify(staneksGift);
this.GoSave = JSON.stringify(getGoSave());
if (Player.gang) this.AllGangsSave = JSON.stringify(AllGangs);
2021-09-25 07:26:03 +02:00
const saveString = btoa(unescape(encodeURIComponent(JSON.stringify(this))));
2021-09-25 00:40:17 +02:00
return saveString;
2021-09-05 01:09:30 +02:00
}
saveGame(emitToastEvent = true): Promise<void> {
const savedOn = new Date().getTime();
Player.lastSave = savedOn;
const saveString = this.getSaveString();
return new Promise((resolve, reject) => {
save(saveString)
.then(() => {
const saveData: SaveData = {
playerIdentifier: Player.identifier,
fileName: this.getSaveFileName(),
save: saveString,
savedOn,
};
pushGameSaved(saveData);
if (emitToastEvent) {
SnackbarEvents.emit("Game Saved!", ToastVariant.INFO, 2000);
}
return resolve();
})
.catch((err) => {
console.error(err);
return reject();
});
});
2021-09-05 01:09:30 +02:00
}
getSaveFileName(isRecovery = false): string {
2021-09-25 00:40:17 +02:00
// Save file name is based on current timestamp and BitNode
const epochTime = Math.round(Date.now() / 1000);
const bn = Player.bitNodeN;
2022-04-14 07:22:50 +02:00
let filename = `bitburnerSave_${epochTime}_BN${bn}x${Player.sourceFileLvl(bn) + 1}.json`;
if (isRecovery) filename = "RECOVERY" + filename;
return filename;
}
exportGame(): void {
const saveString = this.getSaveString();
const filename = this.getSaveFileName();
2021-11-12 05:28:08 +01:00
download(filename, saveString);
2021-09-25 00:40:17 +02:00
}
2021-09-05 01:09:30 +02:00
importGame(base64Save: string, reload = true): Promise<void> {
if (!base64Save || base64Save === "") throw new Error("Invalid import string");
return save(base64Save).then(() => {
if (reload) setTimeout(() => location.reload(), 1000);
return Promise.resolve();
});
}
getImportStringFromFile(files: FileList | null): Promise<string> {
if (files === null) return Promise.reject(new Error("No file selected"));
const file = files[0];
if (!file) return Promise.reject(new Error("Invalid file selected"));
const reader = new FileReader();
const promise = new Promise<string>((resolve, reject) => {
reader.onload = function (this: FileReader, e: ProgressEvent<FileReader>) {
const target = e.target;
if (target === null) {
return reject(new Error("Error importing file"));
}
const result = target.result;
2022-03-01 20:37:47 +01:00
if (typeof result !== "string") {
return reject(new Error("FileReader event was not type string"));
}
const contents = result;
resolve(contents);
};
});
reader.readAsText(file);
return promise;
}
async getImportDataFromString(base64Save: string): Promise<ImportData> {
if (!base64Save || base64Save === "") throw new Error("Invalid import string");
let newSave;
try {
newSave = window.atob(base64Save);
newSave = newSave.trim();
} catch (error) {
console.error(error); // We'll handle below
}
if (!newSave || newSave === "") {
return Promise.reject(new Error("Save game had not content or was not base64 encoded"));
}
let parsedSave;
try {
parsedSave = JSON.parse(newSave);
} catch (error) {
2022-07-10 07:37:36 +02:00
console.error(error); // We'll handle below
}
if (!parsedSave || parsedSave.ctor !== "BitburnerSaveObject" || !parsedSave.data) {
return Promise.reject(new Error("Save game did not seem valid"));
}
const data: ImportData = {
base64: base64Save,
};
const importedPlayer = loadPlayer(parsedSave.data.PlayerSave);
const playerData: ImportPlayerData = {
identifier: importedPlayer.identifier,
lastSave: importedPlayer.lastSave,
totalPlaytime: importedPlayer.totalPlaytime,
money: importedPlayer.money,
skills: importedPlayer.skills,
augmentations: importedPlayer.augmentations?.reduce<number>((total, current) => (total += current.level), 0) ?? 0,
factions: importedPlayer.factions?.length ?? 0,
achievements: importedPlayer.achievements?.length ?? 0,
bitNode: importedPlayer.bitNodeN,
bitNodeLevel: importedPlayer.sourceFileLvl(Player.bitNodeN) + 1,
sourceFiles: [...importedPlayer.sourceFiles].reduce<number>((total, [__bn, lvl]) => (total += lvl), 0),
exploits: importedPlayer.exploits.length,
};
data.playerData = playerData;
return Promise.resolve(data);
}
2022-07-15 01:00:10 +02:00
toJSON(): IReviverValue {
2021-09-25 00:40:17 +02:00
return Generic_toJSON("BitburnerSaveObject", this);
}
2017-09-19 20:38:03 +02:00
2022-07-15 01:00:10 +02:00
static fromJSON(value: IReviverValue): BitburnerSaveObject {
2021-09-25 00:40:17 +02:00
return Generic_fromJSON(BitburnerSaveObject, value.data);
}
}
/** Function for performing a series of defined replacements. See 0.58.0 for usage */
function convert(code: string, changes: [RegExp, string][]): string {
for (const change of changes) {
code = code.replace(change[0], change[1]);
}
return code;
}
2018-11-16 04:45:03 +01:00
// Makes necessary changes to the loaded/imported data to ensure
// the game stills works with new versions
2021-11-03 03:11:22 +01:00
function evaluateVersionCompatibility(ver: string | number): void {
2021-09-25 00:40:17 +02:00
// We have to do this because ts won't let us otherwise
const anyPlayer = Player as any;
2021-11-03 03:11:22 +01:00
if (typeof ver === "string") {
// This version refactored the Company/job-related code
if (ver <= "0.41.2") {
// Player's company position is now a string
if (anyPlayer.companyPosition != null && typeof anyPlayer.companyPosition !== "string") {
anyPlayer.companyPosition = anyPlayer.companyPosition.data.positionName;
if (anyPlayer.companyPosition == null) {
anyPlayer.companyPosition = "";
}
2021-09-05 01:09:30 +02:00
}
}
2021-09-05 01:09:30 +02:00
2021-11-03 03:11:22 +01:00
// This version allowed players to hold multiple jobs
if (ver < "0.43.0") {
if (anyPlayer.companyName !== "" && anyPlayer.companyPosition != null && anyPlayer.companyPosition !== "") {
anyPlayer.jobs[anyPlayer.companyName] = anyPlayer.companyPosition;
2021-10-12 06:29:16 +02:00
}
2021-11-03 03:11:22 +01:00
delete anyPlayer.companyPosition;
2021-10-12 06:29:16 +02:00
}
2021-11-03 03:11:22 +01:00
if (ver < "0.56.0") {
for (const q of anyPlayer.queuedAugmentations) {
if (q.name === "Graphene BranchiBlades Upgrade") {
q.name = "Graphene BrachiBlades Upgrade";
}
2021-10-12 06:29:16 +02:00
}
2021-11-03 03:11:22 +01:00
for (const q of anyPlayer.augmentations) {
if (q.name === "Graphene BranchiBlades Upgrade") {
q.name = "Graphene BrachiBlades Upgrade";
}
2021-10-12 06:29:16 +02:00
}
}
2021-11-03 03:11:22 +01:00
if (ver < "0.56.1") {
if (anyPlayer.bladeburner === 0) {
anyPlayer.bladeburner = null;
}
if (anyPlayer.gang === 0) {
anyPlayer.gang = null;
}
// convert all Messages to just filename to save space.
const home = anyPlayer.getHomeComputer();
for (let i = 0; i < home.messages.length; i++) {
if (home.messages[i].filename) {
home.messages[i] = home.messages[i].filename;
}
2021-10-27 21:16:16 +02:00
}
2021-10-13 01:23:36 +02:00
}
2021-11-03 03:11:22 +01:00
if (ver < "0.58.0") {
const changes: [RegExp, string][] = [
[/getStockSymbols/g, "stock.getSymbols"],
[/getStockPrice/g, "stock.getPrice"],
[/getStockAskPrice/g, "stock.getAskPrice"],
[/getStockBidPrice/g, "stock.getBidPrice"],
[/getStockPosition/g, "stock.getPosition"],
[/getStockMaxShares/g, "stock.getMaxShares"],
[/getStockPurchaseCost/g, "stock.getPurchaseCost"],
[/getStockSaleGain/g, "stock.getSaleGain"],
[/buyStock/g, "stock.buy"],
[/sellStock/g, "stock.sell"],
[/shortStock/g, "stock.short"],
[/sellShort/g, "stock.sellShort"],
[/placeOrder/g, "stock.placeOrder"],
[/cancelOrder/g, "stock.cancelOrder"],
[/getOrders/g, "stock.getOrders"],
[/getStockVolatility/g, "stock.getVolatility"],
[/getStockForecast/g, "stock.getForecast"],
[/purchase4SMarketData/g, "stock.purchase4SMarketData"],
[/purchase4SMarketDataTixApi/g, "stock.purchase4SMarketDataTixApi"],
];
for (const server of GetAllServers()) {
for (const script of server.scripts.values()) {
script.content = convert(script.code, changes);
2021-11-03 03:11:22 +01:00
}
2021-10-27 21:16:16 +02:00
}
2021-10-13 01:23:36 +02:00
}
2021-11-03 03:11:22 +01:00
v1APIBreak();
2021-11-10 05:42:36 +01:00
ver = 1;
}
if (typeof ver !== "number") return;
if (ver < 2) {
AwardNFG(10);
Player.reapplyAllAugmentations();
Player.reapplyAllSourceFiles();
}
if (ver < 3) {
anyPlayer.money = parseFloat(anyPlayer.money);
}
if (ver < 9) {
if (Object.hasOwn(StockMarket, "Joes Guns")) {
const s = StockMarket["Joes Guns"];
delete StockMarket["Joes Guns"];
StockMarket[LocationName.Sector12JoesGuns] = s;
2022-01-02 18:13:01 +01:00
}
}
if (ver < 10) {
// Augmentation name was changed in 0.56.0 but sleeves aug list was missed.
if (anyPlayer.sleeves && anyPlayer.sleeves.length > 0) {
for (const sleeve of anyPlayer.sleeves) {
if (!sleeve.augmentations || sleeve.augmentations.length === 0) continue;
for (const augmentation of sleeve.augmentations) {
if (augmentation.name !== "Graphene BranchiBlades Upgrade") continue;
augmentation.name = "Graphene BrachiBlades Upgrade";
}
}
}
}
if (ver < 12) {
if (anyPlayer.resleeves !== undefined) {
delete anyPlayer.resleeves;
2022-03-29 20:09:17 +02:00
}
}
if (ver < 15) {
Settings.EditorTheme = { ...defaultMonacoTheme };
}
//Fix contract names
if (ver < 16) {
Factions[FactionName.ShadowsOfAnarchy] = new Faction(FactionName.ShadowsOfAnarchy);
//Iterate over all contracts on all servers
for (const server of GetAllServers()) {
for (const contract of server.contracts) {
//Rename old "HammingCodes: Integer to encoded Binary" contracts
//to "HammingCodes: Integer to Encoded Binary"
if (contract.type == "HammingCodes: Integer to encoded Binary") {
contract.type = "HammingCodes: Integer to Encoded Binary";
}
}
}
}
2022-05-05 03:16:23 +02:00
const v22PlayerBreak = () => {
// reset HP correctly to avoid crash
anyPlayer.hp = { current: 1, max: 1 };
for (const sleeve of anyPlayer.sleeves) {
sleeve.hp = { current: 1, max: 1 };
}
2022-05-05 03:16:23 +02:00
// transfer over old exp to new struct
anyPlayer.exp.hacking = anyPlayer.hacking_exp;
anyPlayer.exp.strength = anyPlayer.strength_exp;
anyPlayer.exp.defense = anyPlayer.defense_exp;
anyPlayer.exp.dexterity = anyPlayer.dexterity_exp;
anyPlayer.exp.agility = anyPlayer.agility_exp;
anyPlayer.exp.charisma = anyPlayer.charisma_exp;
anyPlayer.exp.intelligence = anyPlayer.intelligence_exp;
};
// Fix bugged NFG accumulation in owned augmentations
if (ver < 17) {
let ownedNFGs = [...Player.augmentations];
ownedNFGs = ownedNFGs.filter((aug) => aug.name === AugmentationName.NeuroFluxGovernor);
const newNFG = new PlayerOwnedAugmentation(AugmentationName.NeuroFluxGovernor);
newNFG.level = 0;
for (const nfg of ownedNFGs) {
newNFG.level += nfg.level;
}
2022-05-05 03:16:23 +02:00
Player.augmentations = [
...Player.augmentations.filter((aug) => aug.name !== AugmentationName.NeuroFluxGovernor),
newNFG,
];
2022-05-05 08:02:05 +02:00
v22PlayerBreak();
Player.reapplyAllAugmentations();
Player.reapplyAllSourceFiles();
}
if (ver < 20) {
// Create the darkweb for everyone but it won't be linked
const dw = GetServer(SpecialServers.DarkWeb);
if (!dw) {
const darkweb = safelyCreateUniqueServer({
ip: createUniqueRandomIp(),
hostname: SpecialServers.DarkWeb,
organizationName: "",
isConnectedTo: false,
adminRights: false,
purchasedByPlayer: false,
maxRam: 1,
});
AddToAllServers(darkweb);
2022-07-19 20:21:12 +02:00
}
}
if (ver < 21) {
// 2.0.0 work rework
AwardNFG(10);
const create = anyPlayer.createProgramName;
if (create) Player.getHomeComputer().pushProgram(create);
const graft = anyPlayer.graftAugmentationName;
if (graft) Player.augmentations.push({ name: graft, level: 1 });
}
if (ver < 22) {
v22PlayerBreak();
v2APIBreak();
}
if (ver < 23) {
anyPlayer.currentWork = null;
}
if (ver < 25) {
const removePlayerFields = [
"hacking_chance_mult",
"hacking_speed_mult",
"hacking_money_mult",
"hacking_grow_mult",
"hacking_mult",
"strength_mult",
"defense_mult",
"dexterity_mult",
"agility_mult",
"charisma_mult",
"hacking_exp_mult",
"strength_exp_mult",
"defense_exp_mult",
"dexterity_exp_mult",
"agility_exp_mult",
"charisma_exp_mult",
"company_rep_mult",
"faction_rep_mult",
"crime_money_mult",
"crime_success_mult",
"work_money_mult",
"hacknet_node_money_mult",
"hacknet_node_purchase_cost_mult",
"hacknet_node_ram_cost_mult",
"hacknet_node_core_cost_mult",
"hacknet_node_level_cost_mult",
"bladeburner_max_stamina_mult",
"bladeburner_stamina_gain_mult",
"bladeburner_analysis_mult",
"bladeburner_success_chance_mult",
"hacking_exp",
"strength_exp",
"defense_exp",
"dexterity_exp",
"agility_exp",
"charisma_exp",
"intelligence_exp",
"companyName",
"isWorking",
"workType",
"workCostMult",
"workExpMult",
"currentWorkFactionName",
"currentWorkFactionDescription",
"workHackExpGainRate",
"workStrExpGainRate",
"workDefExpGainRate",
"workDexExpGainRate",
"workAgiExpGainRate",
"workChaExpGainRate",
"workRepGainRate",
"workMoneyGainRate",
"workMoneyLossRate",
"workHackExpGained",
"workStrExpGained",
"workDefExpGained",
"workDexExpGained",
"workAgiExpGained",
"workChaExpGained",
"workRepGained",
"workMoneyGained",
"createProgramName",
"createProgramReqLvl",
"graftAugmentationName",
"timeWorkedGraftAugmentation",
"className",
"crimeType",
"timeWorked",
"timeWorkedCreateProgram",
"timeNeededToCompleteWork",
"factionWorkType",
"committingCrimeThruSingFn",
"singFnCrimeWorkerScript",
"hacking",
"max_hp",
"strength",
"defense",
"dexterity",
"agility",
"charisma",
"intelligence",
];
const removeSleeveFields = [
"gymStatType",
"bbAction",
"bbContract",
"hacking",
"strength",
"defense",
"dexterity",
"agility",
"charisma",
"intelligence",
"max_hp",
"hacking_exp",
"strength_exp",
"defense_exp",
"dexterity_exp",
"agility_exp",
"charisma_exp",
"intelligence_exp",
"hacking_mult",
"strength_mult",
"defense_mult",
"dexterity_mult",
"agility_mult",
"charisma_mult",
"hacking_exp_mult",
"strength_exp_mult",
"defense_exp_mult",
"dexterity_exp_mult",
"agility_exp_mult",
"charisma_exp_mult",
"hacking_chance_mult",
"hacking_speed_mult",
"hacking_money_mult",
"hacking_grow_mult",
"company_rep_mult",
"faction_rep_mult",
"crime_money_mult",
"crime_success_mult",
"work_money_mult",
"hacknet_node_money_mult",
"hacknet_node_purchase_cost_mult",
"hacknet_node_ram_cost_mult",
"hacknet_node_core_cost_mult",
"hacknet_node_level_cost_mult",
"bladeburner_max_stamina_mult",
"bladeburner_stamina_gain_mult",
"bladeburner_analysis_mult",
"bladeburner_success_chance_mult",
"className",
"crimeType",
"currentTask",
"currentTaskLocation",
"currentTaskMaxTime",
"currentTaskTime",
"earningsForSleeves",
"earningsForPlayer",
"earningsForTask",
"factionWorkType",
"gainRatesForTask",
"logs",
];
let intExp = Number(anyPlayer.intelligence_exp);
if (isNaN(intExp)) intExp = 0;
anyPlayer.exp.intelligence += intExp;
for (const field of removePlayerFields) {
delete anyPlayer[field];
2022-08-18 18:36:30 +02:00
}
for (const sleeve of anyPlayer.sleeves) {
const anySleeve = sleeve;
let intExp = Number(anySleeve.intelligence_exp);
2022-08-18 19:40:39 +02:00
if (isNaN(intExp)) intExp = 0;
anySleeve.exp.intelligence += intExp;
for (const field of removeSleeveFields) {
delete sleeve[field];
2022-08-18 19:40:39 +02:00
}
}
2021-10-13 01:23:36 +02:00
}
if (ver < 27) {
// Prior to v2.2.0, sleeve shock was 0 to 100 internally but displayed as 100 to 0. This unifies them as 100 to 0.
for (const sleeve of Player.sleeves) sleeve.shock = 100 - sleeve.shock;
}
2023-05-31 00:47:48 +02:00
// Some 2.3 changes are actually in BaseServer.js fromJSONBase function
if (ver < 31) {
Terminal.warn("Migrating to 2.3.0, loading with no scripts.");
for (const server of GetAllServers()) {
// Do not load any saved scripts on migration
server.savedScripts = [];
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (anyPlayer.hashManager?.upgrades) {
anyPlayer.hashManager.upgrades["Company Favor"] ??= 0;
}
if (!anyPlayer.lastAugReset || anyPlayer.lastAugReset === -1) {
anyPlayer.lastAugReset = anyPlayer.lastUpdate - anyPlayer.playtimeSinceLastAug;
}
if (!anyPlayer.lastNodeRest || anyPlayer.lastNodeReset === -1) {
anyPlayer.lastNodeReset = anyPlayer.lastUpdate - anyPlayer.playtimeSinceLastBitnode;
}
// Reset corporation to new format.
const oldCorp = anyPlayer.corporation as Corporation | null | 0;
if (oldCorp && Array.isArray(oldCorp.divisions)) {
// Corp needs to be reset to new format, just keep some valuation data
let valuation = oldCorp.valuation * 2 + oldCorp.revenue * 100;
if (isNaN(valuation)) valuation = 300e9;
Player.startCorporation(String(oldCorp.name), !!oldCorp.seedFunded);
Player.corporation?.gainFunds(valuation, "force majeure");
Terminal.warn("Loading corporation from version prior to 2.3. Corporation has been reset.");
}
// End 2.3 changes
2023-04-09 05:24:09 +02:00
}
2023-05-31 00:47:48 +02:00
//2.3 hotfix changes and 2.3.1 changes
if (ver < 32) {
// Sanitize corporation exports
let anyExportsFailed = false;
if (Player.corporation) {
for (const division of Player.corporation.divisions.values()) {
for (const warehouse of getRecordValues(division.warehouses)) {
for (const material of getRecordValues(warehouse.materials)) {
const originalExports = material.exports;
// Clear all exports for the material
material.exports = [];
for (const originalExport of originalExports) {
// Throw if there was a failure re-establishing an export
try {
const targetDivision = Player.corporation.divisions.get(originalExport.division);
if (!targetDivision) throw new Error(`Target division ${originalExport.division} did not exist`);
// Set the export again. ExportMaterial throws on failure
ExportMaterial(targetDivision, originalExport.city, material, originalExport.amount);
} catch (e) {
anyExportsFailed = true;
// We just need the text error, not a full stack trace
console.error(`Failed to load export of material ${material.name} (${division.name} ${warehouse.city})
Original export details: ${JSON.stringify(originalExport)}
Error: ${e}`);
}
}
}
}
}
}
if (anyExportsFailed)
Terminal.error(
"Some material exports failed to validate while loading and have been removed. See console for more info.",
);
2023-05-31 00:47:48 +02:00
}
if (ver < 33) {
// 2.3.2 fixed what should be the last issue with scripts having the wrong server assigned..
for (const server of GetAllServers()) {
for (const script of server.scripts.values()) {
if (script.server !== server.hostname) {
console.warn(
`Detected script ${script.filename} on ${server.hostname} with incorrect server property: ${script.server}. Repairing.`,
);
script.server = server.hostname;
}
}
}
}
v2_60: if (ver < 38 && "go" in Player) {
const goData = Player.go;
// Remove outdated savedata
delete Player.go;
// Attempt to load back in at least the stats object. The current game will not be loaded.
if (!goData || typeof goData !== "object") break v2_60;
const stats = "status" in goData ? goData.status : "stats" in goData ? goData.stats : null;
if (!stats || typeof stats !== "object") break v2_60;
const freshSaveData = getGoSave();
Object.assign(freshSaveData.stats, stats);
loadGo(JSON.stringify(freshSaveData));
}
2018-11-16 04:45:03 +01:00
}
2021-09-25 00:40:17 +02:00
function loadGame(saveString: string): boolean {
2022-01-21 05:53:33 +01:00
createScamUpdateText();
2021-09-21 23:36:42 +02:00
if (!saveString) return false;
2021-09-21 22:49:38 +02:00
saveString = decodeURIComponent(escape(atob(saveString)));
2021-09-21 22:49:38 +02:00
const saveObj = JSON.parse(saveString, Reviver);
setPlayer(loadPlayer(saveObj.PlayerSave));
2021-09-05 01:09:30 +02:00
loadAllServers(saveObj.AllServersSave);
loadCompanies(saveObj.CompaniesSave);
loadFactions(saveObj.FactionsSave, Player);
loadGo(saveObj.GoSave);
if (Object.hasOwn(saveObj, "StaneksGiftSave")) {
2021-09-25 23:21:50 +02:00
loadStaneksGift(saveObj.StaneksGiftSave);
} else {
console.warn(`Could not load Staneks Gift from save`);
loadStaneksGift("");
}
if (Object.hasOwn(saveObj, "AliasesSave")) {
2021-09-05 01:09:30 +02:00
try {
loadAliases(saveObj.AliasesSave);
} catch (e) {
console.warn(`Could not load Aliases from save`);
loadAliases("");
}
2021-09-05 01:09:30 +02:00
} else {
console.warn(`Save file did not contain an Aliases property`);
loadAliases("");
}
if (Object.hasOwn(saveObj, "GlobalAliasesSave")) {
2021-09-05 01:09:30 +02:00
try {
loadGlobalAliases(saveObj.GlobalAliasesSave);
} catch (e) {
console.warn(`Could not load GlobalAliases from save`);
loadGlobalAliases("");
}
2021-09-05 01:09:30 +02:00
} else {
console.warn(`Save file did not contain a GlobalAliases property`);
loadGlobalAliases("");
}
if (Object.hasOwn(saveObj, "StockMarketSave")) {
2021-09-05 01:09:30 +02:00
try {
loadStockMarket(saveObj.StockMarketSave);
} catch (e) {
console.error("Couldn't load stock market:", e);
2021-09-05 01:09:30 +02:00
loadStockMarket("");
}
2021-09-05 01:09:30 +02:00
} else {
loadStockMarket("");
}
if (Object.hasOwn(saveObj, "SettingsSave")) {
2021-09-05 01:09:30 +02:00
try {
// Try to set saved settings.
2021-09-05 01:09:30 +02:00
Settings.load(saveObj.SettingsSave);
} catch (e) {
console.error("SettingsSave was present but an error occurred while loading:");
console.error(e);
}
2021-09-05 01:09:30 +02:00
}
if (Object.hasOwn(saveObj, "LastExportBonus")) {
2021-09-05 01:09:30 +02:00
try {
ExportBonus.setLastExportBonus(JSON.parse(saveObj.LastExportBonus));
} catch (err) {
ExportBonus.setLastExportBonus(new Date().getTime());
2021-09-21 04:30:11 +02:00
console.error("ERROR: Failed to parse last export bonus Settings " + err);
2021-05-18 05:59:45 +02:00
}
2021-09-05 01:09:30 +02:00
}
if (Player.gang && Object.hasOwn(saveObj, "AllGangsSave")) {
2021-10-07 22:56:01 +02:00
try {
loadAllGangs(saveObj.AllGangsSave);
} catch (e) {
console.error("ERROR: Failed to parse AllGangsSave: " + e);
}
}
if (Object.hasOwn(saveObj, "VersionSave")) {
2021-09-05 01:09:30 +02:00
try {
2021-09-25 07:26:03 +02:00
const ver = JSON.parse(saveObj.VersionSave, Reviver);
2021-09-05 01:09:30 +02:00
evaluateVersionCompatibility(ver);
if (CONSTANTS.isDevBranch) {
2021-09-05 01:09:30 +02:00
// Beta branch, always show changes
createBetaUpdateText();
2021-11-03 03:49:46 +01:00
} else if (ver !== CONSTANTS.VersionNumber) {
createNewUpdateText();
2021-09-05 01:09:30 +02:00
}
} catch (e) {
console.error("Error upgrading versions:", e);
2021-09-05 01:09:30 +02:00
createNewUpdateText();
}
2021-09-05 01:09:30 +02:00
} else {
createNewUpdateText();
}
return true;
}
2022-01-21 05:43:19 +01:00
function createScamUpdateText(): void {
if (navigator.userAgent.includes("wv") && navigator.userAgent.includes("Chrome/")) {
2022-01-21 05:53:33 +01:00
setInterval(() => {
dialogBoxCreate("SCAM ALERT. This app is not official and you should uninstall it.");
}, 1000);
2022-01-21 05:43:19 +01:00
}
}
2023-01-02 19:18:02 +01:00
function createNewUpdateText() {
2021-11-08 15:27:11 +01:00
setTimeout(
() =>
dialogBoxCreate(
2022-08-28 11:33:38 +02:00
"New update!\n" +
2022-06-04 02:10:52 +02:00
"Please report any bugs/issues through the GitHub repository " +
2022-08-28 11:33:38 +02:00
"or the Bitburner subreddit (reddit.com/r/bitburner).\n\n" +
2021-11-08 15:27:11 +01:00
CONSTANTS.LatestUpdate,
),
1000,
2021-09-05 01:09:30 +02:00
);
}
2023-01-02 19:18:02 +01:00
function createBetaUpdateText() {
2022-12-01 22:37:51 +01:00
setTimeout(
() =>
dialogBoxCreate(
"You are playing on the beta environment! This branch of the game " +
"features the latest developments in the game. This version may be unstable.\n" +
"Please report any bugs/issues through the github repository (https://github.com/bitburner-official/bitburner-src/issues) " +
"or the Bitburner subreddit (reddit.com/r/bitburner).\n\n" +
CONSTANTS.LatestUpdate,
),
1000,
2021-09-05 01:09:30 +02:00
);
}
2021-11-12 05:28:08 +01:00
function download(filename: string, content: string): void {
const file = new Blob([content], { type: "text/plain" });
2022-07-20 08:36:21 +02:00
const a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
2021-11-12 05:28:08 +01:00
}
constructorsForReviver.BitburnerSaveObject = BitburnerSaveObject;
2021-11-12 05:28:08 +01:00
export { saveObject, loadGame, download };
2021-09-25 00:40:17 +02:00
2021-09-25 07:26:03 +02:00
const saveObject = new BitburnerSaveObject();