Minimum viable

This commit is contained in:
TheEvilPenguin committed 2025-06-11 18:12:28 +10:00
1 parent 476aff202f
commit 07229424a4
14 files changed
+564

No files matched your search

+141
View File
@@ -0,0 +1,141 @@
using CommunityMapLocation.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using UnityModManagerNet;
namespace CommunityMapLocation.Api
{
public class ApiServer
{
public ApiServer(Settings settings, UnityModManager.ModEntry.ModLogger logger)
{
listener = new HttpListener();
serializerOptions = new JsonSerializerOptions()
{
ReferenceHandler = ReferenceHandler.IgnoreCycles,
IncludeFields = true,
WriteIndented = true
};
this.settings = settings;
this.logger = logger;
}
private readonly Settings settings;
private readonly UnityModManager.ModEntry.ModLogger logger;
private readonly HttpListener listener;
private readonly JsonSerializerOptions serializerOptions;
private readonly List<IEndpoint> endpoints = new List<IEndpoint>();
public void AutoRegister(Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetExecutingAssembly();
}
foreach (var endpointType in assembly.ExportedTypes.Where(t => !t.IsInterface && !t.IsAbstract && typeof(IEndpoint).IsAssignableFrom(t)))
{
try
{
endpoints.Add((IEndpoint)Activator.CreateInstance(endpointType));
}
catch (Exception ex)
{
logger.Warning($"Could not register endpoint {endpointType.Name}: {ex}");
}
}
}
public void RegisterEndpoint(IEndpoint endpoint)
{
endpoints.Add(endpoint);
}
public void Start()
{
try
{
listener.Prefixes.Add($"http://localhost:{settings.Port}/");
listener.Start();
listener.BeginGetContext(HandleConnection, null);
}
catch (Exception ex)
{
logger.Warning(ex.ToString());
Stop();
}
}
private void HandleConnection(IAsyncResult ar)
{
try
{
var context = listener.EndGetContext(ar);
listener.BeginGetContext(HandleConnection, listener);
var request = context.Request;
var response = context.Response;
var matchedEndpoints = endpoints.Where(e => e.Matches(request.Url) &&
(request.HttpMethod == "OPTIONS" || request.HttpMethod.Equals(e.HttpMethod.ToString(), StringComparison.OrdinalIgnoreCase)));
if (!endpoints.Any())
{
response.StatusCode = (int)HttpStatusCode.NotFound;
}
else
{
var methods = matchedEndpoints.Select(e => e.HttpMethod).Distinct();
response.AppendHeader("Access-Control-Allow-Origin", settings.RequestSourceType == RequestSourceType.All ? "*" : settings.RequestSource);
if (request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
response.AddHeader("Access-Control-Allow-Methods", String.Join(", ", methods.Select(m => m.ToString().ToUpper())));
response.AddHeader("Access-Control-Max-Age", "1728000");
}
else
{
var responseBody = matchedEndpoints.First().Handle(logger, request);
var buffer = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(responseBody, serializerOptions));
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
}
}
response.OutputStream.Close();
}
catch (HttpListenerException)
{
// HttpListener is stopping, swallow exception
}
}
internal void Reload()
{
Stop();
Start();
}
public void Stop()
{
listener.Stop();
listener.Prefixes.Clear();
}
}
}
+24
View File
@@ -0,0 +1,24 @@
using System;
using System.Net;
using System.Net.Http;
using UnityModManagerNet;
namespace CommunityMapLocation.Api
{
public abstract class Endpoint<T> : IEndpoint
{
public abstract HttpMethod HttpMethod { get; }
public abstract string RoutePattern { get; }
public bool Matches(Uri uri)
{
return String.Concat(uri.Segments).Equals(RoutePattern, StringComparison.OrdinalIgnoreCase);
}
public abstract T Handle(UnityModManager.ModEntry.ModLogger logger, HttpListenerRequest request);
object IEndpoint.Handle(UnityModManager.ModEntry.ModLogger logger, HttpListenerRequest request)
{
return Handle(logger, request);
}
}
}
+15
View File
@@ -0,0 +1,15 @@
using System;
using System.Net;
using System.Net.Http;
using UnityModManagerNet;
namespace CommunityMapLocation.Api
{
public interface IEndpoint
{
HttpMethod HttpMethod { get; }
string RoutePattern { get; }
bool Matches(Uri uri);
object Handle(UnityModManager.ModEntry.ModLogger logger, HttpListenerRequest request);
}
}
@@ -0,0 +1,40 @@
using DV.HUD;
using DV.OriginShift;
using System.Net;
using System.Net.Http;
using UnityEngine;
using UnityModManagerNet;
namespace CommunityMapLocation.Api.Location
{
public class LocationEndpoint : Endpoint<LocationResponse>
{
public override HttpMethod HttpMethod => HttpMethod.Get;
public override string RoutePattern => "/Location";
public override LocationResponse Handle(UnityModManager.ModEntry.ModLogger logger, HttpListenerRequest request)
{
float angle;
// If the player is in a loco, we want to get the heading of the loco instead of the play
if (PlayerManager.Car?.IsLoco == true)
{
angle = PlayerManager.Car.transform.rotation.eulerAngles.y;
// If the loco is in reverse, rotate the direction 180 degrees to match the direction of travel
if (PlayerManager.Car.interior.GetComponentInChildren<InteriorControlsManager>().TryGetControl(InteriorControlsManager.ControlType.Reverser, out var control) &&
control.controlImplBase.Value <= 0.25)
{
angle += 180;
}
}
else
{
angle = PlayerManager.PlayerCamera.transform.rotation.eulerAngles.y;
}
return new LocationResponse(PlayerManager.PlayerTransform.AbsolutePosition(), angle * Mathf.PI / 180);
}
}
}
@@ -0,0 +1,21 @@
using UnityEngine;
namespace CommunityMapLocation.Api.Location
{
public class LocationResponse
{
public LocationResponse(Vector3 position, float rotation)
{
X = position.x;
Y = position.y;
Z = position.z;
Rotation = rotation;
}
public float X { get; }
public float Y { get; }
public float Z { get; }
public float Rotation { get; }
}
}
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{0A8392E4-B2FA-4018-BD0C-DD6261F10699}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CommunityMapLocation</RootNamespace>
<AssemblyName>CommunityMapLocation</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="0Harmony">
<HintPath>lib\0Harmony.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Assembly-CSharp">
<HintPath>lib\Assembly-CSharp.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="DV.Common">
<HintPath>lib\DV.Common.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="DV.OriginShiftInfo">
<HintPath>lib\DV.OriginShiftInfo.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="DV.RailTrack">
<HintPath>lib\DV.RailTrack.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="DV.UserManagement">
<HintPath>lib\DV.UserManagement.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="DV.Utils">
<HintPath>lib\DV.Utils.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="UnityEngine">
<HintPath>lib\UnityEngine.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnityEngine.CoreModule">
<HintPath>lib\UnityEngine.CoreModule.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnityEngine.IMGUIModule">
<HintPath>lib\UnityEngine.IMGUIModule.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnityEngine.InputLegacyModule">
<HintPath>lib\UnityEngine.InputLegacyModule.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnityEngine.UI">
<HintPath>lib\UnityEngine.UI.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnityModManager">
<HintPath>lib\UnityModManager.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Api\ApiServer.cs" />
<Compile Include="Api\Endpoint.cs" />
<Compile Include="Api\IEndpoint.cs" />
<Compile Include="Api\Location\LocationEndpoint.cs" />
<Compile Include="Api\Location\LocationResponse.cs" />
<Compile Include="Config\RequestSourceType.cs" />
<Compile Include="Main.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Config\Settings.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Info.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Text.Json">
<Version>9.0.6</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36109.1 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommunityMapLocation", "CommunityMapLocation.csproj", "{0A8392E4-B2FA-4018-BD0C-DD6261F10699}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0A8392E4-B2FA-4018-BD0C-DD6261F10699}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A8392E4-B2FA-4018-BD0C-DD6261F10699}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A8392E4-B2FA-4018-BD0C-DD6261F10699}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A8392E4-B2FA-4018-BD0C-DD6261F10699}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {044646D0-2953-41CC-A775-C1C2BAECADCD}
EndGlobalSection
EndGlobal
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommunityMapLocation.Config
{
public enum RequestSourceType
{
Specific,
All
}
}
+34
View File
@@ -0,0 +1,34 @@
using System;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityModManagerNet;
namespace CommunityMapLocation.Config
{
public class Settings : UnityModManager.ModSettings
{
public int Port { get; set; } = 9090;
public RequestSourceType RequestSourceType { get; set; } = RequestSourceType.Specific;
public string RequestSource { get; set; } = "https://pyronicampt.github.io";
public void Draw()
{
GUILayout.BeginVertical(GUILayout.ExpandWidth(false));
GUILayout.Label("Listening Port:");
Port = Int32.TryParse(GUILayout.TextField(Port.ToString()), out var port) ? port : Port;
GUILayout.Label("Allow connections from websites hosted anywhere, or a specific website?");
UnityModManager.UI.ToggleGroup((int)RequestSourceType, Enum.GetNames(typeof(RequestSourceType)), i => RequestSourceType = (RequestSourceType)i);
if (RequestSourceType == RequestSourceType.Specific)
{
GUILayout.Label("Website:");
RequestSource = GUILayout.TextField(RequestSource);
}
GUILayout.EndVertical();
}
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"Id":"CommunityMapLocation",
"DisplayName":"Derail Valley Community Map Location",
"Author":"TheEvilPenguin",
"Version":"0.0.1",
"ManagerVersion":"0.31.1.0",
"EntryMethod":"CommunityMapLocation.Main.Load"
}
+53
View File
@@ -0,0 +1,53 @@
using CommunityMapLocation.Api;
using CommunityMapLocation.Config;
using UnityModManagerNet;
namespace CommunityMapLocation
{
[EnableReloading]
public static class Main
{
public static Settings Settings { get; private set; }
private static ApiServer apiServer;
static bool Load(UnityModManager.ModEntry modEntry)
{
Settings = Settings.Load<Settings>(modEntry);
apiServer = new ApiServer(Settings, modEntry.Logger);
apiServer.AutoRegister();
modEntry.OnToggle = OnToggle;
modEntry.OnGUI = OnGUI;
modEntry.OnSaveGUI = OnSaveGUI;
return true;
}
public static bool OnToggle(UnityModManager.ModEntry modEntry, bool value)
{
if (value)
{
apiServer.Start();
}
else
{
apiServer.Stop();
}
return true;
}
static void OnGUI(UnityModManager.ModEntry modEntry)
{
Settings.Draw();
}
static void OnSaveGUI(UnityModManager.ModEntry modEntry)
{
Settings.Save(modEntry);
apiServer.Reload();
}
}
}
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CommunityMapLocation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CommunityMapLocation")]
[assembly: AssemblyCopyright("Copyright © 2025")]
[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("0a8392e4-b2fa-4018-bd0c-dd6261f10699")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+36
View File
@@ -0,0 +1,36 @@
Assuming Visual Studio Community:
1. Add the following to the `lib` folder from `[steam common dir]/Derail Valley/DerailValley_Data/Managed`:
- `Assembly-CSharp.dll`
- `BezierCurves.dll`
- `DV.Common.dll`
- `DV.OriginShiftInfo.dll`
- `DV.RailTrack.dll`
- `DV.UserManagement.dll`
- `DV.Utils.dll`
- `UnityEngine.dll`
- `UnityEngine.UI.dll`
- `UnityEngine.InputLegacyModule.dll`
- `UnityEngine.IMGUIModule.dll`
- `UnityEngine.CoreModule.dll`
- `/UnityModManager/0Harmony.dll`
- `/UnityModManager/UnityModManager.dll`
2. Build Solution
3. Copy the following files from `bin/Debug/` to `Derail Valley/Mods/CommunityMapLocation`
- `info.json`
- `CommunityMapLocation.dll`
- `Microsoft.Bcl.AsyncInterfaces.dll`
- `System.Buffers.dll`
- `System.IO.Pipelines.dll`
- `System.Memory.dll`
- `System.Numerics.Vectors.dll`
- `System.Runtime.CompilerServices.Unsafe.dll`
- `System.Text.Encodings.Web.dll`
- `System.Text.Json.dll`
- `System.Threading.Tasks.Extensions.dll`
- `System.ValueTuple.dll`
4. Run game using [Unity Mod Manager](https://www.nexusmods.com/site/mods/21)
Mod functions are all within the UMM settings screen.
View File
Whitespace-only changes.