diff --git a/.github/PerPlayerLoot.png b/.github/PerPlayerLoot.png new file mode 100644 index 0000000..95e1f1e Binary files /dev/null and b/.github/PerPlayerLoot.png differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a30d25 --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/PerPlayerLoot.sln b/PerPlayerLoot.sln new file mode 100644 index 0000000..1c0c146 --- /dev/null +++ b/PerPlayerLoot.sln @@ -0,0 +1,30 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34330.188 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PerPlayerLoot", "PerPlayerLoot\PerPlayerLoot.csproj", "{D74EA9A9-A748-45B6-8115-0B474B5E03FE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D74EA9A9-A748-45B6-8115-0B474B5E03FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D74EA9A9-A748-45B6-8115-0B474B5E03FE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D74EA9A9-A748-45B6-8115-0B474B5E03FE}.Debug|x64.ActiveCfg = Debug|x64 + {D74EA9A9-A748-45B6-8115-0B474B5E03FE}.Debug|x64.Build.0 = Debug|x64 + {D74EA9A9-A748-45B6-8115-0B474B5E03FE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D74EA9A9-A748-45B6-8115-0B474B5E03FE}.Release|Any CPU.Build.0 = Release|Any CPU + {D74EA9A9-A748-45B6-8115-0B474B5E03FE}.Release|x64.ActiveCfg = Release|x64 + {D74EA9A9-A748-45B6-8115-0B474B5E03FE}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {DE255809-1CFB-43CC-A13F-3D6270EFADC6} + EndGlobalSection +EndGlobal diff --git a/PerPlayerLoot/FakeChestDatabase.cs b/PerPlayerLoot/FakeChestDatabase.cs new file mode 100644 index 0000000..35e38ca --- /dev/null +++ b/PerPlayerLoot/FakeChestDatabase.cs @@ -0,0 +1,272 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using Terraria; +using TShockAPI; +using TerrariaApi.Server; +using System.IO; +using System.IO.Streams; + +using Newtonsoft.Json; +using System.Data.SQLite; +using Newtonsoft.Json.Bson; +using System.Runtime.Serialization.Formatters.Binary; + +namespace PerPlayerLoot +{ + // barebones class representing item data which can be deserialized from json + public class JItem + { + public int id { get; set; } + public int stack { get; set; } + public byte prefix { get; set; } + } + + + // database of FakeChest's + public class FakeChestDatabase + { + // Map { UUID: { ChestID: Chest } } + public static Dictionary> fakeChestsMap = new Dictionary> { }; + + public static HashSet<(int, int)> playerPlacedChests = new HashSet<(int, int)>(); // tile x, y of player placed chests + + private static string connString = "Data Source=perplayerloot.sqlite;Version=3;"; + + public FakeChestDatabase() { } + + public void Initialize() + { + CreateTables(); + LoadFakeChests(); + } + + public void CreateTables() + { + TSPlayer.Server.SendInfoMessage("Setting up per-player chests database..."); + using (SQLiteConnection conn = new SQLiteConnection(connString)) + { + conn.Open(); + + string sql = @" + CREATE TABLE IF NOT EXISTS chests ( + id INTEGER NOT NULL, + playerUuid TEXT NOT NULL, + x INTEGER NOT NULL, + y INTEGER NOT NULL, + items BLOB NOT NULL, + PRIMARY KEY (id, playerUuid) + ); + + CREATE TABLE IF NOT EXISTS placed ( + x INTEGER NOT NULL, + y INTEGER NOT NULL, + PRIMARY KEY (x, y) + ); + "; + + using (var cmd = new SQLiteCommand(sql, conn)) + cmd.ExecuteNonQuery(); + + } + } + + public void LoadFakeChests() + { + TSPlayer.Server.SendInfoMessage("Loading per-player loot chest inventories..."); + int count = 0; + + using (SQLiteConnection conn = new SQLiteConnection(connString)) + { + conn.Open(); + + // load loot chests + using (var cmd = new SQLiteCommand("SELECT id, playerUuid, x, y, items FROM chests;", conn)) + { + SQLiteDataReader reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + string playerUuid = Convert.ToString(reader["playerUuid"]); + int chestId = Convert.ToInt32(reader["id"]); + + // get the items list + List items = new List(); + + // read blob from column + MemoryStream itemsRaw = new MemoryStream((byte[]) reader["items"]); + // deserialize with bson + using (var br = new BsonReader(itemsRaw)) + { + br.ReadRootValueAsArray = true; + + // do the actual deserialization + var jItems = (new JsonSerializer()).Deserialize>(br); + + // convert each JItem to a real Item + foreach (var jItem in jItems) + { + if (jItem == null) + { + items.Add(null); + continue; + } + + var item = new Item(); + item.netDefaults(jItem.id); + item.stack = jItem.stack; + item.prefix = jItem.prefix; + + items.Add(item); + } + } + + Chest chest = new Chest(); // construct a terraria chest + chest.x = Convert.ToInt32(reader["x"]); + chest.y = Convert.ToInt32(reader["y"]); + chest.item = items.ToArray(); + + // save it in the fake chest map + var playerChests = fakeChestsMap.GetValueOrDefault(playerUuid, new Dictionary()); + fakeChestsMap[playerUuid] = playerChests; + + fakeChestsMap[playerUuid][chestId] = chest; + + count++; + } + } + + // load tile exclusions + using (var cmd = new SQLiteCommand("SELECT x, y FROM placed;", conn)) + { + SQLiteDataReader reader = cmd.ExecuteReader(); + + playerPlacedChests.Clear(); + + while (reader.Read()) + { + int x = Convert.ToInt32(reader["x"]); + int y = Convert.ToInt32(reader["y"]); + + playerPlacedChests.Add((x, y)); + } + } + } + + TSPlayer.Server.SendSuccessMessage($"Loaded {count} loot chest inventories, {playerPlacedChests.Count} player-placed chests."); + } + + public void SaveFakeChests() + { + TSPlayer.Server.SendInfoMessage("Saving per-player loot chest inventories..."); + int count = 0; + + using (SQLiteConnection conn = new SQLiteConnection(connString)) + { + conn.Open(); + + foreach (KeyValuePair> playerEntry in fakeChestsMap) + { + string playerUuid = playerEntry.Key; + var playerChests = playerEntry.Value; + + foreach (KeyValuePair chestEntry in playerChests) + { + int chestId = chestEntry.Key; + var chest = chestEntry.Value; + + List jItems = new List(chest.item.Length); + + foreach (var item in chest.item) + { + var jItem = new JItem(); + + jItem.id = item.type; + jItem.stack = item.stack; + jItem.prefix = item.prefix; + + jItems.Add(jItem); + } + + MemoryStream itemsMs = new MemoryStream(); + using (var writer = new BsonWriter(itemsMs)) + { + JsonSerializer serializer = new JsonSerializer(); + serializer.Serialize(writer, jItems); + } + + var sql = @"REPLACE INTO chests (id, playerUuid, x, y, items) VALUES (@id, @playerUuid, @x, @y, @items);"; + + using (var cmd = new SQLiteCommand(sql, conn)) + { + cmd.Parameters.AddWithValue("@id", chestId); + cmd.Parameters.AddWithValue("@playerUuid", playerUuid); + cmd.Parameters.AddWithValue("@x", chest.x); + cmd.Parameters.AddWithValue("@y", chest.y); + cmd.Parameters.AddWithValue("@items", itemsMs.ToArray()); + + cmd.ExecuteNonQuery(); + } + + count++; + } + } + + foreach ((int x, int y) in playerPlacedChests) + { + var sql = @"REPLACE INTO placed (x, y) VALUES (@x, @y);"; + + using (var cmd = new SQLiteCommand(sql, conn)) + { + cmd.Parameters.AddWithValue("@x", x); + cmd.Parameters.AddWithValue("@y", y); + + cmd.ExecuteNonQuery(); + } + } + } + + TSPlayer.Server.SendSuccessMessage($"Saved {count} loot chest inventories, {playerPlacedChests.Count} player-placed chests."); + } + + public Chest GetOrCreateFakeChest(int chestId, string playerUuid) + { + var playerChests = fakeChestsMap.GetValueOrDefault(playerUuid, new Dictionary()); + fakeChestsMap[playerUuid] = playerChests; + + if (!playerChests.ContainsKey(chestId)) + { + + Chest realChest = Main.chest[chestId]; + + // copy the chest data from the real untouched chest + Chest fakeChest = new Chest(); + fakeChest.x = realChest.x; + fakeChest.y = realChest.y; + realChest.item.CopyTo(fakeChest.item, 0); + + // save it in the fake chest list + fakeChestsMap[playerUuid][chestId] = fakeChest; + + // save the fake chests list to disk + SaveFakeChests(); + + return fakeChest; + } + + return playerChests[chestId]; + } + + public void SetChestPlayerPlaced(int tileX, int tileY) + { + playerPlacedChests.Add((tileX, tileY)); + } + + public bool IsChestPlayerPlaced(int tileX, int tileY) + { + return playerPlacedChests.Contains((tileX, tileY)); + } + } + +} diff --git a/PerPlayerLoot/PPLPlugin.cs b/PerPlayerLoot/PPLPlugin.cs new file mode 100644 index 0000000..3a87e55 --- /dev/null +++ b/PerPlayerLoot/PPLPlugin.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using Terraria; +using TShockAPI; +using TerrariaApi.Server; +using System.IO; +using System.IO.Streams; + +namespace PerPlayerLoot +{ + [ApiVersion(2, 1)] + public class PPLPlugin : TerrariaPlugin + { + #region info + public override string Name => "PerPlayerLoot"; + + public override Version Version => new Version(1, 0); + + public override string Author => "Codian"; + + public override string Description => "Duplicate loot chest inventories for each player."; + #endregion + + public static FakeChestDatabase fakeChestDb = new FakeChestDatabase(); + + public static bool enablePpl = true; + + public PPLPlugin(Main game) : base(game) {} + + public override void Initialize() + { + ServerApi.Hooks.GamePostInitialize.Register(this, OnWorldLoaded); + ServerApi.Hooks.WorldSave.Register(this, OnWorldSave); + + TShockAPI.GetDataHandlers.PlaceChest += OnChestPlace; + TShockAPI.GetDataHandlers.ChestOpen += OnChestOpen; + TShockAPI.GetDataHandlers.ChestItemChange += OnChestItemChange; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + ServerApi.Hooks.GamePostInitialize.Deregister(this, OnWorldLoaded); + ServerApi.Hooks.WorldSave.Deregister(this, OnWorldSave); + + TShockAPI.GetDataHandlers.PlaceChest -= OnChestPlace; + TShockAPI.GetDataHandlers.ChestOpen -= OnChestOpen; + TShockAPI.GetDataHandlers.ChestItemChange -= OnChestItemChange; + } + + base.Dispose(disposing); + } + + + private void OnWorldSave(WorldSaveEventArgs args) + { + fakeChestDb.SaveFakeChests(); + } + + private void OnWorldLoaded(EventArgs args) + { + fakeChestDb.Initialize(); + Commands.ChatCommands.Add(new Command("perplayerloot.toggle", ToggleCommand, "ppltoggle")); + } + + private void ToggleCommand(CommandArgs args) + { + enablePpl = !enablePpl; + if (enablePpl) { + args.Player.SendSuccessMessage("Per player loot is now enabled!"); + } else { + args.Player.SendSuccessMessage("Per player loot is now disabled! You can modify chests now and they will count as loot chests."); + } + } + + private void OnChestItemChange(object sender, GetDataHandlers.ChestItemEventArgs e) + { + if (!enablePpl) return; + + // get the chest object from id + Chest realChest = Main.chest[e.ID]; + if (realChest == null) + return; + + // check if it's a piggy bank or safe transaction + if (realChest.bankChest) + return; + + // check if this is a player placed chest + if (fakeChestDb.IsChestPlayerPlaced(realChest.x, realChest.y)) + return; + + // construct an item from the event data + Item item = new Item(); + item.netDefaults(e.Type); + item.stack = e.Stacks; + item.prefix = e.Prefix; + + // get the per-player chest + Chest fakeChest = fakeChestDb.GetOrCreateFakeChest(e.ID, e.Player.UUID); + + // update the slot with the item + fakeChest.item[e.Slot] = item; + + e.Handled = true; + } + + private byte[] ConstructSpoofedChestItemPacket(int chestId, int slot, Item item) + { + // NetMessage.SendData is hardcode tied to Main.chest, so this method is necessary to reimplement stuff :( + + MemoryStream memoryStream = new MemoryStream(); + OTAPI.PacketWriter packetWriter = new OTAPI.PacketWriter(memoryStream); + + packetWriter.BaseStream.Position = 0L; + long position = packetWriter.BaseStream.Position; + + packetWriter.BaseStream.Position += 2L; + packetWriter.Write((byte) PacketTypes.ChestItem); + + packetWriter.Write((short) chestId); + packetWriter.Write((byte) slot); + + short netId = (short)item.netID; + if (item.Name == null) + { + netId = 0; + } + + packetWriter.Write((short) item.stack); + packetWriter.Write(item.prefix); + packetWriter.Write(netId); + + int positionAfter = (int) packetWriter.BaseStream.Position; + + packetWriter.BaseStream.Position = position; + packetWriter.Write((ushort)positionAfter); + packetWriter.BaseStream.Position = positionAfter; + + return memoryStream.ToArray(); + } + + private void OnChestOpen(object sender, GetDataHandlers.ChestOpenEventArgs e) + { + if (e.Handled) return; + if (!enablePpl) return; + + // get the chest's id + int chestId = Chest.FindChest(e.X, e.Y); + if (chestId == -1) return; + + // retreive the chest object + Chest realChest = Main.chest[chestId]; + + // make sure it exists + if (realChest == null) + return; + + // piggy bank, safe, etc. + if (realChest.bankChest) + return; + + // check if it's player placed + if (fakeChestDb.IsChestPlayerPlaced(realChest.x, realChest.y)) + return; + + // make a per-player chest + Chest fakeChest = fakeChestDb.GetOrCreateFakeChest(chestId, e.Player.UUID); + + // Console.WriteLine($"Opening a fake chest for {e.Player.Name}."); + e.Player.SendInfoMessage("Loot in this chest is saved per-player!"); + + // spoof chest slots + for (int slot = 0; slot < Chest.maxItems; slot++) + { + // make a fake item stack + Item item = fakeChest.item[slot]; + + // spoof clientside slot + byte[] payload = ConstructSpoofedChestItemPacket(chestId, slot, item); + e.Player.SendRawData(payload); + } + + // trigger chest open + e.Player.SendData(PacketTypes.ChestOpen, "", chestId); + + // set the active chest on serverside + e.Player.ActiveChest = chestId; + Main.player[e.Player.Index].chest = chestId; + // notify the client to also update the clientside state + e.Player.SendData(PacketTypes.SyncPlayerChestIndex, null, e.Player.Index, chestId); + + // prevent anything else grabbing control + e.Handled = true; + return; + } + + private void OnChestPlace(object sender, GetDataHandlers.PlaceChestEventArgs e) + { + if (!enablePpl) return; + + if (!fakeChestDb.IsChestPlayerPlaced(e.TileX, e.TileY - 1)) + { + int chestId = Chest.FindChest(e.TileX, e.TileY - 1); + if (chestId != -1) + Main.chest[chestId].item = new Item[Chest.maxItems]; + } + + fakeChestDb.SetChestPlayerPlaced(e.TileX, e.TileY - 1); // this -1 is mysterious + } + } +} diff --git a/PerPlayerLoot/PerPlayerLoot.csproj b/PerPlayerLoot/PerPlayerLoot.csproj new file mode 100644 index 0000000..eba03d4 --- /dev/null +++ b/PerPlayerLoot/PerPlayerLoot.csproj @@ -0,0 +1,25 @@ + + + net6.0 + Library + false + PerPlayerLoot + PerPlayerLoot + Copyright © 2023 + 1.0.0.0 + 1.0.0.0 + AnyCPU;x64 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/PerPlayerLoot/Properties/AssemblyInfo.cs b/PerPlayerLoot/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7ca6657 --- /dev/null +++ b/PerPlayerLoot/Properties/AssemblyInfo.cs @@ -0,0 +1,13 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("d74ea9a9-a748-45b6-8115-0b474b5e03fe")] diff --git a/README.md b/README.md new file mode 100644 index 0000000..d332510 --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +![Per Player Loot](.github/PerPlayerLoot.png) + +# Terraria Per Player Loot +A [TShock](https://github.com/Pryaxis/TShock) server plugin which makes +naturally spawned loot chests have a separate inventory for each player on your +server. Every player that finds a chest can loot it for themselves, even if it +has been looted by someone else before. + +## The Problem +Terraria multiplayer has one big issue - the world you play on is finite, and +there are only so many items and resources to go around. + +When you start a new world to play on with your friends, the few people who +choose to go surface exploring or caving are likely to find most of the chests, +and, as a result, most of the early game loot. + +This is not a problem with bosses in Expert or Master mode, because they drop a +loot bag for each player that damaged them, and everyone can be happy. + +This plugin makes it much more viable to run large Terraria multiplayer servers, +as there is always an incentive for exploring and caving - the loot is still +there for you to find! + +## Installation +1. Copy `PerPlayerLoot.dll` into the `ServerPlugins` directory of your TShock + server. +2. Copy `System.Data.SQLite.dll` into the `bin` directory of your TShock server. +3. Start a new world from scratch (yes, this is important, read below) and play! + +## How it Works +This plugin aims to not modify the server-side chest state +(`Terraria.Main.chest`) on chest interactions, in the hope that it can be as +least destructive to world save data as possible. + +It works by intercepting the `ChestPlace`, `ChestOpen` and `ChestItem` +packets and spoofing the contents of a loot chest by sending carefully crafted +`ChestItem` packets from an internal database. + +The per-player loot data is written on disk to the SQLite file +`perplayerloot.sqlite` on every world save, alongside a list of all +player-placed chest X and Y coordinates. **If your player-placed chests are not +in this exclusion list, they will be treated as world-generated loot chests.** + +This means that In order for player-placed chests to be unaffected, **you need +to have the plugin installed from the very beginning of your server.** If you +install it halfway through a playthrough, all chests in the world will be +treated as if they were generated and will duplicate their inventory contents +for each player. + +The only time when the `Main.chest` array is modified is when a loot chest is +possibly broken (which should rarely happen). In that case, the real chest in +`Main.chest` has its items zeroed. + +## Debug Commands +- `/ppltoggle` - Toggle the plugin packet hooks globally. **WARNING:** using + this command is unsupported and can lead to desynchronization of the + `Main.chest` array and the internal plugin state. + + Debug use only! When in a disabled state, any chests you place will become + loot chests, and any chest inventory accessed will be its **real inventory**, + not a per-player instanced one! \ No newline at end of file