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++
MMO: one-off events happen once for each player, and once together for players near each other
Alan Saunders9686b29f419c
diff --git a/apps/openmw/mwmechanics/actors.cpp b/apps/openmw/mwmechanics/actors.cppindex e2e4dc7..2d1d8e9 100644--- a/apps/openmw/mwmechanics/actors.cpp+++ b/apps/openmw/mwmechanics/actors.cpp@@ -1563,7 +1563,10 @@ namespace MWMechanics= isMultiplayer && mwmp::Main::get().getCellController()->isLocalActor(actor.getPtr());const bool isDedicatedActor= isMultiplayer && mwmp::Main::get().getCellController()->isDedicatedActor(actor.getPtr());- const bool actorAiActive = aiActive || isLocalActor;+ // Isowind MMO: and the ones this client runs for itself only (a one-off event's)+ const bool isClientLocalActor+ = isMultiplayer && mwmp::Main::get().getCellController()->isClientLocalActor(actor.getPtr());+ const bool actorAiActive = aiActive || isLocalActor || isClientLocalActor;const float distSqr = (playerPos - actor.getPtr().getRefData().getPosition().asVec3()).length2();// AI processing is only done within given distance to the player (except for the actors thisdiff --git a/apps/openmw/mwmp/ActorList.cpp b/apps/openmw/mwmp/ActorList.cppindex de09202..9d89e3a 100644--- a/apps/openmw/mwmp/ActorList.cpp+++ b/apps/openmw/mwmp/ActorList.cpp@@ -2,6 +2,7 @@#include "../mwworld/class.hpp"#include "../mwworld/cellstore.hpp"#include "ActorList.hpp"+#include "CellController.hpp"#include "Main.hpp"#include "Networking.hpp"#include "LocalPlayer.hpp"@@ -264,6 +265,10 @@ void ActorList::sendActorsInCell(MWWorld::CellStore* cellStore)if (ptr.getCellRef().getMpRefNum() == 0 && ptr.getCellRef().getMpNum() == 0)return true;+ // Isowind MMO: nor one this client runs for itself only (a one-off event's)+ if (Main::get().getCellController()->isClientLocalActor(ptr))+ return true;+BaseActor actor;actor.refId = idString(ptr.getCellRef().getRefId());actor.refNum = ptr.getCellRef().getMpRefNum();diff --git a/apps/openmw/mwmp/Cell.cpp b/apps/openmw/mwmp/Cell.cppindex d911442..b62b2ff 100644--- a/apps/openmw/mwmp/Cell.cpp+++ b/apps/openmw/mwmp/Cell.cpp@@ -480,6 +480,10 @@ void Cell::readCellChange(ActorList& actorList)void Cell::initializeLocalActor(const MWWorld::Ptr& ptr){+ // Isowind MMO: one this client runs for itself only (a one-off event's), not for the others+ if (Main::get().getCellController()->isClientLocalActor(ptr))+ return;+std::string mapIndex = Main::get().getCellController()->generateMapIndex(ptr);LOG_APPEND(TimedLog::LOG_VERBOSE, "- Initializing LocalActor %s in %s", mapIndex.c_str(), getShortDescription().c_str());@@ -546,8 +550,9 @@ void Cell::initializeDedicatedActors(ActorList& actorList){std::string mapIndex = Main::get().getCellController()->generateMapIndex(baseActor);- // If this key doesn't exist, create it- if (dedicatedActors.count(mapIndex) == 0)+ // If this key doesn't exist, create it (Isowind MMO: unless this client runs that actor itself)+ if (dedicatedActors.count(mapIndex) == 0+ && !Main::get().getCellController()->isClientLocalActor(baseActor.refNum, baseActor.mpNum)){MWWorld::Ptr ptrFound = store->searchExact(baseActor.refNum, baseActor.mpNum, refId(baseActor.refId), true);@@ -574,9 +579,13 @@ void Cell::uninitializeDedicatedActors(ActorList& actorList)for (const auto &baseActor : actorList.baseActors){std::string mapIndex = Main::get().getCellController()->generateMapIndex(baseActor);+ // (none for the actors this client runs itself)+ auto it = dedicatedActors.find(mapIndex);+ if (it == dedicatedActors.end())+ continue;Main::get().getCellController()->removeDedicatedActorRecord(mapIndex);- delete dedicatedActors.at(mapIndex);- dedicatedActors.erase(mapIndex);+ delete it->second;+ dedicatedActors.erase(it);}}diff --git a/apps/openmw/mwmp/CellController.cpp b/apps/openmw/mwmp/CellController.cppindex 14a6968..538b7eb 100644--- a/apps/openmw/mwmp/CellController.cpp+++ b/apps/openmw/mwmp/CellController.cpp@@ -25,6 +25,7 @@ std::map<std::string, mwmp::Cell *> CellController::cellsInitialized;std::map<std::string, std::string> CellController::localActorsToCells;std::map<std::string, std::string> CellController::dedicatedActorsToCells;std::map<std::string, unsigned int> CellController::queuedDeathStates;+std::set<std::string> CellController::clientLocalActors;mwmp::CellController::CellController(){@@ -380,6 +381,65 @@ DedicatedActor *CellController::getDedicatedActor(int refNum, int mpNum)return cellsInitialized.at(cellIndex)->getDedicatedActor(actorIndex);}+void CellController::setClientLocalActor(int refNum, int mpNum)+{+ std::string actorIndex = generateMapIndex(refNum, mpNum);++ if (!clientLocalActors.insert(actorIndex).second)+ return;++ LOG_MESSAGE_SIMPLE(+ TimedLog::LOG_INFO, "Running actor %s here, whoever has authority over its cell", actorIndex.c_str());++ // No longer sent about as a LocalActor, or moved by what another client sends as a DedicatedActor+ auto localIt = localActorsToCells.find(actorIndex);+ if (localIt != localActorsToCells.end())+ {+ auto cellIt = cellsInitialized.find(localIt->second);+ if (cellIt != cellsInitialized.end())+ {+ auto actorIt = cellIt->second->localActors.find(actorIndex);+ if (actorIt != cellIt->second->localActors.end())+ {+ delete actorIt->second;+ cellIt->second->localActors.erase(actorIt);+ }+ }+ localActorsToCells.erase(localIt);+ }++ auto dedicatedIt = dedicatedActorsToCells.find(actorIndex);+ if (dedicatedIt != dedicatedActorsToCells.end())+ {+ auto cellIt = cellsInitialized.find(dedicatedIt->second);+ if (cellIt != cellsInitialized.end())+ {+ auto actorIt = cellIt->second->dedicatedActors.find(actorIndex);+ if (actorIt != cellIt->second->dedicatedActors.end())+ {+ delete actorIt->second;+ cellIt->second->dedicatedActors.erase(actorIt);+ }+ }+ dedicatedActorsToCells.erase(dedicatedIt);+ }++ queuedDeathStates.erase(actorIndex);+}++bool CellController::isClientLocalActor(const MWWorld::Ptr& ptr)+{+ if (ptr.isEmpty() || ptr.mRef == nullptr || clientLocalActors.empty())+ return false;++ return isClientLocalActor(ptr.getCellRef().getMpRefNum(), ptr.getCellRef().getMpNum());+}++bool CellController::isClientLocalActor(int refNum, int mpNum)+{+ return clientLocalActors.count(generateMapIndex(refNum, mpNum)) > 0;+}+std::string CellController::generateMapIndex(int refNum, int mpNum){std::string mapIndex = "";diff --git a/apps/openmw/mwmp/CellController.hpp b/apps/openmw/mwmp/CellController.hppindex 006b1d3..48ed901 100644--- a/apps/openmw/mwmp/CellController.hpp+++ b/apps/openmw/mwmp/CellController.hpp@@ -1,6 +1,8 @@#ifndef OPENMW_CELLCONTROLLER_HPP#define OPENMW_CELLCONTROLLER_HPP+#include <set>+#include "Cell.hpp"#include "ActorList.hpp"#include "LocalActor.hpp"@@ -57,6 +59,13 @@ namespace mwmpvirtual DedicatedActor *getDedicatedActor(MWWorld::Ptr ptr);virtual DedicatedActor *getDedicatedActor(int refNum, int mpNum);+ // Isowind MMO: actors this client runs itself whoever has authority over their cell, sending nothing about+ // them and ignoring what others send (a one-off event's people, each player's own: "isowind local" from the+ // server, see MechanicsHelper::runClientLocalCommand). They stay so for the session.+ void setClientLocalActor(int refNum, int mpNum);+ bool isClientLocalActor(const MWWorld::Ptr& ptr);+ bool isClientLocalActor(int refNum, int mpNum);+std::string generateMapIndex(int refNumindex, int mpNum);std::string generateMapIndex(MWWorld::Ptr ptr);std::string generateMapIndex(mwmp::BaseActor baseActor);@@ -81,6 +90,7 @@ namespace mwmpstatic std::map<std::string, std::string> localActorsToCells;static std::map<std::string, std::string> dedicatedActorsToCells;static std::map<std::string, unsigned int> queuedDeathStates;+ static std::set<std::string> clientLocalActors;};}diff --git a/apps/openmw/mwmp/Hooks.cpp b/apps/openmw/mwmp/Hooks.cppindex 67bd28b..e2c83ab 100644--- a/apps/openmw/mwmp/Hooks.cpp+++ b/apps/openmw/mwmp/Hooks.cpp@@ -489,6 +489,9 @@ namespace mwmp::hooksconst bool finished = actor.getClass().getCreatureStats(actor).isDeathAnimationFinished();if (finished && (isLocalActor(actor) || isDedicatedActor(actor)))startpoint = 1.f;+ // Isowind MMO: a one-off event's person this client runs itself, dead where it died for this player+ if (finished && Main::get().getCellController()->isClientLocalActor(actor))+ startpoint = 1.f;if (isLocalPlayer(actor))Main::get().getLocalPlayer()->sendDeath(static_cast<char>(deathState));else if (!finished && isLocalActor(actor))@@ -499,6 +502,9 @@ namespace mwmp::hooks{if (isLocalActor(actor))Main::get().getCellController()->getLocalActor(actor)->creatureStats.mDeathAnimationFinished = true;+ // Isowind MMO: a one-off event's person this client runs itself died, for this player (the body at rest)+ if (isMultiplayer() && Main::get().getCellController()->isClientLocalActor(actor))+ MechanicsHelper::sendClientLocalDeath(actor);}void recordAnimationPlay(const MWWorld::Ptr& actor, std::string_view group, int mode, int count, bool persist)@@ -1109,6 +1115,9 @@ namespace mwmp::hooksCellController* cellController = Main::get().getCellController();if (cellController->isSameCell(originalCell, newCell))return;+ // Isowind MMO: a one-off event's person this client runs itself goes where it goes here only+ if (cellController->isClientLocalActor(actor))+ return;BaseActor baseActor;baseActor.refNum = actor.getCellRef().getMpRefNum();@@ -1172,6 +1181,9 @@ namespace mwmp::hooksif (!isLoggedIn() || actor.isEmpty() || target.isEmpty() || !actor.isInCell()|| actor.getCell()->getCell()->isEsm4())return;+ // Isowind MMO: a one-off event's person this client runs itself has its AI here only+ if (Main::get().getCellController()->isClientLocalActor(actor))+ return;ActorList* actorList = Main::get().getNetworking()->getActorList();actorList->reset();actorList->cell = actor.getCell()->getCell()->getEsm3();diff --git a/apps/openmw/mwmp/MechanicsHelper.cpp b/apps/openmw/mwmp/MechanicsHelper.cppindex 7e590d5..b82c6d5 100644--- a/apps/openmw/mwmp/MechanicsHelper.cpp+++ b/apps/openmw/mwmp/MechanicsHelper.cpp@@ -1,3 +1,6 @@+#include <locale>+#include <sstream>+#include <components/openmw-mp/TimedLog.hpp>#include <components/openmw-mp/Utils.hpp>@@ -152,6 +155,103 @@ bool MechanicsHelper::respawnActor(const MWWorld::Ptr& ptr)return true;}+bool MechanicsHelper::runClientLocalCommand(const std::string& command, MWWorld::CellStore* cellStore,+ unsigned int refNum, unsigned int mpNum, const std::string& refIdString)+{+ static const std::string deadPrefix = "isowind local dead ";+ const bool dead = command.rfind(deadPrefix, 0) == 0;+ if (command != "isowind local" && !dead)+ return false;++ CellController* cellController = Main::get().getCellController();+ const bool wasClientLocal = cellController->isClientLocalActor(refNum, mpNum);++ MWWorld::Ptr ptr;+ if (cellStore != nullptr && cellStore->getState() == MWWorld::CellStore::State_Loaded)+ ptr = cellStore->searchExact(refNum, mpNum, refId(refIdString));++ // A thing the event changes, not a person: nothing to run+ if (!ptr.isEmpty() && !ptr.getClass().isActor())+ return true;++ cellController->setClientLocalActor(refNum, mpNum);++ // In a cell this client hasn't loaded the actor is as the game's files have it when it loads (the server tells+ // this client again then)+ if (ptr.isEmpty())+ return true;++ if (!dead)+ {+ // What the server sent about it before, from whichever game ran it, is undone; after that it's this+ // client's own for the session+ if (!wasClientLocal)+ respawnActor(ptr);+ return true;+ }++ // This client's own body of it, as it lies+ if (wasClientLocal && ptr.getClass().getCreatureStats(ptr).isDead())+ return true;++ osg::Vec3f position;+ std::istringstream stream(command.substr(deadPrefix.size()));+ stream.imbue(std::locale::classic());+ if (!(stream >> position.x() >> position.y() >> position.z()))+ return true;++ // Its inventory as the game's files have it, under the player's own loot (which the server sends after this)+ if (!wasClientLocal)+ {+ respawnActor(ptr);+ ptr = cellStore->searchExact(refNum, mpNum, refId(refIdString));+ if (ptr.isEmpty())+ return true;+ }++ MWBase::World* world = MWBase::Environment::get().getWorld();+ ptr = world->moveObject(ptr, position);+ MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr);+ if (!stats.isDead())+ {+ // Dead already, its death not played again (no dying words, no OnDeath for scripts)+ MWMechanics::DynamicStat<float> health = stats.getHealth();+ health.setCurrent(0.f);+ stats.setHealth(health);+ stats.setDeathAnimationFinished(true);+ }+ world->enableActorCollision(ptr, false);+ return true;+}++void MechanicsHelper::sendClientLocalDeath(const MWWorld::Ptr& actor)+{+ if (!mwmp::hooks::isLoggedIn() || actor.isEmpty() || !actor.isInCell() || actor.getCell()->getCell()->isEsm4())+ return;++ LOG_MESSAGE_SIMPLE(TimedLog::LOG_INFO, "Sending the death of %s %i-%i, which this client runs itself",+ idString(actor.getCellRef().getRefId()).c_str(), actor.getCellRef().getMpRefNum(),+ actor.getCellRef().getMpNum());++ const osg::Vec3f position = actor.getRefData().getPosition().asVec3();+ ObjectList* objectList = Main::get().getNetworking()->getObjectList();+ objectList->reset();+ objectList->packetOrigin = CLIENT_GAMEPLAY;+ objectList->cell = actor.getCell()->getCell()->getEsm3();+ BaseObject baseObject = objectList->getBaseObjectFromPtr(actor);+ for (int i = 0; i < 3; ++i)+ {+ ClientVariable place;+ place.internalIndex = i;+ place.variableType = VARIABLE_TYPE::FLOAT;+ place.intValue = 0;+ place.floatValue = position[i];+ baseObject.clientLocals.push_back(place);+ }+ objectList->addBaseObject(baseObject);+ objectList->sendClientScriptLocal();+}+bool MechanicsHelper::isUsingRangedWeapon(const MWWorld::Ptr& ptr){if (ptr.getClass().hasInventoryStore(ptr))diff --git a/apps/openmw/mwmp/MechanicsHelper.hpp b/apps/openmw/mwmp/MechanicsHelper.hppindex 2267828..8d800f1 100644--- a/apps/openmw/mwmp/MechanicsHelper.hpp+++ b/apps/openmw/mwmp/MechanicsHelper.hpp@@ -19,6 +19,15 @@ namespace MechanicsHelper/// Morrowind respawns one, in front of the players there too. Returns whether it was done (not for cells this/// game hasn't loaded, where it's as it starts anyway).bool respawnActor(const MWWorld::Ptr& ptr);+ /// Isowind MMO: the server's commands about a one-off event's people, which each player's game runs itself+ /// (CellController::setClientLocalActor): "isowind local" (the first time this session, the actor starts over as+ /// the game's files have it, undoing what others' games sent about it) and "isowind local dead <x> <y> <z>" (its+ /// body, where it died for this player). Things among the objects are left alone. Returns false for other commands.+ bool runClientLocalCommand(const std::string& command, MWWorld::CellStore* cellStore, unsigned int refNum,+ unsigned int mpNum, const std::string& refId);+ /// Isowind MMO: the server hears of the death of one of a one-off event's people that this client runs itself,+ /// with where the body lies, as that player's (a ClientScriptLocal packet as gameplay, floats 0 to 2 the place)+ void sendClientLocalDeath(const MWWorld::Ptr& actor);bool isUsingRangedWeapon(const MWWorld::Ptr& ptr);diff --git a/apps/openmw/mwmp/ObjectList.cpp b/apps/openmw/mwmp/ObjectList.cppindex 34546dc..a553ee4 100644--- a/apps/openmw/mwmp/ObjectList.cpp+++ b/apps/openmw/mwmp/ObjectList.cpp@@ -990,6 +990,11 @@ void ObjectList::runConsoleCommands(MWWorld::CellStore* cellStore){LOG_APPEND(TimedLog::LOG_VERBOSE, "-- Running on object %s %i-%i", baseObject.refId.c_str(), baseObject.refNum, baseObject.mpNum);+ // Isowind MMO: not a console command, one of a one-off event's people for this client to run itself+ if (MechanicsHelper::runClientLocalCommand(+ consoleCommand, cellStore, baseObject.refNum, baseObject.mpNum, baseObject.refId))+ continue;+// A cell this client hasn't loaded has its actors as they start anywayif (consoleCommand == "isowind respawn" && cellStore->getState() != MWWorld::CellStore::State_Loaded)continue;@@ -1004,7 +1009,10 @@ void ObjectList::runConsoleCommands(MWWorld::CellStore* cellStore)// Isowind MMO: not a console command, the server bringing an enemy or NPC backif (consoleCommand == "isowind respawn"){- if (!MechanicsHelper::respawnActor(ptrFound))+ // (not one this client runs itself: a one-off event's, each player's own, dead or alive)+ if (Main::get().getCellController()->isClientLocalActor(ptrFound))+ LOG_APPEND(TimedLog::LOG_INFO, "-- Not respawned here (this client's own)");+ else if (!MechanicsHelper::respawnActor(ptrFound))LOG_APPEND(TimedLog::LOG_INFO, "-- Not respawned here (not an actor)");continue;}diff --git a/isowind/server/CoreScripts/scripts/config.lua b/isowind/server/CoreScripts/scripts/config.luaindex 9105fe3..46f4bd2 100644--- a/isowind/server/CoreScripts/scripts/config.lua+++ b/isowind/server/CoreScripts/scripts/config.lua@@ -143,6 +143,15 @@ config.synchronizedClientScriptIds = {"helsethScript", "KarrodMovement"}+-- Isowind MMO mode: the scripts of the game's one-off events, which happen once for each player, and once for the+-- players near them together (see custom/isowindMmo.lua; MMO mode adds these to synchronizedClientScriptIds for the+-- server to keep how far each player's got). Co-op mode leaves them as they are: one world, so each event happens once.+-- Scripts that go by a quest's journal stages don't belong here: they already go by each player's own journal+config.isowindEventScriptIds = {+ -- Tarhiel falling from the sky near Seyda Neen (the script is on his journal, on the ground below)+ "fallingScript"+}+-- Whether the instanced spawn should be used instead of the noninstanced oneconfig.useInstancedSpawn = truediff --git a/isowind/server/CoreScripts/scripts/custom/isowindMmo.lua b/isowind/server/CoreScripts/scripts/custom/isowindMmo.luaindex 2609f1f..976090a 100644--- a/isowind/server/CoreScripts/scripts/custom/isowindMmo.lua+++ b/isowind/server/CoreScripts/scripts/custom/isowindMmo.lua@@ -12,11 +12,24 @@-- the host's respawn speed. Ones from the game's files are reset on each client ("isowind respawn", a console-- command packet the game handles itself); leveled-list ones are spawned again where they first appeared. Someone a-- quest script brought into the world (Tarhiel falling from the sky) is a one-off and stays dead.+-- * The game's one-off events (the scripts in config.isowindEventScriptIds: Tarhiel falling from the sky near Seyda+-- Neen) happen once for each player. What an event's script does to the world (enabling, disabling or deleting) and+-- how far it has got (its short and long local variables, isowindEventLocals) are each player's own. Players near the+-- one whose event it is (EVENT_BUBBLE_UNITS outdoors, the same cell indoors) who haven't had it see it with them, and+-- it counts as had for them too; the others get their own when they come by. The people an event script brings in or+-- takes away are run by each player's game itself ("isowind local"), not by whoever's game runs the cell, so each+-- player's game has its own of them: their deaths (isowindEventDeaths, which the player's game reports) are each+-- player's own, as their loot already is. The party doesn't share events: they're for whoever is there.if not IsowindHost.IsMmo() thenreturnend+-- The server keeps how far each player's one-off events have got: their games send their scripts' local variables+for _, scriptId in ipairs(config.isowindEventScriptIds or {}) do+ tableHelper.insertValueIfMissing(config.synchronizedClientScriptIds, scriptId)+end+config.shareJournal = falseconfig.shareTopics = falseconfig.shareFactionRanks = false@@ -239,6 +252,511 @@ local function isFromScript(packetOrigin)packetOrigin == enumerations.packetOrigin.CLIENT_DIALOGUEend+-- --- One-off events ----------------------------------------------------------------------------------------------++-- How far apart players outdoors can be to see an event together (a cell is 8192 units across, and the cells around+-- count too); indoors they have to be in the same cell+local EVENT_BUBBLE_UNITS = 4096+-- A run of an event ends this long after the last change made by the script of the player whose run it is+local EVENT_RUN_SECONDS = 120+-- What a player's game sends this soon after loading a cell comes from its scripts starting over there, before the+-- server's replay of how far they got: for an event the player has had, it's answered with what the player has+local EVENT_REFIRE_SECONDS = 10++-- This session's runs of each event, by its script (lower case) and the player whose run it is: { event, starter,+-- members = { name = true }, last = time, changes = { cellDescription = { states, deletes, locals } } }+local eventRuns = {}+-- When each player's game last loaded each cell, this session+local cellLoadedAt = {}+-- The event people each player's game was told to run itself, this session: { name = { cellDescription = { uniqueIndex+-- = true } } }+local runsOwnCopy = {}++-- The event a packet from a script is about (its script, in lower case), or nil+local function eventScriptOf(packetOrigin)+ if packetOrigin ~= enumerations.packetOrigin.CLIENT_SCRIPT_LOCAL and+ packetOrigin ~= enumerations.packetOrigin.CLIENT_SCRIPT_GLOBAL then+ return nil+ end+ local script = string.lower(tes3mp.GetObjectListClientScript() or "")+ for _, scriptId in ipairs(config.isowindEventScriptIds or {}) do+ if string.lower(scriptId) == script then+ return script+ end+ end+ return nil+end++local function getEventsHad()+ WorldInstance.data.isowindEventsHad = WorldInstance.data.isowindEventsHad or {}+ return WorldInstance.data.isowindEventsHad+end++local function hasHadEvent(event, name)+ local had = getEventsHad()[event]+ return had ~= nil and had[name] == true+end++local function markEventHad(event, name)+ local eventsHad = getEventsHad()+ eventsHad[event] = eventsHad[event] or {}+ eventsHad[event][name] = true+ WorldInstance:QuicksaveToDrive()+end++local function isEventObject(cell, uniqueIndex)+ return cell.data.isowindEvents ~= nil and cell.data.isowindEvents[uniqueIndex] ~= nil+end++-- Where a player is: their cell, and their place in the world (which outdoors goes across cells)+local function placeOf(pid)+ return { cell = tes3mp.GetCell(pid), exterior = tes3mp.IsInExterior(pid), x = tes3mp.GetPosX(pid),+ y = tes3mp.GetPosY(pid) }+end++local function inBubble(place, otherPlace)+ if place.exterior and otherPlace.exterior then+ local dx, dy = place.x - otherPlace.x, place.y - otherPlace.y+ return dx * dx + dy * dy <= EVENT_BUBBLE_UNITS * EVENT_BUBBLE_UNITS+ end+ return not place.exterior and not otherPlace.exterior and place.cell == otherPlace.cell+end++local function onlinePidOf(name)+ for pid, player in pairs(Players) do+ if player:IsLoggedIn() and playerKey(pid) == name then+ return pid+ end+ end+ return nil+end++local function isRefire(name, cellDescription)+ local loadedAt = cellLoadedAt[name] ~= nil and cellLoadedAt[name][cellDescription] or nil+ return loadedAt ~= nil and os.time() - loadedAt <= EVENT_REFIRE_SECONDS+end++-- An event script's short and long local variables from a ClientScriptLocal packet, as { "type:index" = value } (keys+-- that stay as they are in the cell's file); its floats are timers, changing all the time, and are never kept+local function intLocals(variables)+ local result = {}+ for variableType, variableTable in pairs(variables or {}) do+ local typeNumber = tonumber(variableType)+ if typeNumber == enumerations.variableType.SHORT or typeNumber == enumerations.variableType.LONG then+ for internalIndex, value in pairs(variableTable) do+ result[typeNumber .. ":" .. tonumber(internalIndex)] = value+ end+ end+ end+ return result+end++-- Back to the packet's form: { variableType = { internalIndex = value } }+local function packetLocals(vars)+ local variables = {}+ for key, value in pairs(vars) do+ local variableType, internalIndex = key:match("^(%d+):(%d+)$")+ if variableType ~= nil then+ variableType = tonumber(variableType)+ variables[variableType] = variables[variableType] or {}+ variables[variableType][tonumber(internalIndex)] = value+ end+ end+ return variables+end++local function setOwnState(cell, uniqueIndex, refId, name, state)+ cell.data.isowindStates = cell.data.isowindStates or {}+ local record = cell.data.isowindStates[uniqueIndex] or { refId = refId, players = {} }+ record.players[name] = state+ cell.data.isowindStates[uniqueIndex] = record+end++local function getOwnState(cell, uniqueIndex, name)+ local record = cell.data.isowindStates ~= nil and cell.data.isowindStates[uniqueIndex] or nil+ if record == nil then+ return nil+ end+ return record.players[name]+end++local function setOwnTaken(cell, uniqueIndex, name)+ cell.data.isowindTaken = cell.data.isowindTaken or {}+ cell.data.isowindTaken[uniqueIndex] = cell.data.isowindTaken[uniqueIndex] or {}+ cell.data.isowindTaken[uniqueIndex][name] = true+end++local function setOwnLocals(cell, uniqueIndex, refId, name, vars)+ cell.data.isowindEventLocals = cell.data.isowindEventLocals or {}+ local record = cell.data.isowindEventLocals[uniqueIndex] or { refId = refId, players = {} }+ local mine = record.players[name] or {}+ for key, value in pairs(vars) do+ mine[key] = value+ end+ record.players[name] = mine+ cell.data.isowindEventLocals[uniqueIndex] = record+end++local function getOwnLocals(cell, uniqueIndex, name)+ local record = cell.data.isowindEventLocals ~= nil and cell.data.isowindEventLocals[uniqueIndex] or nil+ if record == nil then+ return nil+ end+ return record.players[name]+end++-- To one player's game: { uniqueIndex = { refId, state } }+local function sendStates(pid, cellDescription, states)+ tes3mp.ClearObjectList()+ tes3mp.SetObjectListPid(pid)+ tes3mp.SetObjectListCell(cellDescription)+ for uniqueIndex, object in pairs(states) do+ packetBuilder.AddObjectState(uniqueIndex, object)+ end+ tes3mp.SendObjectState(false)+end++-- { uniqueIndex = { refId } }+local function sendDeletes(pid, cellDescription, deletes)+ tes3mp.ClearObjectList()+ tes3mp.SetObjectListPid(pid)+ tes3mp.SetObjectListCell(cellDescription)+ for uniqueIndex, object in pairs(deletes) do+ packetBuilder.AddObjectDelete(uniqueIndex, object)+ end+ tes3mp.SendObjectDelete(false)+end++-- { uniqueIndex = { refId, vars } }+local function sendLocals(pid, cellDescription, locals)+ tes3mp.ClearObjectList()+ tes3mp.SetObjectListPid(pid)+ tes3mp.SetObjectListCell(cellDescription)+ for uniqueIndex, entry in pairs(locals) do+ packetBuilder.AddClientScriptLocal(uniqueIndex, { refId = entry.refId, variables = packetLocals(entry.vars) })+ end+ tes3mp.SendClientScriptLocal(false)+end++-- A command the game handles itself (mwmp::ObjectList::runConsoleCommands), to one player: { uniqueIndex = refId }+local function sendCommand(pid, cellDescription, command, objects)+ tes3mp.ClearObjectList()+ tes3mp.SetObjectListPid(pid)+ tes3mp.SetObjectListCell(cellDescription)+ tes3mp.SetObjectListConsoleCommand(command)+ for uniqueIndex, refId in pairs(objects) do+ local refNum, mpNum = splitIndex(uniqueIndex)+ tes3mp.SetObjectRefNum(refNum)+ tes3mp.SetObjectMpNum(mpNum)+ tes3mp.SetObjectRefId(refId)+ tes3mp.AddObject()+ end+ tes3mp.SendConsoleCommand(false, false)+end++-- Tells a player's game to run some of a cell's event people itself, each as that player has them: dead where they+-- died for them ("isowind local dead x y z"), or else as the game's files have them ("isowind local"), until the event+-- changes them. Their game does nothing with the things among them.+local function sendEventPeople(pid, cell, uniqueIndexes)+ local name = playerKey(pid)+ local deaths = cell.data.isowindEventDeaths or {}+ runsOwnCopy[name] = runsOwnCopy[name] or {}+ runsOwnCopy[name][cell.description] = runsOwnCopy[name][cell.description] or {}+ local alive = {}+ for _, uniqueIndex in ipairs(uniqueIndexes) do+ local entry = cell.data.isowindEvents[uniqueIndex]+ local death = deaths[uniqueIndex] ~= nil and deaths[uniqueIndex][name] or nil+ if death ~= nil then+ sendCommand(pid, cell.description, string.format("isowind local dead %.2f %.2f %.2f", death.posX,+ death.posY, death.posZ), { [uniqueIndex] = entry.refId })+ else+ alive[uniqueIndex] = entry.refId+ end+ runsOwnCopy[name][cell.description][uniqueIndex] = true+ end+ if next(alive) ~= nil then+ sendCommand(pid, cell.description, "isowind local", alive)+ end+end++-- What an event script enables or disables becomes one of its cell's event objects; from then on the people among+-- them are run by each player's game itself, so every game that has the cell loaded is told now (the others when they+-- load it)+local function registerEventObjects(cell, objects, event)+ cell.data.isowindEvents = cell.data.isowindEvents or {}+ local added = {}+ for uniqueIndex, object in pairs(objects) do+ if cell.data.isowindEvents[uniqueIndex] == nil then+ cell.data.isowindEvents[uniqueIndex] = { refId = object.refId, script = event }+ table.insert(added, uniqueIndex)+ end+ end+ if #added == 0 then+ return+ end+ for _, visitor in pairs(cell.visitors) do+ if Players[visitor] ~= nil and Players[visitor]:IsLoggedIn() then+ sendEventPeople(visitor, cell, added)+ end+ end+end++local function runChanges(run, cellDescription)+ run.changes[cellDescription] = run.changes[cellDescription] or { states = {}, deletes = {}, locals = {} }+ return run.changes[cellDescription]+end++local function memberNames(run)+ local names = {}+ for member in pairs(run.members) do+ table.insert(names, member)+ end+ return names+end++-- A player joining a run gets what it has done so far, kept as theirs+local function giveRunSoFar(run, pid)+ local name = playerKey(pid)+ for cellDescription, changes in pairs(run.changes) do+ local hasCellLoaded = false+ withCell(cellDescription, function(cell)+ for uniqueIndex, object in pairs(changes.states) do+ setOwnState(cell, uniqueIndex, object.refId, name, object.state)+ end+ for uniqueIndex in pairs(changes.deletes) do+ setOwnTaken(cell, uniqueIndex, name)+ end+ for uniqueIndex, entry in pairs(changes.locals) do+ setOwnLocals(cell, uniqueIndex, entry.refId, name, entry.vars)+ end+ hasCellLoaded = tableHelper.containsValue(cell.visitors, pid)+ cell:QuicksaveToDrive()+ end)+ if next(changes.states) ~= nil then+ sendStates(pid, cellDescription, changes.states)+ end+ if next(changes.deletes) ~= nil then+ sendDeletes(pid, cellDescription, changes.deletes)+ end+ -- (the variables only to a game that has the cell loaded; the replay when it loads the cell gives them)+ if next(changes.locals) ~= nil and hasCellLoaded then+ sendLocals(pid, cellDescription, changes.locals)+ end+ end+end++-- The players near the one whose run it is, who haven't had the event, join it: it's theirs too from now on+local function joinNearby(run, starterPid)+ local here = placeOf(starterPid)+ for otherPid, player in pairs(Players) do+ if otherPid ~= starterPid and player:IsLoggedIn() then+ local other = playerKey(otherPid)+ if not run.members[other] and not hasHadEvent(run.event, other) and inBubble(here, placeOf(otherPid)) then+ run.members[other] = true+ markEventHad(run.event, other)+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. other .. " has the " .. run.event ..+ " event with " .. run.starter)+ giveRunSoFar(run, otherPid)+ end+ end+ end+end++-- The run a change from a player's event script belongs to, and whether the run is theirs: the one they're in, or a new+-- one of theirs if they haven't had the event. Nil for a player who has had it and is in none.+local function eventRunOf(pid, event)+ local name = playerKey(pid)+ local now = os.time()+ eventRuns[event] = eventRuns[event] or {}+ local runs = eventRuns[event]+ for starter, run in pairs(runs) do+ if now - run.last > EVENT_RUN_SECONDS then+ runs[starter] = nil+ end+ end+ for _, run in pairs(runs) do+ if run.members[name] then+ if run.starter == name then+ run.last = now+ joinNearby(run, pid)+ end+ return run, run.starter == name+ end+ end+ if hasHadEvent(event, name) then+ return nil, false+ end+ local run = { event = event, starter = name, members = { [name] = true }, last = now, changes = {} }+ runs[name] = run+ markEventHad(event, name)+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. name .. " has the " .. event .. " event")+ joinNearby(run, pid)+ return run, true+end++-- An event script enabling or disabling the game's own people or things: for the player, and the others in their run+-- if it's theirs+local function onEventStates(pid, cell, mine, event)+ local name = playerKey(pid)+ registerEventObjects(cell, mine, event)+ local run, isStarter = eventRunOf(pid, event)++ if run == nil and isRefire(name, cell.description) then+ -- Their game's scripts starting over on loading the cell: it gets back what the player already has+ local answer = {}+ for uniqueIndex, object in pairs(mine) do+ local state = getOwnState(cell, uniqueIndex, name)+ if state == nil then+ state = object.state+ setOwnState(cell, uniqueIndex, object.refId, name, state)+ end+ answer[uniqueIndex] = { refId = object.refId, state = state }+ end+ sendStates(pid, cell.description, answer)+ return+ end++ local names = { name }+ if isStarter then+ names = memberNames(run)+ local changes = runChanges(run, cell.description)+ for uniqueIndex, object in pairs(mine) do+ changes.states[uniqueIndex] = { refId = object.refId, state = object.state }+ end+ end+ -- Each of them sees it now (the player's own game waits for the server to make the change)+ for _, member in ipairs(names) do+ for uniqueIndex, object in pairs(mine) do+ setOwnState(cell, uniqueIndex, object.refId, member, object.state)+ end+ local memberPid = member == name and pid or onlinePidOf(member)+ if memberPid ~= nil then+ sendStates(memberPid, cell.description, mine)+ end+ end+end++-- Whose an event script's deletion is: the run's if it's the player's run, else the player's own+local function eventDeleters(pid, cell, mine, event)+ local run, isStarter = eventRunOf(pid, event)+ if not isStarter then+ return { playerKey(pid) }+ end+ local changes = runChanges(run, cell.description)+ for uniqueIndex, object in pairs(mine) do+ changes.deletes[uniqueIndex] = { refId = object.refId }+ end+ return memberNames(run)+end++-- A player's game telling of the death of its own copy of an event person, and where the body lies: a ClientScriptLocal+-- packet as gameplay (no script's), with the place as floats 0 to 2 (mwmp::MechanicsHelper::sendClientLocalDeath; the+-- server only takes ActorDeath from the game that runs the cell, and a console command would be one of the player's).+-- Kept as that player's, only for this cell's event people that the server told that player's game to run itself and+-- that are there for them; anything else in such a packet changes nothing.+local function onEventDeath(pid, cellDescription, objects)+ local name = playerKey(pid)+ local own = runsOwnCopy[name] ~= nil and runsOwnCopy[name][cellDescription] or {}+ withCell(cellDescription, function(cell)+ for uniqueIndex, object in pairs(objects) do+ local place = object.variables ~= nil and object.variables[enumerations.variableType.FLOAT] or {}+ local x, y, z = tonumber(place[0]), tonumber(place[1]), tonumber(place[2])+ if x ~= nil and y ~= nil and z ~= nil and isEventObject(cell, uniqueIndex) and own[uniqueIndex] and+ getOwnState(cell, uniqueIndex, name) == true then+ cell.data.isowindEventDeaths = cell.data.isowindEventDeaths or {}+ cell.data.isowindEventDeaths[uniqueIndex] = cell.data.isowindEventDeaths[uniqueIndex] or {}+ cell.data.isowindEventDeaths[uniqueIndex][name] = { posX = x, posY = y, posZ = z }+ tes3mp.LogMessage(enumerations.log.INFO, "[Isowind] " .. name .. "'s " .. tostring(object.refId) ..+ " " .. uniqueIndex .. " died in " .. cellDescription)+ else+ tes3mp.LogMessage(enumerations.log.WARN, "[Isowind] Ignored a death of " .. tostring(object.refId) ..+ " " .. uniqueIndex .. " from " .. name .. ": not their game's own event person")+ end+ end+ cell:QuicksaveToDrive()+ end)+ return customEventHooks.makeEventStatus(false, false)+end++-- How far an event's script has got for a player (its short and long variables; ClientScriptLocal packets, which the+-- game sends for the scripts in config.synchronizedClientScriptIds): theirs, and their run's others' if the run is+-- theirs. Their own game already has it (it sets the variable before it tells the server), so it isn't sent back.+local function onClientScriptLocal(eventStatus, pid, cellDescription, objects)+ if eventStatus.validDefaultHandler == false then+ return+ end+ local packetOrigin = tes3mp.GetObjectListOrigin()+ if packetOrigin == enumerations.packetOrigin.CLIENT_GAMEPLAY then+ return onEventDeath(pid, cellDescription, objects)+ end+ local event = eventScriptOf(packetOrigin)+ if event == nil then+ return+ end+ local cell = LoadedCells[cellDescription]+ if cell == nil then+ return customEventHooks.makeEventStatus(false, true)+ end++ local changes = {}+ for uniqueIndex, object in pairs(objects) do+ local vars = intLocals(object.variables)+ if next(vars) ~= nil then+ changes[uniqueIndex] = { refId = object.refId, vars = vars }+ end+ end+ -- Only timers: nothing to keep+ if next(changes) == nil then+ return customEventHooks.makeEventStatus(false, true)+ end++ local name = playerKey(pid)+ local run, isStarter = eventRunOf(pid, event)+ if run == nil and isRefire(name, cellDescription) then+ -- Their game's script starting over on loading the cell: it gets back how far the player had got+ local answer = {}+ for uniqueIndex, change in pairs(changes) do+ local own = getOwnLocals(cell, uniqueIndex, name)+ if own ~= nil then+ answer[uniqueIndex] = { refId = change.refId, vars = own }+ else+ setOwnLocals(cell, uniqueIndex, change.refId, name, change.vars)+ end+ end+ if next(answer) ~= nil then+ sendLocals(pid, cellDescription, answer)+ end+ cell:QuicksaveToDrive()+ return customEventHooks.makeEventStatus(false, true)+ end++ local names = { name }+ if isStarter then+ names = memberNames(run)+ local runLocals = runChanges(run, cellDescription).locals+ for uniqueIndex, change in pairs(changes) do+ local entry = runLocals[uniqueIndex] or { refId = change.refId, vars = {} }+ for key, value in pairs(change.vars) do+ entry.vars[key] = value+ end+ runLocals[uniqueIndex] = entry+ end+ end+ for _, member in ipairs(names) do+ for uniqueIndex, change in pairs(changes) do+ setOwnLocals(cell, uniqueIndex, change.refId, member, change.vars)+ end+ -- (to a game that has the cell loaded: in one that hasn't, the script's variables aren't there to set; the+ -- replay when it loads the cell gives them)+ local memberPid = member ~= name and onlinePidOf(member) or nil+ if memberPid ~= nil and tableHelper.containsValue(cell.visitors, memberPid) then+ sendLocals(memberPid, cellDescription, changes)+ end+ end+ cell:QuicksaveToDrive()+ return customEventHooks.makeEventStatus(false, true)+end+local function onObjectDelete(eventStatus, pid, cellDescription, objects)local packetOrigin = tes3mp.GetObjectListOrigin()local fromScript = isFromScript(packetOrigin)@@ -266,8 +784,14 @@ local function onObjectDelete(eventStatus, pid, cellDescription, objects)returnend- -- A quest's deletion is the whole party's; a pickup only the player's- local names = fromScript and questSharers(pid) or { playerKey(pid) }+ -- A quest's deletion is the whole party's, an event's its run's; a pickup only the player's+ local event = fromScript and eventScriptOf(packetOrigin) or nil+ local names+ if event ~= nil then+ names = eventDeleters(pid, cell, mine, event)+ else+ names = fromScript and questSharers(pid) or { playerKey(pid) }+ endcell.data.isowindTaken = cell.data.isowindTaken or {}for uniqueIndex, object in pairs(mine) docell.data.isowindTaken[uniqueIndex] = cell.data.isowindTaken[uniqueIndex] or {}@@ -296,9 +820,11 @@ local function onObjectDelete(eventStatus, pid, cellDescription, objects)return customEventHooks.makeEventStatus(false, true)end--- A quest script enabling or disabling one of the game's own people or things: for that player (and their party) only+-- A quest script enabling or disabling one of the game's own people or things: for that player (and their party) only;+-- an event script's, for that player (and the others in their run)local function onObjectState(eventStatus, pid, cellDescription, objects)- if eventStatus.validDefaultHandler == false or not isFromScript(tes3mp.GetObjectListOrigin()) then+ local packetOrigin = tes3mp.GetObjectListOrigin()+ if eventStatus.validDefaultHandler == false or not isFromScript(packetOrigin) thenreturnendlocal cell = LoadedCells[cellDescription]@@ -319,27 +845,32 @@ local function onObjectState(eventStatus, pid, cellDescription, objects)returnend- local names = questSharers(pid)- cell.data.isowindStates = cell.data.isowindStates or {}- for uniqueIndex, object in pairs(mine) do- local record = cell.data.isowindStates[uniqueIndex] or { refId = object.refId, players = {} }- for _, name in ipairs(names) do- record.players[name] = object.state- end- cell.data.isowindStates[uniqueIndex] = record- end- -- The player and the party's others who are on see it now (the player's own game waits for the server to make- -- the change, mwmp::hooks::requestScriptObjectState)- local recipients = otherOnlinePids(pid, names)- table.insert(recipients, pid)- for _, recipient in ipairs(recipients) do- tes3mp.ClearObjectList()- tes3mp.SetObjectListPid(recipient)- tes3mp.SetObjectListCell(cellDescription)+ local event = eventScriptOf(packetOrigin)+ if event ~= nil then+ onEventStates(pid, cell, mine, event)+ else+ local names = questSharers(pid)+ cell.data.isowindStates = cell.data.isowindStates or {}for uniqueIndex, object in pairs(mine) do- packetBuilder.AddObjectState(uniqueIndex, object)+ local record = cell.data.isowindStates[uniqueIndex] or { refId = object.refId, players = {} }+ for _, name in ipairs(names) do+ record.players[name] = object.state+ end+ cell.data.isowindStates[uniqueIndex] = record+ end+ -- The player and the party's others who are on see it now (the player's own game waits for the server to+ -- make the change, mwmp::hooks::requestScriptObjectState)+ local recipients = otherOnlinePids(pid, names)+ table.insert(recipients, pid)+ for _, recipient in ipairs(recipients) do+ tes3mp.ClearObjectList()+ tes3mp.SetObjectListPid(recipient)+ tes3mp.SetObjectListCell(cellDescription)+ for uniqueIndex, object in pairs(mine) do+ packetBuilder.AddObjectState(uniqueIndex, object)+ end+ tes3mp.SendObjectState(false)end- tes3mp.SendObjectState(false)end-- The rest as the default handler does@@ -383,6 +914,15 @@ local function onCellLoad(eventStatus, pid, cellDescription)endlocal name = playerKey(pid)+ -- Their game's scripts start over there now, before the replay of how far its events got (isRefire)+ cellLoadedAt[name] = cellLoadedAt[name] or {}+ cellLoadedAt[name][cellDescription] = os.time()++ -- The cell's event people, run by their game itself, before what the player's events did to them+ if cell.data.isowindEvents ~= nil then+ sendEventPeople(pid, cell, tableHelper.getArrayFromIndexes(cell.data.isowindEvents))+ end+if cell.data.isowindTaken ~= nil thentes3mp.ClearObjectList()tes3mp.SetObjectListPid(pid)@@ -462,6 +1002,19 @@ local function onCellLoad(eventStatus, pid, cellDescription)regrown[name][cellDescription] = nilend+ -- How far the player's events there have got (their game's scripts start from nothing at each login)+ if cell.data.isowindEventLocals ~= nil then+ local locals = {}+ for uniqueIndex, record in pairs(cell.data.isowindEventLocals) do+ if record.players[name] ~= nil then+ locals[uniqueIndex] = { refId = record.refId, vars = record.players[name] }+ end+ end+ if next(locals) ~= nil then+ sendLocals(pid, cellDescription, locals)+ end+ end+seenCells[name] = seenCells[name] or {}seenCells[name][cellDescription] = trueend@@ -595,7 +1148,7 @@ local function onActorDeath(eventStatus, pid, cellDescription, actors)local _, mpNum = splitIndex(uniqueIndex)local isSummon = objectData ~= nil and objectData.summon ~= nillocal spawnPoints = cell.data.isowindSpawnPoints or {}- if not isSummon and not isQuestAppearance(cell, uniqueIndex) and+ if not isSummon and not isQuestAppearance(cell, uniqueIndex) and not isEventObject(cell, uniqueIndex) and(mpNum == 0 or spawnPoints[uniqueIndex] ~= nil) thenlocal minutes = respawnMinutes(actor.refId or (objectData and objectData.refId), objectData)respawns[cellDescription] = respawns[cellDescription] or {}@@ -618,7 +1171,8 @@ local function respawnInCell(cellDescription, uniqueIndexes)-- disabled stays that way for them (it's in isowindStates, which a respawn keeps)local disabled = objectData ~= nil and objectData.state == falselocal _, mpNum = splitIndex(uniqueIndex)- if not moved and not disabled then+ -- A one-off event's people are each player's game's own, dead or alive+ if not moved and not disabled and not isEventObject(cell, uniqueIndex) thenif cell.data.isowindLoot ~= nil thencell.data.isowindLoot[uniqueIndex] = nilend@@ -712,6 +1266,7 @@ customEventHooks.registerHandler("OnServerPostInit", function(eventStatus)customEventHooks.registerValidator("OnContainer", onContainer)customEventHooks.registerValidator("OnObjectDelete", onObjectDelete)customEventHooks.registerValidator("OnObjectState", onObjectState)+ customEventHooks.registerValidator("OnClientScriptLocal", onClientScriptLocal)customEventHooks.registerHandler("OnCellLoad", onCellLoad)customEventHooks.registerHandler("OnObjectSpawn", onObjectSpawn)customEventHooks.registerHandler("OnActorDeath", onActorDeath)@@ -720,6 +1275,8 @@ customEventHooks.registerHandler("OnServerPostInit", function(eventStatus)if Players[pid] ~= nil thenseenCells[playerKey(pid)] = nilregrown[playerKey(pid)] = nil+ cellLoadedAt[playerKey(pid)] = nil+ runsOwnCopy[playerKey(pid)] = nilendend)respawnTimer = tes3mp.CreateTimer("IsowindMmoRespawnTimer", time.seconds(CHECK_SECONDS))diff --git a/isowind/server/tests/eventtest.lua b/isowind/server/tests/eventtest.luanew file mode 100644index 0000000..32b4d5b--- /dev/null+++ b/isowind/server/tests/eventtest.lua@@ -0,0 +1,337 @@+-- How to run: copy this into a copy of the server folder as CoreScripts/scripts/custom/, add+-- require("custom/eventtest") at the end of customScripts.lua, put mode = mmo under [Isowind] in tes3mp-server.cfg and+-- start tes3mp-server for a few seconds; the log shows PASS/FAIL lines and "done, N failed".+-- Tests of isowindMmo.lua's one-off events (Tarhiel falling near Seyda Neen) inside a real server: fake players and+-- packets, real cells and world data.+local log = function(text) tes3mp.LogMessage(enumerations.log.INFO, "[eventtest] " .. text) end+local failures = 0+local function check(name, condition)+ if condition then log("PASS " .. name) else log("FAIL " .. name); failures = failures + 1 end+end++-- Every Set/Add/Send/Clear call is recorded instead of done+local sent = {}+local current = {}+local function newList()+ return { objects = {}, object = { locals = {} } }+end+local function installMocks()+ for name, fn in pairs(tes3mp) do+ if type(name) == "string" and (name:find("^Set") or name:find("^Add") or name:find("^Send") or+ name:find("^Clear") or name == "CopyReceivedObjectListToStore") then+ tes3mp[name] = function(...)+ local args = { ... }+ if name == "ClearObjectList" then current = newList()+ elseif name == "SetObjectListPid" then current.pid = args[1]+ elseif name == "SetObjectListConsoleCommand" then current.command = args[1]+ elseif name == "SetObjectRefNum" then current.object.refNum = tostring(args[1])+ elseif name == "SetObjectMpNum" then current.object.mpNum = tostring(args[1])+ elseif name == "SetObjectRefId" then current.object.refId = args[1]+ elseif name == "SetObjectState" then current.object.state = args[1]+ elseif name == "AddClientLocalInteger" then+ table.insert(current.object.locals, { index = args[1], value = args[2], type = args[3] })+ elseif name == "AddClientLocalFloat" then+ table.insert(current.object.locals, { index = args[1], value = args[2], type = 2 })+ elseif name == "AddObject" then+ table.insert(current.objects, current.object)+ current.object = { locals = {} }+ elseif name:find("^Send") then+ table.insert(sent, { name = name, args = args, pid = current.pid, command = current.command,+ objects = current.objects })+ end+ end+ end+ end+ current = newList()+end++local incoming = { origin = enumerations.packetOrigin.CLIENT_SCRIPT_LOCAL, script = "" }+tes3mp.ReadReceivedObjectList = function() end+tes3mp.GetObjectListOrigin = function() return incoming.origin end+tes3mp.GetObjectListClientScript = function() return incoming.script end+local function receive(origin, script)+ incoming = { origin = origin, script = script or "" }+end++-- Where the fake players are+local places = {}+tes3mp.GetCell = function(pid) return places[pid].cell end+tes3mp.IsInExterior = function(pid) return places[pid].exterior end+tes3mp.GetPosX = function(pid) return places[pid].x end+tes3mp.GetPosY = function(pid) return places[pid].y end++local function sentTo(name, pid)+ local found = {}+ for _, packet in ipairs(sent) do+ if packet.name == name and packet.pid == pid then table.insert(found, packet) end+ end+ return found+end+local function firstIndexOf(name, pid)+ for i, packet in ipairs(sent) do+ if packet.name == name and packet.pid == pid then return i end+ end+end+local function hasObject(packet, refNum, state)+ for _, object in ipairs(packet.objects) do+ if object.refNum == refNum and (state == nil or object.state == state) then return true end+ end+ return false+end+local function localValue(packet, refNum, index)+ for _, object in ipairs(packet.objects) do+ if object.refNum == refNum then+ for _, entry in ipairs(object.locals) do+ if entry.index == index and entry.type ~= 2 then return entry.value end+ end+ end+ end+end++local function validate(event, args)+ return customEventHooks.triggerValidators(event, args)+end++local LOCAL = enumerations.packetOrigin.CLIENT_SCRIPT_LOCAL+local SHORT, FLOAT = enumerations.variableType.SHORT, enumerations.variableType.FLOAT+local CELL = "-3, -8"+local TARHIEL, PLATFORM, BOOK = "474443-0", "476745-0", "476746-0"++local function makePlayer(pid, name, place)+ Players[pid] = { pid = pid, accountName = name, name = name, consoleCommandsQueued = {}, summons = {},+ data = { location = { cell = place.cell }, alliedPlayers = {} }, IsLoggedIn = function() return true end,+ QuicksaveToDrive = function() end, Message = function() end }+ places[pid] = place+end++local function enableTarhiel(pid)+ receive(LOCAL, "fallingScript")+ return validate("OnObjectState", { pid, CELL, { [TARHIEL] = { refId = "agronian guy", uniqueIndex = TARHIEL,+ state = true } }, {} })+end+local function setFellonce(pid, value, timer)+ receive(LOCAL, "fallingScript")+ local variables = { [SHORT] = { [0] = value } }+ if timer ~= nil then variables[FLOAT] = { [0] = timer } end+ return validate("OnClientScriptLocal", { pid, CELL, { [BOOK] = { refId = "bk_falljournal_unique",+ uniqueIndex = BOOK, variables = variables } }, {} })+end++local function runTests()+ installMocks()+ WorldInstance.data.isowindEventsHad = nil+ logicHandler.LoadCell(CELL)+ local cell = LoadedCells[CELL]+ for _, key in ipairs({ "isowindEvents", "isowindEventLocals", "isowindEventDeaths", "isowindStates" }) do+ cell.data[key] = nil+ end++ -- Alpha and Beta stand near Tarhiel's journal, Gamma is far off; Delta is in a house in Seyda Neen+ makePlayer(0, "Alpha", { cell = CELL, exterior = true, x = -16750, y = -58560 })+ makePlayer(1, "Beta", { cell = CELL, exterior = true, x = -15000, y = -56500 })+ makePlayer(2, "Gamma", { cell = "-1, -8", exterior = true, x = -4000, y = -60000 })+ makePlayer(3, "Delta", { cell = "Seyda Neen, Arrille's Tradehouse", exterior = false, x = -16700, y = -58500 })+ cell.visitors = { 0, 1 }++ check("the event's script reports its variables",+ tableHelper.containsValue(config.synchronizedClientScriptIds, "fallingScript"))++ -- Alpha's game brings Tarhiel in: Alpha's run, with Beta who is near+ sent = {}+ local status = enableTarhiel(0)+ check("event enable skips the shared save", status.validDefaultHandler == false)+ check("Tarhiel is an event person now", cell.data.isowindEvents[TARHIEL] ~= nil)+ local states = cell.data.isowindStates[TARHIEL].players+ check("enabled for Alpha and Beta", states.alpha == true and states.beta == true)+ check("not for Gamma (far) or Delta (indoors)", states.gamma == nil and states.delta == nil)+ check("the event counts as had for Alpha and Beta", WorldInstance.data.isowindEventsHad.fallingscript.alpha and+ WorldInstance.data.isowindEventsHad.fallingscript.beta)+ check("but not for Gamma or Delta", not WorldInstance.data.isowindEventsHad.fallingscript.gamma and+ not WorldInstance.data.isowindEventsHad.fallingscript.delta)+ local localAlpha = sentTo("SendConsoleCommand", 0)[1]+ local localBeta = sentTo("SendConsoleCommand", 1)[1]+ check("Alpha's and Beta's games run Tarhiel themselves", localAlpha ~= nil and localAlpha.command ==+ "isowind local" and hasObject(localAlpha, "474443") and localBeta ~= nil and localBeta.command ==+ "isowind local")+ check("they're told that before he's enabled", firstIndexOf("SendConsoleCommand", 0) <+ firstIndexOf("SendObjectState", 0) and firstIndexOf("SendConsoleCommand", 1) < firstIndexOf("SendObjectState", 1))+ check("Alpha's game gets the enable back", sentTo("SendObjectState", 0)[1] ~= nil and+ hasObject(sentTo("SendObjectState", 0)[1], "474443", true))+ check("Beta's game gets it too", sentTo("SendObjectState", 1)[1] ~= nil and+ hasObject(sentTo("SendObjectState", 1)[1], "474443", true))+ check("Gamma's and Delta's don't", #sentTo("SendObjectState", 2) == 0 and #sentTo("SendObjectState", 3) == 0)++ -- How far Alpha's script has got: kept for both, Beta's game told, the timer dropped+ sent = {}+ status = setFellonce(0, 1, 1.5)+ check("event variables skip the shared save", status.validDefaultHandler == false)+ local record = cell.data.isowindEventLocals[BOOK]+ check("fellonce 1 kept for Alpha and Beta", record.players.alpha["0:0"] == 1 and record.players.beta["0:0"] == 1)+ check("the timer isn't kept", record.players.alpha["2:0"] == nil)+ check("not shared", cell.data.objectData[BOOK] == nil or cell.data.objectData[BOOK].variables == nil)+ local toBeta = sentTo("SendClientScriptLocal", 1)[1]+ check("Beta's game told fellonce 1", toBeta ~= nil and localValue(toBeta, "476746", 0) == 1)+ check("Alpha's game not told (it set it)", #sentTo("SendClientScriptLocal", 0) == 0)++ sent = {}+ receive(LOCAL, "fallingScript")+ status = validate("OnClientScriptLocal", { 0, CELL, { [BOOK] = { refId = "bk_falljournal_unique",+ uniqueIndex = BOOK, variables = { [FLOAT] = { [0] = 2.5 } } } }, {} })+ check("a timer alone is dropped", status.validDefaultHandler == false and #sent == 0)++ -- Beta's own game runs the script too: Beta's alone+ sent = {}+ setFellonce(1, 2)+ check("Beta's own progress is Beta's", record.players.beta["0:0"] == 2 and record.players.alpha["0:0"] == 1)+ check("and goes to no one", #sent == 0)+ receive(LOCAL, "fallingScript")+ validate("OnObjectState", { 1, CELL, { [PLATFORM] = { refId = "fallguy_collision_unique", uniqueIndex = PLATFORM,+ state = false } }, {} })+ check("Beta's platform disable is Beta's", cell.data.isowindStates[PLATFORM].players.beta == false and+ cell.data.isowindStates[PLATFORM].players.alpha == nil)+ check("and comes back to Beta only", #sentTo("SendObjectState", 1) == 1 and #sentTo("SendObjectState", 0) == 0)++ -- Alpha's script carries on: both+ sent = {}+ receive(LOCAL, "fallingScript")+ validate("OnObjectState", { 0, CELL, { [PLATFORM] = { refId = "fallguy_collision_unique", uniqueIndex = PLATFORM,+ state = false } }, {} })+ check("Alpha's platform disable is both's", cell.data.isowindStates[PLATFORM].players.alpha == false and+ cell.data.isowindStates[PLATFORM].players.beta == false)+ check("and both games get it", #sentTo("SendObjectState", 0) == 1 and #sentTo("SendObjectState", 1) == 1)++ -- Delta comes out of the house while it goes on: Delta joins Alpha's run, with what it has done so far+ places[3] = { cell = CELL, exterior = true, x = -17500, y = -59000 }+ cell.visitors = { 0, 1, 3 }+ sent = {}+ setFellonce(0, -1)+ check("Delta has the event now", WorldInstance.data.isowindEventsHad.fallingscript.delta == true)+ check("Delta has Tarhiel enabled and the platform gone", cell.data.isowindStates[TARHIEL].players.delta == true+ and cell.data.isowindStates[PLATFORM].players.delta == false)+ local soFar = sentTo("SendObjectState", 3)[1]+ check("Delta's game gets both", soFar ~= nil and hasObject(soFar, "474443", true) and+ hasObject(soFar, "476745", false))+ local deltaLocals = sentTo("SendClientScriptLocal", 3)+ check("Delta's game gets fellonce 1 so far, then -1", #deltaLocals == 2 and+ localValue(deltaLocals[1], "476746", 0) == 1 and localValue(deltaLocals[2], "476746", 0) == -1)+ check("fellonce -1 for all three", record.players.alpha["0:0"] == -1 and record.players.beta["0:0"] == -1 and+ record.players.delta["0:0"] == -1)+ check("Alpha's and Beta's games hear only the -1 (Beta's)", #sentTo("SendClientScriptLocal", 0) == 0 and+ #sentTo("SendClientScriptLocal", 1) == 1)++ -- Gamma comes by later, from far off: Gamma's own run+ places[2] = { cell = CELL, exterior = true, x = -16740, y = -58550 }+ places[0] = { cell = "-1, -8", exterior = true, x = -4000, y = -60000 }+ places[1] = { cell = "-1, -8", exterior = true, x = -4100, y = -60000 }+ sent = {}+ enableTarhiel(2)+ check("Gamma has the event", WorldInstance.data.isowindEventsHad.fallingscript.gamma == true and+ cell.data.isowindStates[TARHIEL].players.gamma == true)+ check("Gamma's run gives the others nothing", #sentTo("SendObjectState", 0) == 0 and+ #sentTo("SendObjectState", 1) == 0 and #sentTo("SendObjectState", 2) == 1)++ -- Tarhiel dies in Alpha's game, which says so (as gameplay, with where the body lies)+ local function reportDeath(pid, origin, uniqueIndex, refId, x, y, z)+ receive(origin)+ return validate("OnClientScriptLocal", { pid, CELL, { [uniqueIndex] = { refId = refId,+ uniqueIndex = uniqueIndex, variables = { [FLOAT] = { [0] = x, [1] = y, [2] = z } } } }, {} })+ end+ sent = {}+ status = reportDeath(0, enumerations.packetOrigin.CLIENT_GAMEPLAY, TARHIEL, "agronian guy", -16747.4, -58568, 668.5)+ check("the death report skips the default handlers", status.validDefaultHandler == false and+ status.validCustomHandlers == false)+ local death = cell.data.isowindEventDeaths ~= nil and cell.data.isowindEventDeaths[TARHIEL] ~= nil and+ cell.data.isowindEventDeaths[TARHIEL].alpha or nil+ check("Alpha's Tarhiel is dead where he fell", death ~= nil and death.posZ == 668.5)+ check("nothing's shared", cell.data.objectData[TARHIEL] == nil or cell.data.objectData[TARHIEL].variables == nil)+ reportDeath(1, enumerations.packetOrigin.CLIENT_CONSOLE, TARHIEL, "agronian guy", 0, 0, 0)+ check("one from the console isn't a death", cell.data.isowindEventDeaths[TARHIEL].beta == nil)+ reportDeath(2, enumerations.packetOrigin.CLIENT_GAMEPLAY, TARHIEL, "agronian guy", 0, 0, 0)+ check("one from a game that wasn't told to run him is ignored", cell.data.isowindEventDeaths[TARHIEL].gamma == nil)+ reportDeath(0, enumerations.packetOrigin.CLIENT_GAMEPLAY, BOOK, "bk_falljournal_unique", 0, 0, 0)+ check("one about something else is ignored", cell.data.isowindEventDeaths[BOOK] == nil and+ (cell.data.objectData[BOOK] == nil or cell.data.objectData[BOOK].variables == nil))++ -- Someone the authority's game says died isn't brought back+ customEventHooks.triggerHandlers("OnActorDeath", customEventHooks.makeEventStatus(true, true),+ { 0, CELL, { [TARHIEL] = { refId = "agronian guy", killer = {} } } })+ check("an event person doesn't respawn", WorldInstance.data.isowindRespawns == nil or+ WorldInstance.data.isowindRespawns[CELL] == nil or WorldInstance.data.isowindRespawns[CELL][TARHIEL] == nil)++ -- Alpha logs in again later and loads the cell: dead Tarhiel, the platform gone, fellonce -1+ local realTime = os.time+ os.time = function() return realTime() + 200 end+ places[0] = { cell = CELL, exterior = true, x = -16750, y = -58560 }+ cell.visitors = { 0 }+ sent = {}+ customEventHooks.triggerHandlers("OnCellLoad", customEventHooks.makeEventStatus(true, true), { 0, CELL })+ local commands = sentTo("SendConsoleCommand", 0)+ local dead, alive = nil, nil+ for _, packet in ipairs(commands) do+ if packet.command:find("^isowind local dead") then dead = packet end+ if packet.command == "isowind local" then alive = packet end+ end+ check("cell load: Alpha's game runs its dead Tarhiel", dead ~= nil and+ dead.command == "isowind local dead -16747.40 -58568.00 668.50" and hasObject(dead, "474443"))+ check("cell load: the platform isn't a person but is told too (the game ignores it)", alive ~= nil and+ hasObject(alive, "476745"))+ local stateReplay = sentTo("SendObjectState", 0)[1]+ check("cell load: Tarhiel enabled and the platform gone", stateReplay ~= nil and+ hasObject(stateReplay, "474443", true) and hasObject(stateReplay, "476745", false))+ local localsReplay = sentTo("SendClientScriptLocal", 0)[1]+ check("cell load: fellonce -1", localsReplay ~= nil and localValue(localsReplay, "476746", 0) == -1)+ check("cell load: the event marks come before the states", firstIndexOf("SendConsoleCommand", 0) <+ firstIndexOf("SendObjectState", 0))++ -- Alpha's game's script starts over before the replay arrives: answered with what Alpha has, no new run+ sent = {}+ status = setFellonce(0, 1)+ local answer = sentTo("SendClientScriptLocal", 0)[1]+ check("a re-fired variable is answered with Alpha's", status.validDefaultHandler == false and answer ~= nil and+ localValue(answer, "476746", 0) == -1)+ check("and isn't kept", record.players.alpha["0:0"] == -1)+ receive(LOCAL, "fallingScript")+ validate("OnObjectState", { 0, CELL, { [PLATFORM] = { refId = "fallguy_collision_unique", uniqueIndex = PLATFORM,+ state = true } }, {} })+ local stateAnswer = sentTo("SendObjectState", 0)[1]+ check("a re-fired enable is answered with Alpha's state", stateAnswer ~= nil and+ hasObject(stateAnswer, "476745", false) and cell.data.isowindStates[PLATFORM].players.alpha == false)+ check("no one else hears of it", #sent == 2)++ -- Someone who has never had it loads the cell: their game runs Tarhiel itself, as the game's files have him+ makePlayer(4, "Epsilon", { cell = CELL, exterior = true, x = -16750, y = -58560 })+ cell.visitors = { 0, 4 }+ sent = {}+ customEventHooks.triggerHandlers("OnCellLoad", customEventHooks.makeEventStatus(true, true), { 4, CELL })+ local firstTime = sentTo("SendConsoleCommand", 4)+ check("first load: one isowind local, Tarhiel and the platform", #firstTime == 1 and+ firstTime[1].command == "isowind local" and hasObject(firstTime[1], "474443") and+ hasObject(firstTime[1], "476745"))+ check("first load: nothing of the others' events", #sentTo("SendObjectState", 4) == 0 and+ #sentTo("SendClientScriptLocal", 4) == 0)+ Players[4] = nil++ -- Long after the cell loaded, a change of Alpha's script is Alpha's+ os.time = function() return realTime() + 300 end+ sent = {}+ setFellonce(0, 5)+ check("later progress is kept, for Alpha only", record.players.alpha["0:0"] == 5 and+ record.players.beta["0:0"] == -1 and #sent == 0)+ os.time = realTime++ -- Other scripts' variables are as before+ receive(LOCAL, "GG_OpenGate1")+ status = validate("OnClientScriptLocal", { 0, CELL, { ["1-0"] = { refId = "x", uniqueIndex = "1-0",+ variables = { [SHORT] = { [0] = 1 } } } }, {} })+ check("a mechanism's variables stay shared", status.validDefaultHandler ~= false)++ for _, key in ipairs({ "isowindEvents", "isowindEventLocals", "isowindEventDeaths", "isowindStates" }) do+ cell.data[key] = nil+ end+ log("done, " .. failures .. " failed")+end++customEventHooks.registerHandler("OnServerPostInit", function()+ local ok, err = pcall(runTests)+ if not ok then log("ERROR " .. tostring(err)) end+end)diff --git a/isowind/server/tests/mmotest.lua b/isowind/server/tests/mmotest.luaindex b879b39..1ca6ee0 100644--- a/isowind/server/tests/mmotest.lua+++ b/isowind/server/tests/mmotest.lua@@ -51,6 +51,7 @@ tes3mp.ReadReceivedObjectList = function() endtes3mp.GetObjectListAction = function() return incoming.action endtes3mp.GetObjectListContainerSubAction = function() return incoming.subAction or 0 endtes3mp.GetObjectListOrigin = function() return incoming.origin or enumerations.packetOrigin.CLIENT_GAMEPLAY end+tes3mp.GetObjectListClientScript = function() return incoming.script or "" endtes3mp.GetObjectListSize = function() return #incoming.objects endtes3mp.GetObjectRefNum = function(i) return incoming.objects[i + 1].refNum endtes3mp.GetObjectMpNum = function(i) return incoming.objects[i + 1].mpNum enddiff --git a/isowind/server/tests/partytest.lua b/isowind/server/tests/partytest.luaindex 033e1e1..dd5cc6b 100644--- a/isowind/server/tests/partytest.lua+++ b/isowind/server/tests/partytest.lua@@ -72,6 +72,7 @@ local function runTests()tes3mp.GetTopicChangesSize = function() return #topicChanges endtes3mp.GetTopicId = function(pid, i) return topicChanges[i + 1] endtes3mp.GetObjectListOrigin = function() return enumerations.packetOrigin.CLIENT_SCRIPT_LOCAL end+ tes3mp.GetObjectListClientScript = function() return "" endWorldInstance.data.isowindParties = nillocal ENTRY = enumerations.journal.ENTRY