This commit is contained in:
zznty
2022-11-16 22:56:13 +07:00
commit 017174ac53
11 changed files with 834 additions and 0 deletions

365
.gitignore vendored Normal file
View File

@@ -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
# 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/
[Oo]ut/
[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
TorchBinaries

16
AreaJumpDepleter.sln Normal file
View File

@@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AreaJumpDepleter", "AreaJumpDepleter\AreaJumpDepleter.csproj", "{CA91AC84-36AD-4C1D-92C0-7388DC872CEF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CA91AC84-36AD-4C1D-92C0-7388DC872CEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CA91AC84-36AD-4C1D-92C0-7388DC872CEF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CA91AC84-36AD-4C1D-92C0-7388DC872CEF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CA91AC84-36AD-4C1D-92C0-7388DC872CEF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PlatformTarget>x64</PlatformTarget>
<LangVersion>11</LangVersion>
<UseWpf>true</UseWpf>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PropertyChanged.Fody" Version="4.1.0" PrivateAssets="all" />
<PackageReference Include="Torch.Server.ReferenceAssemblies" Version="1.3.1.207-master" PrivateAssets="all" IncludeAssets="compile" />
</ItemGroup>
<ItemGroup>
<None Update="manifest.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,59 @@
using System.Text;
using AreaJumpDepleter.Managers;
using Torch.API.Managers;
using Torch.Commands;
namespace AreaJumpDepleter;
[Category("jp")]
public class Commands : CommandModule
{
private Config Config => ((Plugin)Context.Plugin).Cfg;
private AreaManager Manager => Context.Torch.CurrentSession.Managers.GetManager<AreaManager>();
[Command("area list", "Lists all deplete areas")]
public void List()
{
var sb = new StringBuilder("Areas:\n");
foreach (var area in Config.Areas)
{
sb.AppendLine($"{area.Name}: pos {area.Position} radius {area.Radius}");
}
Context.Respond(sb.ToString());
}
[Command("area delete", "Delete deplete area by name")]
public void Delete(string name)
{
if (Config.Areas.FirstOrDefault(
b => b.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) is not { } area) return;
Manager.RemoveArea(area);
Config.Areas.Remove(area);
Config.RefreshModel();
Context.Respond($"Successfully deleted {name}");
}
[Command("area create", "Create area from character position")]
public void Create(string name, float radius)
{
if (Context.Player is null)
{
Context.Respond("From console, please use !jp area create <name> <x> <y> <z> <radius>");
return;
}
var area = new DepleteArea
{
Name = name,
Radius = radius,
Position = Context.Player.GetPosition()
};
Config.Areas.Add(area);
Config.RefreshModel();
Manager.AddArea(area);
Context.Respond($"Successfully created {name}");
Context.Respond($"GPS:{name}:{area.Position.X}:{area.Position.Y}:{area.Position.Z}");
}
}

View File

@@ -0,0 +1,43 @@
using System.Collections.ObjectModel;
using Torch;
using Torch.Views;
using VRageMath;
#nullable disable
namespace AreaJumpDepleter;
public class Config : ViewModel
{
public ObservableCollection<DepleteArea> Areas { get; set; } = new();
[Display(Name = "Over Time Multiplier", Description = "stores percents - minutes spent in zone * multiplier * discharge rate")]
public double OverTimeMultiplier { get; set; } = 0;
[Display(Name = "Discharge Rate", Description = "stores percents - minutes spent in zone * multiplier * discharge rate")]
public double DischargeRate { get; set; } = 0.0006944444444444444;
}
public class DepleteArea : ViewModel, IEquatable<DepleteArea>
{
public Vector3D Position { get; set; }
public float Radius { get; set; }
public string Name { get; set; }
public bool Equals(DepleteArea other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Name == other.Name;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((DepleteArea)obj);
}
public override int GetHashCode()
{
return (Name != null ? Name.GetHashCode() : 0);
}
}

View File

@@ -0,0 +1,3 @@
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<PropertyChanged />
</Weavers>

View File

@@ -0,0 +1,134 @@
using System.Runtime.CompilerServices;
using AreaJumpDepleter.Patches;
using AreaJumpDepleter.Utils;
using Sandbox.Game.Entities;
using Torch.API;
using Torch.Managers;
using Torch.Mod;
using Torch.Mod.Messages;
using VRage.Game;
using VRage.Game.Entity;
namespace AreaJumpDepleter.Managers;
public class AreaManager : Manager
{
private readonly Config _config;
private readonly Dictionary<DepleteArea, TriggerArea> _areas = new();
private readonly ConditionalWeakTable<MyJumpDrive, State> _states = new();
public AreaManager(ITorchBase torchInstance, Config config) : base(torchInstance)
{
_config = config;
}
public void AddArea(DepleteArea area)
{
if (_areas.ContainsKey(area))
throw new InvalidOperationException($"Area with name {area.Name} already exists");
var triggerArea = new TriggerArea(new(area.Position, area.Radius));
_areas.Add(area, triggerArea);
triggerArea.Create();
triggerArea.EntityEntered += (sender, entity) =>
{
if (entity is not MyCubeGrid grid) return;
foreach (var drive in grid.GridSystems.TerminalSystem.Blocks.OfType<MyJumpDrive>())
{
_states.GetOrCreateValue(drive).Area = area;
}
/*foreach (var cockpit in grid.GridSystems.TerminalSystem.Blocks.OfType<MyCockpit>())
{
if (cockpit.Pilot is { ControlSteamId: { } steamId })
ModCommunication.SendMessageTo(new NotificationMessage($"Entering {area.Name}", 15000, MyFontEnum.Red), steamId);
}*/
};
triggerArea.EntityLeft += TriggerAreaOnEntityLeft;
}
private void TriggerAreaOnEntityLeft(object sender, MyEntity e)
{
if (e is not MyCubeGrid grid) return;
foreach (var drive in grid.GridSystems.TerminalSystem.Blocks.OfType<MyJumpDrive>())
{
if (_states.TryGetValue(drive, out var state))
state.Area = null;
}
}
public void RemoveArea(DepleteArea area)
{
if (!_areas.TryGetValue(area, out var trigger))
throw new KeyNotFoundException($"Area with name {area.Name} not found");
trigger.Dispose();
_areas.Remove(area);
}
public override void Attach()
{
foreach (var area in _config.Areas)
{
AddArea(area);
}
JumpDriveUpdatePatch.Deplete += JumpDriveUpdatePatchOnDeplete;
}
private float? JumpDriveUpdatePatchOnDeplete(MyJumpDrive drive, float storedPower)
{
if (!_states.TryGetValue(drive, out var state))
return null;
state.Update();
if (_config.OverTimeMultiplier == 0)
return (float)(storedPower - _config.DischargeRate);
return (float)(storedPower - state.Duration.TotalMinutes * _config.OverTimeMultiplier * _config.DischargeRate);
}
public override void Detach()
{
foreach (var triggerArea in _areas.Values)
{
triggerArea.Dispose();
}
}
private class State
{
private DepleteArea? _area;
public DepleteArea? Area
{
get => _area;
set
{
_area = value;
if (_area is not null)
LastEnterTime = DateTime.Now;
}
}
public DateTime? LastEnterTime { get; set; }
public TimeSpan Duration { get; set; }
public bool IsInside => Area is not null;
public void Update()
{
if (LastEnterTime is not null && IsInside)
Duration = DateTime.Now - LastEnterTime.Value;
else if (Duration > TimeSpan.Zero)
{
Duration -= TimeSpan.FromSeconds(10);
if (Duration < TimeSpan.Zero)
Duration = TimeSpan.Zero;
}
}
}
}

View File

@@ -0,0 +1,33 @@
using System.Reflection;
using Sandbox.Game.Entities;
using Torch.Managers.PatchManager;
using Torch.Utils;
using VRage.Sync;
namespace AreaJumpDepleter.Patches;
[PatchShim]
public static class JumpDriveUpdatePatch
{
[ReflectedMethodInfo(typeof(MyJumpDrive), nameof(MyJumpDrive.UpdateAfterSimulation100))]
private static readonly MethodInfo UpdateMethod = null!;
[ReflectedMethodInfo(typeof(JumpDriveUpdatePatch), nameof(Suffix))]
private static readonly MethodInfo SuffixMethod = null!;
public static event Func<MyJumpDrive, float, float?>? Deplete;
public static void Patch(PatchContext context)
{
context.GetPattern(UpdateMethod).Suffixes.Add(SuffixMethod);
}
private static void Suffix(MyJumpDrive __instance, Sync<float, SyncDirection.FromServer> __field_m_storedPower)
{
var value = Deplete?.Invoke(__instance, __field_m_storedPower.Value);
if (value is null)
return;
__field_m_storedPower.Value = value.Value < 0 ? 0 : value.Value;
}
}

View File

@@ -0,0 +1,32 @@
using System.IO;
using System.Windows.Controls;
using AreaJumpDepleter.Managers;
using Torch;
using Torch.API;
using Torch.API.Managers;
using Torch.API.Plugins;
using Torch.API.Session;
using Torch.Views;
namespace AreaJumpDepleter;
public class Plugin : TorchPluginBase, IWpfPlugin
{
private Persistent<Config> _config = null!;
public Config Cfg => _config.Data;
public override void Init(ITorchBase torch)
{
base.Init(torch);
_config = Persistent<Config>.Load(Path.Combine(StoragePath, "AreaJumpDepleter.cfg"));
Torch.Managers.GetManager<ITorchSessionManager>().AddFactory(s => new AreaManager(s.Torch, Cfg));
}
public UserControl GetControl() => new PropertyGrid
{
Margin = new(3),
DataContext = _config.Data
};
}

View File

@@ -0,0 +1,116 @@
using Havok;
using Sandbox.Engine.Physics;
using Sandbox.Game.Entities;
using VRage;
using VRage.Game.Components;
using VRage.Game.Entity;
using VRage.ObjectBuilders;
using VRageMath;
namespace AreaJumpDepleter.Utils;
public class TriggerArea : IDisposable, IEquatable<TriggerArea>
{
private Dummy? _entity;
public BoundingSphere Sphere { get; }
public event EventHandler<MyEntity>? EntityEntered;
public event EventHandler<MyEntity>? EntityLeft;
public TriggerArea(BoundingSphere sphere)
{
Sphere = sphere;
}
public void Create()
{
_entity = new Dummy(Sphere, EnterHandler, ExitHandler);
_entity.Init(null);
MyEntities.Add(_entity);
}
private void ExitHandler(MyEntity entity)
{
EntityEntered?.Invoke(this, entity);
}
private void EnterHandler(MyEntity entity)
{
EntityLeft?.Invoke(this, entity);
}
public void Dispose()
{
if (_entity != null)
MyEntities.Close(_entity);
}
public bool Equals(TriggerArea? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Sphere.Equals(other.Sphere);
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((TriggerArea)obj);
}
public override int GetHashCode()
{
return Sphere.GetHashCode();
}
private class Dummy : MyEntity
{
private readonly BoundingSphere _sphere;
private readonly Action<MyEntity> _enterHandler;
private readonly Action<MyEntity> _exitHandler;
public Dummy(BoundingSphere sphere, Action<MyEntity> enterHandler, Action<MyEntity> exitHandler)
{
_sphere = sphere;
_enterHandler = enterHandler;
_exitHandler = exitHandler;
}
public override void Init(MyObjectBuilder_EntityBase? objectBuilder)
{
base.Init(objectBuilder);
PositionComp.LocalAABB = BoundingBox.CreateFromSphere(_sphere);
Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_STATIC);
Physics.IsPhantom = true;
var phantom = new HkPhantomCallbackShape(EnterCallback, LeaveCallback);
var shape = new HkBvShape(new HkSphereShape(_sphere.Radius), phantom, HkReferencePolicy.TakeOwnership);
((MyPhysicsBody)Physics).CreateFromCollisionObject(shape, _sphere.Center, MatrixD.Identity);
shape.Base.RemoveReference();
Physics.Enabled = true;
BoundingSphereD sphere = _sphere;
foreach (var entity in MyEntities.GetTopMostEntitiesInSphere(ref sphere))
{
_enterHandler(entity);
}
}
private void LeaveCallback(HkPhantomCallbackShape shape, HkRigidBody body)
{
if (body.GetSingleEntity() is MyEntity entity)
_exitHandler(entity);
}
private void EnterCallback(HkPhantomCallbackShape shape, HkRigidBody body)
{
if (body.GetSingleEntity() is MyEntity entity)
_enterHandler(entity);
}
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0"?>
<PluginManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>AreaJumpDepleter</Name>
<Guid>208FCD32-71CB-4184-86C3-11C557E7AC35</Guid>
<Version>v1.0.0</Version>
</PluginManifest>