From 5e33dfd660b2b6fe04056997bc4d233def657598 Mon Sep 17 00:00:00 2001 From: Anna Clemens Date: Fri, 24 Sep 2021 13:39:47 -0400 Subject: [PATCH] chore: initial commit --- .gitignore | 365 +++++++++++++++++++++++++++++ NominaOcculta.sln | 16 ++ NominaOcculta.sln.DotSettings | 3 + NominaOcculta/Commands.cs | 24 ++ NominaOcculta/Configuration.cs | 17 ++ NominaOcculta/GameFunctions.cs | 111 +++++++++ NominaOcculta/NameRepository.cs | 146 ++++++++++++ NominaOcculta/NominaOcculta.csproj | 43 ++++ NominaOcculta/NominaOcculta.yaml | 6 + NominaOcculta/Obscurer.cs | 168 +++++++++++++ NominaOcculta/Plugin.cs | 77 ++++++ NominaOcculta/PluginUi.cs | 54 +++++ NominaOcculta/Util.cs | 83 +++++++ 13 files changed, 1113 insertions(+) create mode 100644 .gitignore create mode 100755 NominaOcculta.sln create mode 100755 NominaOcculta.sln.DotSettings create mode 100755 NominaOcculta/Commands.cs create mode 100755 NominaOcculta/Configuration.cs create mode 100755 NominaOcculta/GameFunctions.cs create mode 100755 NominaOcculta/NameRepository.cs create mode 100755 NominaOcculta/NominaOcculta.csproj create mode 100755 NominaOcculta/NominaOcculta.yaml create mode 100755 NominaOcculta/Obscurer.cs create mode 100755 NominaOcculta/Plugin.cs create mode 100755 NominaOcculta/PluginUi.cs create mode 100755 NominaOcculta/Util.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1db30bf --- /dev/null +++ b/.gitignore @@ -0,0 +1,365 @@ +## 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/master/VisualStudio.gitignore + +# Packaging +pack/ + +# 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 +*.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 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/ + +# 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 diff --git a/NominaOcculta.sln b/NominaOcculta.sln new file mode 100755 index 0000000..89addba --- /dev/null +++ b/NominaOcculta.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NominaOcculta", "NominaOcculta\NominaOcculta.csproj", "{155AB0C2-BE0B-4864-A447-E6CBA6195E84}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {155AB0C2-BE0B-4864-A447-E6CBA6195E84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {155AB0C2-BE0B-4864-A447-E6CBA6195E84}.Debug|Any CPU.Build.0 = Debug|Any CPU + {155AB0C2-BE0B-4864-A447-E6CBA6195E84}.Release|Any CPU.ActiveCfg = Release|Any CPU + {155AB0C2-BE0B-4864-A447-E6CBA6195E84}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/NominaOcculta.sln.DotSettings b/NominaOcculta.sln.DotSettings new file mode 100755 index 0000000..7b8a251 --- /dev/null +++ b/NominaOcculta.sln.DotSettings @@ -0,0 +1,3 @@ + + True + True \ No newline at end of file diff --git a/NominaOcculta/Commands.cs b/NominaOcculta/Commands.cs new file mode 100755 index 0000000..4de0a71 --- /dev/null +++ b/NominaOcculta/Commands.cs @@ -0,0 +1,24 @@ +using System; +using Dalamud.Game.Command; + +namespace NominaOcculta { + internal class Commands : IDisposable { + private Plugin Plugin { get; } + + internal Commands(Plugin plugin) { + this.Plugin = plugin; + + this.Plugin.CommandManager.AddHandler("/occulta", new CommandInfo(this.OnCommand) { + HelpMessage = "Toggle the Nomina Occulta interface", + }); + } + + public void Dispose() { + this.Plugin.CommandManager.RemoveHandler("/occulta"); + } + + private void OnCommand(string command, string arguments) { + this.Plugin.Ui.Visible ^= true; + } + } +} diff --git a/NominaOcculta/Configuration.cs b/NominaOcculta/Configuration.cs new file mode 100755 index 0000000..e882e8c --- /dev/null +++ b/NominaOcculta/Configuration.cs @@ -0,0 +1,17 @@ +using System; +using Dalamud.Configuration; + +namespace NominaOcculta { + [Serializable] + internal class Configuration : IPluginConfiguration { + public int Version { get; set; } = 1; + + public bool Enabled; + public bool SelfFull; + public bool SelfFirst; + public bool SelfLast; + public bool Party; + public bool Others; + public bool ExcludeFriends; + } +} diff --git a/NominaOcculta/GameFunctions.cs b/NominaOcculta/GameFunctions.cs new file mode 100755 index 0000000..d23bf33 --- /dev/null +++ b/NominaOcculta/GameFunctions.cs @@ -0,0 +1,111 @@ +using System; +using System.Runtime.InteropServices; +using Dalamud.Game.Text.SeStringHandling; +using Dalamud.Hooking; + +namespace NominaOcculta { + internal class GameFunctions : IDisposable { + private static class Signatures { + internal const string GenerateName = "E8 ?? ?? ?? ?? 48 8D 8B ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 85 C0 74 1B 48 8D 8B ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8B 8B ?? ?? ?? ?? 48 8B D0 E8 ?? ?? ?? ?? 48 8B CB 48 8B 7C 24"; + internal const string Utf8StringCtor = "E8 ?? ?? ?? ?? 44 2B F7"; + internal const string Utf8StringDtor = "80 79 21 00 75 12"; + internal const string AtkTextNodeSetText = "E8 ?? ?? ?? ?? 49 8B FC"; + internal const string LoadExd = "40 53 56 57 48 81 EC ?? ?? ?? ?? 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 84 24 ?? ?? ?? ?? 41 0F B6 D9"; + } + + private delegate IntPtr GenerateNameDelegate(int race, int clan, int gender, IntPtr first, IntPtr last); + + private delegate IntPtr Utf8StringCtorDelegate(IntPtr memory); + + private delegate void Utf8StringDtorDelegate(IntPtr memory); + + private delegate void AtkTextNodeSetTextDelegate(IntPtr node, IntPtr text); + + private delegate byte LoadExdDelegate(IntPtr a1, string sheetName, byte a3, byte a4); + + private delegate IntPtr GetExcelModuleDelegate(IntPtr uiModule); + + private Utf8StringCtorDelegate Utf8StringCtor { get; } + private Utf8StringDtorDelegate Utf8StringDtor { get; } + private GenerateNameDelegate InternalGenerateName { get; } + private LoadExdDelegate LoadExd { get; } + + private Hook AtkTextNodeSetTextHook { get; } + + internal delegate void AtkTextNodeSetTextEventDelegate(IntPtr node, IntPtr text, ref SeString? overwrite); + internal event AtkTextNodeSetTextEventDelegate? AtkTextNodeSetText; + + private Plugin Plugin { get; } + + private IntPtr First { get; } + private IntPtr Last { get; } + + internal GameFunctions(Plugin plugin) { + this.Plugin = plugin; + + this.Utf8StringCtor = Marshal.GetDelegateForFunctionPointer(this.Plugin.SigScanner.ScanText(Signatures.Utf8StringCtor)); + this.Utf8StringDtor = Marshal.GetDelegateForFunctionPointer(this.Plugin.SigScanner.ScanText(Signatures.Utf8StringDtor)); + this.InternalGenerateName = Marshal.GetDelegateForFunctionPointer(this.Plugin.SigScanner.ScanText(Signatures.GenerateName)); + this.LoadExd = Marshal.GetDelegateForFunctionPointer(this.Plugin.SigScanner.ScanText(Signatures.LoadExd)); + + this.AtkTextNodeSetTextHook = new Hook( + this.Plugin.SigScanner.ScanText(Signatures.AtkTextNodeSetText), + this.OnAtkTextNodeSetText + ); + this.AtkTextNodeSetTextHook.Enable(); + + this.First = Marshal.AllocHGlobal(128); + this.Last = Marshal.AllocHGlobal(128); + + this.Utf8StringCtor(this.First); + this.Utf8StringCtor(this.Last); + } + + public void Dispose() { + this.Utf8StringDtor(this.Last); + this.Utf8StringDtor(this.First); + Marshal.FreeHGlobal(this.Last); + Marshal.FreeHGlobal(this.First); + this.AtkTextNodeSetTextHook.Dispose(); + } + + private unsafe void OnAtkTextNodeSetText(IntPtr node, IntPtr text) { + SeString? overwrite = null; + this.AtkTextNodeSetText?.Invoke(node, text, ref overwrite); + + if (overwrite != null) { + fixed (byte* newText = overwrite.Encode().Terminate()) { + this.AtkTextNodeSetTextHook.Original(node, (IntPtr) newText); + } + + return; + } + + this.AtkTextNodeSetTextHook.Original(node, text); + } + + public string? GenerateName(int race, int clan, int gender) { + this.InternalGenerateName(race, clan, gender, this.First, this.Last); + + var first = Marshal.PtrToStringUTF8(Marshal.ReadIntPtr(this.First)); + var last = Marshal.PtrToStringUTF8(Marshal.ReadIntPtr(this.Last)); + + if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(last)) { + return null; + } + + return $"{first} {last}"; + } + + public unsafe void LoadSheet(string name) { + var ui = this.Plugin.Common.Functions.GetUiModule(); + var getExcelModulePtr = *(*(IntPtr**) ui + 5); + var getExcelModule = Marshal.GetDelegateForFunctionPointer(getExcelModulePtr); + var excelModule = getExcelModule(ui); + var exdModule = *(IntPtr*) (excelModule + 8); + var excel = *(IntPtr*) (exdModule + 0x20); + + this.LoadExd(excel, name, 0, 1); + } + } +} diff --git a/NominaOcculta/NameRepository.cs b/NominaOcculta/NameRepository.cs new file mode 100755 index 0000000..8928d3a --- /dev/null +++ b/NominaOcculta/NameRepository.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Dalamud.Game; +using Lumina.Excel.GeneratedSheets; + +namespace NominaOcculta { + internal class NameRepository : IDisposable { + private Plugin Plugin { get; } + + private Random Rng { get; } = new(); + + private Dictionary<(byte, byte, byte), Queue> Names { get; } = new(); + private Dictionary Replacements { get; } = new(); + private Dictionary LastSeenInfo { get; } = new(); + + private readonly int _numRaces; + + internal bool Initialised; + + internal NameRepository(Plugin plugin) { + this.Plugin = plugin; + + this._numRaces = this.Plugin.DataManager.GetExcelSheet()!.Count(row => row.RowId != 0); + + this.Plugin.Functions.LoadSheet("CharaMakeName"); + this.Plugin.ClientState.Login += this.OnLogin; + + for (var race = (byte) 1; race <= this._numRaces; race++) { + for (var clan = (byte) 0; clan <= 1; clan++) { + for (var sex = (byte) 0; sex <= 1; sex++) { + this.Names[(race, clan, sex)] = new Queue(); + } + } + } + + this.Plugin.Framework.Update += this.OnFrameworkUpdate; + } + + public void Dispose() { + this.Plugin.Framework.Update -= this.OnFrameworkUpdate; + this.Plugin.ClientState.Login -= this.OnLogin; + } + + private void OnFrameworkUpdate(Framework framework) { + // The in-game name generator will generate duplicate names if it is given + // identical parameters on the same frame. Instead, we will fill up a queue + // with 100 names (the maximum amount of players in the object table) for + // each combination of parameters, generating one name per combination per + // frame. + + for (var race = (byte) 1; race <= this._numRaces; race++) { + for (var clan = (byte) 0; clan <= 1; clan++) { + for (var sex = (byte) 0; sex <= 1; sex++) { + var queue = this.Names[(race, clan, sex)]; + if (queue.Count >= 100) { + this.Initialised = true; + continue; + } + + var name = this.Plugin.Functions.GenerateName(race, clan, sex); + if (name != null && (!queue.TryPeek(out var peek) || peek != name)) { + queue.Enqueue(name); + } + } + } + } + } + + private void OnLogin(object? sender, EventArgs e) { + // The game unloads the CharaMakeName sheet after logging in. + // We need this sheet to generate names, so we load it again. + + this.Plugin.Functions.LoadSheet("CharaMakeName"); + } + + /// + /// + /// Get a consistent replacement name for a real name. + /// + /// + /// This will generate a new name if the given info changes. + /// + /// + /// + /// (race, clan, sex) if known. Any unknowns should be 0xFF to be replaced with random, valid values. + /// A replacement name. Returns null if name is null/empty or no name could be generated. + internal string? GetReplacement(string name, (byte race, byte clan, byte sex) info) { + if (string.IsNullOrEmpty(name)) { + return null; + } + + if (this.LastSeenInfo.TryGetValue(name, out var lastInfo) && lastInfo != info) { + this.Replacements.Remove(name); + } + + this.LastSeenInfo[name] = info; + + if (this.Replacements.TryGetValue(name, out var replacement)) { + return replacement; + } + + // need to generate a name after this point + + // use random parameters for info if none was specified + if (info.race == 0xFF) { + info.race = (byte) this.Rng.Next(1, this._numRaces + 1); + } + + if (info.clan == 0xFF) { + info.clan = (byte) this.Rng.Next(0, 2); + } + + if (info.sex == 0xFF) { + info.clan = (byte) this.Rng.Next(0, 2); + } + + // get a name for the given info if possible + if (this.Names.TryGetValue(info, out var names)) { + // make sure the new name is not the same as the old name + names.TryDequeue(out var newName); + while (newName == name) { + names.TryDequeue(out newName); + } + + if (newName != null) { + this.Replacements[name] = newName; + return newName; + } + } + + // otherwise, get a random name + // can't really do anything about conflicts here, but this should be a very rare/impossible case + var random = this.Plugin.Functions.GenerateName(info.race, info.clan, info.sex); + if (random != null) { + this.Replacements[name] = random; + } + + return random; + } + + internal void Reset() { + this.Replacements.Clear(); + } + } +} diff --git a/NominaOcculta/NominaOcculta.csproj b/NominaOcculta/NominaOcculta.csproj new file mode 100755 index 0000000..dceb543 --- /dev/null +++ b/NominaOcculta/NominaOcculta.csproj @@ -0,0 +1,43 @@ + + + + net5-windows + enable + latest + false + true + + $(AppData)\XIVLauncher\addon\Hooks\dev + + true + + + + + $(Dalamud)\Dalamud.dll + false + + + $(Dalamud)\ImGui.NET.dll + false + + + $(Dalamud)\Lumina.dll + false + + + $(Dalamud)\Lumina.Excel.dll + false + + + D:\code\XivCommon\XivCommon\bin\Release\net5-windows\XivCommon.dll + + + + + + + + + + diff --git a/NominaOcculta/NominaOcculta.yaml b/NominaOcculta/NominaOcculta.yaml new file mode 100755 index 0000000..4f55efc --- /dev/null +++ b/NominaOcculta/NominaOcculta.yaml @@ -0,0 +1,6 @@ +name: Nomina Occulta +author: ascclemens +description: |- + Hide the names of characters on your screen by turning + them into random names. +punchline: Hide character names. diff --git a/NominaOcculta/Obscurer.cs b/NominaOcculta/Obscurer.cs new file mode 100755 index 0000000..c5735cb --- /dev/null +++ b/NominaOcculta/Obscurer.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using Dalamud.Game; +using Dalamud.Game.ClientState.Objects.Enums; +using Dalamud.Game.ClientState.Objects.Types; +using Dalamud.Game.Text; +using Dalamud.Game.Text.SeStringHandling; +using XivCommon.Functions.NamePlates; + +namespace NominaOcculta { + internal class Obscurer : IDisposable { + private Plugin Plugin { get; } + + private Stopwatch UpdateTimer { get; } = new(); + private IList Friends { get; set; } + + internal Obscurer(Plugin plugin) { + this.Plugin = plugin; + + this.UpdateTimer.Start(); + + this.Friends = this.Plugin.Common.Functions.FriendList.List + .Select(friend => friend.Name.TextValue) + .ToList(); + + this.Plugin.Framework.Update += this.OnFrameworkUpdate; + this.Plugin.Functions.AtkTextNodeSetText += this.OnAtkTextNodeSetText; + this.Plugin.Common.Functions.NamePlates.OnUpdate += this.OnNamePlateUpdate; + this.Plugin.ChatGui.ChatMessage += this.OnChatMessage; + } + + public void Dispose() { + this.Plugin.ChatGui.ChatMessage -= this.OnChatMessage; + this.Plugin.Common.Functions.NamePlates.OnUpdate -= this.OnNamePlateUpdate; + this.Plugin.Functions.AtkTextNodeSetText -= this.OnAtkTextNodeSetText; + this.Plugin.Framework.Update -= this.OnFrameworkUpdate; + } + + private void OnFrameworkUpdate(Framework framework) { + if (this.UpdateTimer.Elapsed < TimeSpan.FromSeconds(5)) { + return; + } + + this.Friends = this.Plugin.Common.Functions.FriendList.List + .Select(friend => friend.Name.TextValue) + .ToList(); + this.UpdateTimer.Restart(); + } + + private void OnAtkTextNodeSetText(IntPtr node, IntPtr textPtr, ref SeString? overwrite) { + // A catch-all for UI text. This is slow, so specialised methods should be preferred. + + var text = Util.ReadRawSeString(textPtr); + + var changed = this.ChangeNames(text); + if (changed) { + overwrite = text; + } + } + + private void OnNamePlateUpdate(NamePlateUpdateEventArgs args) { + this.ChangeNames(args.Name); + this.ChangeNames(args.Title); // for minions + } + + private void OnChatMessage(XivChatType type, uint senderId, ref SeString sender, ref SeString message, ref bool isHandled) { + this.ChangeNames(sender); + this.ChangeNames(message); + } + + private bool ChangeNames(SeString text) { + if (!this.Plugin.Config.Enabled || !this.Plugin.NameRepository.Initialised) { + return false; + } + + var changed = false; + + var player = this.Plugin.ClientState.LocalPlayer; + + if (this.Plugin.Config.SelfFull) { + var playerName = player?.Name.TextValue; + if (playerName != null && text.ContainsPlayerName(playerName) && this.Plugin.NameRepository.GetReplacement(playerName, GetInfo(player!)) is { } replacement) { + text.ReplacePlayerName(playerName, replacement); + changed = true; + } + } + + if (this.Plugin.Config.SelfFirst || this.Plugin.Config.SelfLast) { + var playerName = player?.Name.TextValue; + if (playerName != null && this.Plugin.NameRepository.GetReplacement(playerName, GetInfo(player!)) is { } replacement) { + var parts = playerName.Split(' ', 2); + var replacementParts = replacement.Split(' ', 2); + + if (this.Plugin.Config.SelfFirst && text.ContainsPlayerName(parts[0])) { + text.ReplacePlayerName(parts[0], replacementParts[0]); + changed = true; + } + + if (this.Plugin.Config.SelfLast && text.ContainsPlayerName(parts[1])) { + text.ReplacePlayerName(parts[1], replacementParts[1]); + changed = true; + } + } + } + + if (this.Plugin.Config.Party) { + foreach (var member in this.Plugin.PartyList) { + var name = member.Name.TextValue; + + var info = ((byte) 0xFF, (byte) 0xFF, member.Sex); + if (member.GameObject is Character chara) { + info = GetInfo(chara); + } + + if (member.ObjectId == player?.ObjectId || !text.ContainsPlayerName(name) || this.Plugin.NameRepository.GetReplacement(name, info) is not { } replacement) { + continue; + } + + if (this.Plugin.Config.ExcludeFriends && this.Friends.Contains(name)) { + continue; + } + + text.ReplacePlayerName(name, replacement); + changed = true; + } + } + + if (this.Plugin.Config.Others) { + var party = this.Plugin.PartyList.Select(member => member.ObjectId).ToList(); + + foreach (var obj in this.Plugin.ObjectTable) { + if (obj.ObjectKind != ObjectKind.Player || obj is not Character chara || obj.ObjectId == player?.ObjectId || party.Contains(obj.ObjectId)) { + continue; + } + + var name = chara.Name.TextValue; + if (this.Plugin.Config.ExcludeFriends && this.Friends.Contains(name)) { + continue; + } + + var info = GetInfo(chara); + if (info.race == 0) { + continue; + } + + if (this.Plugin.NameRepository.GetReplacement(name, GetInfo(chara)) is not { } replacement) { + continue; + } + + text.ReplacePlayerName(name, replacement); + changed = true; + } + } + + return changed; + } + + private static (byte race, byte clan, byte gender) GetInfo(Character chara) { + return ( + chara.Customize[(byte) CustomizeIndex.Race], + (byte) ((chara.Customize[(byte) CustomizeIndex.Tribe] - 1) % 2), + chara.Customize[(byte) CustomizeIndex.Gender] + ); + } + } +} diff --git a/NominaOcculta/Plugin.cs b/NominaOcculta/Plugin.cs new file mode 100755 index 0000000..66c26c9 --- /dev/null +++ b/NominaOcculta/Plugin.cs @@ -0,0 +1,77 @@ +using Dalamud.Data; +using Dalamud.Game; +using Dalamud.Game.ClientState; +using Dalamud.Game.ClientState.Objects; +using Dalamud.Game.ClientState.Party; +using Dalamud.Game.Command; +using Dalamud.Game.Gui; +using Dalamud.IoC; +using Dalamud.Plugin; +using XivCommon; + +namespace NominaOcculta { + public class Plugin : IDalamudPlugin { + public string Name => "Nomina Occulta"; + + [PluginService] + internal DalamudPluginInterface Interface { get; private init; } + + [PluginService] + internal ChatGui ChatGui { get; private init; } + + [PluginService] + internal ClientState ClientState { get; private init; } + + [PluginService] + internal CommandManager CommandManager { get; private init; } + + [PluginService] + internal DataManager DataManager { get; private init; } + + [PluginService] + internal Framework Framework { get; private init; } + + [PluginService] + internal PartyList PartyList { get; private init; } + + [PluginService] + internal ObjectTable ObjectTable { get; private init; } + + [PluginService] + internal SigScanner SigScanner { get; private init; } + + internal XivCommonBase Common { get; } + internal GameFunctions Functions { get; } + + internal Configuration Config { get; } + internal Commands Commands { get; } + internal NameRepository NameRepository { get; } + internal Obscurer Obscurer { get; } + internal PluginUi Ui { get; } + + public Plugin() { + this.Common = new XivCommonBase(Hooks.NamePlates); + this.Functions = new GameFunctions(this); + + this.Config = this.Interface.GetPluginConfig() as Configuration ?? new Configuration(); + this.Ui = new PluginUi(this); + this.NameRepository = new NameRepository(this); + this.Obscurer = new Obscurer(this); + this.Commands = new Commands(this); + } + + public void Dispose() { + this.Commands.Dispose(); + this.Obscurer.Dispose(); + this.NameRepository.Dispose(); + this.Ui.Dispose(); + + this.Functions.Dispose(); + this.Common.Dispose(); + } + + internal void SaveConfig() { + this.Interface.SavePluginConfig(this.Config); + } + } +} diff --git a/NominaOcculta/PluginUi.cs b/NominaOcculta/PluginUi.cs new file mode 100755 index 0000000..8f1cc3c --- /dev/null +++ b/NominaOcculta/PluginUi.cs @@ -0,0 +1,54 @@ +using System; +using ImGuiNET; + +namespace NominaOcculta { + internal class PluginUi : IDisposable { + private Plugin Plugin { get; } + + internal bool Visible; + + internal PluginUi(Plugin plugin) { + this.Plugin = plugin; + + this.Plugin.Interface.UiBuilder.Draw += this.Draw; + } + + public void Dispose() { + this.Plugin.Interface.UiBuilder.Draw -= this.Draw; + } + + private void Draw() { + if (!this.Visible) { + return; + } + + if (!ImGui.Begin(this.Plugin.Name, ref this.Visible)) { + ImGui.End(); + return; + } + + var anyChanged = ImGui.Checkbox("Enabled", ref this.Plugin.Config.Enabled); + ImGui.Separator(); + anyChanged |= ImGui.Checkbox("Obscure self (full name)", ref this.Plugin.Config.SelfFull); + ImGui.TreePush(); + anyChanged |= ImGui.Checkbox("First name", ref this.Plugin.Config.SelfFirst); + anyChanged |= ImGui.Checkbox("Last name", ref this.Plugin.Config.SelfLast); + ImGui.TreePop(); + anyChanged |= ImGui.Checkbox("Obscure party members", ref this.Plugin.Config.Party); + anyChanged |= ImGui.Checkbox("Obscure others", ref this.Plugin.Config.Others); + anyChanged |= ImGui.Checkbox("Exclude friends", ref this.Plugin.Config.ExcludeFriends); + + if (anyChanged) { + this.Plugin.SaveConfig(); + } + + ImGui.Separator(); + + if (ImGui.Button("Reset names")) { + this.Plugin.NameRepository.Reset(); + } + + ImGui.End(); + } + } +} diff --git a/NominaOcculta/Util.cs b/NominaOcculta/Util.cs new file mode 100755 index 0000000..2560933 --- /dev/null +++ b/NominaOcculta/Util.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Dalamud.Game.Text.SeStringHandling; +using Dalamud.Game.Text.SeStringHandling.Payloads; + +namespace NominaOcculta { + internal static class Util { + internal static bool ContainsPlayerName(this SeString text, string name) { + foreach (var payload in text.Payloads) { + switch (payload) { + case PlayerPayload pp: + if (pp.PlayerName.Contains(name)) { + return true; + } + + break; + case ITextProvider prov: + if (prov.Text.Contains(name)) { + return true; + } + + break; + } + } + + return false; + } + + internal static void ReplacePlayerName(this SeString text, string name, string replacement) { + if (string.IsNullOrEmpty(name)) { + return; + } + + foreach (var payload in text.Payloads) { + switch (payload) { + case PlayerPayload pp: + if (pp.PlayerName.Contains(name)) { + pp.PlayerName = pp.PlayerName.Replace(name, replacement); + } + + break; + case TextPayload txt: + txt.Text = txt.Text.Replace(name, replacement); + break; + } + } + } + + internal static byte[] Terminate(this byte[] bs) { + var terminated = new byte[bs.Length + 1]; + Array.Copy(bs, terminated, bs.Length); + terminated[^1] = 0; + return terminated; + } + + internal static SeString ReadRawSeString(IntPtr ptr) { + var bytes = ReadRawBytes(ptr); + return SeString.Parse(bytes); + } + + internal static string ReadRawString(IntPtr ptr) { + var bytes = ReadRawBytes(ptr); + return Encoding.UTF8.GetString(bytes); + } + + internal static unsafe byte[] ReadRawBytes(IntPtr ptr) { + if (ptr == IntPtr.Zero) { + return Array.Empty(); + } + + var bytes = new List(); + + var bytePtr = (byte*) ptr; + while (*bytePtr != 0) { + bytes.Add(*bytePtr); + bytePtr += 1; + } + + return bytes.ToArray(); + } + } +}