324 lines
12 KiB
C#
Raw Normal View History

2024-08-02 20:04:45 +02:00
using System;
2024-08-16 01:51:12 +02:00
using System.Collections;
2024-08-02 20:04:45 +02:00
using System.Collections.Generic;
2025-01-09 19:34:16 +01:00
using System.Diagnostics.CodeAnalysis;
2024-08-02 20:04:45 +02:00
using System.IO;
using System.Linq;
using System.Numerics;
2024-08-11 18:59:42 +02:00
using System.Text.Encodings.Web;
2024-08-02 20:04:45 +02:00
using System.Text.Json;
using System.Text.Json.Nodes;
2024-08-03 03:21:11 +02:00
using System.Text.Json.Serialization;
2024-08-16 01:51:12 +02:00
using System.Text.Json.Serialization.Metadata;
2024-08-03 03:21:11 +02:00
using Dalamud.Game.ClientState.Objects;
using Dalamud.Interface.Windowing;
2024-08-02 20:04:45 +02:00
using Dalamud.Plugin;
using Dalamud.Plugin.Services;
2024-08-03 03:21:11 +02:00
using GatheringPathRenderer.Windows;
2024-08-12 16:21:34 +02:00
using LLib.GameData;
using Pictomancy;
2024-08-02 20:04:45 +02:00
using Questionable.Model.Gathering;
2024-08-02 18:30:21 +02:00
namespace GatheringPathRenderer;
2025-01-09 19:34:16 +01:00
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
2024-08-02 18:30:21 +02:00
public sealed class RendererPlugin : IDalamudPlugin
{
2024-08-03 03:21:11 +02:00
private readonly WindowSystem _windowSystem = new(nameof(RendererPlugin));
private readonly List<uint> _colors = [0x40FF2020, 0x4020FF20, 0x402020FF, 0x40FFFF20, 0x40FF20FF, 0x4020FFFF];
2024-08-03 03:21:11 +02:00
2024-08-02 20:04:45 +02:00
private readonly IDalamudPluginInterface _pluginInterface;
private readonly IClientState _clientState;
private readonly IPluginLog _pluginLog;
2024-08-03 03:21:11 +02:00
private readonly EditorCommands _editorCommands;
private readonly EditorWindow _editorWindow;
private readonly List<GatheringLocationContext> _gatheringLocations = [];
private EClassJob _currentClassJob;
2024-08-03 03:21:11 +02:00
public RendererPlugin(IDalamudPluginInterface pluginInterface, IClientState clientState,
ICommandManager commandManager, IDataManager dataManager, ITargetManager targetManager, IChatGui chatGui,
2024-08-03 11:17:20 +02:00
IObjectTable objectTable, IPluginLog pluginLog)
2024-08-02 20:04:45 +02:00
{
_pluginInterface = pluginInterface;
_clientState = clientState;
_pluginLog = pluginLog;
2024-08-03 21:33:52 +02:00
Configuration? configuration = (Configuration?)pluginInterface.GetPluginConfig();
if (configuration == null)
{
configuration = new Configuration();
pluginInterface.SavePluginConfig(configuration);
}
_editorCommands = new EditorCommands(this, dataManager, commandManager, targetManager, clientState, chatGui,
configuration);
2025-01-09 19:34:16 +01:00
var configWindow = new ConfigWindow(pluginInterface, configuration);
_editorWindow = new EditorWindow(this, _editorCommands, dataManager, targetManager, clientState, objectTable,
configWindow)
2024-08-03 11:17:20 +02:00
{ IsOpen = true };
2025-01-09 19:34:16 +01:00
_windowSystem.AddWindow(configWindow);
2024-08-03 03:21:11 +02:00
_windowSystem.AddWindow(_editorWindow);
2024-11-19 15:57:15 +01:00
_currentClassJob = (EClassJob?)_clientState.LocalPlayer?.ClassJob.RowId ?? EClassJob.Adventurer;
2024-08-03 03:21:11 +02:00
2024-08-02 20:04:45 +02:00
_pluginInterface.GetIpcSubscriber<object>("Questionable.ReloadData")
.Subscribe(Reload);
PictoService.Initialize(pluginInterface);
2024-08-02 20:04:45 +02:00
LoadGatheringLocationsFromDirectory();
2024-08-03 03:21:11 +02:00
_pluginInterface.UiBuilder.Draw += _windowSystem.Draw;
_pluginInterface.UiBuilder.Draw += Draw;
2024-08-12 16:21:34 +02:00
_clientState.ClassJobChanged += ClassJobChanged;
2024-08-02 20:04:45 +02:00
}
2024-08-03 03:21:11 +02:00
internal DirectoryInfo PathsDirectory
{
get
{
2025-01-09 19:34:16 +01:00
#if DEBUG
DirectoryInfo? solutionDirectory = _pluginInterface.AssemblyLocation.Directory?.Parent?.Parent;
2024-08-03 03:21:11 +02:00
if (solutionDirectory != null)
{
DirectoryInfo pathProjectDirectory =
new DirectoryInfo(Path.Combine(solutionDirectory.FullName, "GatheringPaths"));
if (pathProjectDirectory.Exists)
return pathProjectDirectory;
}
throw new Exception($"Unable to resolve project path ({_pluginInterface.AssemblyLocation.Directory})");
2025-01-09 19:34:16 +01:00
#else
var allPluginsDirectory =
_pluginInterface.ConfigFile.Directory ?? throw new Exception("Unknown directory for plugin configs");
2025-01-09 19:34:16 +01:00
return allPluginsDirectory
.CreateSubdirectory("Questionable")
.CreateSubdirectory("GatheringPaths");
#endif
2024-08-03 03:21:11 +02:00
}
}
internal void Reload()
2024-08-02 20:04:45 +02:00
{
LoadGatheringLocationsFromDirectory();
}
private void LoadGatheringLocationsFromDirectory()
{
_gatheringLocations.Clear();
2024-08-03 03:21:11 +02:00
try
2024-08-02 20:04:45 +02:00
{
2025-01-09 19:34:16 +01:00
#if DEBUG
2025-01-09 19:48:27 +01:00
foreach (var expansionFolder in Questionable.Model.ExpansionData.ExpansionFolders.Values)
2024-08-03 03:21:11 +02:00
LoadFromDirectory(
new DirectoryInfo(Path.Combine(PathsDirectory.FullName, expansionFolder)));
_pluginLog.Information(
$"Loaded {_gatheringLocations.Count} gathering root locations from project directory");
2025-01-09 19:34:16 +01:00
#else
LoadFromDirectory(PathsDirectory);
_pluginLog.Information(
$"Loaded {_gatheringLocations.Count} gathering root locations from {PathsDirectory.FullName} directory");
#endif
2024-08-03 03:21:11 +02:00
}
catch (Exception e)
{
_pluginLog.Error(e, "Failed to load paths from project directory");
2024-08-02 20:04:45 +02:00
}
}
private void LoadFromDirectory(DirectoryInfo directory)
{
if (!directory.Exists)
return;
//_pluginLog.Information($"Loading locations from {directory}");
2024-08-02 20:04:45 +02:00
foreach (FileInfo fileInfo in directory.GetFiles("*.json"))
{
try
{
using FileStream stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
2024-08-03 03:21:11 +02:00
LoadLocationFromStream(fileInfo, stream);
2024-08-02 20:04:45 +02:00
}
catch (Exception e)
{
throw new InvalidDataException($"Unable to load file {fileInfo.FullName}", e);
}
}
foreach (DirectoryInfo childDirectory in directory.GetDirectories())
LoadFromDirectory(childDirectory);
}
2024-08-03 03:21:11 +02:00
private void LoadLocationFromStream(FileInfo fileInfo, Stream stream)
2024-08-02 20:04:45 +02:00
{
var locationNode = JsonNode.Parse(stream)!;
GatheringRoot root = locationNode.Deserialize<GatheringRoot>()!;
2024-08-03 03:21:11 +02:00
_gatheringLocations.Add(new GatheringLocationContext(fileInfo, ushort.Parse(fileInfo.Name.Split('_')[0]),
root));
2024-08-02 20:04:45 +02:00
}
2024-08-03 03:21:11 +02:00
internal IEnumerable<GatheringLocationContext> GetLocationsInTerritory(ushort territoryId)
=> _gatheringLocations.Where(x => x.Root.Steps.LastOrDefault()?.TerritoryId == territoryId);
2024-08-03 03:21:11 +02:00
internal void Save(FileInfo targetFile, GatheringRoot root)
{
JsonSerializerOptions options = new()
{
2024-08-11 18:59:42 +02:00
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
2024-08-03 03:21:11 +02:00
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
WriteIndented = true,
2024-08-16 01:51:12 +02:00
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers = { NoEmptyCollectionModifier }
},
2024-08-03 03:21:11 +02:00
};
using (var stream = File.Create(targetFile.FullName))
{
var jsonNode = (JsonObject)JsonSerializer.SerializeToNode(root, options)!;
var newNode = new JsonObject();
newNode.Add("$schema",
"https://git.carvel.li/liza/Questionable/raw/branch/master/GatheringPaths/gatheringlocation-v1.json");
foreach (var (key, value) in jsonNode)
newNode.Add(key, value?.DeepClone());
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions
{
2024-08-11 18:59:42 +02:00
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
2024-08-03 03:21:11 +02:00
Indented = true
});
newNode.WriteTo(writer, options);
}
Reload();
}
2024-08-16 01:51:12 +02:00
private static void NoEmptyCollectionModifier(JsonTypeInfo typeInfo)
{
foreach (var property in typeInfo.Properties)
{
if (typeof(ICollection).IsAssignableFrom(property.PropertyType))
{
property.ShouldSerialize = (_, val) => val is ICollection { Count: > 0 };
}
}
}
private void ClassJobChanged(uint classJobId)
{
_currentClassJob = (EClassJob)classJobId;
}
2024-08-12 16:21:34 +02:00
private void Draw()
2024-08-02 20:04:45 +02:00
{
if (!_currentClassJob.IsGatherer())
2024-08-12 16:21:34 +02:00
return;
2024-08-02 20:04:45 +02:00
using var drawList = PictoService.Draw();
if (drawList == null)
return;
2024-08-03 03:21:11 +02:00
Vector3 position = _clientState.LocalPlayer?.Position ?? Vector3.Zero;
foreach (var location in GetLocationsInTerritory(_clientState.TerritoryType))
{
if (!location.Root.Groups.Any(gr =>
gr.Nodes.Any(
no => no.Locations.Any(
loc => Vector3.Distance(loc.Position, position) < 200f))))
continue;
foreach (var group in location.Root.Groups)
{
foreach (GatheringNode node in group.Nodes)
{
foreach (var x in node.Locations)
{
bool isUnsaved = false;
bool isCone = false;
float minimumAngle = 0;
float maximumAngle = 0;
if (_editorWindow.TryGetOverride(x.InternalId, out LocationOverride? locationOverride) &&
locationOverride != null)
{
isUnsaved = locationOverride.NeedsSave();
if (locationOverride.IsCone())
2024-08-02 20:04:45 +02:00
{
2024-08-03 03:21:11 +02:00
isCone = true;
minimumAngle = locationOverride.MinimumAngle.GetValueOrDefault();
maximumAngle = locationOverride.MaximumAngle.GetValueOrDefault();
2024-08-03 03:21:11 +02:00
}
}
2024-08-03 03:21:11 +02:00
if (!isCone && x.IsCone())
{
isCone = true;
minimumAngle = x.MinimumAngle.GetValueOrDefault();
maximumAngle = x.MaximumAngle.GetValueOrDefault();
}
minimumAngle *= (float)Math.PI / 180;
maximumAngle *= (float)Math.PI / 180;
if (!isCone || maximumAngle - minimumAngle >= 2 * Math.PI)
{
minimumAngle = 0;
maximumAngle = (float)Math.PI * 2;
}
uint color = _colors[location.Root.Groups.IndexOf(group) % _colors.Count];
drawList.AddFanFilled(x.Position,
locationOverride?.MinimumDistance ?? x.CalculateMinimumDistance(),
locationOverride?.MaximumDistance ?? x.CalculateMaximumDistance(),
minimumAngle, maximumAngle, color);
drawList.AddFan(x.Position,
locationOverride?.MinimumDistance ?? x.CalculateMinimumDistance(),
locationOverride?.MaximumDistance ?? x.CalculateMaximumDistance(),
minimumAngle, maximumAngle, color | 0xFF000000);
drawList.AddText(x.Position, 0xFFFFFFFF, $"{location.Root.Groups.IndexOf(group)} // {node.DataId} / {node.Locations.IndexOf(x)} || {minimumAngle}, {maximumAngle}", 1f);
2024-08-20 02:50:47 +02:00
#if false
var a = GatheringMath.CalculateLandingLocation(x, 0, 0);
var b = GatheringMath.CalculateLandingLocation(x, 1, 1);
new Element(ElementType.CircleAtFixedCoordinates)
{
refX = a.X,
refY = a.Z,
refZ = a.Y,
color = _colors[0],
radius = 0.1f,
Enabled = true,
overlayText = "Min Angle"
},
new Element(ElementType.CircleAtFixedCoordinates)
{
refX = b.X,
refY = b.Z,
refZ = b.Y,
color = _colors[1],
radius = 0.1f,
Enabled = true,
overlayText = "Max Angle"
}
2024-08-12 16:21:17 +02:00
#endif
}
}
2024-08-02 20:04:45 +02:00
}
}
2024-08-02 20:04:45 +02:00
}
2024-08-02 18:30:21 +02:00
public void Dispose()
{
2024-08-12 16:21:34 +02:00
_clientState.ClassJobChanged -= ClassJobChanged;
_pluginInterface.UiBuilder.Draw -= Draw;
2024-08-03 03:21:11 +02:00
_pluginInterface.UiBuilder.Draw -= _windowSystem.Draw;
2024-08-02 20:04:45 +02:00
PictoService.Dispose();
2024-08-02 18:30:21 +02:00
2024-08-02 20:04:45 +02:00
_pluginInterface.GetIpcSubscriber<object>("Questionable.ReloadData")
.Unsubscribe(Reload);
2024-08-03 03:21:11 +02:00
_editorCommands.Dispose();
2024-08-02 18:30:21 +02:00
}
2024-08-03 03:21:11 +02:00
internal sealed record GatheringLocationContext(FileInfo File, ushort Id, GatheringRoot Root);
2024-08-02 18:30:21 +02:00
}