An OpenMW mod that lets you play the whole Elder Scrolls III: Morrowind as a top-down isometric game — with full online co-op or MMO modes.
C++
Characters that go between single-player and servers, picked in the launchers
pw-tfbff34a8d38c5
diff --git a/apps/openmw-mp/Script/Functions/Mechanics.cpp b/apps/openmw-mp/Script/Functions/Mechanics.cppindex 78c1923..80b2481 100644--- a/apps/openmw-mp/Script/Functions/Mechanics.cpp+++ b/apps/openmw-mp/Script/Functions/Mechanics.cpp@@ -136,6 +136,46 @@ const char *MechanicsFunctions::GetSelectedSpellId(unsigned short pid) noexceptreturn player->selectedSpellId.c_str();}+const char *MechanicsFunctions::GetPortableCharacterId(unsigned short pid) noexcept+{+ Player *player;+ GET_PLAYER(pid, player, "");++ return player->portableId.c_str();+}++double MechanicsFunctions::GetPortableCharacterPlayed(unsigned short pid) noexcept+{+ Player *player;+ GET_PLAYER(pid, player, 0);++ return player->portablePlayed;+}++unsigned int MechanicsFunctions::GetPortableDataChunk(unsigned short pid) noexcept+{+ Player *player;+ GET_PLAYER(pid, player, 0);++ return player->portableChunk;+}++unsigned int MechanicsFunctions::GetPortableDataChunkCount(unsigned short pid) noexcept+{+ Player *player;+ GET_PLAYER(pid, player, 0);++ return player->portableChunkCount;+}++const char *MechanicsFunctions::GetPortableData(unsigned short pid) noexcept+{+ Player *player;+ GET_PLAYER(pid, player, "");++ return player->portableData.c_str();+}+unsigned int MechanicsFunctions::GetDrawState(unsigned short pid) noexcept{Player *player;@@ -225,6 +265,33 @@ void MechanicsFunctions::SendSelectedSpell(unsigned short pid)packet->Send(false);}+void MechanicsFunctions::SendPortableRequest(unsigned short pid)+{+ Player *player;+ GET_PLAYER(pid, player, );++ player->miscellaneousChangeType = mwmp::MISCELLANEOUS_CHANGE_TYPE::PORTABLE_REQUEST;++ mwmp::PlayerPacket *packet = mwmp::Networking::get().getPlayerPacketController()->GetPacket(ID_PLAYER_MISCELLANEOUS);+ packet->setPlayer(player);++ packet->Send(false);+}++void MechanicsFunctions::SendPortableLinked(unsigned short pid, const char *characterId)+{+ Player *player;+ GET_PLAYER(pid, player, );++ player->miscellaneousChangeType = mwmp::MISCELLANEOUS_CHANGE_TYPE::PORTABLE_LINKED;+ player->portableId = characterId;++ mwmp::PlayerPacket *packet = mwmp::Networking::get().getPlayerPacketController()->GetPacket(ID_PLAYER_MISCELLANEOUS);+ packet->setPlayer(player);++ packet->Send(false);+}+void MechanicsFunctions::SendAlliedPlayers(unsigned short pid, bool sendToOtherPlayers){Player *player;diff --git a/apps/openmw-mp/Script/Functions/Mechanics.hpp b/apps/openmw-mp/Script/Functions/Mechanics.hppindex fa0ee91..e9f5978 100644--- a/apps/openmw-mp/Script/Functions/Mechanics.hpp+++ b/apps/openmw-mp/Script/Functions/Mechanics.hpp@@ -15,6 +15,11 @@{"GetMarkRotX", MechanicsFunctions::GetMarkRotX},\{"GetMarkRotZ", MechanicsFunctions::GetMarkRotZ},\{"GetSelectedSpellId", MechanicsFunctions::GetSelectedSpellId},\+ {"GetPortableCharacterId", MechanicsFunctions::GetPortableCharacterId},\+ {"GetPortableCharacterPlayed", MechanicsFunctions::GetPortableCharacterPlayed},\+ {"GetPortableDataChunk", MechanicsFunctions::GetPortableDataChunk},\+ {"GetPortableDataChunkCount", MechanicsFunctions::GetPortableDataChunkCount},\+ {"GetPortableData", MechanicsFunctions::GetPortableData},\\{"DoesPlayerHavePlayerKiller", MechanicsFunctions::DoesPlayerHavePlayerKiller},\{"GetPlayerKillerPid", MechanicsFunctions::GetPlayerKillerPid},\@@ -35,6 +40,8 @@\{"SendMarkLocation", MechanicsFunctions::SendMarkLocation},\{"SendSelectedSpell", MechanicsFunctions::SendSelectedSpell},\+ {"SendPortableRequest", MechanicsFunctions::SendPortableRequest},\+ {"SendPortableLinked", MechanicsFunctions::SendPortableLinked},\{"SendAlliedPlayers", MechanicsFunctions::SendAlliedPlayers},\\{"Jail", MechanicsFunctions::Jail},\@@ -119,6 +126,47 @@ public:*/static const char *GetSelectedSpellId(unsigned short pid) noexcept;+ /**+ * \brief Isowind: get the id of the single-player character a player joined with (from a PlayerMiscellaneous+ * packet of the PORTABLE_CHARACTER type).+ *+ * \param pid The player ID.+ * \return The character's id.+ */+ static const char *GetPortableCharacterId(unsigned short pid) noexcept;++ /**+ * \brief Isowind: get when the single-player character a player joined with was last played.+ *+ * \param pid The player ID.+ * \return Seconds since 1970, by the player's clock.+ */+ static double GetPortableCharacterPlayed(unsigned short pid) noexcept;++ /**+ * \brief Isowind: get which chunk of a single-player character a PORTABLE_DATA packet has (from 0).+ *+ * \param pid The player ID.+ * \return The chunk's index.+ */+ static unsigned int GetPortableDataChunk(unsigned short pid) noexcept;++ /**+ * \brief Isowind: get how many chunks a single-player character is sent in.+ *+ * \param pid The player ID.+ * \return The number of chunks.+ */+ static unsigned int GetPortableDataChunkCount(unsigned short pid) noexcept;++ /**+ * \brief Isowind: get a chunk of a single-player character (JSON, whole once the chunks are joined).+ *+ * \param pid The player ID.+ * \return The chunk.+ */+ static const char *GetPortableData(unsigned short pid) noexcept;+/*** \brief Check whether the killer of a certain player is also a player.*@@ -255,6 +303,25 @@ public:*/static void SendMarkLocation(unsigned short pid);+ /**+ * \brief Isowind: ask a player for the single-player character they joined with; it comes back in+ * PlayerMiscellaneous packets of the PORTABLE_DATA type.+ *+ * \param pid The player ID.+ * \return void+ */+ static void SendPortableRequest(unsigned short pid);++ /**+ * \brief Isowind: tell a player they are logged in as a character that goes to single-player (the one they joined+ * with, or one made here), so what it gains here is written back there.+ *+ * \param pid The player ID.+ * \param characterId The character's id (the single-player one's, or one made for a character made here).+ * \return void+ */+ static void SendPortableLinked(unsigned short pid, const char *characterId);+/*** \brief Send a PlayerMiscellaneous packet with a selected spell ID to a player.*diff --git a/apps/openmw/engine.cpp b/apps/openmw/engine.cppindex 5236de5..794aecc 100644--- a/apps/openmw/engine.cpp+++ b/apps/openmw/engine.cpp@@ -2,6 +2,7 @@#include "mwmp/GUIController.hpp"#include "mwmp/Main.hpp"+#include "mwmp/PortableCharacter.hpp"#include "mwmp/Hooks.hpp"@@ -40,6 +41,7 @@#include <components/sceneutil/workqueue.hpp>#include <components/files/configurationmanager.hpp>+#include <components/files/conversion.hpp>#include <components/version/version.hpp>@@ -418,6 +420,8 @@ OMW::Engine::~Engine()// Isowind multiplayerif (mwmp::Main::isInitialized()){+ // A character from single-player takes what it gained back with it, while the world is still there+ mwmp::PortableCharacter::finish(*mwmp::Main::get().getLocalPlayer());mwmp::Main::get().getGUIController()->cleanUp();mwmp::Main::destroy();}@@ -747,6 +751,7 @@ void OMW::Engine::setWindowIcon()void OMW::Engine::prepareEngine(){mStateManager = std::make_unique<MWState::StateManager>(mCfgMgr.getUserDataPath() / "saves", mContentFiles);+ mwmp::Main::setSavesPath(mCfgMgr.getUserDataPath() / "saves");mEnvironment.setStateManager(*mStateManager);const bool stereoEnabled = Settings::stereo().mStereoEnabled || osg::DisplaySettings::instance().get()->getStereo();@@ -1032,6 +1037,11 @@ void OMW::Engine::go(){mStateManager->loadGame(mSaveGameFile);}+ else if (!mwmp::Main::getServerCharacter().empty())+ {+ // Isowind: a character made on a multiplayer server, played offline for the first time+ mStateManager->startServerCharacter(Files::pathFromUnicodeString(mwmp::Main::getServerCharacter()));+ }else if (!mSkipMenu){// start in main menudiff --git a/apps/openmw/mwmp/LocalPlayer.cpp b/apps/openmw/mwmp/LocalPlayer.cppindex 0b2c93e..b5ce772 100644--- a/apps/openmw/mwmp/LocalPlayer.cpp+++ b/apps/openmw/mwmp/LocalPlayer.cpp@@ -57,7 +57,9 @@#include "CellController.hpp"#include "GUIController.hpp"#include "MechanicsHelper.hpp"+#include "RecordHelper.hpp"#include "Ids.hpp"+#include "PortableCharacter.hpp"using namespace mwmp;@@ -163,8 +165,21 @@ bool LocalPlayer::processCharGen()switch (charGenState.currentStage){case 0:+ {+ // A character from single-player keeps its name: no asking for one+ if (!Main::getCharacterSave().empty())+ {+ std::string name = PortableCharacter::readName(Main::getCharacterSave());+ if (!name.empty())+ {+ MWBase::Environment::get().getMechanicsManager()->setPlayerName(name.substr(0, 31));+ charGenState.currentStage = 1;+ return false;+ }+ }windowManager->pushGuiMode(MWGui::GM_Name);break;+ }case 1:windowManager->pushGuiMode(MWGui::GM_Race);break;@@ -221,6 +236,21 @@ bool LocalPlayer::processCharGen()return true;}+void LocalPlayer::waitInVoid()+{+ MWBase::World *world = MWBase::Environment::get().getWorld();+ ESM::Position pos;+ pos.pos[0] = pos.pos[1] = pos.pos[2] = 0;+ pos.rot[0] = pos.rot[1] = pos.rot[2] = 0;+ world->getPlayer().setTeleported(true);+ world->changeToInteriorCell(RecordHelper::getPlaceholderInteriorCellName(), pos, false);+ // Collision off: nothing to stand on there, so no falling either+ if (!world->toggleCollisionMode())+ waitingInVoid = true;+ else+ world->toggleCollisionMode();+}+bool LocalPlayer::isLoggedIn(){if (charGenState.isFinished && (charGenState.endStage > 1 || receivedCharacter))@@ -1147,6 +1177,16 @@ void LocalPlayer::setCell()// To avoid crashes, close container windows this player may be incloseInventoryWindows();+ // Placed for the first time: out of the void, falling as everyone does+ if (waitingInVoid)+ {+ waitingInVoid = false;+ if (!world->toggleCollisionMode())+ world->toggleCollisionMode();+ }+ MWWorld::Ptr ptrPlayer = getPlayerPtr();+ ptrPlayer.getClass().getCreatureStats(ptrPlayer).land(true);+world->getPlayer().setTeleported(true);if (cell.isExterior())diff --git a/apps/openmw/mwmp/LocalPlayer.hpp b/apps/openmw/mwmp/LocalPlayer.hppindex 92bd2da..bb8dd8f 100644--- a/apps/openmw/mwmp/LocalPlayer.hpp+++ b/apps/openmw/mwmp/LocalPlayer.hpp@@ -19,6 +19,8 @@ namespace mwmptime_t deathTime;bool receivedCharacter;+ // Isowind: out of sight until the server places the player (see waitInVoid)+ bool waitingInVoid = false;bool isUsingBed;bool avoidSendingInventoryPackets;@@ -71,6 +73,10 @@ namespace mwmpvoid setPosition();void setMomentum();void setCell();++ // Isowind: until the server places the player (logging in, or after character creation), they wait in the+ // empty placeholder cell, not falling, instead of standing where a new game puts them+ void waitInVoid();void setClass();void setEquipment();void setInventory();diff --git a/apps/openmw/mwmp/Main.cpp b/apps/openmw/mwmp/Main.cppindex c26dd4c..a2bdb44 100644--- a/apps/openmw/mwmp/Main.cpp+++ b/apps/openmw/mwmp/Main.cpp@@ -1,5 +1,7 @@#include <cstdlib>+#include <components/files/configurationmanager.hpp>+#include <components/files/conversion.hpp>#include <components/openmw-mp/Utils.hpp>#include <components/openmw-mp/TimedLog.hpp>#include <components/openmw-mp/Version.hpp>@@ -44,12 +46,16 @@#include "CellController.hpp"#include "MechanicsHelper.hpp"#include "RecordHelper.hpp"+#include "PortableCharacter.hpp"using namespace mwmp;Main *Main::pMain = 0;std::string Main::address = "";std::string Main::serverPassword = TES3MP_DEFAULT_PASSW;+std::string Main::characterSave = "";+std::string Main::serverCharacter = "";+std::filesystem::path Main::savesPath;Main::Main(){@@ -81,7 +87,11 @@ void Main::optionsDesc(boost::program_options::options_description *desc)("connect", bpo::value<std::string>()->default_value(""),"play multiplayer on this server (e.g. --connect=127.0.0.1:25565)")("password", bpo::value<std::string>()->default_value(TES3MP_DEFAULT_PASSW),- "the server's password, if it has one");+ "the server's password, if it has one")+ ("character", bpo::value<Files::MaybeQuotedPath>()->default_value(Files::MaybeQuotedPath(), ""),+ "play multiplayer with this single-player character, from its save (if the server takes them)")+ ("server-character", bpo::value<Files::MaybeQuotedPath>()->default_value(Files::MaybeQuotedPath(), ""),+ "play a character made on a multiplayer server offline for the first time (its saves folder)");}void Main::configure(const boost::program_options::variables_map &variables)@@ -90,6 +100,8 @@ void Main::configure(const boost::program_options::variables_map &variables)serverPassword = variables["password"].as<std::string>();if (serverPassword.empty())serverPassword = TES3MP_DEFAULT_PASSW;+ characterSave = Files::pathToUnicodeString(variables["character"].as<Files::MaybeQuotedPath>());+ serverCharacter = Files::pathToUnicodeString(variables["server-character"].as<Files::MaybeQuotedPath>());if (isRequested())LOG_INIT(TimedLog::LOG_INFO);}@@ -127,6 +139,8 @@ void Main::postInit()// Only the client the server makes a region's authority creates its weather; the others follow itMWBase::Environment::get().getWorld()->setWeatherCreationState(false);RecordHelper::createPlaceholderInteriorCell();+ // Out of sight until the server places the player (not where a new game starts, which isn't where they are)+ pMain->mLocalPlayer->waitInVoid();}bool Main::isInitialized()@@ -169,6 +183,9 @@ void Main::updateWorld(float dt) constmNetworking->getPlayerPacket(ID_LOADED)->setPlayer(getLocalPlayer());mNetworking->getPlayerPacket(ID_PLAYER_BASEINFO)->Send();mNetworking->getPlayerPacket(ID_LOADED)->Send();+ // A character from single-player: the server asks for it if it takes them+ if (!characterSave.empty())+ PortableCharacter::sendInfo(*mLocalPlayer);mLocalPlayer->updateStatsDynamic(true);get().getGUIController()->setChatVisible(true);}@@ -177,6 +194,7 @@ void Main::updateWorld(float dt) constmLocalPlayer->update();mCellController->updateLocal(false);MechanicsHelper::updatePrivateFollowers(dt);+ PortableCharacter::update(*mLocalPlayer, dt);}}@@ -210,6 +228,26 @@ CellController *Main::getCellController() constreturn mCellController;}+const std::string &Main::getCharacterSave()+{+ return characterSave;+}++const std::string &Main::getServerCharacter()+{+ return serverCharacter;+}++void Main::setSavesPath(const std::filesystem::path &path)+{+ savesPath = path;+}++const std::filesystem::path &Main::getSavesPath()+{+ return savesPath;+}+bool Main::isValidPacketScript(const std::string &scriptId){mwmp::BaseWorldstate *worldstate = get().getNetworking()->getWorldstate();diff --git a/apps/openmw/mwmp/Main.hpp b/apps/openmw/mwmp/Main.hppindex 6066057..7997f83 100644--- a/apps/openmw/mwmp/Main.hpp+++ b/apps/openmw/mwmp/Main.hpp@@ -1,6 +1,7 @@#ifndef OPENMW_MWMP_MAIN#define OPENMW_MWMP_MAIN+#include <filesystem>#include <string>#include <vector>@@ -40,6 +41,18 @@ namespace mwmpstatic const Main &get();static void frame(float dt);+ // The single-player save of the character the player joined with (--character), or empty: see+ // PortableCharacter.hpp+ static const std::string &getCharacterSave();++ // Single-player: the saves folder of a character made on a server, to play offline for the first time+ // (--server-character), or empty+ static const std::string &getServerCharacter();++ // Where the single-player characters' saves are (the engine sets it)+ static void setSavesPath(const std::filesystem::path &path);+ static const std::filesystem::path &getSavesPath();+static bool isValidPacketScript(const std::string &scriptId);static bool isValidPacketGlobal(const std::string &globalId);@@ -54,6 +67,9 @@ namespace mwmpprivate:static std::string address;static std::string serverPassword;+ static std::string characterSave;+ static std::string serverCharacter;+ static std::filesystem::path savesPath;Main (const Main&) = delete;Main& operator= (const Main&) = delete;static Main *pMain;diff --git a/apps/openmw/mwmp/PortableCharacter.cpp b/apps/openmw/mwmp/PortableCharacter.cppnew file mode 100644index 0000000..ee907fb--- /dev/null+++ b/apps/openmw/mwmp/PortableCharacter.cpp@@ -0,0 +1,1568 @@+#include "PortableCharacter.hpp"++#include <algorithm>+#include <array>+#include <cctype>+#include <charconv>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <filesystem>+#include <fstream>+#include <iomanip>+#include <map>+#include <random>+#include <set>+#include <sstream>+#include <vector>++#include <components/debug/debuglog.hpp>+#include <components/esm/defs.hpp>+#include <components/esm3/dialoguestate.hpp>+#include <components/esm3/esmreader.hpp>+#include <components/esm3/esmwriter.hpp>+#include <components/esm3/formatversion.hpp>+#include <components/esm3/npcstate.hpp>+#include <components/esm3/journalentry.hpp>+#include <components/esm/attr.hpp>+#include <components/esm3/loadalch.hpp>+#include <components/esm3/loadarmo.hpp>+#include <components/esm3/loadbook.hpp>+#include <components/esm3/loadclas.hpp>+#include <components/esm3/loadclot.hpp>+#include <components/esm3/loaddial.hpp>+#include <components/esm3/loadench.hpp>+#include <components/esm3/loadglob.hpp>+#include <components/esm3/quickkeys.hpp>+#include <components/misc/strings/lower.hpp>+#include <components/esm3/loadmgef.hpp>+#include <components/esm3/loadnpc.hpp>+#include <components/esm3/loadskil.hpp>+#include <components/esm3/loadspel.hpp>+#include <components/esm3/loadweap.hpp>+#include <components/esm3/player.hpp>+#include <components/esm3/queststate.hpp>+#include <components/esm3/savedgame.hpp>+#include <components/files/conversion.hpp>+#include <components/loadinglistener/loadinglistener.hpp>+#include <components/openmw-mp/NetworkMessages.hpp>+#include <components/openmw-mp/TimedLog.hpp>++#include "../mwbase/dialoguemanager.hpp"+#include "../mwbase/environment.hpp"+#include "../mwbase/journal.hpp"+#include "../mwbase/mechanicsmanager.hpp"+#include "../mwbase/windowmanager.hpp"+#include "../mwbase/world.hpp"+#include "../mwworld/cellstore.hpp"+#include "../mwworld/datetimemanager.hpp"+#include "../mwworld/inventorystore.hpp"+#include "../mwworld/player.hpp"+#include "../mwworld/worldmodel.hpp"+#include "../mwmechanics/actorutil.hpp"+#include "../mwmechanics/creaturestats.hpp"+#include "../mwmechanics/spells.hpp"+#include "../mwworld/class.hpp"+#include "../mwworld/esmstore.hpp"+#include "../mwworld/ptr.hpp"++#include "Ids.hpp"+#include "LocalPlayer.hpp"+#include "Main.hpp"+#include "Networking.hpp"+#include "Worldstate.hpp"++namespace mwmp+{+namespace+{+ // Records a game made for the player (potions they brewed, items they enchanted, spells they made), by id: what+ // their inventory and spells can need besides the game's own+ struct MadeRecords+ {+ std::map<ESM::RefId, ESM::Potion> potions;+ std::map<ESM::RefId, ESM::Spell> spells;+ std::map<ESM::RefId, ESM::Enchantment> enchantments;+ std::map<ESM::RefId, ESM::Weapon> weapons;+ std::map<ESM::RefId, ESM::Armor> armors;+ std::map<ESM::RefId, ESM::Clothing> clothes;+ std::map<ESM::RefId, ESM::Book> books;++ template <class T>+ static void readInto(ESM::ESMReader &reader, std::map<ESM::RefId, T> &records)+ {+ T record;+ bool isDeleted = false;+ record.load(reader, isDeleted);+ if (!isDeleted)+ records[record.mId] = record;+ }++ // Reads the record the reader is at if it's one of these kinds; false if it isn't+ bool read(ESM::ESMReader &reader, uint32_t type)+ {+ switch (type)+ {+ case ESM::REC_ALCH: readInto(reader, potions); return true;+ case ESM::REC_SPEL: readInto(reader, spells); return true;+ case ESM::REC_ENCH: readInto(reader, enchantments); return true;+ case ESM::REC_WEAP: readInto(reader, weapons); return true;+ case ESM::REC_ARMO: readInto(reader, armors); return true;+ case ESM::REC_CLOT: readInto(reader, clothes); return true;+ case ESM::REC_BOOK: readInto(reader, books); return true;+ default: return false;+ }+ }+ };++ // What the server needs from a save: the player and their records+ struct SaveContents+ {+ ESM::SavedGame profile;+ ESM::Player player;+ bool hasPlayer = false;+ ESM::NPC npc;+ bool hasNpc = false;+ std::map<ESM::RefId, ESM::Class> classes;+ std::vector<ESM::JournalEntry> journal;+ std::vector<ESM::QuestState> quests;+ ESM::DialogueState dialogue;+ MadeRecords made;+ // Kills by actor, the global variables, and the quick keys+ std::map<ESM::RefId, int> kills;+ std::vector<ESM::Global> globals;+ ESM::QuickKeys quickKeys;+ };++ // (Filled in place: the player's state can't be copied)+ void readSave(const std::string &save, SaveContents &contents)+ {+ ESM::ESMReader reader;+ reader.open(Files::pathFromUnicodeString(save));+ while (reader.hasMoreRecs())+ {+ ESM::NAME name = reader.getRecName();+ reader.getRecHeader();+ bool isDeleted = false;+ switch (name.toInt())+ {+ case ESM::REC_SAVE:+ contents.profile.load(reader);+ break;+ case ESM::REC_PLAY:+ contents.player.load(reader);+ contents.hasPlayer = true;+ break;+ case ESM::REC_NPC_:+ {+ ESM::NPC npc;+ npc.load(reader, isDeleted);+ if (isSameId(npc.mId, "player"))+ {+ contents.npc = npc;+ contents.hasNpc = true;+ }+ break;+ }+ case ESM::REC_CLAS:+ {+ ESM::Class record;+ record.load(reader, isDeleted);+ contents.classes[record.mId] = record;+ break;+ }+ case ESM::REC_JOUR:+ {+ ESM::JournalEntry entry;+ entry.load(reader);+ if (entry.mType == ESM::JournalEntry::Type_Journal)+ contents.journal.push_back(entry);+ break;+ }+ case ESM::REC_QUES:+ {+ ESM::QuestState quest;+ quest.load(reader);+ contents.quests.push_back(quest);+ break;+ }+ case ESM::REC_DIAS:+ contents.dialogue.load(reader);+ break;+ case ESM::REC_DCOU:+ // (as MWMechanics::Actors keeps them)+ while (reader.isNextSub("ID__"))+ {+ ESM::RefId id = reader.getRefId();+ int count = 0;+ reader.getHNT(count, "COUN");+ contents.kills[id] = count;+ }+ break;+ case ESM::REC_GLOB:+ {+ ESM::Global global;+ global.load(reader, isDeleted);+ contents.globals.push_back(global);+ break;+ }+ case ESM::REC_KEYS:+ contents.quickKeys.load(reader);+ break;+ default:+ if (!contents.made.read(reader, name.toInt()))+ reader.skipRecord();+ break;+ }+ }+ }++ // Just enough JSON: objects and arrays written in order, their members separated by commas+ class JsonWriter+ {+ public:+ void beginObject(std::string_view key = {})+ {+ prefix(key);+ mOut += '{';+ mFirst = true;+ }++ void endObject()+ {+ mOut += '}';+ mFirst = false;+ }++ void beginArray(std::string_view key = {})+ {+ prefix(key);+ mOut += '[';+ mFirst = true;+ }++ void endArray()+ {+ mOut += ']';+ mFirst = false;+ }++ void string(std::string_view key, std::string_view value)+ {+ prefix(key);+ quote(value);+ }++ void number(std::string_view key, double value)+ {+ prefix(key);+ if (!std::isfinite(value))+ value = 0;+ std::array<char, 32> buffer;+ auto result = std::to_chars(buffer.data(), buffer.data() + buffer.size(), value);+ mOut.append(buffer.data(), result.ptr);+ }++ void boolean(std::string_view key, bool value)+ {+ prefix(key);+ mOut += value ? "true" : "false";+ }++ const std::string &str() const { return mOut; }++ private:+ // The comma before a member, and its key in an object (none in an array)+ void prefix(std::string_view key)+ {+ if (!mFirst)+ mOut += ',';+ mFirst = false;+ if (!key.empty())+ {+ quote(key);+ mOut += ':';+ }+ }++ void quote(std::string_view text)+ {+ mOut += '"';+ for (char c : text)+ {+ if (c == '"' || c == '\\')+ {+ mOut += '\\';+ mOut += c;+ }+ else if (static_cast<unsigned char>(c) < 0x20)+ {+ char escaped[8];+ std::snprintf(escaped, sizeof(escaped), "\\u%04x", static_cast<unsigned char>(c));+ mOut += escaped;+ }+ else+ mOut += c;+ }+ mOut += '"';+ }++ std::string mOut;+ bool mFirst = true;+ };++ // Whether the server can know a record: one of the game's own, not one only this player's game made (a potion+ // they brewed, a spell they made)+ bool isKnown(const ESM::RefId &id)+ {+ return !id.empty() && !isLocalOnlyId(id) && MWBase::Environment::get().getESMStore()->find(id) != 0;+ }++ // The game's own item an enchanted one was made from (the server makes it again from that): the same model and+ // icon, not enchanted+ template <class T>+ const T *findBase(const T &item)+ {+ for (const T &candidate : MWBase::Environment::get().getESMStore()->get<T>())+ {+ if (!isLocalOnlyId(candidate.mId) && candidate.mEnchant.empty() && candidate.mModel == item.mModel+ && candidate.mIcon == item.mIcon)+ return &candidate;+ }+ return nullptr;+ }++ void writeEffects(JsonWriter &json, const ESM::EffectList &effects)+ {+ json.beginArray("effects");+ for (const ESM::IndexedENAMstruct &indexed : effects.mList)+ {+ const ESM::ENAMstruct &effect = indexed.mData;+ json.beginObject();+ json.number("id", ESM::MagicEffect::refIdToIndex(effect.mEffectID));+ json.number("attribute", ESM::Attribute::refIdToIndex(effect.mAttribute));+ json.number("skill", ESM::Skill::refIdToIndex(effect.mSkill));+ json.number("rangeType", effect.mRange);+ json.number("area", effect.mArea);+ json.number("duration", effect.mDuration);+ json.number("magnitudeMin", effect.mMagnMin);+ json.number("magnitudeMax", effect.mMagnMax);+ json.endObject();+ }+ json.endArray();+ }++ // The records the player's own game made that their items and spells take along, written as the server's record+ // stores keep them, under the ids the save has (the server gives them ids of its own)+ class MadeForServer+ {+ public:+ explicit MadeForServer(const MadeRecords &made)+ : mMade(made)+ {+ }++ // Whether an item or spell only the player's game knows can go (its records going with it)+ bool take(const ESM::RefId &id)+ {+ if (mMade.potions.count(id))+ mPotions.insert(id);+ else if (mMade.spells.count(id))+ mSpells.insert(id);+ else+ return takeEnchanted(mMade.weapons, mWeapons, id) || takeEnchanted(mMade.armors, mArmors, id)+ || takeEnchanted(mMade.clothes, mClothes, id) || takeEnchanted(mMade.books, mBooks, id);+ return true;+ }++ void write(JsonWriter &json) const+ {+ json.beginObject("records");+ json.beginObject("enchantment");+ for (const ESM::RefId &id : mEnchantments)+ {+ const ESM::Enchantment &record = mMade.enchantments.at(id);+ json.beginObject(idString(id));+ json.number("subtype", record.mData.mType);+ json.number("cost", record.mData.mCost);+ json.number("charge", record.mData.mCharge);+ json.number("flags", record.mData.mFlags);+ writeEffects(json, record.mEffects);+ json.endObject();+ }+ json.endObject();+ json.beginObject("potion");+ for (const ESM::RefId &id : mPotions)+ {+ const ESM::Potion &record = mMade.potions.at(id);+ json.beginObject(idString(id));+ json.string("name", record.mName);+ json.number("weight", record.mData.mWeight);+ json.number("value", record.mData.mValue);+ json.number("autoCalc", record.mData.mFlags & ESM::Potion::Autocalc);+ json.string("icon", record.mIcon);+ json.string("model", record.mModel);+ json.string("script", idString(record.mScript));+ writeEffects(json, record.mEffects);+ json.endObject();+ }+ json.endObject();+ json.beginObject("spell");+ for (const ESM::RefId &id : mSpells)+ {+ const ESM::Spell &record = mMade.spells.at(id);+ json.beginObject(idString(id));+ json.string("name", record.mName);+ json.number("subtype", record.mData.mType);+ json.number("cost", record.mData.mCost);+ json.number("flags", record.mData.mFlags);+ writeEffects(json, record.mEffects);+ json.endObject();+ }+ json.endObject();+ writeEnchanted(json, "weapon", mMade.weapons, mWeapons);+ writeEnchanted(json, "armor", mMade.armors, mArmors);+ writeEnchanted(json, "clothing", mMade.clothes, mClothes);+ writeEnchanted(json, "book", mMade.books, mBooks);+ json.endObject();+ }++ private:+ // An enchanted item goes as the game's item it was made from, its name, and its enchantment+ template <class T>+ bool takeEnchanted(const std::map<ESM::RefId, T> &records, std::set<ESM::RefId> &taken, const ESM::RefId &id)+ {+ auto found = records.find(id);+ if (found == records.end() || findBase(found->second) == nullptr)+ return false;+ const ESM::RefId &enchantment = found->second.mEnchant;+ if (isLocalOnlyId(enchantment))+ {+ if (!mMade.enchantments.count(enchantment))+ return false;+ mEnchantments.insert(enchantment);+ }+ taken.insert(id);+ return true;+ }++ template <class T>+ static void writeEnchanted(JsonWriter &json, std::string_view storeType, const std::map<ESM::RefId, T> &records,+ const std::set<ESM::RefId> &taken)+ {+ json.beginObject(storeType);+ for (const ESM::RefId &id : taken)+ {+ const T &record = records.at(id);+ json.beginObject(idString(id));+ json.string("name", record.mName);+ json.string("baseId", idString(findBase(record)->mId));+ json.number("enchantmentCharge", record.mData.mEnchant);+ json.string("enchantmentId", idString(record.mEnchant));+ json.endObject();+ }+ json.endObject();+ }++ const MadeRecords &mMade;+ std::set<ESM::RefId> mPotions, mSpells, mEnchantments, mWeapons, mArmors, mClothes, mBooks;+ };++ std::string cellDescription(const ESM::RefId &cellId)+ {+ if (const auto *exterior = cellId.getIf<ESM::ESM3ExteriorCellRefId>())+ return std::to_string(exterior->getX()) + ", " + std::to_string(exterior->getY());+ return idString(cellId);+ }++ // The character as the server keeps it, in its terms (attributes and skills by their numbers; it names them)+ std::string toJson(const SaveContents &save)+ {+ const MWWorld::ESMStore &store = *MWBase::Environment::get().getESMStore();+ const ESM::NpcState &state = save.player.mObject;+ const ESM::CreatureStats &creatureStats = state.mCreatureStats;+ const ESM::NpcStats &npcStats = state.mNpcStats;++ JsonWriter json;+ json.beginObject();+ json.number("version", 1);+ json.string("name", save.npc.mName);+ json.string("race", idString(save.npc.mRace));+ json.string("head", idString(save.npc.mHead));+ json.string("hair", idString(save.npc.mHair));+ json.boolean("male", save.npc.isMale());+ json.string("birthsign", idString(save.player.mBirthsign));++ // A class of the game's is named; one the player made comes whole+ auto customClass = save.classes.find(save.npc.mClass);+ if (store.get<ESM::Class>().search(save.npc.mClass) != nullptr || customClass == save.classes.end())+ json.string("class", idString(save.npc.mClass));+ else+ {+ const ESM::Class &record = customClass->second;+ json.beginObject("customClass");+ json.string("name", record.mName);+ json.string("description", record.mDescription);+ json.number("specialization", record.mData.mSpecialization);+ json.beginArray("majorAttributes");+ for (int attribute : record.mData.mAttribute)+ json.number({}, attribute);+ json.endArray();+ json.beginArray("majorSkills");+ for (int i = 0; i < 5; ++i)+ json.number({}, record.mData.getSkill(i, true));+ json.endArray();+ json.beginArray("minorSkills");+ for (int i = 0; i < 5; ++i)+ json.number({}, record.mData.getSkill(i, false));+ json.endArray();+ json.endObject();+ }+ // Character creation not finished in single-player: nothing to bring yet+ json.boolean("unfinished", save.npc.mClass.empty() || save.player.mBirthsign.empty());++ json.number("level", creatureStats.mLevel);+ json.number("levelProgress", npcStats.mLevelProgress);+ const char *dynamicNames[] = { "health", "magicka", "fatigue" };+ for (int i = 0; i < 3; ++i)+ {+ json.beginArray(dynamicNames[i]);+ json.number({}, creatureStats.mDynamic[i].mBase);+ json.number({}, creatureStats.mDynamic[i].mCurrent);+ json.endArray();+ }+ json.beginArray("attributes");+ for (size_t i = 0; i < creatureStats.mAttributes.size(); ++i)+ {+ json.beginArray();+ json.number({}, creatureStats.mAttributes[i].mBase);+ json.number({}, creatureStats.mAttributes[i].mDamage);+ json.number({}, npcStats.mSkillIncrease[i]);+ json.endArray();+ }+ json.endArray();+ json.beginArray("skills");+ for (const auto &skill : npcStats.mSkills)+ {+ json.beginArray();+ json.number({}, skill.mBase);+ json.number({}, skill.mDamage);+ json.number({}, skill.mProgress);+ json.endArray();+ }+ json.endArray();++ // Items and spells the player made go with the records they need; any the server can't be given (an item+ // whose own records are missing from the save, say) are left behind, and counted so the player can be told+ MadeForServer made(save.made);+ int skippedItems = 0;+ const std::vector<ESM::ObjectState> &items = state.mInventory.mItems;+ std::vector<bool> goes(items.size());+ for (size_t i = 0; i < items.size(); ++i)+ {+ const ESM::RefId &id = items[i].mRef.mRefID;+ goes[i] = isKnown(id) || (isLocalOnlyId(id) && made.take(id));+ }+ json.beginArray("inventory");+ for (size_t i = 0; i < items.size(); ++i)+ {+ const ESM::ObjectState &item = items[i];+ if (!goes[i])+ {+ ++skippedItems;+ continue;+ }+ json.beginArray();+ json.string({}, idString(item.mRef.mRefID));+ json.number({}, item.mRef.mCount);+ json.number({}, item.mRef.mChargeInt);+ json.number({}, item.mRef.mEnchantmentCharge);+ json.string({}, idString(item.mRef.mSoul));+ json.endArray();+ }+ json.endArray();+ // The equipment slots, by the inventory store's numbers (the server's too)+ json.beginObject("equipment");+ for (const auto &[index, slot] : state.mInventory.mEquipmentSlots)+ {+ if (index >= items.size() || !goes[index])+ continue;+ const ESM::CellRef &ref = items[index].mRef;+ json.beginArray(std::to_string(slot));+ json.string({}, idString(ref.mRefID));+ json.number({}, ref.mCount);+ json.number({}, ref.mChargeInt);+ json.number({}, ref.mEnchantmentCharge);+ json.endArray();+ }+ json.endObject();++ // The spells known: a save keeps those learned in the player's record and the rest in their state+ std::vector<ESM::RefId> knownSpells = save.npc.mSpells.mList;+ for (const ESM::RefId &spell : creatureStats.mSpells.mSpells)+ {+ if (std::find(knownSpells.begin(), knownSpells.end(), spell) == knownSpells.end())+ knownSpells.push_back(spell);+ }+ int skippedSpells = 0;+ json.beginArray("spells");+ for (const ESM::RefId &spell : knownSpells)+ {+ bool known = isLocalOnlyId(spell) ? made.take(spell) : store.get<ESM::Spell>().search(spell) != nullptr;+ if (known)+ json.string({}, idString(spell));+ else+ ++skippedSpells;+ }+ json.endArray();+ json.number("skippedItems", skippedItems);+ json.number("skippedSpells", skippedSpells);+ made.write(json);++ // Skill books read+ json.beginArray("books");+ for (const ESM::RefId &book : npcStats.mUsedIds)+ json.string({}, idString(book));+ json.endArray();++ json.number("bounty", npcStats.mBounty);+ json.number("reputation", npcStats.mReputation);+ // Rank (-1: not a member), expelled, reputation+ json.beginObject("factions");+ for (const auto &[faction, stats] : npcStats.mFactions)+ {+ json.beginArray(idString(faction));+ json.number({}, stats.mRank);+ json.boolean({}, stats.mExpelled);+ json.number({}, stats.mReputation);+ json.endArray();+ }+ json.endObject();++ // The journal's entries in order (quest, its index, and the day: days passed, month, day of the month), the+ // quests' stages, and the topics known+ json.beginArray("journal");+ for (const ESM::JournalEntry &entry : save.journal)+ {+ const ESM::Dialogue *quest = store.get<ESM::Dialogue>().search(entry.mTopic);+ if (quest == nullptr)+ continue;+ auto info = std::find_if(quest->mInfo.begin(), quest->mInfo.end(),+ [&](const ESM::DialInfo &each) { return each.mId == entry.mInfo; });+ if (info == quest->mInfo.end())+ continue;+ json.beginArray();+ json.string({}, idString(quest->mId));+ json.number({}, info->mData.mJournalIndex);+ json.number({}, entry.mDay);+ json.number({}, entry.mMonth);+ json.number({}, entry.mDayOfMonth);+ json.endArray();+ }+ json.endArray();+ json.beginArray("quests");+ for (const ESM::QuestState &quest : save.quests)+ {+ const ESM::Dialogue *dialogue = store.get<ESM::Dialogue>().search(quest.mTopic);+ if (dialogue == nullptr)+ continue;+ json.beginArray();+ json.string({}, idString(dialogue->mId));+ json.number({}, quest.mState);+ json.endArray();+ }+ json.endArray();+ json.beginArray("topics");+ for (const ESM::RefId &topic : save.dialogue.mKnownTopics)+ {+ if (const ESM::Dialogue *dialogue = store.get<ESM::Dialogue>().search(topic))+ json.string({}, idString(dialogue->mId));+ }+ json.endArray();++ // Kills by actor (quests count them), and the global variables the server keeps in step (quests' own among+ // them): type (0 short, 1 long, 2 float) and value+ json.beginObject("kills");+ for (const auto &[id, count] : save.kills)+ {+ if (store.find(id) != 0)+ json.number(idString(id), count);+ }+ json.endObject();+ json.beginObject("globals");+ for (const ESM::Global &global : save.globals)+ {+ const std::string id = Misc::StringUtils::lowerCase(idString(global.mId));+ if (!Main::isValidPacketGlobal(id))+ continue;+ json.beginArray(id);+ if (global.mValue.getType() == ESM::VT_Float)+ {+ json.number({}, 2);+ json.number({}, global.mValue.getFloat());+ }+ else+ {+ json.number({}, global.mValue.getType() == ESM::VT_Short ? 0 : 1);+ json.number({}, global.mValue.getInteger());+ }+ json.endArray();+ }+ json.endObject();++ // The quick keys: slot (from 1), type (0 item, 1 spell, 2 item's magic) and the item or spell+ json.beginArray("quickKeys");+ for (size_t i = 0; i < save.quickKeys.mKeys.size() && i < 9; ++i)+ {+ const ESM::QuickKeys::QuickKey &key = save.quickKeys.mKeys[i];+ if (key.mType != ESM::QuickKeys::Type::Item && key.mType != ESM::QuickKeys::Type::Magic+ && key.mType != ESM::QuickKeys::Type::MagicItem)+ continue;+ json.beginArray();+ json.number({}, static_cast<double>(i + 1));+ json.number({}, static_cast<double>(key.mType));+ json.string({}, idString(key.mId));+ json.endArray();+ }+ json.endArray();++ // Where they were+ json.string("cell", cellDescription(save.player.mCellId));+ json.beginArray("position");+ for (float coordinate : state.mPosition.pos)+ json.number({}, coordinate);+ json.endArray();+ json.beginArray("rotation");+ json.number({}, state.mPosition.rot[0]);+ json.number({}, state.mPosition.rot[2]);+ json.endArray();++ json.endObject();+ return json.str();+ }++ // The character's id, beside its saves; made the first time it's needed+ std::string characterId(const std::filesystem::path &save)+ {+ std::filesystem::path file = save.parent_path() / "isowind-character.txt";+ std::string id;+ {+ std::ifstream in(file);+ std::getline(in, id);+ }+ id.erase(std::remove_if(id.begin(), id.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)); }),+ id.end());+ if (!id.empty())+ return id;++ std::random_device random;+ std::ostringstream text;+ for (int i = 0; i < 4; ++i)+ text << std::hex << std::setw(8) << std::setfill('0') << random();+ id = text.str();+ std::ofstream out(file);+ out << id << "\n";+ if (!out)+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_WARN, "Could not write %s", Files::pathToUnicodeString(file).c_str());+ return id;+ }++ // When the save was last written, in seconds since 1970+ double lastPlayed(const std::filesystem::path &save)+ {+ std::error_code error;+ auto fileTime = std::filesystem::last_write_time(save, error);+ if (error)+ return 0;+ auto systemTime = std::chrono::system_clock::now()+ + std::chrono::duration_cast<std::chrono::system_clock::duration>(+ fileTime - std::filesystem::file_time_type::clock::now());+ return std::chrono::duration<double>(systemTime.time_since_epoch()).count();+ }++ void sendMiscellaneous(LocalPlayer &player)+ {+ PlayerPacket *packet = Main::get().getNetworking()->getPlayerPacket(ID_PLAYER_MISCELLANEOUS);+ packet->setPlayer(&player);+ packet->Send();+ }++ // What the character gains on a server, beside its saves, in a save's terms: the player's inventory, NPC stats and+ // creature stats (an NpcState's own parts, in its order) in a record of their own; the records the server made+ // that the inventory and spells need (potions brewed, items enchanted, spells made there, and their+ // enchantments); and the journal and the topics known, as a save has them+ const char *const progressFileName = "isowind-server-progress.dat";+ const float progressInterval = 30;++ bool linked = false;+ float sinceWritten = 0;+ // Where the character's saves are (the one joined with, or one made on the server)+ std::filesystem::path progressFolder;++ // A record the server made (none of the game's own), kept to write with the progress+ template <class T>+ bool keepMade(const ESM::RefId &id, std::map<ESM::RefId, T> &records)+ {+ const MWWorld::Store<T> &store = MWBase::Environment::get().getESMStore()->get<T>();+ const T *record = store.search(id);+ if (record == nullptr || store.searchStatic(id) != nullptr)+ return false;+ records[id] = *record;+ return true;+ }++ template <class T>+ void keepMadeEnchanted(const ESM::RefId &id, std::map<ESM::RefId, T> &records, MadeRecords &made)+ {+ if (keepMade(id, records))+ keepMade(records[id].mEnchant, made.enchantments);+ }++ template <class T>+ void writeRecords(ESM::ESMWriter &writer, const std::map<ESM::RefId, T> &records)+ {+ for (const auto &[id, record] : records)+ {+ writer.startRecord(T::sRecordId);+ record.save(writer);+ writer.endRecord(T::sRecordId);+ }+ }++ void writeProgress(LocalPlayer &player)+ {+ if (!linked || progressFolder.empty() || !player.isLoggedIn())+ return;+ MWBase::World &world = *MWBase::Environment::get().getWorld();+ const MWWorld::ESMStore &store = *MWBase::Environment::get().getESMStore();+ MWWorld::Ptr ptr = MWMechanics::getPlayer();+ // Dead, they'd come back dead: the progress written last stays+ if (ptr.isEmpty() || !ptr.isInCell() || ptr.getClass().getCreatureStats(ptr).isDead())+ return;++ // The player as a save has them, and where they are+ ESM::Player record{};+ ptr.getBase()->save(record.mObject);+ if (!record.mObject.mHasCustomState)+ return;+ record.mCellId = ptr.getCell()->getCell()->getId();+ record.mBirthsign = world.getPlayer().getBirthSign();+ record.mHasMark = 0;+ record.mCurrentCrimeId = -1;+ record.mPaidCrimeId = -1;+ ESM::NpcState &state = record.mObject;+ // Every spell known (a state leaves out those its record has, and the ones learned are there)+ state.mCreatureStats.mSpells.mSpells.clear();+ for (const ESM::Spell *spell : ptr.getClass().getCreatureStats(ptr).getSpells())+ state.mCreatureStats.mSpells.mSpells.push_back(spell->mId);++ // Who they are: race, looks, name and class (a class the player made comes whole)+ const ESM::NPC &npc = *ptr.get<ESM::NPC>()->mBase;+ const ESM::Class *customClass+ = store.get<ESM::Class>().isDynamic(npc.mClass) ? store.get<ESM::Class>().search(npc.mClass) : nullptr;++ // What the launchers show of a character, as a save's header has it+ ESM::SavedGame profile;+ profile.mContentFiles = world.getContentFiles();+ profile.mPlayerName = npc.mName;+ profile.mPlayerLevel = ptr.getClass().getCreatureStats(ptr).getLevel();+ if (customClass != nullptr)+ profile.mPlayerClassName = customClass->mName;+ else+ profile.mPlayerClassId = npc.mClass;+ profile.mPlayerCellName = world.getCellName();+ profile.mInGameTime = world.getTimeManager()->getEpochTimeStamp();+ profile.mTimePlayed = 0;+ profile.mDescription = "From multiplayer";+ profile.mCurrentDay = world.getTimeManager()->getTimeStamp().getDay();+ profile.mCurrentHealth = ptr.getClass().getCreatureStats(ptr).getHealth().getCurrent();+ profile.mMaximumHealth = ptr.getClass().getCreatureStats(ptr).getHealth().getModified();++ MadeRecords made;+ for (const ESM::ObjectState &item : state.mInventory.mItems)+ {+ const ESM::RefId &id = item.mRef.mRefID;+ if (!keepMade(id, made.potions))+ {+ keepMadeEnchanted(id, made.weapons, made);+ keepMadeEnchanted(id, made.armors, made);+ keepMadeEnchanted(id, made.clothes, made);+ keepMadeEnchanted(id, made.books, made);+ }+ }+ for (const ESM::RefId &spell : state.mCreatureStats.mSpells.mSpells)+ keepMade(spell, made.spells);++ std::filesystem::path file = progressFolder / progressFileName;+ std::filesystem::path temporary = file;+ temporary += ".tmp";+ try+ {+ {+ std::ofstream out(temporary, std::ios::binary);+ ESM::ESMWriter writer;+ writer.setFormatVersion(ESM::CurrentSaveGameFormatVersion);+ writer.setVersion(0);+ writer.setType(0);+ writer.setAuthor("");+ writer.setDescription("");+ writer.save(out);+ writer.startRecord(ESM::REC_SAVE);+ profile.save(writer);+ writer.endRecord(ESM::REC_SAVE);+ writer.startRecord(ESM::REC_PLAY);+ record.save(writer);+ writer.endRecord(ESM::REC_PLAY);+ writer.startRecord(ESM::REC_NPC_);+ npc.save(writer);+ writer.endRecord(ESM::REC_NPC_);+ if (customClass != nullptr)+ {+ writer.startRecord(ESM::REC_CLAS);+ customClass->save(writer);+ writer.endRecord(ESM::REC_CLAS);+ }+ writeRecords(writer, made.enchantments);+ writeRecords(writer, made.potions);+ writeRecords(writer, made.spells);+ writeRecords(writer, made.weapons);+ writeRecords(writer, made.armors);+ writeRecords(writer, made.clothes);+ writeRecords(writer, made.books);+ Loading::Listener listener;+ MWBase::Environment::get().getJournal()->write(writer, listener);+ MWBase::Environment::get().getDialogueManager()->write(writer, listener);+ // Kills (and things stolen, which stay behind), the map and the quick keys, as a save has them+ MWBase::Environment::get().getMechanicsManager()->write(writer, listener);+ MWBase::Environment::get().getWindowManager()->write(writer, listener);+ // The global variables the server keeps in step (quests' own among them)+ for (const std::string &id : Main::get().getNetworking()->getWorldstate()->synchronizedClientGlobalIds)+ {+ char type = world.getGlobalVariableType(id);+ if (type == ' ')+ continue;+ ESM::Global global;+ global.mRecordFlags = 0;+ global.mId = ESM::RefId::stringRefId(id);+ if (type == 'f')+ {+ global.mValue.setType(ESM::VT_Float);+ global.mValue.setFloat(world.getGlobalFloat(id));+ }+ else+ {+ global.mValue.setType(type == 's' ? ESM::VT_Short : ESM::VT_Long);+ global.mValue.setInteger(world.getGlobalInt(id));+ }+ writer.startRecord(ESM::REC_GLOB);+ global.save(writer);+ writer.endRecord(ESM::REC_GLOB);+ }+ writer.close();+ if (!out)+ throw std::runtime_error("writing failed");+ }+ // Whole or not at all+ std::filesystem::rename(temporary, file);+ }+ catch (const std::exception &e)+ {+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_ERROR, "Could not write the character's progress to %s: %s",+ Files::pathToUnicodeString(file).c_str(), e.what());+ }+ }++ // What a progress file has, but its journal and topics (read in applyJournal, once these have gone on)+ struct Progress+ {+ ESM::Player player{};+ bool hasPlayer = false;+ ESM::NPC npc;+ bool hasNpc = false;+ std::map<ESM::RefId, ESM::Class> classes;+ MadeRecords made;+ };++ // (Filled in place: the player's state can't be copied)+ bool readProgress(const std::filesystem::path &file, Progress &progress)+ {+ ESM::ESMReader reader;+ reader.open(file);+ while (reader.hasMoreRecs())+ {+ ESM::NAME name = reader.getRecName();+ reader.getRecHeader();+ bool isDeleted = false;+ switch (name.toInt())+ {+ case ESM::REC_PLAY:+ progress.player.load(reader);+ progress.hasPlayer = true;+ break;+ case ESM::REC_NPC_:+ progress.npc.load(reader, isDeleted);+ progress.hasNpc = true;+ break;+ case ESM::REC_CLAS:+ {+ ESM::Class record;+ record.load(reader, isDeleted);+ progress.classes[record.mId] = record;+ break;+ }+ default:+ if (!progress.made.read(reader, name.toInt()))+ reader.skipRecord();+ break;+ }+ }+ return progress.hasPlayer;+ }++ // A record as a save has it, but its id: two the same are the same thing+ template <class T>+ std::string recordBytes(T record)+ {+ record.mId = ESM::RefId();+ std::ostringstream out;+ ESM::ESMWriter writer;+ writer.setFormatVersion(ESM::CurrentSaveGameFormatVersion);+ writer.save(out);+ writer.startRecord(T::sRecordId);+ record.save(writer);+ writer.endRecord(T::sRecordId);+ writer.close();+ return out.str();+ }++ // The records the server made, made again here (under ids of this game's), or found here already (one made the+ // same before, coming back from a server once more): the ids they had there, to this one's+ std::map<ESM::RefId, ESM::RefId> remakeRecords(const MadeRecords &made)+ {+ MWWorld::ESMStore &store = *MWBase::Environment::get().getESMStore();+ std::map<ESM::RefId, ESM::RefId> ids;+ auto remake = [&](const auto &records) {+ for (auto [id, record] : records)+ {+ if constexpr (requires { record.mEnchant; })+ {+ auto enchantment = ids.find(record.mEnchant);+ if (enchantment != ids.end())+ record.mEnchant = enchantment->second;+ }+ using Record = std::decay_t<decltype(record)>;+ const std::string bytes = recordBytes(record);+ ESM::RefId same;+ for (const Record &existing : store.get<Record>())+ {+ if (store.get<Record>().isDynamic(existing.mId) && recordBytes(existing) == bytes)+ {+ same = existing.mId;+ break;+ }+ }+ ids[id] = same.empty() ? store.insert(record)->mId : same;+ }+ };+ remake(made.enchantments);+ remake(made.potions);+ remake(made.spells);+ remake(made.weapons);+ remake(made.armors);+ remake(made.clothes);+ remake(made.books);+ return ids;+ }++ // The character as they were on the server, on the single-player character: stats, skills, spells, the whole+ // inventory, factions, bounty and reputation. Everything else (where they are, their world) stays.+ void mergeProgress(ESM::NpcState ¤t, const ESM::NpcState &progress,+ const std::map<ESM::RefId, ESM::RefId> &remade)+ {+ const MWWorld::ESMStore &store = *MWBase::Environment::get().getESMStore();+ ESM::CreatureStats &creatureStats = current.mCreatureStats;+ ESM::NpcStats &npcStats = current.mNpcStats;+ const ESM::CreatureStats &serverCreatureStats = progress.mCreatureStats;+ const ESM::NpcStats &serverNpcStats = progress.mNpcStats;++ // An id the server's game had, as this one has it (a record it made, made again here); empty for one only that+ // game knew. (Whether this game has the record is up to the caller: the store finds items by id, not spells.)+ auto idHere = [&](const ESM::RefId &id) {+ auto found = remade.find(id);+ if (found != remade.end())+ return found->second;+ return isLocalOnlyId(id) ? ESM::RefId() : id;+ };++ for (size_t i = 0; i < creatureStats.mAttributes.size(); ++i)+ {+ creatureStats.mAttributes[i].mBase = serverCreatureStats.mAttributes[i].mBase;+ creatureStats.mAttributes[i].mDamage = serverCreatureStats.mAttributes[i].mDamage;+ }+ for (size_t i = 0; i < creatureStats.mDynamic.size(); ++i)+ {+ creatureStats.mDynamic[i].mBase = serverCreatureStats.mDynamic[i].mBase;+ creatureStats.mDynamic[i].mCurrent = serverCreatureStats.mDynamic[i].mCurrent;+ }+ creatureStats.mLevel = serverCreatureStats.mLevel;+ for (size_t i = 0; i < npcStats.mSkills.size(); ++i)+ {+ npcStats.mSkills[i].mBase = serverNpcStats.mSkills[i].mBase;+ npcStats.mSkills[i].mDamage = serverNpcStats.mSkills[i].mDamage;+ npcStats.mSkills[i].mProgress = serverNpcStats.mSkills[i].mProgress;+ }+ npcStats.mLevelProgress = serverNpcStats.mLevelProgress;+ npcStats.mSkillIncrease = serverNpcStats.mSkillIncrease;+ npcStats.mSpecIncreases = serverNpcStats.mSpecIncreases;+ npcStats.mFactions = serverNpcStats.mFactions;+ npcStats.mBounty = serverNpcStats.mBounty;+ npcStats.mReputation = serverNpcStats.mReputation;+ // Skill books read in either+ for (const ESM::RefId &book : serverNpcStats.mUsedIds)+ {+ if (std::find(npcStats.mUsedIds.begin(), npcStats.mUsedIds.end(), book) == npcStats.mUsedIds.end())+ npcStats.mUsedIds.push_back(book);+ }++ std::vector<ESM::RefId> spells;+ creatureStats.mSpells.mSpellParams.clear();+ for (const ESM::RefId &spell : serverCreatureStats.mSpells.mSpells)+ {+ ESM::RefId here = idHere(spell);+ if (here.empty() || store.get<ESM::Spell>().search(here) == nullptr)+ continue;+ spells.push_back(here);+ auto params = serverCreatureStats.mSpells.mSpellParams.find(spell);+ if (params != serverCreatureStats.mSpells.mSpellParams.end())+ creatureStats.mSpells.mSpellParams[here] = params->second;+ }+ creatureStats.mSpells.mSpells = spells;++ // The whole inventory as it was there, equipped as it was+ ESM::InventoryState inventory;+ for (size_t i = 0; i < progress.mInventory.mItems.size(); ++i)+ {+ const ESM::ObjectState &item = progress.mInventory.mItems[i];+ ESM::RefId here = idHere(item.mRef.mRefID);+ if (here.empty() || store.find(here) == 0)+ continue;+ auto slot = progress.mInventory.mEquipmentSlots.find(static_cast<uint32_t>(i));+ if (slot != progress.mInventory.mEquipmentSlots.end())+ inventory.mEquipmentSlots[static_cast<uint32_t>(inventory.mItems.size())] = slot->second;+ inventory.mItems.push_back(item);+ inventory.mItems.back().mRef.mRefID = here;+ // Numbered by the server's game, not this one's+ inventory.mItems.back().mRef.mRefNum = ESM::RefNum();+ }+ for (const auto &[id, magnitudes] : progress.mInventory.mPermanentMagicEffectMagnitudes)+ {+ ESM::RefId here = idHere(id);+ if (!here.empty() && store.find(here) != 0)+ inventory.mPermanentMagicEffectMagnitudes[here] = magnitudes;+ }+ current.mInventory = std::move(inventory);+ }++ // The rest of the progress, as a save has it, the server's in place of the single-player: the journal (quests,+ // its entries, the topics' entries) and the topics known, kills, the map, the quick keys (on the items and+ // spells as this game has them now) and the global variables the server kept in step+ void applyRecords(const std::filesystem::path &file, const std::map<ESM::RefId, ESM::RefId> &remade)+ {+ MWBase::World &world = *MWBase::Environment::get().getWorld();+ MWBase::WindowManager &windows = *MWBase::Environment::get().getWindowManager();+ ESM::ESMReader reader;+ reader.open(file);+ bool cleared = false;+ while (reader.hasMoreRecs())+ {+ ESM::NAME name = reader.getRecName();+ reader.getRecHeader();+ uint32_t type = name.toInt();+ if (type == ESM::REC_JOUR || type == ESM::REC_QUES)+ {+ if (!cleared)+ {+ MWBase::Environment::get().getJournal()->clear();+ cleared = true;+ }+ MWBase::Environment::get().getJournal()->readRecord(reader, type);+ }+ else if (type == ESM::REC_DIAS)+ MWBase::Environment::get().getDialogueManager()->readRecord(reader, type);+ else if (type == ESM::REC_DCOU)+ MWBase::Environment::get().getMechanicsManager()->readRecord(reader, type);+ else if (type == ESM::REC_GMAP)+ windows.readRecord(reader, type);+ else if (type == ESM::REC_KEYS)+ {+ ESM::QuickKeys keys;+ keys.load(reader);+ MWWorld::Ptr player = MWMechanics::getPlayer();+ MWWorld::InventoryStore &inventory = player.getClass().getInventoryStore(player);+ for (size_t i = 0; i < keys.mKeys.size() && i < 9; ++i)+ {+ const int slot = static_cast<int>(i) + 1;+ const ESM::QuickKeys::QuickKey &key = keys.mKeys[i];+ auto found = remade.find(key.mId);+ const ESM::RefId id = found != remade.end() ? found->second : key.mId;+ if (key.mType == ESM::QuickKeys::Type::Item || key.mType == ESM::QuickKeys::Type::MagicItem)+ {+ auto item = std::find_if(inventory.begin(), inventory.end(),+ [&](const MWWorld::Ptr &each) { return each.getCellRef().getRefId() == id; });+ if (item != inventory.end())+ windows.setQuickKey(slot, static_cast<int>(key.mType), *item, ESM::RefId());+ else+ windows.setQuickKey(slot, static_cast<int>(ESM::QuickKeys::Type::Unassigned),+ MWWorld::Ptr(), ESM::RefId());+ }+ else if (key.mType == ESM::QuickKeys::Type::Magic+ && player.getClass().getCreatureStats(player).getSpells().hasSpell(id))+ windows.setQuickKey(slot, static_cast<int>(key.mType), MWWorld::Ptr(), id);+ else+ windows.setQuickKey(+ slot, static_cast<int>(ESM::QuickKeys::Type::Unassigned), MWWorld::Ptr(), ESM::RefId());+ }+ }+ else if (type == ESM::REC_GLOB)+ {+ ESM::Global global;+ bool isDeleted = false;+ global.load(reader, isDeleted);+ const std::string id = idString(global.mId);+ const char kind = world.getGlobalVariableType(id);+ if (kind == 'f')+ world.setGlobalFloat(id, global.mValue.getFloat());+ else if (kind == 's' || kind == 'l')+ world.setGlobalInt(id, global.mValue.getInteger());+ }+ else+ reader.skipRecord();+ }+ }+}++std::string PortableCharacter::readName(const std::string &save)+{+ try+ {+ ESM::ESMReader reader;+ reader.open(Files::pathFromUnicodeString(save));+ if (reader.getRecName() != ESM::REC_SAVE)+ return {};+ reader.getRecHeader();+ ESM::SavedGame profile;+ profile.load(reader);+ return profile.mPlayerName;+ }+ catch (const std::exception &e)+ {+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_ERROR, "Could not read the character's save %s: %s", save.c_str(), e.what());+ return {};+ }+}++void PortableCharacter::sendInfo(LocalPlayer &player)+{+ std::filesystem::path save = Files::pathFromUnicodeString(Main::getCharacterSave());+ player.miscellaneousChangeType = MISCELLANEOUS_CHANGE_TYPE::PORTABLE_CHARACTER;+ player.portableId = characterId(save);+ player.portablePlayed = lastPlayed(save);+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "Joining with the single-player character %s (%s)",+ player.portableId.c_str(), Main::getCharacterSave().c_str());+ sendMiscellaneous(player);+}++void PortableCharacter::send(LocalPlayer &player)+{+ std::string json;+ try+ {+ SaveContents save;+ readSave(Main::getCharacterSave(), save);+ if (!save.hasPlayer || !save.hasNpc)+ throw std::runtime_error("it has no player in it");+ json = toJson(save);+ }+ catch (const std::exception &e)+ {+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_ERROR, "Could not read the character's save %s: %s",+ Main::getCharacterSave().c_str(), e.what());+ // The server tells the player, and lets them go+ json = "{\"version\":1,\"error\":\"the save couldn't be read\"}";+ }++ // In pieces below the packets' longest string+ const size_t chunkSize = 60000;+ const unsigned int count = static_cast<unsigned int>(std::max<size_t>(1, (json.size() + chunkSize - 1) / chunkSize));+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "Sending the single-player character (%zu bytes, %u packets)", json.size(),+ count);+ for (unsigned int i = 0; i < count; ++i)+ {+ player.miscellaneousChangeType = MISCELLANEOUS_CHANGE_TYPE::PORTABLE_DATA;+ player.portableChunk = i;+ player.portableChunkCount = count;+ player.portableData = json.substr(i * chunkSize, chunkSize);+ sendMiscellaneous(player);+ }+ player.portableData.clear();+}++namespace+{+ // A character's saves folder by the id kept in it, among the single-player characters; empty if there's none+ std::filesystem::path findCharacterFolder(const std::string &id)+ {+ std::error_code error;+ for (const auto &entry : std::filesystem::directory_iterator(Main::getSavesPath(), error))+ {+ if (!entry.is_directory())+ continue;+ std::ifstream in(entry.path() / "isowind-character.txt");+ std::string kept;+ std::getline(in, kept);+ kept.erase(std::remove_if(kept.begin(), kept.end(),+ [](char c) { return std::isspace(static_cast<unsigned char>(c)); }),+ kept.end());+ if (kept == id)+ return entry.path();+ }+ return {};+ }++ // A saves folder for a character made on a server, named as the game names its characters' (letters and digits+ // of the name, a number after it if that's taken), with the character's id in it+ std::filesystem::path makeCharacterFolder(const std::string &name, const std::string &id)+ {+ std::string base;+ for (char c : name)+ base += (static_cast<unsigned char>(c) <= 0x7F && std::isalnum(static_cast<unsigned char>(c))) ? c : '_';+ std::filesystem::path folder = Main::getSavesPath() / base;+ for (int i = 1; std::filesystem::exists(folder); ++i)+ folder = Main::getSavesPath() / (base + " - " + std::to_string(i));+ std::filesystem::create_directories(folder);+ std::ofstream out(folder / "isowind-character.txt");+ out << id << "\n";+ return folder;+ }++ // The progress on the player: stats, skills, the whole inventory (the records the server made, made again here),+ // the spells known, factions, the journal and topics+ void putProgress(const std::filesystem::path &file, const Progress &progress)+ {+ MWWorld::Ptr ptr = MWMechanics::getPlayer();+ ESM::NpcState current;+ current.blank();+ ptr.getClass().writeAdditionalState(ptr, current);+ if (!current.mHasCustomState)+ throw std::runtime_error("the player has no state to put it on");+ const std::map<ESM::RefId, ESM::RefId> remade = remakeRecords(progress.made);+ mergeProgress(current, progress.player.mObject, remade);+ // The state read below adds the effects in force to those the player has (it's made for a player just+ // loaded), so those go first, or each ability's would be there twice, and come off its stat twice if the+ // ability ever went (a birthsign's +25 Speed is in the base stat). Taking them off undoes them on the stats,+ // which the state then sets as they should be.+ ptr.getClass().getCreatureStats(ptr).getActiveSpells().clear(ptr);+ ptr.getClass().readAdditionalState(ptr, current);+ // The spells known are the server's: those the player's record had here and the server's didn't go+ const std::vector<ESM::RefId> &spells = current.mCreatureStats.mSpells.mSpells;+ MWMechanics::Spells &known = ptr.getClass().getCreatureStats(ptr).getSpells();+ std::vector<ESM::RefId> forgotten;+ for (const ESM::Spell *spell : known)+ {+ if (std::find(spells.begin(), spells.end(), spell->mId) == spells.end())+ forgotten.push_back(spell->mId);+ }+ for (const ESM::RefId &spell : forgotten)+ known.remove(spell);+ for (const ESM::RefId &spell : spells)+ {+ if (!known.hasSpell(spell))+ known.add(spell);+ }+ applyRecords(file, remade);+ }+}++void PortableCharacter::setLinked(LocalPlayer &player)+{+ // (A server from before characters had ids: nothing to keep it under)+ if (player.portableId.empty() && Main::getCharacterSave().empty())+ return;+ linked = true;+ sinceWritten = 0;+ if (!Main::getCharacterSave().empty())+ progressFolder = Files::pathFromUnicodeString(Main::getCharacterSave()).parent_path();+ else+ {+ // A character made on the server: among the single-player characters too, in its own folder+ progressFolder = findCharacterFolder(player.portableId);+ if (progressFolder.empty())+ {+ try+ {+ MWWorld::Ptr ptr = MWMechanics::getPlayer();+ progressFolder = makeCharacterFolder(ptr.get<ESM::NPC>()->mBase->mName, player.portableId);+ }+ catch (const std::exception &e)+ {+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_ERROR, "Could not make a saves folder for the character: %s", e.what());+ return;+ }+ }+ }+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "The character goes to single-player too: its progress goes to %s",+ Files::pathToUnicodeString(progressFolder).c_str());++ // The map as they know it (from their save, or what a server wrote back last): what they explore here goes on+ // it, and back with them+ std::filesystem::path mapSource = !Main::getCharacterSave().empty()+ ? Files::pathFromUnicodeString(Main::getCharacterSave())+ : progressFolder / progressFileName;+ std::error_code error;+ if (std::filesystem::exists(mapSource, error))+ {+ try+ {+ ESM::ESMReader reader;+ reader.open(mapSource);+ while (reader.hasMoreRecs())+ {+ ESM::NAME name = reader.getRecName();+ reader.getRecHeader();+ if (name.toInt() != ESM::REC_GMAP)+ {+ reader.skipRecord();+ continue;+ }+ MWBase::Environment::get().getWindowManager()->readRecord(reader, ESM::REC_GMAP);+ break;+ }+ }+ catch (const std::exception &e)+ {+ LOG_MESSAGE_SIMPLE(TimedLog::LOG_ERROR, "Could not read the character's map: %s", e.what());+ }+ }+}++void PortableCharacter::update(LocalPlayer &player, float dt)+{+ if (!linked)+ return;+ sinceWritten += dt;+ if (sinceWritten >= progressInterval)+ {+ sinceWritten = 0;+ writeProgress(player);+ }+}++void PortableCharacter::finish(LocalPlayer &player)+{+ writeProgress(player);+}++bool PortableCharacter::applyServerProgress(const std::filesystem::path &characterFolder,+ const std::filesystem::path &save)+{+ std::filesystem::path file = characterFolder / progressFileName;+ std::error_code error;+ if (!std::filesystem::exists(file, error))+ return false;+ try+ {+ // Played in single-player since (on another computer, say): that's the newer+ if (std::filesystem::last_write_time(file) <= std::filesystem::last_write_time(save))+ {+ Log(Debug::Info) << "The progress from multiplayer is older than " << save.filename() << ": dropped";+ std::filesystem::remove(file, error);+ return false;+ }++ Progress progress;+ if (!readProgress(file, progress))+ throw std::runtime_error("it has no character in it");+ putProgress(file, progress);+ Log(Debug::Info) << "Put the progress from multiplayer on the character";+ return true;+ }+ catch (const std::exception &e)+ {+ Log(Debug::Error) << "Could not put the progress from multiplayer (" << file << ") on the character: "+ << e.what();+ return false;+ }+}++bool PortableCharacter::setUpServerCharacter(const std::filesystem::path &characterFolder)+{+ std::filesystem::path file = characterFolder / progressFileName;+ try+ {+ Progress progress;+ if (!readProgress(file, progress) || !progress.hasNpc)+ throw std::runtime_error("it has no character in it");+ const ESM::NPC &npc = progress.npc;+ MWBase::MechanicsManager &mechanics = *MWBase::Environment::get().getMechanicsManager();+ mechanics.setPlayerName(npc.mName);+ mechanics.setPlayerRace(npc.mRace, npc.isMale(), npc.mHead, npc.mHair);+ auto customClass = progress.classes.find(npc.mClass);+ if (customClass != progress.classes.end())+ mechanics.setPlayerClass(customClass->second);+ else+ mechanics.setPlayerClass(npc.mClass);+ mechanics.setPlayerBirthsign(progress.player.mBirthsign);+ Log(Debug::Info) << "Starting " << npc.mName << ", a character from multiplayer";+ return true;+ }+ catch (const std::exception &e)+ {+ Log(Debug::Error) << "Could not start the character from multiplayer (" << file << "): " << e.what();+ return false;+ }+}++bool PortableCharacter::finishServerCharacter(const std::filesystem::path &characterFolder)+{+ std::filesystem::path file = characterFolder / progressFileName;+ try+ {+ Progress progress;+ if (!readProgress(file, progress))+ throw std::runtime_error("it has no character in it");+ putProgress(file, progress);++ // Where they were on the server, if this game has the place (not one only the server made); as a teleport,+ // or the game puts them back where the new game started+ if (MWBase::Environment::get().getWorldModel()->findCell(progress.player.mCellId) != nullptr)+ {+ MWBase::World &world = *MWBase::Environment::get().getWorld();+ MWWorld::Ptr ptr = MWMechanics::getPlayer();+ ptr.getClass().getCreatureStats(ptr).land(true);+ ptr.getClass().getCreatureStats(ptr).setTeleported(true);+ world.getPlayer().setTeleported(true);+ const ESM::Position &position = progress.player.mObject.mPosition;+ world.changeToCell(progress.player.mCellId, position, false);+ // (and the physics told, as Lua's teleport does, or they're put back where they were)+ MWWorld::Ptr moved = world.getPlayerPtr();+ moved = world.moveObject(moved, position.asVec3());+ world.rotateObject(moved, position.asRotationVec3());+ }+ else+ Log(Debug::Warning) << "The character's cell from multiplayer isn't in this game: they start here";+ MWBase::Environment::get().getWindowManager()->updatePlayer();+ return true;+ }+ catch (const std::exception &e)+ {+ Log(Debug::Error) << "Could not start the character from multiplayer (" << file << "): " << e.what();+ return false;+ }+}++void PortableCharacter::clearServerProgress(const std::filesystem::path &characterFolder)+{+ std::error_code error;+ std::filesystem::remove(characterFolder / progressFileName, error);+}+}diff --git a/apps/openmw/mwmp/PortableCharacter.hpp b/apps/openmw/mwmp/PortableCharacter.hppnew file mode 100644index 0000000..346cb17--- /dev/null+++ b/apps/openmw/mwmp/PortableCharacter.hpp@@ -0,0 +1,64 @@+#ifndef OPENMW_MWMP_PORTABLECHARACTER_HPP+#define OPENMW_MWMP_PORTABLECHARACTER_HPP++#include <filesystem>+#include <string>++namespace mwmp+{+ class LocalPlayer;++ // Isowind: a single-player character taken onto a server that allows it (the launcher's Character list, passed+ // as --character with the character's newest save). It keeps its name; after connecting the client says which+ // character it is, and the server either carries on as usual (it doesn't take them, or its own copy of the+ // character is newer) or asks for it, and the character is sent as the server keeps characters (JSON, read from+ // the save; custom/isowindPortable.lua on the server takes it from there).+ //+ // A character is told apart from others of the same name by an id kept beside its saves (isowind-character.txt+ // in its saves folder, made the first time it joins a server).+ //+ // The whole character goes, and comes back: items and spells the player made go with their records (the server+ // makes them again), and once the server has said the character is theirs there, the client writes the+ // character as it is there beside its saves every half minute and when the game closes+ // (isowind-server-progress.dat): stats, skills, spells, the whole inventory and the records the server made for+ // it, factions, bounty, reputation, the journal and the topics known. The next time the character is loaded in+ // single-player that goes on top of the save, and the game saves; they are where they were in single-player.+ namespace PortableCharacter+ {+ // The character's name, from its save; empty if the save can't be read+ std::string readName(const std::string &save);++ // Tells the server which character this is: its id, and when it was last played (its save's time)+ void sendInfo(LocalPlayer &player);++ // Sends the character, the server having asked for it+ void send(LocalPlayer &player);++ // The server has logged the player in as a character that goes to single-player (with its id): what they gain+ // is written back from now on, to the folder of the character they joined with, or (a character made on the+ // server) to its own among the single-player characters, found by its id or made+ void setLinked(LocalPlayer &player);++ // Writes the character's progress back every half minute+ void update(LocalPlayer &player, float dt);++ // And once more as the game closes+ void finish(LocalPlayer &player);++ // Single-player: puts the progress written back from a server on the character just loaded, if there is some+ // newer than the save. True if it did; the game should then save, and call clearServerProgress.+ bool applyServerProgress(const std::filesystem::path &characterFolder, const std::filesystem::path &save);++ // The progress is in a save now: it goes+ void clearServerProgress(const std::filesystem::path &characterFolder);++ // Single-player, a character made on a server and played offline for the first time (its folder has the+ // progress and no saves), on a new game: first who they are (name, race, looks, class, birthsign), then,+ // once the game has made the player from those, the rest of the progress and where they were. False if it+ // can't be done.+ bool setUpServerCharacter(const std::filesystem::path &characterFolder);+ bool finishServerCharacter(const std::filesystem::path &characterFolder);+ }+}++#endif //OPENMW_MWMP_PORTABLECHARACTER_HPPdiff --git a/apps/openmw/mwmp/processors/player/ProcessorPlayerMiscellaneous.hpp b/apps/openmw/mwmp/processors/player/ProcessorPlayerMiscellaneous.hppindex 4ba5cf3..6510c20 100644--- a/apps/openmw/mwmp/processors/player/ProcessorPlayerMiscellaneous.hpp+++ b/apps/openmw/mwmp/processors/player/ProcessorPlayerMiscellaneous.hpp@@ -2,6 +2,8 @@#define OPENMW_PROCESSORPLAYERMISCELLANEOUS_HPP+#include "apps/openmw/mwmp/PortableCharacter.hpp"+#include "../PlayerProcessor.hpp"namespace mwmp@@ -28,6 +30,10 @@ namespace mwmplocalPlayer.setMarkLocation();else if (player->miscellaneousChangeType == mwmp::MISCELLANEOUS_CHANGE_TYPE::SELECTED_SPELL)localPlayer.setSelectedSpell();+ else if (player->miscellaneousChangeType == mwmp::MISCELLANEOUS_CHANGE_TYPE::PORTABLE_REQUEST)+ PortableCharacter::send(localPlayer);+ else if (player->miscellaneousChangeType == mwmp::MISCELLANEOUS_CHANGE_TYPE::PORTABLE_LINKED)+ PortableCharacter::setLinked(localPlayer);}}};diff --git a/apps/openmw/mwstate/character.cpp b/apps/openmw/mwstate/character.cppindex 5199445..6b9f168 100644--- a/apps/openmw/mwstate/character.cpp+++ b/apps/openmw/mwstate/character.cpp@@ -106,6 +106,9 @@ MWState::Character::Character(const std::filesystem::path& saves, const std::str{for (const auto& iter : std::filesystem::directory_iterator(mPath)){+ // Isowind keeps a character's multiplayer id beside its saves (mwmp/PortableCharacter.hpp)+ if (iter.path().extension() != ".omwsave")+ continue;try{addSlot(iter, game);diff --git a/apps/openmw/mwstate/charactermanager.cpp b/apps/openmw/mwstate/charactermanager.cppindex 1989f31..a3e0761 100644--- a/apps/openmw/mwstate/charactermanager.cpp+++ b/apps/openmw/mwstate/charactermanager.cpp@@ -54,6 +54,16 @@ void MWState::CharacterManager::deleteSlot(const MWState::Slot* slot, const MWSt}}+MWState::Character* MWState::CharacterManager::adoptCharacter(const std::filesystem::path& path)+{+ for (Character& character : mCharacters)+ {+ if (character.getPath() == path)+ return &character;+ }+ return &mCharacters.emplace_front(path, mGame);+}+MWState::Character* MWState::CharacterManager::createCharacter(const std::string& name){std::ostringstream stream;diff --git a/apps/openmw/mwstate/charactermanager.hpp b/apps/openmw/mwstate/charactermanager.hppindex 015144d..800451b 100644--- a/apps/openmw/mwstate/charactermanager.hpp+++ b/apps/openmw/mwstate/charactermanager.hpp@@ -36,6 +36,10 @@ namespace MWStatevoid deleteSlot(const MWState::Slot* slot, const Character*& character);Character* createCharacter(const std::string& name);++ /// Isowind: the character whose saves are in this folder, taken on even with no saves yet (a character made+ /// on a multiplayer server, played offline for the first time)+ Character* adoptCharacter(const std::filesystem::path& path);///< Create new character within saved game management/// \param name Name for the character (does not need to be unique)diff --git a/apps/openmw/mwstate/statemanagerimp.cpp b/apps/openmw/mwstate/statemanagerimp.cppindex 2f569f4..57bdf9a 100644--- a/apps/openmw/mwstate/statemanagerimp.cpp+++ b/apps/openmw/mwstate/statemanagerimp.cpp@@ -1,4 +1,5 @@#include "../mwmp/Main.hpp"+#include "../mwmp/PortableCharacter.hpp"#include "statemanagerimp.hpp"#include <filesystem>@@ -614,6 +615,11 @@ void MWState::StateManager::loadGame(const Character* character, const std::fileactorIdConverter.apply();MWBase::Environment::get().getWorld()->setupPlayer();MWBase::Environment::get().getWorld()->renderPlayer();+ // Isowind: what the character gained on a multiplayer server since this save goes on it (and is saved)+ mServerProgressToSave = std::nullopt;+ mServerProgressWait = 0;+ if (character && mwmp::PortableCharacter::applyServerProgress(character->getPath(), filepath))+ mServerProgressToSave = character->getPath();MWBase::Environment::get().getWindowManager()->updatePlayer();MWBase::Environment::get().getMechanicsManager()->playerLoaded();MWBase::Environment::get().getWorld()->toggleVanityMode(false);@@ -693,6 +699,13 @@ void MWState::StateManager::loadGame(const Character* character, const std::file}}+void MWState::StateManager::startServerCharacter(const std::filesystem::path& characterFolder)+{+ newGame(true);+ mServerCharacterToStart = characterFolder;+ mServerCharacterSetUp = false;+}+void MWState::StateManager::printSavegameFormatError(const std::string& exceptionText, const std::string& messageBoxText){@@ -794,6 +807,44 @@ void MWState::StateManager::update(float duration)loadGame(character, mLoadRequest->second);mLoadRequest = std::nullopt;}++ // Isowind: a character made on a server put on the new game: their race, class and the like, then (the next frame,+ // the game having made the player from those) their stats, things, journal, and where they were+ if (mServerCharacterToStart && mState == State_Running)+ {+ std::filesystem::path characterFolder = *mServerCharacterToStart;+ if (!mServerCharacterSetUp)+ {+ mServerCharacterSetUp = true;+ if (!mwmp::PortableCharacter::setUpServerCharacter(characterFolder))+ mServerCharacterToStart = std::nullopt;+ }+ else+ {+ mServerCharacterToStart = std::nullopt;+ if (mwmp::PortableCharacter::finishServerCharacter(characterFolder))+ {+ // Saved into the folder they came in+ mCharacterManager.setCurrentCharacter(mCharacterManager.adoptCharacter(characterFolder));+ mServerProgressToSave = characterFolder;+ mServerProgressWait = 0;+ }+ }+ }++ // Isowind: progress from a multiplayer server put on the character loaded, saved once the game has run a moment+ // (so the save's picture is of the game, not the loading screen)+ if (mServerProgressToSave && mState == State_Running)+ {+ mServerProgressWait += duration;+ if (mServerProgressWait >= 1)+ {+ std::filesystem::path characterFolder = *mServerProgressToSave;+ mServerProgressToSave = std::nullopt;+ saveGame("Back from multiplayer", nullptr);+ mwmp::PortableCharacter::clearServerProgress(characterFolder);+ }+ }}bool MWState::StateManager::confirmLoading(const std::vector<std::string_view>& missingFiles) constdiff --git a/apps/openmw/mwstate/statemanagerimp.hpp b/apps/openmw/mwstate/statemanagerimp.hppindex 4b8a9b0..12fde14 100644--- a/apps/openmw/mwstate/statemanagerimp.hpp+++ b/apps/openmw/mwstate/statemanagerimp.hpp@@ -17,6 +17,13 @@ namespace MWStatebool mAskLoadRecent;bool mNewGameRequest = false;std::optional<std::pair<const Character*, std::filesystem::path>> mLoadRequest;+ // Isowind: a character loaded with progress from a multiplayer server on it, to save (its saves folder)+ std::optional<std::filesystem::path> mServerProgressToSave;+ float mServerProgressWait = 0;+ // Isowind: a character made on a server being put on a new game (its saves folder), and how far along: its+ // race, class and so on first, then (once the game has made the player from those) the rest+ std::optional<std::filesystem::path> mServerCharacterToStart;+ bool mServerCharacterSetUp = false;State mState;CharacterManager mCharacterManager;double mTimePlayed;@@ -85,6 +92,10 @@ namespace MWStatevoid loadGame(const Character* character, const std::filesystem::path& filepath) override;///< Load a saved game file belonging to the given character.+ /// Isowind: starts a new game as a character made on a multiplayer server (from what was written back to its+ /// saves folder, which has no saves yet), where they were there; the game then saves into that folder.+ void startServerCharacter(const std::filesystem::path& characterFolder);+Character* getCurrentCharacter() override;///< @note May return null.diff --git a/components/openmw-mp/Base/BasePlayer.hpp b/components/openmw-mp/Base/BasePlayer.hppindex a8293bc..a5f5908 100644--- a/components/openmw-mp/Base/BasePlayer.hpp+++ b/components/openmw-mp/Base/BasePlayer.hpp@@ -137,7 +137,15 @@ namespace mwmpenum MISCELLANEOUS_CHANGE_TYPE{MARK_LOCATION = 0,- SELECTED_SPELL+ SELECTED_SPELL,+ // Isowind: a character brought from single-player. The client says which one it is (its id and when it was+ // last played), the server asks for it, and the client sends it (JSON, in chunks). Logged in as it (or as a+ // character made on the server), the server says so with the character's id, and what the character gains+ // there is written back to single-player+ PORTABLE_CHARACTER,+ PORTABLE_REQUEST,+ PORTABLE_DATA,+ PORTABLE_LINKED};class BasePlayer@@ -284,6 +292,12 @@ namespace mwmpESM::Position markPosition;std::string selectedSpellId;+ std::string portableId;+ double portablePlayed = 0; // seconds since 1970+ std::string portableData;+ unsigned int portableChunk = 0;+ unsigned int portableChunkCount = 0;+mwmp::Item usedItem;bool usingItemMagic;char itemUseDrawState;diff --git a/components/openmw-mp/Packets/Player/PacketPlayerMiscellaneous.cpp b/components/openmw-mp/Packets/Player/PacketPlayerMiscellaneous.cppindex ac9931e..91e5a48 100644--- a/components/openmw-mp/Packets/Player/PacketPlayerMiscellaneous.cpp+++ b/components/openmw-mp/Packets/Player/PacketPlayerMiscellaneous.cpp@@ -25,4 +25,17 @@ void PacketPlayerMiscellaneous::Packet(RakNet::BitStream *newBitstream, bool sen}else if (player->miscellaneousChangeType == mwmp::MISCELLANEOUS_CHANGE_TYPE::SELECTED_SPELL)RW(player->selectedSpellId, send, true);+ else if (player->miscellaneousChangeType == mwmp::MISCELLANEOUS_CHANGE_TYPE::PORTABLE_LINKED)+ RW(player->portableId, send, true);+ else if (player->miscellaneousChangeType == mwmp::MISCELLANEOUS_CHANGE_TYPE::PORTABLE_CHARACTER)+ {+ RW(player->portableId, send, true);+ RW(player->portablePlayed, send);+ }+ else if (player->miscellaneousChangeType == mwmp::MISCELLANEOUS_CHANGE_TYPE::PORTABLE_DATA)+ {+ RW(player->portableChunk, send);+ RW(player->portableChunkCount, send);+ RW(player->portableData, send);+ }}diff --git a/isowind/README.txt b/isowind/README.txtindex c688830..f3facd5 100644--- a/isowind/README.txt+++ b/isowind/README.txt@@ -14,7 +14,8 @@ Getting started(not Program Files).2. Run Isowind.exe.Windows may warn that the app is unrecognised: click "More info", then "Run anyway".-3. Pick a look and press Play.+3. Pick a look and a character and press Play: a character you have saves for carries on from their newest+ save, "New character" starts a new game.- The very first time, the OpenMW launcher opens instead: follow its wizard and point it at yourMorrowind installation (it finds Steam/GOG installs), then close it and press Play again.- The first time you play the pixel art look, Isowind builds its low-res textures from your own@@ -23,6 +24,8 @@ Getting startedOn Linux, unpack the folder and use isowind.sh instead of Isowind.exe, from a terminal:./isowind.sh play (pixel art; ./isowind.sh normal for the normal look)./isowind.sh join ADDRESS play on a server+ ./isowind.sh load SAVE play a save (an .omwsave file in ~/.local/share/openmw/saves)+ ./isowind.sh new start a new character./isowind.sh host run a server in that terminal (it asks its settings first)./isowind.sh gui a launcher window like Isowind.exe (also what a file manager opens)The first time it finds Morrowind in Steam's usual places and sets up OpenMW for it; otherwise run it as@@ -46,6 +49,20 @@ Joining a friend's serverpassword, which you need to log in as that character again); an existing name logs you in.The address is remembered for next time.+Playing a single-player character on a server: pick them under Character before pressing Join. If the+server takes characters from single-player, the whole character comes as their newest save has them:+stats, skills, spells, inventory (potions you brewed, items you enchanted and spells you made too), quick+keys, the map and where they were, and on MMO servers their quests, topics, factions and kills; you only+choose a password.+What they gain there comes back: the next time you play them in single-player they have it all,+quests done on the server included (the game saves it as "Back from multiplayer"), where you left them+in single-player. Whichever copy was played last wins: join after playing them in single-player and+the server takes the save; if you played them on the server since, it keeps its own. A name already+taken there by someone else's character can't be used. A character you make on such a server shows up+under Character too, "(from multiplayer)": Play starts them offline where they were on the server.+If the server doesn't take characters, you play the character of that name there (or make a new one)+as usual, and nothing comes back.+Hosting a server1. Press "Host a server" in Isowind.exe and choose its settings:- Name, port (25565 unless you change it), most players, and a password (empty: anyone can join).@@ -66,6 +83,8 @@ Hosting a server/dismiss all) sends one back where it came from, and /follow <number>, said where they are,has one follow you again.- PvP (whether players can hurt each other), difficulty and how fast the time of day goes.+ - Whether players can bring their single-player characters (see above). The server takes them as their+ saves have them: anyone can bring a character as strong as they like.Then the server's window opens; it runs the server, and closing it stops the server (saved). It shows:- The players in the world, their staff rank, ping, level and cell. Pick one to change their staff rank(Player, Moderator, Admin, Server owner: at once), kick or ban them, send them a message, teleport them todiff --git a/isowind/linux/isowind-launcher.py b/isowind/linux/isowind-launcher.pyindex b19c823..949edfe 100755--- a/isowind/linux/isowind-launcher.py+++ b/isowind/linux/isowind-launcher.py@@ -7,8 +7,10 @@ settings and starts the server, as Isowind.exe's "Host a server" does."""import osimport reimport shutil+import structimport subprocessimport sys+import timeimport tkinter as tkfrom tkinter import filedialog, messagebox, ttkfrom tkinter import font as tkfont@@ -21,11 +23,18 @@ SERVER = os.path.join(ENGINE, 'tes3mp-server')LOOK_FILE = os.path.join(ROOT, 'look.txt')MODE_FILE = os.path.join(ROOT, 'profiles', 'launcher-mode.txt') # as Isowind.exe keeps itADDRESS_FILE = os.path.join(ROOT, 'profiles', 'launcher-server.txt')+CHARACTER_FILE = os.path.join(ROOT, 'profiles', 'launcher-character.txt') # its saves folder's name, or "new"MORROWIND_FILE = os.path.join(ROOT, 'morrowind-folder.txt')LOG = os.path.join(ROOT, 'launcher.log')USER_CFG = os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.join(os.path.expanduser('~'), '.config'),'openmw', 'openmw.cfg')+SAVES_DIR = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'share'),+ 'openmw', 'saves')DEFAULT_PORT = 25565+# Save format versions up to this one have record ids as plain strings (ESM::MaxStringRefIdFormatVersion)+MAX_STRING_REFID_FORMAT_VERSION = 23+# What a multiplayer server writes back beside a character's saves (apps/openmw/mwmp/PortableCharacter.hpp)+SERVER_PROGRESS_FILE = 'isowind-server-progress.dat'# Isowind.exe's coloursBACK = '#181512'@@ -77,6 +86,102 @@ def parse_server_address(text):return f'{address}:{port}'+# A save's name, level, class and cell, from its SAVE record (after the TES3 header; the screenshot follows them), or+# None if it isn't a save (Isowind.cs)+def read_save(path):+ try:+ with open(path, 'rb') as f:+ data = f.read(1 << 18)+ if data[:4] != b'TES3':+ return None+ header_end = 16 + struct.unpack_from('<I', data, 4)[0]+ form = 0+ pos = 16+ while pos + 8 <= header_end and pos + 12 <= len(data):+ if data[pos:pos + 4] == b'FORM':+ form = struct.unpack_from('<I', data, pos + 8)[0]+ pos += 8 + struct.unpack_from('<I', data, pos + 4)[0]+ if data[header_end:header_end + 4] != b'SAVE':+ return None+ fields = {}+ end = min(len(data), header_end + 16 + struct.unpack_from('<I', data, header_end + 4)[0])+ pos = header_end + 16+ while pos + 8 <= end:+ name, size = data[pos:pos + 4], struct.unpack_from('<I', data, pos + 4)[0]+ if name == b'SCRN' or pos + 8 + size > end:+ break+ fields.setdefault(name, data[pos + 8:pos + 8 + size])+ pos += 8 + size+ except (OSError, struct.error):+ return None+ if b'PLNA' not in fields:+ return None++ # Saves keep text in Morrowind's own encoding (Windows-1252 for the English game)+ def text(value):+ return value.decode('cp1252', errors='replace').rstrip('\0')++ level = struct.unpack('<i', fields[b'PLLE'][:4])[0] if len(fields.get(b'PLLE', b'')) >= 4 else 1+ class_name = ''+ if b'PLCL' in fields:+ value = fields[b'PLCL']+ if form <= MAX_STRING_REFID_FORMAT_VERSION:+ class_name = text(value)+ elif value[:1] == b'\x02': # an unsized string id+ class_name = text(value[1:])+ elif value[:1] == b'\x01': # a sized one: its length, then the string+ class_name = text(value[5:])+ elif b'PLCN' in fields:+ class_name = text(fields[b'PLCN'])+ return {'name': text(fields[b'PLNA']), 'level': level, 'class': class_name,+ 'cell': text(fields.get(b'PLCE', b''))}+++# The characters that have saves, the last played first: each one's folder, newest save and what it says+def read_characters():+ characters = []+ try:+ folders = [os.path.join(SAVES_DIR, name) for name in os.listdir(SAVES_DIR)]+ except OSError:+ return characters+ for folder in folders:+ try:+ saves = [os.path.join(folder, name) for name in os.listdir(folder) if name.endswith('.omwsave')]+ except OSError:+ continue+ # The newest save it can read (OpenMW's own order: the files' times)+ found = None+ for save in sorted(saves, key=os.path.getmtime, reverse=True):+ found = read_save(save)+ if found:+ found.update(save=save, played=os.path.getmtime(save), from_server=False)+ break+ # What a multiplayer server wrote back (the game puts it on the character when it's next loaded; one made on+ # a server has only that): shown when it's newer+ progress = os.path.join(folder, SERVER_PROGRESS_FILE)+ if os.path.exists(progress) and (not found or os.path.getmtime(progress) > found['played']):+ from_server = read_save(progress)+ if from_server:+ from_server.update(save=found['save'] if found else progress, played=os.path.getmtime(progress),+ from_server=not found)+ found = from_server+ if found:+ found['folder'] = folder+ characters.append(found)+ return sorted(characters, key=lambda c: c['played'], reverse=True)+++def character_label(character):+ text = f"{character['name']}{' (from multiplayer)' if character['from_server'] else ''} - level {character['level']}"+ if character['class']:+ text += ' ' + character['class']+ day = time.localtime(character['played'])+ text += f" - {day.tm_mday} {time.strftime('%b', day)}"+ if character['cell']:+ text += ', ' + character['cell']+ return text++# The server's settings: tes3mp-server.cfg's over tes3mp-server-default.cfg's, as isowind.sh host keeps themdef server_setting(section, key, default):value = default@@ -279,7 +384,7 @@ def centre(window, width, height):class Launcher(tk.Tk, Styled):- WIDTH, HEIGHT = 460, 532+ WIDTH, HEIGHT = 460, 584def __init__(self):tk.Tk.__init__(self)@@ -309,9 +414,28 @@ class Launcher(tk.Tk, Styled):self.label(look, 'The top-down camera works in both. The zoom (or F7) in game switches camera.', 14, 96,380, 18, fg=DIM, font=self.tiny_font)- self.play = self.button(self, 'Play', 30, 246, 400, 52, self.on_play, font=self.play_font)-- multiplayer = self.panel(self, 30, 310, 400, 122)+ # Who Play plays: a character with saves (their newest one), or a new one; the one picked last is picked+ # again (the last played if none was)+ self.characters = {character_label(c): c for c in read_characters()}+ self.characters['New character'] = None+ picked = read_file(CHARACTER_FILE)+ labels = list(self.characters)+ self.character = tk.StringVar(value=labels[0])+ for label, character in self.characters.items():+ if picked == (os.path.basename(character['folder']) if character else 'new'):+ self.character.set(label)+ character_panel = self.panel(self, 30, 242, 400, 44)+ self.label(character_panel, 'Character', 14, 11, 80, 22, fg=GOLD)+ self.character_menu = tk.OptionMenu(character_panel, self.character, *labels)+ self.character_menu.configure(bg=BACK, fg=SAND, activebackground=HOVER, activeforeground=SAND,+ relief='flat', highlightthickness=1, highlightbackground=DIM,+ font=self.small_font, bd=0, indicatoron=False, cursor='hand2', anchor='w')+ self.character_menu['menu'].configure(bg=PANEL, fg=SAND, activebackground=HOVER, activeforeground=SAND)+ self.character_menu.place(x=94, y=9, width=292, height=26)++ self.play = self.button(self, 'Play', 30, 298, 400, 52, self.on_play, font=self.play_font)++ multiplayer = self.panel(self, 30, 362, 400, 122)self.label(multiplayer, 'Multiplayer', 14, 8, 300, 22, fg=GOLD)self.label(multiplayer, 'Server address', 14, 38, 110, 22)entry = self.entry(multiplayer, self.address, 126, 37, 160, 24)@@ -321,16 +445,16 @@ class Launcher(tk.Tk, Styled):self.label(multiplayer, f'Friends need UDP port {DEFAULT_PORT}\nforwarded to you, or a shared VPN', 162, 72,230, 34, fg=DIM, font=self.tiny_font)- self.morrowind = self.button(self, 'Morrowind folder (where Morrowind is installed)', 30, 444, 300, 34,+ self.morrowind = self.button(self, 'Morrowind folder (where Morrowind is installed)', 30, 496, 300, 34,self.on_morrowind_folder, font=self.small_font)- self.button(self, 'Licenses', 340, 444, 90, 34, self.show_licenses, font=self.small_font)+ self.button(self, 'Licenses', 340, 496, 90, 34, self.show_licenses, font=self.small_font)style = ttk.Style(self)style.theme_use('default')style.configure('Isowind.Horizontal.TProgressbar', troughcolor=PANEL, background=GOLD, bordercolor=PANEL,lightcolor=GOLD, darkcolor=GOLD)self.progress = ttk.Progressbar(self, style='Isowind.Horizontal.TProgressbar', mode='indeterminate')- self.label(self, '', 30, 502, 400, 22, fg=DIM, font=self.small_font).configure(textvariable=self.status)+ self.label(self, '', 30, 554, 400, 22, fg=DIM, font=self.small_font).configure(textvariable=self.status)if not os.path.exists(SERVER) or not os.path.isdir(SERVER_DIR):self.host.configure(state='disabled')@@ -357,9 +481,10 @@ class Launcher(tk.Tk, Styled):except OSError as e:messagebox.showerror('Isowind', f"Could not start {os.path.basename(SCRIPT)}:\n{e}", parent=self)return- for widget in (self.play, self.join, self.host, self.pixel_art, self.normal, self.morrowind):+ for widget in (self.play, self.join, self.host, self.pixel_art, self.normal, self.morrowind,+ self.character_menu):widget.configure(state='disabled')- self.progress.place(x=30, y=486, width=400, height=12)+ self.progress.place(x=30, y=538, width=400, height=12)self.progress.start(12)first = not morrowind_configured()textures = look == 'pixelart' and not os.path.exists(os.path.join(ROOT, 'pixelart', 'textures',@@ -384,7 +509,8 @@ class Launcher(tk.Tk, Styled):returnself.progress.stop()self.progress.place_forget()- for widget in (self.play, self.join, self.host, self.pixel_art, self.normal, self.morrowind):+ for widget in (self.play, self.join, self.host, self.pixel_art, self.normal, self.morrowind,+ self.character_menu):widget.configure(state='normal')if not os.path.exists(SERVER):self.host.configure(state='disabled')@@ -395,8 +521,20 @@ class Launcher(tk.Tk, Styled):output = read_file(LOG, 'It stopped without saying why.')messagebox.showerror('Isowind', output[-1500:], parent=self)+ # The character picked (None: a new one), remembered for next time+ def remember_pick(self):+ character = self.characters.get(self.character.get())+ write_file(CHARACTER_FILE, os.path.basename(character['folder']) if character else 'new')+ return character+def on_play(self):- self.launch([])+ character = self.remember_pick()+ if not character:+ self.launch(['new'])+ elif character['from_server']:+ self.launch(['server-character', character['folder']])+ else:+ self.launch(['load', character['save']])def on_join(self):address = parse_server_address(self.address.get())@@ -407,7 +545,9 @@ class Launcher(tk.Tk, Styled):'To join a server on this computer, use 127.0.0.1.', parent=self)returnwrite_file(ADDRESS_FILE, self.address.get().strip())- self.launch(['join', address])+ # The character picked comes along, if the server takes characters from single-player+ character = self.remember_pick()+ self.launch(['join', address] + ([character['save']] if character else []))# The Morrowind folder, for when it isn't where isowind.sh looks (Steam's usual places)def on_morrowind_folder(self):@@ -481,10 +621,10 @@ class HostDialog(tk.Toplevel, Styled):self.configure(bg=BACK)self.resizable(False, False)self.transient(parent)- centre(self, 460, 468)+ centre(self, 460, 498)self.label(self, 'Host a server', 0, 14, 460, 30, fg=GOLD, font=self.play_font, anchor='center')- panel = self.panel(self, 30, 56, 400, 332)+ panel = self.panel(self, 30, 56, 400, 362)self.fields = {}rows = [('Server name', 'General', 'hostname', 'Isowind server', None),@@ -514,12 +654,15 @@ class HostDialog(tk.Toplevel, Styled):self.pvp = tk.BooleanVar(value=server_setting('Isowind', 'pvp', 'false') == 'true')self.check(panel, 'Players can hurt each other (PvP)', self.pvp, 14, y, 370, 26)y += 30+ self.portable = tk.BooleanVar(value=server_setting('Isowind', 'portableCharacters', 'false') == 'true')+ self.check(panel, 'Players can bring their single-player characters', self.portable, 14, y, 370, 26)+ y += 30self.label(panel, 'Co-op: one shared world, as in single player. MMO: everyone loots and quests for\n''themselves, and enemies come back. Keep the same game for a world.', 14, y, 370, 34, fg=DIM,font=self.tiny_font)- self.button(self, 'Start the server', 30, 404, 180, 40, self.start, font=self.text_font)- self.button(self, 'Cancel', 330, 404, 100, 40, self.destroy, font=self.text_font)+ self.button(self, 'Start the server', 30, 434, 180, 40, self.start, font=self.text_font)+ self.button(self, 'Cancel', 330, 434, 100, 40, self.destroy, font=self.text_font)def start(self):values = {key: var.get().strip() for key, var in self.fields.items()}@@ -541,6 +684,7 @@ class HostDialog(tk.Toplevel, Styled):for (section, key), value in values.items():set_server_setting(section, key, value)set_server_setting('Isowind', 'pvp', 'true' if self.pvp.get() else 'false')+ set_server_setting('Isowind', 'portableCharacters', 'true' if self.portable.get() else 'false')terminals = [('x-terminal-emulator', ['-e']), ('foot', []), ('alacritty', ['-e']), ('kitty', []),('ghostty', ['-e']), ('gnome-terminal', ['--']), ('konsole', ['-e']),diff --git a/isowind/linux/isowind.sh b/isowind/linux/isowind.shindex 5fe02ae..94fed8c 100755--- a/isowind/linux/isowind.sh+++ b/isowind/linux/isowind.sh@@ -3,7 +3,11 @@## ./isowind.sh play (pixel art look, or the look you used last)# ./isowind.sh normal play with the normal look (or: pixelart)-# ./isowind.sh join ADDRESS play on a server, e.g. ./isowind.sh join 203.0.113.7:25565 (look optional after it)+# ./isowind.sh join ADDRESS play on a server, e.g. ./isowind.sh join 203.0.113.7:25565 (look optional after it;+# a save after it brings that single-player character, if the server takes them)+# ./isowind.sh load SAVE play a single-player save (an .omwsave file; look optional after it)+# ./isowind.sh new start a new character, without the main menu (look optional after it)+# ./isowind.sh server-character FOLDER play offline a character made on a server (its saves folder, look optional)# ./isowind.sh host run a server here, in this terminal, after asking its settings (others join# with this computer's address)# ./isowind.sh gui the launcher window (look, join, host), like Isowind.exe; also what@@ -132,6 +136,11 @@ ask_host_settings() {ask "Can players hurt each other (PvP)? (yes or no)" "$PVP" 'yes|no'[ "$REPLY" = yes ] && REPLY=true || REPLY=falseset_setting "$FILE" Isowind pvp "$REPLY"+ PORTABLE=$(get_server_setting Isowind portableCharacters false)+ [ "$PORTABLE" = true ] && PORTABLE=yes || PORTABLE=no+ ask "Can players bring their single-player characters (as their saves have them)? (yes or no)" "$PORTABLE" 'yes|no'+ [ "$REPLY" = yes ] && REPLY=true || REPLY=false+ set_setting "$FILE" Isowind portableCharacters "$REPLY"ask "Difficulty, -100 (very easy) to 100 (very hard), 0 is Morrowind's normal" \"$(get_server_setting Isowind difficulty 0)" '-?[0-9]{1,3}'set_setting "$FILE" Isowind difficulty "$REPLY"@@ -154,7 +163,8 @@ play() {# Xbox controllers through the kernel's driver, not SDL's own: SDL's skips one it can't open (a Bluetooth one,# whose hidraw only root reads) when it has another with the same ids (Sunshine's virtual one, left after a stream)export SDL_JOYSTICK_HIDAPI_XBOX=${SDL_JOYSTICK_HIDAPI_XBOX:-0}- exec "$ENGINE/openmw" --config "$ROOT/profiles/$LOOK" $CONNECT+ # shellcheck disable=SC2086+ exec "$ENGINE/openmw" --config "$ROOT/profiles/$LOOK" $CONNECT $SKIP_MENU ${SAVE:+"--load-savegame=$SAVE"} ${CHARACTER:+"--character=$CHARACTER"} ${SERVER_CHARACTER:+"--server-character=$SERVER_CHARACTER"}}launcher() {@@ -164,17 +174,15 @@ launcher() {exec python3 "$ROOT/isowind-launcher.py"}-# --controller / --no-controller, from before the game picked the menus by itself: taken and ignored (none of the-# other arguments has spaces in it)-ARGS=""+# --controller / --no-controller, from before the game picked the menus by itself: taken and ignored (the others+# kept as they are, a save's path with spaces in it too)for arg in "$@"; do+ shiftcase $arg in--controller | --no-controller) ;;- *) ARGS="$ARGS $arg" ;;+ *) set -- "$@" "$arg" ;;esacdone-# shellcheck disable=SC2086-set -- $ARGScase $1 inhost)@@ -187,6 +195,28 @@ case $1 injoin)[ -n "$2" ] || die "join needs the server's address, e.g. $0 join 203.0.113.7"CONNECT="--connect=$2"+ # The look and a single-player character's save, in either order+ LOOK=""+ shift 2+ for arg in "$@"; do+ case $arg in+ *.omwsave | *isowind-server-progress.dat) CHARACTER=$arg ;;+ *) LOOK=$arg ;;+ esac+ done+ play "$LOOK" ;;+ load)+ [ -f "$2" ] || die "load needs a save file, e.g. $0 load ~/.local/share/openmw/saves/Name/Quicksave.omwsave"+ SAVE=$2+ SKIP_MENU=--skip-menu+ play "$3" ;;+ new)+ SKIP_MENU="--skip-menu --new-game"+ play "$2" ;;+ server-character)+ [ -d "$2" ] || die "server-character needs the character's saves folder"+ SERVER_CHARACTER=$2+ SKIP_MENU=--skip-menuplay "$3" ;;gui)launcher ;;@@ -197,6 +227,6 @@ case $1 inpixelart|normal)play "$1" ;;*)- sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//'+ sed -n '2,17p' "$0" | sed 's/^# \{0,1\}//'exit 1 ;;esacdiff --git a/isowind/server/CoreScripts/scripts/custom/isowindHost.lua b/isowind/server/CoreScripts/scripts/custom/isowindHost.luaindex 2028cd7..5186960 100644--- a/isowind/server/CoreScripts/scripts/custom/isowindHost.lua+++ b/isowind/server/CoreScripts/scripts/custom/isowindHost.lua@@ -6,10 +6,11 @@-- difficulty -100 to 100, 0 is Morrowind's normal-- respawnSpeed MMO: how much faster than normal enemies come back (0.5 to 4)-- timeSpeed how much faster than Morrowind's the time of day goes (0.5 to 4)+-- portableCharacters whether players can bring their single-player characters (custom/isowindPortable.lua)---- Players are told the mode and PvP with the game settings sent at login ("isowind mode", "isowind pvp").-IsowindHost = { mode = "coop", pvp = false, difficulty = 0, respawnSpeed = 1, timeSpeed = 1 }+IsowindHost = { mode = "coop", pvp = false, difficulty = 0, respawnSpeed = 1, timeSpeed = 1, portableCharacters = false }local function readSettings(path, values)local file = io.open(path, "r")@@ -51,6 +52,7 @@ IsowindHost.pvp = string.lower(values.pvp or "false") == "true"IsowindHost.difficulty = math.floor(clamp(values.difficulty, -500, 500, 0))IsowindHost.respawnSpeed = clamp(values.respawnSpeed, 0.1, 10, 1)IsowindHost.timeSpeed = clamp(values.timeSpeed, 0.1, 10, 1)+IsowindHost.portableCharacters = string.lower(values.portableCharacters or "false") == "true"function IsowindHost.IsMmo()return IsowindHost.mode == "mmo"@@ -63,7 +65,8 @@ table.insert(config.gameSettings, { name = "isowind pvp", value = IsowindHost.pvtes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. config.gameMode .. ", PvP " ..(IsowindHost.pvp and "on" or "off") .. ", difficulty " .. IsowindHost.difficulty .. ", respawns x" ..- IsowindHost.respawnSpeed .. ", time x" .. IsowindHost.timeSpeed)+ IsowindHost.respawnSpeed .. ", time x" .. IsowindHost.timeSpeed .. ", single-player characters " ..+ (IsowindHost.portableCharacters and "allowed" or "not allowed"))-- Morrowind's time of day goes 30 times (40 at night) faster than real time; the host's speed scales bothcustomEventHooks.registerHandler("OnServerInit", function(eventStatus)diff --git a/isowind/server/CoreScripts/scripts/custom/isowindPortable.lua b/isowind/server/CoreScripts/scripts/custom/isowindPortable.luanew file mode 100644index 0000000..8ad6572--- /dev/null+++ b/isowind/server/CoreScripts/scripts/custom/isowindPortable.lua@@ -0,0 +1,392 @@+-- Isowind: characters from single-player (the launcher's Character list). With "portableCharacters = true" under+-- [Isowind] in the server's settings, a player who joins with one plays it here: the client says which character it+-- is (an id kept beside its saves) and when it was last played, before logging in, and after the password+--+-- a name new here registers it, and the character comes from the save instead of character creation+-- the same character the newer copy wins: a newer save replaces the one here, an older one is left be+-- another character (a different id, or one made here) with the name: the player can't take it, and goes+--+-- What comes is what the server keeps of a character: race, class, birthsign, stats, attributes, skills, the whole+-- inventory and equipment, quick keys, spells, skill books read and bounty, and where they were; and what this server+-- keeps for each player rather than for everyone (in MMO the journal, topics, factions, reputation, kills and the+-- quests' global variables; in co-op those are the world's). Potions they brewed, items they enchanted and spells they+-- made come with their records, which are made here again under this server's ids (as if made here; ones made for+-- them before are reused) and linked to the player.+--+-- Logged in as their character (whichever copy won), the client is told so, and writes what the character gains+-- here (quests too) back to single-player. So is a character made here: it's given an id the first time, and the+-- client keeps it among the player's single-player characters, to play offline too.+--+-- The client's half is apps/openmw/mwmp/PortableCharacter.cpp; the id lives in the player's file as+-- customVariables.isowindPortable.++local json = require("dkjson")++-- pid: { id, played, chunks, action ("register" or "replace") } for players joining with a character+local joining = {}++local function message(pid, text)+ tes3mp.SendMessage(pid, color.Yellow .. text .. color.Default .. "\n", false)+end++-- Tells the player why in a box, then lets them go (time to read it)+function IsowindPortableKick(pid)+ if Players[pid] ~= nil and not Players[pid]:IsLoggedIn() then+ Players[pid]:Kick()+ end+end++local function refuse(pid, text)+ joining[pid] = nil+ tes3mp.MessageBox(pid, -1, text)+ -- (and in the chat: the game shows the last thing said there when it's let go)+ message(pid, text)+ tes3mp.StartTimer(tes3mp.CreateTimerEx("IsowindPortableKick", time.seconds(8), "i", pid))+end++-- The records the player's game made (by store type, under that game's ids), made here as generated records linked to+-- the player: that game's ids to this server's+local function bringRecords(player, records)+ local ids = {}+ if records == nil then+ return ids+ end+ -- Enchantments first: the enchanted items need their ids+ for _, storeType in ipairs({ "enchantment", "potion", "spell", "armor", "book", "clothing", "weapon" }) do+ local recordStore = RecordStores[storeType]+ local made = {}+ for oldId, record in pairs(records[storeType] or {}) do+ if record.enchantmentId ~= nil and ids[record.enchantmentId] ~= nil then+ record.enchantmentId = ids[record.enchantmentId]+ end+ -- One the same, made for the player before (coming from single-player once more), is that one+ local id = recordStore:GetMatchingRecordId(record, recordStore.data.generatedRecords,+ player.data.recordLinks ~= nil and player.data.recordLinks[storeType] or nil, { "quantity" })+ if id == nil then+ id = recordStore:GenerateRecordId()+ made[id] = record+ end+ ids[oldId] = id+ end+ if next(made) ~= nil then+ recordStore:SaveGeneratedRecords(made)+ for id, record in pairs(made) do+ player:AddLinkToRecord(storeType, id)+ if storeType ~= "enchantment" and record.enchantmentId ~= nil and+ RecordStores["enchantment"].data.generatedRecords[record.enchantmentId] ~= nil then+ RecordStores["enchantment"]:AddLinkToRecord(record.enchantmentId, id, storeType)+ end+ end+ recordStore:QuicksaveToDrive()+ end+ end+ RecordStores["enchantment"]:QuicksaveToDrive()+ return ids+end++-- Whether the server keeps a global variable for everyone rather than for each player (as eventHandler's+-- OnClientScriptGlobal decides it), or not at all+local function isWorldGlobal(id)+ local scopes = clientVariableScopes.globals or {}+ local function listed(list)+ return list ~= nil and tableHelper.containsCaseInsensitiveString(list, id)+ end+ return listed(scopes.ignored) or listed(scopes.kills) or (config.shareJournal and listed(scopes.quest)) or+ (config.shareFactionRanks and listed(scopes.factionRanks)) or+ (config.shareFactionExpulsion and listed(scopes.factionExpulsion)) or listed(scopes.worldwide)+end++-- The character as the server keeps it, from what the client sent (PortableCharacter.cpp's toJson)+local function apply(player, character)+ local data = player.data+ local ids = bringRecords(player, character.records)+ local function idHere(id)+ return ids[id] or id+ end++ data.character.race = character.race+ data.character.head = character.head+ data.character.hair = character.hair+ data.character.gender = character.male and 1 or 0+ data.character.birthsign = character.birthsign+ data.character.modelOverride = ""+ if character.customClass ~= nil then+ local custom = character.customClass+ local function names(numbers, nameOf)+ local list = {}+ for _, number in ipairs(numbers) do+ table.insert(list, nameOf(number))+ end+ return table.concat(list, ", ")+ end+ data.character.class = "custom"+ data.customClass = {+ name = custom.name,+ description = custom.description,+ specialization = custom.specialization,+ majorAttributes = names(custom.majorAttributes, tes3mp.GetAttributeName),+ majorSkills = names(custom.majorSkills, tes3mp.GetSkillName),+ minorSkills = names(custom.minorSkills, tes3mp.GetSkillName)+ }+ else+ data.character.class = character.class+ data.customClass = {}+ end++ data.stats = {+ level = character.level,+ levelProgress = character.levelProgress,+ healthBase = character.health[1], healthCurrent = character.health[2],+ magickaBase = character.magicka[1], magickaCurrent = character.magicka[2],+ fatigueBase = character.fatigue[1], fatigueCurrent = character.fatigue[2]+ }+ for index, attribute in ipairs(character.attributes) do+ data.attributes[tes3mp.GetAttributeName(index - 1)] = {+ base = attribute[1], damage = attribute[2], skillIncrease = attribute[3]+ }+ end+ for index, skill in ipairs(character.skills) do+ data.skills[tes3mp.GetSkillName(index - 1)] = { base = skill[1], damage = skill[2], progress = skill[3] }+ end++ data.inventory = {}+ for _, item in ipairs(character.inventory) do+ table.insert(data.inventory, {+ refId = idHere(item[1]), count = item[2], charge = item[3], enchantmentCharge = item[4], soul = item[5]+ })+ end+ data.equipment = {}+ for slot, item in pairs(character.equipment) do+ data.equipment[tonumber(slot)] = {+ refId = idHere(item[1]), count = item[2], charge = item[3], enchantmentCharge = item[4]+ }+ end+ data.spellbook = {}+ for _, spell in ipairs(character.spells) do+ table.insert(data.spellbook, idHere(spell))+ end+ data.books = character.books+ -- The quick keys, on the items and spells as they're called here; what was cooling down or in effect belongs to+ -- the old copy+ data.quickKeys = {}+ for _, key in ipairs(character.quickKeys or {}) do+ data.quickKeys[key[1]] = { keyType = key[2], itemId = idHere(key[3]) }+ end+ data.cooldowns = {}+ data.spellsActive = {}++ if data.fame == nil then data.fame = {} end+ if not config.shareBounty then data.fame.bounty = character.bounty end++ data.location = {+ cell = character.cell, regionName = "",+ posX = character.position[1], posY = character.position[2], posZ = character.position[3],+ rotX = character.rotation[1], rotZ = character.rotation[2]+ }++ if not config.shareReputation then data.fame.reputation = character.reputation end++ if not config.shareFactionRanks then+ data.factionRanks = {}+ for faction, stats in pairs(character.factions) do+ if stats[1] >= 0 then data.factionRanks[faction] = stats[1] end+ end+ end+ if not config.shareFactionExpulsion then+ data.factionExpulsion = {}+ for faction, stats in pairs(character.factions) do+ if stats[2] then data.factionExpulsion[faction] = true end+ end+ end+ if not config.shareFactionReputation then+ data.factionReputation = {}+ for faction, stats in pairs(character.factions) do+ if stats[3] ~= 0 then data.factionReputation[faction] = stats[3] end+ end+ end+ if not config.shareJournal then+ data.journal = {}+ for _, entry in ipairs(character.journal) do+ table.insert(data.journal, {+ type = enumerations.journal.ENTRY, quest = entry[1], index = entry[2], actorRefId = "player",+ timestamp = { daysPassed = entry[3], month = entry[4], day = entry[5] }+ })+ end+ -- Then each quest where it is now+ for _, quest in ipairs(character.quests) do+ table.insert(data.journal, { type = enumerations.journal.INDEX, quest = quest[1], index = quest[2] })+ end+ end+ if not config.shareKills then+ data.kills = character.kills or {}+ end+ -- The global variables this server keeps for each player (quests' own, here), not those it keeps for everyone+ if data.clientVariables == nil then data.clientVariables = {} end+ if data.clientVariables.globals == nil then data.clientVariables.globals = {} end+ for id, global in pairs(character.globals or {}) do+ if not isWorldGlobal(id) then+ if global[1] == enumerations.variableType.FLOAT then+ data.clientVariables.globals[id] = { variableType = global[1], floatValue = global[2] }+ else+ data.clientVariables.globals[id] = { variableType = global[1], intValue = global[2] }+ end+ end+ end+ if not config.shareTopics then+ data.topics = character.topics+ end+end++-- The whole character has come: it's applied, and the player logs in with it as with one kept here+local function arrived(pid, text)+ local player = Players[pid]+ local entry = joining[pid]+ joining[pid] = nil++ local character = json.decode(text)+ if type(character) ~= "table" or character.error ~= nil or character.attributes == nil then+ tes3mp.LogMessage(enumerations.log.ERROR, "[Isowind] " .. logicHandler.GetChatName(pid) ..+ "'s single-player character couldn't be read: " .. tostring(character and character.error))+ refuse(pid, "Your single-player character couldn't be read from its save. Join without it (pick " ..+ "\"New character\" in Isowind) or try another save.")+ return+ end+ if character.unfinished then+ refuse(pid, "This character hasn't finished character creation in single-player yet. Finish it there " ..+ "first, or join with \"New character\".")+ return+ end++ apply(player, character)+ if player.data.customVariables == nil then player.data.customVariables = {} end+ player.data.customVariables.isowindPortable = { id = entry.id, played = entry.played }++ if entry.action == "register" then+ player:SaveLogin()+ player:CreateAccount()+ if not player:HasAccount() then+ return+ end+ else+ player:SaveToDrive()+ end+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. logicHandler.GetChatName(pid) ..+ " brought their single-player character (" .. entry.action .. ")")++ player:FinishLogin()+ if entry.action == "register" then+ player:Message("You have successfully registered.\n" .. config.chatWindowInstructions)+ else+ player:Message("You have successfully logged in.\n" .. config.chatWindowInstructions)+ end+ message(pid, "Your character came from single-player" ..+ (entry.action == "replace" and " (newer there than here)" or "") .. ".")+ if (character.skippedItems or 0) > 0 or (character.skippedSpells or 0) > 0 then+ message(pid, "Some things couldn't come (their records weren't in your save): " ..+ (character.skippedItems or 0) .. " items, " .. (character.skippedSpells or 0) .. " spells.")+ end+end++-- Before logging in: which character it is, then (once asked for) the character in chunks+local function onPortableCharacter(eventStatus, pid, changeType)+ if Players[pid] == nil or Players[pid]:IsLoggedIn() then+ return+ end+ if changeType == enumerations.miscellaneous.PORTABLE_CHARACTER then+ if not IsowindHost.portableCharacters then+ message(pid, "This server doesn't take characters from single-player: " ..+ (Players[pid]:HasAccount() and "log in to the character of that name here." or+ "you'll make a new one here."))+ return+ end+ joining[pid] = {+ id = tes3mp.GetPortableCharacterId(pid),+ played = tes3mp.GetPortableCharacterPlayed(pid),+ chunks = {}+ }+ return+ end++ local entry = joining[pid]+ if entry == nil or entry.action == nil then+ return+ end+ local count = tes3mp.GetPortableDataChunkCount(pid)+ entry.chunks[tes3mp.GetPortableDataChunk(pid) + 1] = tes3mp.GetPortableData(pid)+ for index = 1, count do+ if entry.chunks[index] == nil then+ return+ end+ end+ arrived(pid, table.concat(entry.chunks, "", 1, count))+end++-- The password typed: with a character from single-player, it's sent for instead of making one or loading this one+local function onGUIAction(eventStatus, pid, idGui, data)+ local entry = joining[pid]+ local player = Players[pid]+ if entry == nil or player == nil or player:IsLoggedIn() or data == nil then+ return+ end++ if idGui == guiHelper.ID.REGISTER and not player:HasAccount() then+ player.isNewlyRegistered = true+ player:GenerateSaltedHash(data)+ player.data.settings.consoleAllowed = "default"+ entry.action = "register"+ tes3mp.SendPortableRequest(pid)+ return customEventHooks.makeEventStatus(false, false)+ end++ if idGui == guiHelper.ID.LOGIN and player:HasAccount() then+ -- A wrong password or a banned name: as usual+ player:LoadFromDrive()+ if player.data.login.passwordHash ~= tes3mp.GetSHA256Hash(data .. player.data.login.passwordSalt) or+ tableHelper.containsValue(banList.playerNames, string.lower(player.accountName)) then+ return+ end++ local kept = player.data.customVariables ~= nil and player.data.customVariables.isowindPortable or nil+ if kept == nil or kept.id ~= entry.id then+ refuse(pid, "Someone else's character, or one made on this server, is called " .. player.accountName ..+ " here, so yours can't come in under that name. Rename yours in single-player (a new " ..+ "character), or join with \"New character\".")+ return customEventHooks.makeEventStatus(false, false)+ end+ if entry.played > (player.data.timestamps.lastDisconnect or 0) then+ entry.action = "replace"+ tes3mp.SendPortableRequest(pid)+ return customEventHooks.makeEventStatus(false, false)+ end+ -- Played here since: this copy is the newer one (and what it gains goes back to single-player too)+ joining[pid] = nil+ message(pid, "Your character here is newer than your single-player save, so you play this one.")+ end+end++-- Logged in (or just made here): the character goes to single-player, under its id (one is made for a character made+-- here the first time)+local function link(eventStatus, pid)+ local player = Players[pid]+ if not IsowindHost.portableCharacters or player == nil or not player:IsLoggedIn() then+ return+ end+ if player.data.customVariables == nil then player.data.customVariables = {} end+ local kept = player.data.customVariables.isowindPortable+ if kept == nil then+ kept = { id = string.lower(tes3mp.GenerateRandomString(32)), played = 0 }+ player.data.customVariables.isowindPortable = kept+ player:QuicksaveToDrive()+ end+ tes3mp.SendPortableLinked(pid, kept.id)+end++customEventHooks.registerHandler("OnServerPostInit", function(eventStatus)+ customEventHooks.registerHandler("OnPlayerPortableCharacter", onPortableCharacter)+ customEventHooks.registerValidator("OnGUIAction", onGUIAction)+ customEventHooks.registerHandler("OnPlayerAuthentified", link)+ customEventHooks.registerHandler("OnPlayerEndCharGen", link)+ customEventHooks.registerHandler("OnPlayerDisconnect", function(eventStatus, pid)+ joining[pid] = nil+ end)+end)diff --git a/isowind/server/CoreScripts/scripts/customScripts.lua b/isowind/server/CoreScripts/scripts/customScripts.luaindex 2d8db72..aedc04c 100644--- a/isowind/server/CoreScripts/scripts/customScripts.lua+++ b/isowind/server/CoreScripts/scripts/customScripts.lua@@ -12,3 +12,4 @@ require("custom/isowindMmo")require("custom/isowindParty")require("custom/isowindLocks")require("custom/isowindAdmin")+require("custom/isowindPortable")diff --git a/isowind/server/CoreScripts/scripts/enumerations.lua b/isowind/server/CoreScripts/scripts/enumerations.luaindex 2935ea2..54b8bce 100644--- a/isowind/server/CoreScripts/scripts/enumerations.lua+++ b/isowind/server/CoreScripts/scripts/enumerations.lua@@ -47,7 +47,8 @@ enumerations.faction = { RANK = 0, EXPULSION = 1, REPUTATION = 2 }enumerations.inventory = { SET = 0, ADD = 1, REMOVE = 2 }enumerations.journal = { ENTRY = 0, INDEX = 1 }enumerations.log = { VERBOSE = 0, INFO = 1, WARN = 2, ERROR = 3, FATAL = 4 }-enumerations.miscellaneous = { MARK_LOCATION = 0, SELECTED_SPELL = 1 }+enumerations.miscellaneous = { MARK_LOCATION = 0, SELECTED_SPELL = 1, PORTABLE_CHARACTER = 2, PORTABLE_REQUEST = 3,+ PORTABLE_DATA = 4, PORTABLE_LINKED = 5 }enumerations.objectCategories = { PLAYER = 0, ACTOR = 1, PLACED_OBJECT = 2 }enumerations.packetOrigin = { CLIENT_GAMEPLAY = 0, CLIENT_CONSOLE = 1, CLIENT_DIALOGUE = 2,CLIENT_SCRIPT_LOCAL = 3, CLIENT_SCRIPT_GLOBAL = 4, SERVER_SCRIPT = 5 }diff --git a/isowind/server/CoreScripts/scripts/eventHandler.lua b/isowind/server/CoreScripts/scripts/eventHandler.luaindex 284e01f..0920799 100644--- a/isowind/server/CoreScripts/scripts/eventHandler.lua+++ b/isowind/server/CoreScripts/scripts/eventHandler.lua@@ -1168,9 +1168,20 @@ eventHandler.OnPlayerItemUse = function(pid)endeventHandler.OnPlayerMiscellaneous = function(pid)- if Players[pid] ~= nil and Players[pid]:IsLoggedIn() then- local changeType = tes3mp.GetMiscellaneousChangeType(pid)+ if Players[pid] == nil then+ return+ end+ local changeType = tes3mp.GetMiscellaneousChangeType(pid)++ -- Isowind: a character from single-player is sent before its player logs in (custom/isowindPortable.lua)+ if changeType == enumerations.miscellaneous.PORTABLE_CHARACTER or+ changeType == enumerations.miscellaneous.PORTABLE_DATA then+ customEventHooks.triggerHandlers("OnPlayerPortableCharacter", customEventHooks.makeEventStatus(true, true),+ {pid, changeType})+ return+ end+ if Players[pid]:IsLoggedIn() thenif changeType == enumerations.miscellaneous.MARK_LOCATION thenlocal eventStatus = customEventHooks.triggerValidators("OnPlayerMarkLocation", {pid})if eventStatus.validDefaultHandler thendiff --git a/isowind/windows/Isowind.cs b/isowind/windows/Isowind.csindex 7da3566..d6e07a9 100644--- a/isowind/windows/Isowind.cs+++ b/isowind/windows/Isowind.cs@@ -61,6 +61,7 @@ class LauncherForm : Formreadonly string root = AppDomain.CurrentDomain.BaseDirectory;readonly RadioButton pixelArt;readonly RadioButton normal;+ readonly ComboBox character;readonly Button play;readonly Button openmwLauncher;readonly TextBox serverAddress;@@ -75,6 +76,8 @@ class LauncherForm : Formstring TexturesMarker { get { return Path.Combine(TexturesDir, "isowind-generated.txt"); } }string ModeFile { get { return Path.Combine(root, "profiles", "launcher-mode.txt"); } }string ServerFile { get { return Path.Combine(root, "profiles", "launcher-server.txt"); } }+ // The character picked last: its saves folder's name, or "new"+ string CharacterFile { get { return Path.Combine(root, "profiles", "launcher-character.txt"); } }string ServerDir { get { return Path.Combine(root, "server"); } }internal const int DefaultPort = 25565;@@ -93,7 +96,7 @@ class LauncherForm : FormFormBorderStyle = FormBorderStyle.FixedSingle;MaximizeBox = false;StartPosition = FormStartPosition.CenterScreen;- ClientSize = new Size(460, 554);+ ClientSize = new Size(460, 606);BackColor = Back;ForeColor = Sand;Font = new Font("Segoe UI", 10f);@@ -147,11 +150,26 @@ class LauncherForm : Form};look.Controls.AddRange(new Control[] { lookTitle, pixelArt, normal, hint });- play = MakeButton("Play", new Rectangle(30, 268, 400, 52), 16f);- play.Click += delegate { Launch(null); };+ // Who Play plays: a character with saves (their newest one), or a new one+ var characterPanel = new Panel { BackColor = Panel, Bounds = new Rectangle(30, 264, 400, 44) };+ var characterTitle = new Label+ {+ Text = "Character",+ ForeColor = Gold,+ Bounds = new Rectangle(14, 11, 80, 22),+ TextAlign = ContentAlignment.MiddleLeft,+ };+ character = HostForm.MakeChoice(new string[0]);+ character.Bounds = new Rectangle(94, 10, 292, 24);+ character.DropDownWidth = 420;+ characterPanel.Controls.AddRange(new Control[] { characterTitle, character });+ FillCharacters();++ play = MakeButton("Play", new Rectangle(30, 320, 400, 52), 16f);+ play.Click += delegate { OnPlay(); };// Multiplayer: join a server by its address, or host one on this computer- var multiplayer = new Panel { BackColor = Panel, Bounds = new Rectangle(30, 332, 400, 122) };+ var multiplayer = new Panel { BackColor = Panel, Bounds = new Rectangle(30, 384, 400, 122) };var multiplayerTitle = new Label { Text = "Multiplayer", ForeColor = Gold, Bounds = new Rectangle(14, 8, 300, 22) };var addressLabel = new Label{@@ -189,16 +207,16 @@ class LauncherForm : Form};openmwLauncher = MakeButton("OpenMW Launcher (Morrowind, mods, options)",- new Rectangle(30, 466, 300, 34), 9f);+ new Rectangle(30, 518, 300, 34), 9f);openmwLauncher.Click += delegate { StartOpenMWLauncher(); };- var licenses = MakeButton("Licenses", new Rectangle(340, 466, 90, 34), 9.5f);+ var licenses = MakeButton("Licenses", new Rectangle(340, 518, 90, 34), 9.5f);licenses.Click += delegate { ShowLicenses(); };- progress = new ProgressBar { Bounds = new Rectangle(30, 508, 400, 12), Visible = false };- status = new Label { ForeColor = Dim, Bounds = new Rectangle(30, 524, 400, 22), Font = new Font("Segoe UI", 9f) };+ progress = new ProgressBar { Bounds = new Rectangle(30, 560, 400, 12), Visible = false };+ status = new Label { ForeColor = Dim, Bounds = new Rectangle(30, 576, 400, 22), Font = new Font("Segoe UI", 9f) };- Controls.AddRange(new Control[] { title, look, play, multiplayer, openmwLauncher, licenses, progress,- status });+ Controls.AddRange(new Control[] { title, look, characterPanel, play, multiplayer, openmwLauncher, licenses,+ progress, status });try{@@ -379,6 +397,49 @@ class LauncherForm : Formreturn address + ":" + port;}+ // The characters in OpenMW's saves folder, the last played first, then "New character"; the one picked last is+ // picked again (the last played if none was)+ void FillCharacters()+ {+ string picked = null;+ try { picked = File.Exists(CharacterFile) ? File.ReadAllText(CharacterFile).Trim() : null; } catch { }+ character.Items.Clear();+ foreach (var each in Character.ReadAll())+ character.Items.Add(each);+ character.Items.Add(new Character());+ character.SelectedIndex = 0;+ for (int i = 0; i < character.Items.Count; i++)+ {+ string folder = ((Character)character.Items[i]).Folder;+ if (picked != null && picked.Equals(folder == null ? "new" : Path.GetFileName(folder),+ StringComparison.OrdinalIgnoreCase))+ character.SelectedIndex = i;+ }+ }++ // The character picked, remembered for next time+ Character RememberPick()+ {+ var picked = (Character)character.SelectedItem;+ try+ {+ File.WriteAllText(CharacterFile, picked.Folder == null ? "new" : Path.GetFileName(picked.Folder));+ }+ catch { }+ return picked;+ }++ void OnPlay()+ {+ var picked = RememberPick();+ if (picked.Folder == null)+ Launch("--skip-menu --new-game");+ else if (picked.FromServer)+ Launch("--skip-menu --server-character \"" + picked.Folder + "\"");+ else+ Launch("--skip-menu --load-savegame \"" + picked.NewestSave + "\"");+ }+void OnJoin(){string address = ParseServerAddress(serverAddress.Text);@@ -392,7 +453,12 @@ class LauncherForm : Formreturn;}try { File.WriteAllText(ServerFile, serverAddress.Text.Trim()); } catch { }- Launch("--connect=" + address);+ // The character picked comes along, if the server takes characters from single-player+ var picked = RememberPick();+ if (picked.Folder == null)+ Launch("--connect=" + address);+ else+ Launch("--connect=" + address + " --character \"" + picked.NewestSave + "\"");}void OnHost()@@ -430,7 +496,8 @@ class LauncherForm : Formstatus.Text = "Server started (its window shows what happens). Press Join to play on it.";}- async void Launch(string connectArgument)+ // Starts the game with the look picked; extraArguments: what to play (a save, a new game or a server)+ async void Launch(string extraArguments){string mode = pixelArt.Checked ? "pixelart" : "normal";try { File.WriteAllText(ModeFile, mode); } catch { }@@ -448,19 +515,21 @@ class LauncherForm : Formif (mode == "pixelart" && !File.Exists(TexturesMarker)){- play.Enabled = openmwLauncher.Enabled = pixelArt.Enabled = normal.Enabled = join.Enabled = false;+ play.Enabled = openmwLauncher.Enabled = pixelArt.Enabled = normal.Enabled = join.Enabled =+ character.Enabled = false;progress.Visible = true;bool ok = await Task.Run(() => GenerateTextures());progress.Visible = false;- play.Enabled = openmwLauncher.Enabled = pixelArt.Enabled = normal.Enabled = join.Enabled = true;+ play.Enabled = openmwLauncher.Enabled = pixelArt.Enabled = normal.Enabled = join.Enabled =+ character.Enabled = true;if (!ok)return;}string profile = Path.Combine(root, "profiles", mode);string arguments = "--config \"" + profile + "\"";- if (connectArgument != null)- arguments += " " + connectArgument;+ if (extraArguments != null)+ arguments += " " + extraArguments;if (Start(Path.Combine(EngineDir, "openmw.exe"), arguments))CloseOrHide();}@@ -575,6 +644,170 @@ class LauncherForm : Form}}+// A single-player character: a folder in OpenMW's saves folder, as its newest save has them (the character folder+// with no saves, Folder null: "New character")+class Character+{+ public string Folder;+ public string NewestSave;+ public DateTime LastPlayed;+ public string Name = "";+ public int Level = 1;+ public string ClassName = "";+ public string Cell = "";+ // Made on a multiplayer server and never played offline: NewestSave is what the server wrote back+ public bool FromServer;++ // Save format versions up to this one have record ids as plain strings (ESM::MaxStringRefIdFormatVersion)+ const uint MaxStringRefIdFormatVersion = 23;+ // What a multiplayer server writes back beside a character's saves (apps/openmw/mwmp/PortableCharacter.hpp)+ const string ServerProgressFile = "isowind-server-progress.dat";++ static string SavesDir { get { return Path.Combine(LauncherForm.UserConfigDir, "saves"); } }++ public override string ToString()+ {+ if (Folder == null)+ return "New character";+ string text = Name + (FromServer ? " (from multiplayer)" : "") + " - level " + Level;+ if (ClassName.Length > 0)+ text += " " + ClassName;+ text += " - " + LastPlayed.ToString("d MMM");+ if (Cell.Length > 0)+ text += ", " + Cell;+ return text;+ }++ // The characters that have saves, the last played first+ internal static List<Character> ReadAll()+ {+ var characters = new List<Character>();+ try+ {+ if (!Directory.Exists(SavesDir))+ return characters;+ foreach (string folder in Directory.GetDirectories(SavesDir))+ {+ // The newest save it can read (OpenMW's own order: the files' times)+ Character found = null;+ foreach (var save in new DirectoryInfo(folder).GetFiles("*.omwsave")+ .OrderByDescending(f => f.LastWriteTimeUtc))+ {+ found = ReadSave(save.FullName);+ if (found == null)+ continue;+ found.NewestSave = save.FullName;+ found.LastPlayed = save.LastWriteTime;+ break;+ }++ // What a multiplayer server wrote back (the game puts it on the character when it's next loaded; one+ // made on a server has only that): shown when it's newer+ var progressFile = new FileInfo(Path.Combine(folder, ServerProgressFile));+ if (progressFile.Exists && (found == null || progressFile.LastWriteTime > found.LastPlayed))+ {+ var fromServer = ReadSave(progressFile.FullName);+ if (fromServer != null)+ {+ fromServer.NewestSave = found != null ? found.NewestSave : progressFile.FullName;+ fromServer.FromServer = found == null;+ fromServer.LastPlayed = progressFile.LastWriteTime;+ found = fromServer;+ }+ }+ if (found == null)+ continue;+ found.Folder = folder;+ characters.Add(found);+ }+ }+ catch { }+ return characters.OrderByDescending(c => c.LastPlayed).ToList();+ }++ // A save's name, level, class and cell, from its SAVE record (after the TES3 header; the screenshot follows+ // them), or null if it isn't a save+ static Character ReadSave(string path)+ {+ try+ {+ byte[] data;+ using (var file = File.OpenRead(path))+ {+ data = new byte[Math.Min(file.Length, 1 << 18)];+ int read = 0, count;+ while (read < data.Length && (count = file.Read(data, read, data.Length - read)) > 0)+ read += count;+ }+ if (data.Length < 16 || Ascii(data, 0) != "TES3")+ return null;+ int headerEnd = 16 + (int)BitConverter.ToUInt32(data, 4);+ uint format = 0;+ for (int pos = 16; pos + 8 <= headerEnd && pos + 12 <= data.Length;+ pos += 8 + (int)BitConverter.ToUInt32(data, pos + 4))+ {+ if (Ascii(data, pos) == "FORM")+ format = BitConverter.ToUInt32(data, pos + 8);+ }+ if (headerEnd + 16 > data.Length || Ascii(data, headerEnd) != "SAVE")+ return null;++ var fields = new Dictionary<string, byte[]>();+ long end = Math.Min(data.Length, headerEnd + 16L + BitConverter.ToUInt32(data, headerEnd + 4));+ for (int pos = headerEnd + 16; pos + 8 <= end;)+ {+ string name = Ascii(data, pos);+ int size = (int)BitConverter.ToUInt32(data, pos + 4);+ if (name == "SCRN" || pos + 8L + size > end)+ break;+ if (!fields.ContainsKey(name))+ {+ var value = new byte[size];+ Array.Copy(data, pos + 8, value, 0, size);+ fields[name] = value;+ }+ pos += 8 + size;+ }+ if (!fields.ContainsKey("PLNA"))+ return null;++ var character = new Character { Name = Text(fields["PLNA"], 0) };+ if (fields.ContainsKey("PLLE") && fields["PLLE"].Length >= 4)+ character.Level = BitConverter.ToInt32(fields["PLLE"], 0);+ if (fields.ContainsKey("PLCL"))+ {+ byte[] id = fields["PLCL"];+ if (format <= MaxStringRefIdFormatVersion)+ character.ClassName = Text(id, 0);+ else if (id.Length > 0 && id[0] == 2) // an unsized string id+ character.ClassName = Text(id, 1);+ else if (id.Length > 5 && id[0] == 1) // a sized one: its length, then the string+ character.ClassName = Text(id, 5);+ }+ else if (fields.ContainsKey("PLCN"))+ character.ClassName = Text(fields["PLCN"], 0);+ if (fields.ContainsKey("PLCE"))+ character.Cell = Text(fields["PLCE"], 0);+ return character;+ }+ catch+ {+ return null;+ }+ }++ static string Ascii(byte[] data, int offset)+ {+ return Encoding.ASCII.GetString(data, offset, 4);+ }++ // Saves keep text in Morrowind's own encoding (Windows-1252 for the English game)+ static string Text(byte[] value, int offset)+ {+ return Encoding.GetEncoding(1252).GetString(value, offset, value.Length - offset).TrimEnd('\0');+ }+}+// "Host a server": the server's settings, kept in server\tes3mp-server.cfg (over tes3mp-server-default.cfg). The// [Isowind] ones are read by the server's CoreScripts (scripts\custom\isowindHost.lua).class HostForm : Form@@ -591,6 +824,7 @@ class HostForm : Formreadonly RadioButton coop;readonly RadioButton mmo;readonly CheckBox pvp;+ readonly CheckBox portableCharacters;readonly ComboBox difficulty;readonly ComboBox respawnSpeed;readonly ComboBox timeSpeed;@@ -607,7 +841,7 @@ class HostForm : FormMaximizeBox = false;MinimizeBox = false;StartPosition = FormStartPosition.CenterParent;- ClientSize = new Size(460, 450);+ ClientSize = new Size(460, 490);BackColor = LauncherForm.Back;ForeColor = LauncherForm.Sand;Font = new Font("Segoe UI", 9.5f);@@ -649,6 +883,11 @@ class HostForm : FormChecked = get("Isowind/pvp", "false").Equals("true", StringComparison.OrdinalIgnoreCase) };AddRow("", pvp, ref y);+ portableCharacters = new CheckBox { Text = "Players can bring their single-player characters", AutoSize = true,+ Checked = get("Isowind/portableCharacters", "false").Equals("true", StringComparison.OrdinalIgnoreCase) };+ AddRow("", portableCharacters, ref y);+ AddHint("Taken as their saves have them: no checks on what they bring.", ref y);+difficulty = MakeChoice(DifficultyNames);int savedDifficulty = ParseInt(get("Isowind/difficulty", "0"), 0, -500, 500);difficulty.SelectedIndex = Nearest(DifficultyValues.Select(v => (double)v).ToArray(), savedDifficulty);@@ -720,7 +959,8 @@ class HostForm : Formif (e.Index >= 0)TextRenderer.DrawText(e.Graphics, box.Items[e.Index].ToString(), box.Font, e.Bounds,box.Enabled ? LauncherForm.Sand : LauncherForm.Dim,- TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.NoPrefix);+ TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.NoPrefix |+ TextFormatFlags.EndEllipsis);};return box;}@@ -771,6 +1011,8 @@ class HostForm : FormLauncherForm.SetConfigValue(file, "General", "password", password.Text.Trim());LauncherForm.SetConfigValue(file, "Isowind", "mode", mmo.Checked ? "mmo" : "coop");LauncherForm.SetConfigValue(file, "Isowind", "pvp", pvp.Checked ? "true" : "false");+ LauncherForm.SetConfigValue(file, "Isowind", "portableCharacters",+ portableCharacters.Checked ? "true" : "false");LauncherForm.SetConfigValue(file, "Isowind", "difficulty",DifficultyValues[difficulty.SelectedIndex].ToString());LauncherForm.SetConfigValue(file, "Isowind", "respawnSpeed", SpeedValues[respawnSpeed.SelectedIndex]);