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: locks and traps are each player's own, shared with their party; probe disarms reach the server
Alan Saundersb71c214f9632
diff --git a/apps/openmw/mwmechanics/security.cpp b/apps/openmw/mwmechanics/security.cppindex c3f0c62..d323743 100644--- a/apps/openmw/mwmechanics/security.cpp+++ b/apps/openmw/mwmechanics/security.cpp@@ -131,9 +131,18 @@ namespace MWMechanicsauto& prng = MWBase::Environment::get().getWorld()->getPrng();if (Misc::Rng::roll0to99(prng) <= x){- trap.getCellRef().setTrap(ESM::RefId());-- resultSound = "Disarm Trap";+ // Isowind multiplayer: the server takes the trap away, for everyone it concerns, and its reply plays+ // the sound (mwmp::ObjectList::triggerTrapObjects)+ if (mwmp::hooks::isMultiplayer())+ {+ mwmp::hooks::sendObjectTrap(trap, trap.getRefData().getPosition(), true);+ resultSound = {};+ }+ else+ {+ trap.getCellRef().setTrap(ESM::RefId());+ resultSound = "Disarm Trap";+ }resultMessage = "#{sTrapSuccess}";mActor.getClass().skillUsageSucceeded(mActor, ESM::Skill::Security, ESM::Skill::Security_DisarmTrap);}diff --git a/apps/openmw/mwmp/ObjectList.cpp b/apps/openmw/mwmp/ObjectList.cppindex 6a6d6f0..34546dc 100644--- a/apps/openmw/mwmp/ObjectList.cpp+++ b/apps/openmw/mwmp/ObjectList.cpp@@ -639,7 +639,9 @@ void ObjectList::lockObjects(MWWorld::CellStore* cellStore)if (baseObject.lockLevel > 0)ptrFound.getCellRef().lock(baseObject.lockLevel);- else+ // Isowind: only if locked, since unlock() turns the lock level around: the same unlock can come twice+ // (an MMO server replays each player's locks whenever they load the cell, isowindLocks.lua)+ else if (ptrFound.getCellRef().isLocked())ptrFound.getCellRef().unlock();}}@@ -653,7 +655,8 @@ void ObjectList::triggerTrapObjects(MWWorld::CellStore* cellStore)MWWorld::Ptr ptrFound = cellStore->searchExact(baseObject.refNum, baseObject.mpNum, mwmp::refId(baseObject.refId));- if (!ptrFound.isEmpty())+ // Isowind: one whose trap is already gone has nothing to spring or disarm (an MMO server's replay at cell load)+ if (!ptrFound.isEmpty() && !ptrFound.getCellRef().getTrap().empty()){LOG_APPEND(TimedLog::LOG_VERBOSE, "-- Found %s %i-%i", mwmp::idString(ptrFound.getCellRef().getRefId()).c_str(),ptrFound.getCellRef().getMpRefNum(), ptrFound.getCellRef().getMpNum());diff --git a/isowind/README.txt b/isowind/README.txtindex a8f7d04..3af17be 100644--- a/isowind/README.txt+++ b/isowind/README.txt@@ -56,7 +56,9 @@ Hosting a server(containers, corpses, plants, items lying around) and their own quests, and enemies and NPCscome back after they die, players there or not: weak ones after 1.5 minutes, normal ones 5,tough ones 15, bosses 20 ("Enemy respawns" speeds that up or slows it down). Plants and ore- you harvested grow back for you after 10 minutes; chests don't refill.+ you harvested grow back for you after 10 minutes; chests don't refill. Locks and traps are+ yours too: a door or chest you picked or unlocked stays locked for others, and a trap you+ disarmed or set off is still there for them.Quests that count kills (like the Fighters Guild's rats) count the kills you made yourself,or your party made; someone else killing them first doesn't take them from you, they come back.- PvP (whether players can hurt each other), difficulty and how fast the time of day goes.@@ -81,8 +83,8 @@ The world never pauses, not even in menus. Saving and loading are off: the serveWhen you die you wake up at the nearest temple.Parties (MMO servers): players in a party share their quests as on a co-op server - journal,-topics, quest progress, kill credit and what quests change in the world - while each keeps their-own loot. Type in the chat:+topics, quest progress, kill credit and what quests change in the world - and the locks and traps+they open, from when they joined, while each keeps their own loot. Type in the chat:/party invite NAME invite a player (their name, or the number before it in the player list)/party accept join the party you were invited to (or /party decline)/party who is in your partydiff --git a/isowind/server/CoreScripts/scripts/custom/isowindLocks.lua b/isowind/server/CoreScripts/scripts/custom/isowindLocks.luanew file mode 100644index 0000000..72ff077--- /dev/null+++ b/isowind/server/CoreScripts/scripts/custom/isowindLocks.lua@@ -0,0 +1,175 @@+-- Isowind MMO mode: the locks and traps of the game's own doors and containers are each player's own, shared with+-- their party (isowindParty.lua) as quests are. A chest one player picked, unlocked with its key, opened with a spell or+-- had a quest script unlock stays locked for everyone else, and a trap one disarmed or set off is still there for them.+--+-- * Kept in the cell's data, per player: isowindLocks (the lock level they have, 0 for unlocked) and isowindTraps (the+-- traps gone for them). A change is written for the party's members at the time of it; someone who joins the party+-- later doesn't get it, as with what quests change in the world (isowindMmo.lua's isowindStates).+-- * The player's game makes the change when the server sends it back (it waits for that), and the party's other+-- members who are on get it at once. Each player's are sent again whenever their game loads the cell, after the+-- shared state.+-- * Things players placed stay shared, and so do the console's changes. A door's being open or closed stays shared too:+-- one a player unlocked and opened is open for everyone, though still locked for the others.+-- Co-op servers don't load this: their world is one, locks and traps included.++if not IsowindHost.IsMmo() then+ return+end++local isowindLocks = {}++-- The same helpers as isowindMmo.lua's+local function playerKey(pid)+ return string.lower(Players[pid].accountName)+end++local function otherOnlinePids(pid, names)+ local pids = {}+ for otherPid, player in pairs(Players) do+ if otherPid ~= pid and player:IsLoggedIn() and+ tableHelper.containsValue(names, string.lower(player.accountName)) then+ table.insert(pids, otherPid)+ end+ end+ return pids+end++local function splitIndex(uniqueIndex)+ local parts = uniqueIndex:split("-")+ return tonumber(parts[1]), tonumber(parts[2])+end++-- Who shares a player's change: their party, or just them (isowindMmo.lua's questSharers)+local function sharers(pid)+ local name = playerKey(pid)+ if IsowindParty ~= nil then+ return IsowindParty.GetMemberNames(name)+ end+ return { name }+end++-- The player's hands, spells and keys, and quest scripts and dialogue; not the console+local function isPlayersOwn(packetOrigin)+ return packetOrigin == enumerations.packetOrigin.CLIENT_GAMEPLAY or+ packetOrigin == enumerations.packetOrigin.CLIENT_SCRIPT_LOCAL or+ packetOrigin == enumerations.packetOrigin.CLIENT_SCRIPT_GLOBAL or+ packetOrigin == enumerations.packetOrigin.CLIENT_DIALOGUE+end++-- The two kinds of change, by packet. A trap is either there or gone: the game doesn't tell the server whether it was+-- disarmed or set off, and what the server sends always says disarmed (set off would set it off again in every game)+local kinds = {+ {+ packetType = "ObjectLock",+ field = "isowindLocks",+ value = function(object) return object.lockLevel end,+ add = function(uniqueIndex, record, value)+ packetBuilder.AddObjectLock(uniqueIndex, { refId = record.refId, lockLevel = value })+ end,+ send = function() tes3mp.SendObjectLock(false, false) end+ },+ {+ packetType = "ObjectTrap",+ field = "isowindTraps",+ value = function() return true end,+ add = function(uniqueIndex, record) packetBuilder.AddObjectTrap(uniqueIndex, { refId = record.refId }) end,+ send = function() tes3mp.SendObjectTrap(false, false) end+ }+}++-- A lock or trap change from a player: the game's own objects in it become theirs and their party's+local function onChange(kind, eventStatus, pid, cellDescription, objects)+ if eventStatus.validDefaultHandler == false or not isPlayersOwn(tes3mp.GetObjectListOrigin()) then+ return+ end+ local cell = LoadedCells[cellDescription]+ if cell == nil or Players[pid] == nil then+ return+ end++ local mine, shared = {}, {}+ for uniqueIndex, object in pairs(objects) do+ local _, mpNum = splitIndex(uniqueIndex)+ if mpNum == 0 then+ mine[uniqueIndex] = object+ else+ shared[uniqueIndex] = object+ end+ end+ if next(mine) == nil then+ return+ end++ local names = sharers(pid)+ cell.data[kind.field] = cell.data[kind.field] or {}+ local records = cell.data[kind.field]+ for uniqueIndex, object in pairs(mine) do+ local record = records[uniqueIndex] or { refId = object.refId, players = {} }+ for _, name in ipairs(names) do+ record.players[name] = kind.value(object)+ end+ records[uniqueIndex] = record+ end++ 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+ kind.add(uniqueIndex, records[uniqueIndex], kind.value(object))+ end+ kind.send()+ end++ -- The rest as the default handler does+ if next(shared) ~= nil then+ cell:SaveObjectsByPacketType(kind.packetType, shared)+ cell:LoadObjectsByPacketType(kind.packetType, pid, shared, tableHelper.getArrayFromIndexes(shared), true)+ end+ cell:QuicksaveToDrive()+ return customEventHooks.makeEventStatus(false, true)+end++-- A player loading a cell gets their own locks and traps there, on top of the shared state just sent (their game makes+-- the same change twice harmlessly, mwmp::ObjectList::lockObjects and triggerTrapObjects)+local function onCellLoad(eventStatus, pid, cellDescription)+ local cell = LoadedCells[cellDescription]+ if cell == nil or Players[pid] == nil then+ return+ end+ local name = playerKey(pid)++ for _, kind in ipairs(kinds) do+ local records = cell.data[kind.field]+ if records ~= nil then+ tes3mp.ClearObjectList()+ tes3mp.SetObjectListPid(pid)+ tes3mp.SetObjectListCell(cellDescription)+ local count = 0+ for uniqueIndex, record in pairs(records) do+ local value = record.players[name]+ if value ~= nil then+ kind.add(uniqueIndex, record, value)+ count = count + 1+ end+ end+ if count > 0 then+ kind.send()+ end+ end+ end+end++-- After the server's own validators (added when it starts), so these see what they decided+customEventHooks.registerHandler("OnServerPostInit", function(eventStatus)+ for _, kind in ipairs(kinds) do+ customEventHooks.registerValidator("On" .. kind.packetType, function(eventStatus, pid, cellDescription, objects)+ return onChange(kind, eventStatus, pid, cellDescription, objects)+ end)+ end+ customEventHooks.registerHandler("OnCellLoad", onCellLoad)+end)++return isowindLocksdiff --git a/isowind/server/CoreScripts/scripts/customScripts.lua b/isowind/server/CoreScripts/scripts/customScripts.luaindex dc27093..7364b13 100644--- a/isowind/server/CoreScripts/scripts/customScripts.lua+++ b/isowind/server/CoreScripts/scripts/customScripts.lua@@ -9,3 +9,4 @@require("custom/isowindHost")require("custom/isowindMmo")require("custom/isowindParty")+require("custom/isowindLocks")diff --git a/isowind/server/tests/locktest.lua b/isowind/server/tests/locktest.luanew file mode 100644index 0000000..b46c739--- /dev/null+++ b/isowind/server/tests/locktest.lua@@ -0,0 +1,240 @@+-- How to run: copy this into a copy of the server folder as CoreScripts/scripts/custom/, add+-- require("custom/locktest") 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 isowindLocks.lua inside a real server: three fake players and packets, a real party and cell.+local log = function(text) tes3mp.LogMessage(enumerations.log.INFO, "[locktest] " .. 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/Copy call is recorded instead of done, with whom each packet was for and what it carried+local sent = {}+local current = {}+local incoming = { origin = enumerations.packetOrigin.CLIENT_GAMEPLAY }+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 = { objects = {}, object = {} }+ elseif name == "SetObjectListPid" then current.pid = 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 == "SetObjectLockLevel" then current.object.lockLevel = args[1]+ elseif name == "SetObjectDisarmState" then current.object.disarmed = args[1]+ elseif name == "AddObject" then table.insert(current.objects, current.object); current.object = {}+ elseif name:find("^Send") then+ table.insert(sent, { name = name, args = args, pid = current.pid, objects = current.objects })+ end+ end+ end+ end+ current = { objects = {}, object = {} }+ tes3mp.ReadReceivedObjectList = function() end+ tes3mp.GetObjectListOrigin = function() return incoming.origin end+ tes3mp.GetTopicChangesSize = function() return 0 end+end++local function packetsNamed(name)+ local list = {}+ for _, packet in ipairs(sent) do+ if packet.name == name then table.insert(list, packet) end+ end+ return list+end+local function sentTo(name, pid)+ for _, packet in ipairs(sent) do+ if packet.name == name and packet.pid == pid then return packet end+ end+end+local function carries(packet, refNum)+ if packet == nil then return nil end+ for _, object in ipairs(packet.objects) do+ if object.refNum == refNum then return object end+ end+end++local function makePlayer(pid, name)+ local player = { pid = pid, accountName = name, name = name, consoleCommandsQueued = {}, summons = {},+ data = { location = { cell = "-3, 6" }, alliedPlayers = {}, journal = {}, topics = {},+ clientVariables = { globals = {} }, customVariables = {} } }+ player.IsLoggedIn = function() return true end+ player.QuicksaveToDrive = function() end+ player.Save = function() end+ player.Message = function() end+ player.LoadAllies = function() end+ Players[pid] = player+ return player+end+local function command(pid, text)+ local cmd = text:split(" ")+ customCommandHooks.getCallback(cmd[1])(pid, cmd)+end++local CELL = "-3, 6"+local function lockPacket(pid, origin, objects)+ incoming.origin = origin or enumerations.packetOrigin.CLIENT_GAMEPLAY+ return customEventHooks.triggerValidators("OnObjectLock", { pid, CELL, objects, {} })+end+local function trapPacket(pid, objects)+ incoming.origin = enumerations.packetOrigin.CLIENT_GAMEPLAY+ return customEventHooks.triggerValidators("OnObjectTrap", { pid, CELL, objects, {} })+end+local function lockObject(refNum, mpNum, refId, lockLevel)+ local uniqueIndex = refNum .. "-" .. mpNum+ return { [uniqueIndex] = { refId = refId, uniqueIndex = uniqueIndex, lockLevel = lockLevel } }+end+local function loadCell(pid)+ sent = {}+ customEventHooks.triggerHandlers("OnCellLoad", customEventHooks.makeEventStatus(true, true), { pid, CELL })+end++local function runTests()+ installMocks()+ WorldInstance.data.isowindParties = nil+ makePlayer(0, "Alpha")+ makePlayer(1, "Beta")+ makePlayer(2, "Gamma")+ logicHandler.LoadCell(CELL)+ local cell = LoadedCells[CELL]++ -- Alone: a pick is the picker's own+ sent = {}+ local status = lockPacket(0, nil, lockObject(8101, 0, "contain_chest_locked", 0))+ check("pick skips the shared save", status.validDefaultHandler == false)+ local locks = cell.data.isowindLocks+ check("pick kept for the picker", locks ~= nil and locks["8101-0"].players.alpha == 0)+ check("pick not for the others", locks["8101-0"].players.beta == nil and locks["8101-0"].players.gamma == nil)+ check("pick not in the shared state", not tableHelper.containsValue(cell.data.packets.lock or {}, "8101-0") and+ (cell.data.objectData["8101-0"] == nil or cell.data.objectData["8101-0"].lockLevel == nil))+ local packets = packetsNamed("SendObjectLock")+ local back = packets[1]+ check("pick sent back to the picker only, once", #packets == 1 and back.pid == 0 and back.args[1] == false and+ back.args[2] == false)+ check("send-back unlocks the chest", carries(back, "8101") ~= nil and carries(back, "8101").lockLevel == 0 and+ carries(back, "8101").refId == "contain_chest_locked")++ -- Loading the cell: the picker's game gets it again, the others' don't+ loadCell(0)+ check("cell load replays the pick to the picker", carries(sentTo("SendObjectLock", 0), "8101") ~= nil and+ #packetsNamed("SendObjectLock") == 1)+ loadCell(1)+ check("cell load gives the others nothing", #packetsNamed("SendObjectLock") == 0 and+ #packetsNamed("SendObjectTrap") == 0)++ -- Kept on the drive: still there after the cell is unloaded and loaded again+ logicHandler.UnloadCell(CELL)+ logicHandler.LoadCell(CELL)+ cell = LoadedCells[CELL]+ loadCell(0)+ check("pick kept through an unload", carries(sentTo("SendObjectLock", 0), "8101") ~= nil)++ -- Something a player placed stays shared+ sent = {}+ status = lockPacket(0, nil, lockObject(8102, 5, "contain_placed", 0))+ check("placed object goes to the default handler", status.validDefaultHandler ~= false and+ cell.data.isowindLocks["8102-5"] == nil)++ -- Both in one packet: the game's own one is the player's, the placed one shared (sent to everyone)+ sent = {}+ local both = lockObject(8103, 0, "door_locked", 0)+ both["8104-7"] = { refId = "contain_placed", uniqueIndex = "8104-7", lockLevel = 0 }+ status = lockPacket(0, nil, both)+ check("mixed packet skips the default handler", status.validDefaultHandler == false)+ check("mixed packet: own one kept per player", cell.data.isowindLocks["8103-0"].players.alpha == 0 and+ cell.data.isowindLocks["8104-7"] == nil)+ check("mixed packet: placed one saved as shared", tableHelper.containsValue(cell.data.packets.lock, "8104-7") and+ not tableHelper.containsValue(cell.data.packets.lock, "8103-0"))+ local toEveryone = nil+ for _, packet in ipairs(packetsNamed("SendObjectLock")) do+ if packet.args[1] == true then toEveryone = packet end+ end+ check("mixed packet: placed one sent to everyone, without the own one", carries(toEveryone, "8104") ~= nil and+ carries(toEveryone, "8103") == nil)++ -- The console stays shared+ status = lockPacket(0, enumerations.packetOrigin.CLIENT_CONSOLE, lockObject(8106, 0, "door_console", 0))+ check("console change goes to the default handler", status.validDefaultHandler ~= false and+ cell.data.isowindLocks["8106-0"] == nil)++ -- One the server's config refuses is left alone+ local disallowed = config.disallowedLockRefIds+ config.disallowedLockRefIds = { "door_refused" }+ status = lockPacket(0, nil, lockObject(8110, 0, "door_refused", 0))+ config.disallowedLockRefIds = disallowed+ check("refused lock change isn't recorded", status.validDefaultHandler == false and+ cell.data.isowindLocks["8110-0"] == nil)++ -- Alone: a disarmed trap is the disarmer's own+ sent = {}+ status = trapPacket(1, { ["8107-0"] = { refId = "contain_trapped", uniqueIndex = "8107-0" } })+ check("disarm skips the shared save", status.validDefaultHandler == false and+ not tableHelper.containsValue(cell.data.packets.trap or {}, "8107-0"))+ check("disarm kept for the disarmer only", cell.data.isowindTraps["8107-0"].players.beta == true and+ cell.data.isowindTraps["8107-0"].players.alpha == nil)+ local trapBack = packetsNamed("SendObjectTrap")+ check("disarm sent back to the disarmer only, as disarmed", #trapBack == 1 and trapBack[1].pid == 1 and+ carries(trapBack[1], "8107") ~= nil and carries(trapBack[1], "8107").disarmed == true)++ -- A party: Alpha and Beta+ command(0, "party invite Beta")+ command(1, "party accept")+ check("party formed", #IsowindParty.GetMemberNames("alpha") == 2)++ -- Beta picks: the whole party has it, and the online members are told+ sent = {}+ lockPacket(1, nil, lockObject(8105, 0, "contain_chest_party", 0))+ local record = cell.data.isowindLocks["8105-0"]+ check("party pick kept for both members", record.players.alpha == 0 and record.players.beta == 0)+ check("party pick not for someone outside it", record.players.gamma == nil)+ check("party pick sent back to the picker", carries(sentTo("SendObjectLock", 1), "8105") ~= nil)+ check("party pick sent to the other member", carries(sentTo("SendObjectLock", 0), "8105") ~= nil)+ check("party pick not sent outside the party", sentTo("SendObjectLock", 2) == nil)++ -- A Lock spell on it afterwards locks it again for the party+ lockPacket(0, nil, lockObject(8105, 0, "contain_chest_party", 50))+ check("Lock spell kept for the party", record.players.alpha == 50 and record.players.beta == 50)++ -- Alpha sets off a trap: gone for the party, and what is sent says disarmed (not set off again)+ sent = {}+ trapPacket(0, { ["8108-0"] = { refId = "door_trapped", uniqueIndex = "8108-0" } })+ local sprung = cell.data.isowindTraps["8108-0"]+ check("sprung trap gone for both members", sprung.players.alpha == true and sprung.players.beta == true and+ sprung.players.gamma == nil)+ check("sprung trap sent to both as disarmed", carries(sentTo("SendObjectTrap", 0), "8108") ~= nil and+ carries(sentTo("SendObjectTrap", 0), "8108").disarmed == true and+ carries(sentTo("SendObjectTrap", 1), "8108") ~= nil and sentTo("SendObjectTrap", 2) == nil)++ -- Loading the cell: Beta gets the party's and their own, Gamma nothing+ loadCell(1)+ local betaLocks = sentTo("SendObjectLock", 1)+ check("Beta's replay: the party's lock", carries(betaLocks, "8105") ~= nil and+ carries(betaLocks, "8105").lockLevel == 50)+ check("Beta's replay: not Alpha's pick from before the party", carries(betaLocks, "8101") == nil)+ local betaTraps = sentTo("SendObjectTrap", 1)+ check("Beta's replay: both traps", carries(betaTraps, "8107") ~= nil and carries(betaTraps, "8108") ~= nil)+ loadCell(2)+ check("Gamma's replay: nothing", #sent == 0)++ -- Gamma joins later: not the party's earlier changes, but the ones after+ command(0, "party invite Gamma")+ command(2, "party accept")+ check("joining later doesn't give earlier changes", record.players.gamma == nil and sprung.players.gamma == nil)+ sent = {}+ lockPacket(0, enumerations.packetOrigin.CLIENT_SCRIPT_GLOBAL, lockObject(8109, 0, "door_quest", 0))+ local quest = cell.data.isowindLocks["8109-0"]+ check("quest script unlock kept for the whole party", quest.players.alpha == 0 and quest.players.beta == 0 and+ quest.players.gamma == 0)+ check("quest script unlock sent to all three", sentTo("SendObjectLock", 0) ~= nil and+ sentTo("SendObjectLock", 1) ~= nil and sentTo("SendObjectLock", 2) ~= nil)++ log("done, " .. failures .. " failed")+end++customEventHooks.registerHandler("OnServerPostInit", function()+ local ok, err = pcall(runTests)+ if not ok then log("ERROR " .. tostring(err)) end+end)