feat: add Godot C# compatibility and shared codegen weaving
Validate ShrinkSDK Workspace / unity (push) Failing after 3m18s

This commit is contained in:
2026-09-05 02:37:43 +08:00
parent 60cf457230
commit 88ba3cdc48
95 changed files with 2712 additions and 19 deletions
@@ -0,0 +1,137 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
namespace ShrinkApp;
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class ShrinkAppModuleInstallerAttribute : Attribute { }
public interface IShrinkAppModuleInstaller
{
string ModuleId { get; }
int Order { get; }
IReadOnlyList<string> DependsOn { get; }
void RegisterServices(ShrinkAppContext context);
UniTask InitializeAsync(ShrinkAppContext context);
}
public interface IShrinkAppModuleShutdown
{
UniTask ShutdownAsync(ShrinkAppContext context);
}
public sealed class ShrinkAppSettings
{
public bool VerboseLogging { get; set; }
public string[] DisabledModuleIds { get; set; } = Array.Empty<string>();
}
public sealed class ShrinkAppServices
{
private readonly Dictionary<Type, object> _services = new();
public void Register<T>(T service) where T : class => _services[typeof(T)] = service ?? throw new ArgumentNullException(nameof(service));
public bool TryGet<T>(out T? service) where T : class
{
service = _services.TryGetValue(typeof(T), out var value) ? value as T : null;
return service != null;
}
public T GetRequired<T>() where T : class => TryGet<T>(out var value) ? value! : throw new InvalidOperationException($"Required service is not registered: {typeof(T).FullName}");
public bool TryUnregister<T>(T service) where T : class => _services.TryGetValue(typeof(T), out var value) && ReferenceEquals(value, service) && _services.Remove(typeof(T));
}
public sealed class ShrinkAppContext
{
public ShrinkAppContext(object? host, ShrinkAppSettings settings, ShrinkAppServices services)
{
Host = host;
Settings = settings ?? throw new ArgumentNullException(nameof(settings));
Services = services ?? throw new ArgumentNullException(nameof(services));
}
public object? Host { get; }
public ShrinkAppSettings Settings { get; }
public ShrinkAppServices Services { get; }
public static ShrinkAppContext CreateStandalone(ShrinkAppServices services, ShrinkAppSettings? settings = null) => new(null, settings ?? new ShrinkAppSettings(), services);
}
public sealed class ShrinkAppRuntime
{
private readonly List<IShrinkAppModuleInstaller> _started = new();
public ShrinkAppRuntime(object? host = null, ShrinkAppSettings? settings = null, ShrinkAppServices? services = null)
{
Context = new ShrinkAppContext(host, settings ?? new ShrinkAppSettings(), services ?? new ShrinkAppServices());
}
public ShrinkAppContext Context { get; }
public bool IsRunning { get; private set; }
public IReadOnlyList<string> StartedModules => _started.Select(item => item.ModuleId).ToArray();
public async UniTask StartAsync()
{
if (IsRunning) return;
var installers = Sort(CreateInstallers(), Context.Settings.DisabledModuleIds);
try
{
foreach (var installer in installers) installer.RegisterServices(Context);
foreach (var installer in installers)
{
await installer.InitializeAsync(Context);
_started.Add(installer);
}
IsRunning = true;
}
catch
{
await ShutdownStartedAsync();
throw;
}
}
public async UniTask ShutdownAsync()
{
await ShutdownStartedAsync();
IsRunning = false;
}
private async UniTask ShutdownStartedAsync()
{
for (var index = _started.Count - 1; index >= 0; index--)
if (_started[index] is IShrinkAppModuleShutdown shutdown) await shutdown.ShutdownAsync(Context);
_started.Clear();
}
private static IReadOnlyList<IShrinkAppModuleInstaller> CreateInstallers() =>
ShrinkAppInstallers.GetDiscoveredInstallerTypes().Select(type =>
Activator.CreateInstance(type) as IShrinkAppModuleInstaller ?? throw new InvalidOperationException($"Failed to create installer: {type.FullName}"))
.ToArray();
private static IReadOnlyList<IShrinkAppModuleInstaller> Sort(IEnumerable<IShrinkAppModuleInstaller> source, IEnumerable<string> disabledIds)
{
var disabled = new HashSet<string>(disabledIds ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase);
var byId = source.Where(item => !disabled.Contains(item.ModuleId)).ToDictionary(item => item.ModuleId, StringComparer.OrdinalIgnoreCase);
var states = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var result = new List<IShrinkAppModuleInstaller>();
foreach (var installer in byId.Values.OrderBy(item => item.Order).ThenBy(item => item.ModuleId, StringComparer.OrdinalIgnoreCase))
Visit(installer, byId, states, result);
return result;
}
private static void Visit(IShrinkAppModuleInstaller installer, IReadOnlyDictionary<string, IShrinkAppModuleInstaller> byId,
IDictionary<string, int> states, ICollection<IShrinkAppModuleInstaller> result)
{
var state = states.TryGetValue(installer.ModuleId, out var value) ? value : 0;
if (state == 2) return;
if (state == 1) throw new InvalidOperationException($"Circular installer dependency: {installer.ModuleId}");
states[installer.ModuleId] = 1;
foreach (var dependencyId in installer.DependsOn ?? Array.Empty<string>())
{
if (!byId.TryGetValue(dependencyId, out var dependency))
throw new InvalidOperationException($"Installer dependency missing. Module={installer.ModuleId}, DependsOn={dependencyId}");
Visit(dependency, byId, states, result);
}
states[installer.ModuleId] = 2;
result.Add(installer);
}
}
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkApp.Core.Runtime</AssemblyName>
<RootNamespace>ShrinkApp</RootNamespace>
<PackageId>ShrinkSDK.App.Core</PackageId>
<Version>0.2.0</Version>
<Description>ShrinkSDK engine-neutral application composition runtime.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="Runtime\ShrinkAppCore.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkApp.Core\Runtime\ShrinkAppGeneratedRegistry.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkApp.Core\Runtime\ShrinkAppInstallers.cs" />
<PackageReference Include="UniTask" Version="2.5.10" />
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,34 @@
#nullable enable
using System.Collections.Generic;
using ShrinkApp;
using ShrinkCommand.Integration.App;
using ShrinkContext;
using ShrinkContext.AppAdapter;
using ShrinkDataSaver.Integration.App;
using ShrinkNetwork.Integration.App;
namespace ShrinkApp.Starter.Basic;
public static class ShrinkBasicComposition
{
public static ShrinkContextAppHost CreateHost(ShrinkAppServices? services = null)
{
var host = new ShrinkContextAppHost(services);
host.Register<ShrinkCommandAppComponent>("shrink.command");
host.Register<ShrinkDataSaverAppComponent>("shrink.datasaver");
host.Register<ShrinkNetworkAppComponent>("shrink.network");
return host;
}
public static IReadOnlyList<ShrinkLoaderEntry> CreateEntries(ShrinkAppServices services,
ShrinkNetworkAppModuleConfig? network = null) => new[]
{
new ShrinkLoaderEntry("datasaver", "shrink.datasaver", services),
new ShrinkLoaderEntry("command", "shrink.command", services),
new ShrinkLoaderEntry("network", "shrink.network", network ?? new ShrinkNetworkAppModuleConfig
{
Services = services
})
};
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkApp.Starter.Basic</AssemblyName>
<RootNamespace>ShrinkApp.Starter.Basic</RootNamespace>
<PackageId>ShrinkSDK.App.Starter.Basic</PackageId>
<Version>0.3.0</Version>
<Description>Engine-neutral basic ShrinkApp composition.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="Runtime\*.cs" />
<ProjectReference Include="..\ShrinkSDK.App.Core\ShrinkSDK.App.Core.csproj" />
<ProjectReference Include="..\ShrinkSDK.Context.Core\ShrinkSDK.Context.Core.csproj" />
<ProjectReference Include="..\ShrinkSDK.Context.AppAdapter\ShrinkSDK.Context.AppAdapter.csproj" />
<ProjectReference Include="..\ShrinkSDK.Command.Integration.App\ShrinkSDK.Command.Integration.App.csproj" />
<ProjectReference Include="..\ShrinkSDK.DataSaver.Integration.App\ShrinkSDK.DataSaver.Integration.App.csproj" />
<ProjectReference Include="..\ShrinkSDK.Network.Integration.App\ShrinkSDK.Network.Integration.App.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkCommand.Integration.EventBus</AssemblyName>
<RootNamespace>ShrinkCommand.Integration</RootNamespace>
<PackageId>ShrinkSDK.Command.Integration.EventBus</PackageId>
<Version>0.2.0</Version>
<Description>ShrinkCommand and EventBus integration.</Description>
<ShrinkCodeGenEnabled>true</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkCommand.Integration.EventBus\*.cs" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
<ProjectReference Include="..\ShrinkSDK.Context.Core\ShrinkSDK.Context.Core.csproj" />
<ProjectReference Include="..\ShrinkSDK.EventBus\ShrinkSDK.EventBus.csproj" />
<ProjectReference Include="..\ShrinkSDK.Command\ShrinkSDK.Command.csproj" />
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
</ItemGroup>
</Project>
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkCommand.Integration.Network</AssemblyName>
<RootNamespace>ShrinkCommand.Integration</RootNamespace>
<PackageId>ShrinkSDK.Command.Integration.Network</PackageId>
<Version>0.2.0</Version>
<Description>ShrinkCommand and Network RPC integration.</Description>
<ShrinkCodeGenEnabled>true</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkCommand.Integration.Network\*.cs" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
<ProjectReference Include="..\ShrinkSDK.Context.Core\ShrinkSDK.Context.Core.csproj" />
<ProjectReference Include="..\ShrinkSDK.Command\ShrinkSDK.Command.csproj" />
<ProjectReference Include="..\ShrinkSDK.Network\ShrinkSDK.Network.csproj" />
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
</ItemGroup>
</Project>
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkCommand.Runtime</AssemblyName>
<RootNamespace>ShrinkCommand</RootNamespace>
<PackageId>ShrinkSDK.Command</PackageId>
<Version>0.3.0</Version>
<Description>ShrinkSDK command parsing, permissions and execution runtime.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkCommand\Runtime\**\*.cs" />
<PackageReference Include="UniTask" Version="2.5.10" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
</ItemGroup>
</Project>
@@ -0,0 +1,31 @@
#nullable enable
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using ShrinkApp;
namespace ShrinkContext.AppAdapter;
public sealed class ShrinkContextAppHost
{
private readonly ShrinkContextRuntime _runtime = new();
private readonly ShrinkComponentCatalog _catalog = new();
private readonly ShrinkContextLoader _loader;
public ShrinkContextAppHost(ShrinkAppServices? services = null)
{
Services = services ?? new ShrinkAppServices();
_loader = new ShrinkContextLoader(_runtime, _catalog);
}
public ShrinkAppServices Services { get; }
public ShrinkContextRuntime Runtime => _runtime;
public ShrinkLoaderTransactionDiagnostic? LastTransaction => _loader.LastTransaction;
public void Register(string name, Func<IShrinkComponent> factory) => _catalog.Register(name, factory);
public void Register<TComponent>(string name) where TComponent : IShrinkComponent, new() =>
_catalog.Register<TComponent>(name);
public UniTask ApplyAsync(IReadOnlyList<ShrinkLoaderEntry> entries) => _loader.ApplyAsync(entries);
public UniTask ShutdownAsync() => _runtime.ShutdownAsync();
}
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkContext.AppAdapter</AssemblyName>
<RootNamespace>ShrinkContext.AppAdapter</RootNamespace>
<PackageId>ShrinkSDK.Context.AppAdapter</PackageId>
<Version>0.2.0</Version>
<Description>Engine-neutral ShrinkContext composition host for ShrinkApp.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="Runtime\*.cs" />
<ProjectReference Include="..\ShrinkSDK.Context.Core\ShrinkSDK.Context.Core.csproj" />
<ProjectReference Include="..\ShrinkSDK.App.Core\ShrinkSDK.App.Core.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkContext.Core.Runtime</AssemblyName>
<RootNamespace>ShrinkContext</RootNamespace>
<PackageId>ShrinkSDK.Context.Core</PackageId>
<Version>0.2.0</Version>
<Description>ShrinkSDK reversible context and fiber runtime.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkContext.Core\Runtime\**\*.cs" />
<PackageReference Include="UniTask" Version="2.5.10" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkDataSaver.Integration.EventBus</AssemblyName>
<RootNamespace>ShrinkDataSaver.Integration</RootNamespace>
<PackageId>ShrinkSDK.DataSaver.Integration.EventBus</PackageId>
<Version>2.2.0</Version>
<Description>ShrinkDataSaver and EventBus integration.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver.Integration.EventBus\*.cs" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
<ProjectReference Include="..\ShrinkSDK.Context.Core\ShrinkSDK.Context.Core.csproj" />
<ProjectReference Include="..\ShrinkSDK.EventBus\ShrinkSDK.EventBus.csproj" />
<ProjectReference Include="..\ShrinkSDK.DataSaver\ShrinkSDK.DataSaver.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,43 @@
#nullable enable
using System.IO;
using Cysharp.Threading.Tasks;
using ShrinkSDK.Runtime;
namespace ShrinkDataSaver;
public sealed class ShrinkDataSaverRuntimeConfig
{
public string? RootPath { get; set; }
public string SaveFileExtension { get; set; } = ".sav";
public string SettingsFileName { get; set; } = "settings.json";
public int CurrentSaveVersion { get; set; } = 1;
public int MaxSlots { get; set; } = 3;
public float SettingsWriteDebounceSeconds { get; set; } = 0.35f;
public bool DontDestroyOnLoadDriver { get; set; }
}
public static class ShrinkDataSaverRuntime
{
public static bool IsInitialized { get; private set; }
public static void Initialize(ShrinkDataSaverRuntimeConfig? config = null)
{
if (IsInitialized) return;
config ??= new ShrinkDataSaverRuntimeConfig();
var root = string.IsNullOrWhiteSpace(config.RootPath)
? ShrinkRuntimeServices.Paths.PersistentDataPath
: config.RootPath!;
Directory.CreateDirectory(root);
var storage = new LocalStorageProvider(root);
ShrinkDataSaverPlatform.SettingsWriteDebounceSeconds = config.SettingsWriteDebounceSeconds;
ShrinkDataSaverPlatform.MaxSlots = config.MaxSlots;
ShrinkSettings.Initialize(storage, Path.Combine(root, config.SettingsFileName));
ShrinkSave.Initialize(storage, Path.Combine(root, "saves"), config.SaveFileExtension,
config.CurrentSaveVersion);
ShrinkSettings.LoadAsync().Forget();
IsInitialized = true;
ShrinkRuntimeServices.Logger.Log(ShrinkLogLevel.Information,
$"[ShrinkDataSaver] Runtime initialized. Root: {root}");
}
}
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkDataSaver.Runtime</AssemblyName>
<RootNamespace>ShrinkDataSaver</RootNamespace>
<PackageId>ShrinkSDK.DataSaver</PackageId>
<Version>2.3.0</Version>
<Description>ShrinkSDK engine-neutral versioned save and settings runtime.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="Runtime\ShrinkDataSaverRuntime.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\AssemblyInfo.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\DataSerializer.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\IStorageProvider.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\LocalStorageProvider.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\MigrationChain.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\SaveEncryptor.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\SaveTypes.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\ShrinkDataSaverPlatform.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\ShrinkSave.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkDataSaver\Runtime\ShrinkSettings.cs" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="UniTask" Version="2.5.10" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkEventBus.Runtime</AssemblyName>
<RootNamespace>ShrinkEventBus</RootNamespace>
<PackageId>ShrinkSDK.EventBus</PackageId>
<Version>2.1.0</Version>
<Description>ShrinkSDK typed event bus runtime.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkEventBus\Runtime\**\*.cs"
Exclude="..\..\..\Assets\Modules\ShrinkEventBus\Runtime\ShrinkMonoEventScope.cs" />
<PackageReference Include="UniTask" Version="2.5.10" />
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,154 @@
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Godot;
using ShrinkEventBus;
using ShrinkDataSaver;
using ShrinkApp;
using ShrinkNetwork;
using ShrinkSDK.Runtime;
namespace ShrinkSDK.Godot;
public partial class ShrinkGodotHost : Node, IShrinkMainThreadDispatcher,
IShrinkLogger, IShrinkClock, IShrinkPathProvider, IShrinkScreenshotProvider,
IShrinkApplicationLifecycle
{
private readonly ConcurrentQueue<Action> _dispatchQueue = new();
private readonly Dictionary<ShrinkNetworkService, ShrinkNetworkDispatchQueue> _networkServices = new();
private int _mainThreadId;
private bool _networkPumpRunning;
private ShrinkAppRuntime? _appRuntime;
public event Action? Paused;
public event Action? Resumed;
public event Action? Exiting;
[Export] public int DispatchBudgetPerFrame { get; set; } = 256;
[Export] public int NetworkDispatchBudgetPerFrame { get; set; } = 256;
public bool IsMainThread => Thread.CurrentThread.ManagedThreadId == _mainThreadId;
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
public double UnscaledTimeSeconds => Time.GetTicksMsec() / 1000d;
public string PersistentDataPath => ProjectSettings.GlobalizePath("user://");
public string TemporaryDataPath => OS.GetCacheDir();
public override void _Ready()
{
_mainThreadId = Thread.CurrentThread.ManagedThreadId;
ShrinkRuntimeServices.Configure(this, this, this, this, this, this);
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(this);
ShrinkDataSaverPlatform.Configure(this, this, this, this);
SetProcess(true);
}
public override void _Process(double delta)
{
var budget = Math.Max(1, DispatchBudgetPerFrame);
while (budget-- > 0 && _dispatchQueue.TryDequeue(out var action))
action();
PumpNetworkAsync().Forget();
}
public override void _Notification(int what)
{
switch ((long)what)
{
case NotificationApplicationPaused:
case NotificationApplicationFocusOut:
Paused?.Invoke();
break;
case NotificationApplicationResumed:
case NotificationApplicationFocusIn:
Resumed?.Invoke();
break;
case NotificationWMCloseRequest:
case NotificationPredelete:
Exiting?.Invoke();
break;
}
}
public async UniTask<ShrinkAppRuntime> StartAppAsync(ShrinkAppSettings? settings = null, ShrinkAppServices? services = null)
{
if (_appRuntime?.IsRunning == true) return _appRuntime;
_appRuntime = new ShrinkAppRuntime(this, settings, services);
await _appRuntime.StartAsync();
return _appRuntime;
}
public async UniTask ShutdownAppAsync()
{
if (_appRuntime == null) return;
await _appRuntime.ShutdownAsync();
_appRuntime = null;
}
public bool TryPost(Action action)
{
if (action == null) throw new ArgumentNullException(nameof(action));
_dispatchQueue.Enqueue(action);
return true;
}
public void AddNetworkService(ShrinkNetworkService service)
{
if (service == null) throw new ArgumentNullException(nameof(service));
if (_networkServices.ContainsKey(service)) return;
var queue = new ShrinkNetworkDispatchQueue(Math.Max(1, NetworkDispatchBudgetPerFrame * 4));
service.DispatchScheduler = queue;
_networkServices.Add(service, queue);
}
public bool RemoveNetworkService(ShrinkNetworkService service)
{
if (!_networkServices.Remove(service, out var queue)) return false;
service.DispatchScheduler = ShrinkNetworkDispatchSchedulers.Inline;
queue.Dispose();
return true;
}
public static ShrinkCodeGenWovenAttribute RequireWoven(Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
return assembly.GetCustomAttribute<ShrinkCodeGenWovenAttribute>() ??
throw new InvalidOperationException(
$"Assembly '{assembly.GetName().Name}' was not woven by ShrinkSDK.CodeGen. Ensure the package is installed and ShrinkCodeGenEnabled is not false.");
}
public void Log(ShrinkLogLevel level, string message, Exception? exception = null)
{
var text = exception == null ? message : $"{message}{System.Environment.NewLine}{exception}";
if (level >= ShrinkLogLevel.Error) GD.PushError(text);
else if (level >= ShrinkLogLevel.Warning) GD.PushWarning(text);
else GD.Print(text);
}
public ValueTask<byte[]> CapturePngAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var image = GetViewport().GetTexture().GetImage();
return ValueTask.FromResult(image.SavePngToBuffer());
}
private async UniTaskVoid PumpNetworkAsync()
{
if (_networkPumpRunning) return;
_networkPumpRunning = true;
try
{
foreach (var queue in _networkServices.Values)
await queue.PumpAsync(Math.Max(1, NetworkDispatchBudgetPerFrame));
}
finally
{
_networkPumpRunning = false;
}
}
}
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AssemblyName>ShrinkSDK.Godot</AssemblyName>
<RootNamespace>ShrinkSDK.Godot</RootNamespace>
<PackageId>ShrinkSDK.Godot</PackageId>
<Version>0.1.0</Version>
<Description>Godot 4.6 host and platform services for ShrinkSDK.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="GodotSharp" Version="4.6.3" />
<PackageReference Include="UniTask" Version="2.5.10" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
<ProjectReference Include="..\ShrinkSDK.EventBus\ShrinkSDK.EventBus.csproj" />
<ProjectReference Include="..\ShrinkSDK.Network\ShrinkSDK.Network.csproj" />
<ProjectReference Include="..\ShrinkSDK.DataSaver\ShrinkSDK.DataSaver.csproj" />
<ProjectReference Include="..\ShrinkSDK.App.Core\ShrinkSDK.App.Core.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,66 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace ShrinkModFramework.Godot;
public sealed class ShrinkGodotModLoader : IDisposable
{
private sealed record LoadedMod(AssemblyLoadContext LoadContext, WeakReference UnloadReference,
ShrinkModContext Context, IReadOnlyList<IShrinkMod> Instances);
private readonly Dictionary<string, LoadedMod> _loaded = new(StringComparer.OrdinalIgnoreCase);
public IReadOnlyCollection<string> LoadedAssemblyPaths => _loaded.Keys;
public IReadOnlyList<IShrinkMod> Load(string assemblyPath)
{
assemblyPath = Path.GetFullPath(assemblyPath);
if (_loaded.ContainsKey(assemblyPath)) throw new InvalidOperationException($"Mod assembly is already loaded: {assemblyPath}");
var loadContext = new AssemblyLoadContext($"ShrinkMod:{Path.GetFileNameWithoutExtension(assemblyPath)}", true);
loadContext.Resolving += (_, name) => ResolveDependency(loadContext, Path.GetDirectoryName(assemblyPath)!, name);
try
{
var assembly = loadContext.LoadFromAssemblyPath(assemblyPath);
var entries = assembly.GetTypes().Where(type => !type.IsAbstract && typeof(IShrinkMod).IsAssignableFrom(type) &&
type.GetCustomAttribute<ShrinkModAttribute>() != null).OrderBy(type => type.GetCustomAttribute<ShrinkModAttribute>()!.LoadOrder).ToArray();
var context = new ShrinkModContext(Path.GetDirectoryName(assemblyPath)!);
var instances = entries.Select(type => (IShrinkMod)(Activator.CreateInstance(type) ??
throw new InvalidOperationException($"Failed to create mod entry: {type.FullName}"))).ToArray();
foreach (var mod in instances) mod.OnConstruct(context);
foreach (var mod in instances) mod.OnRegisterContent(context);
foreach (var mod in instances) mod.OnInitialize(context);
foreach (var mod in instances) mod.OnReady(context);
_loaded[assemblyPath] = new LoadedMod(loadContext, new WeakReference(loadContext), context, instances);
return instances;
}
catch { loadContext.Unload(); throw; }
}
public bool Unload(string assemblyPath)
{
assemblyPath = Path.GetFullPath(assemblyPath);
if (!_loaded.Remove(assemblyPath, out var loaded)) return false;
for (var index = loaded.Instances.Count - 1; index >= 0; index--)
if (loaded.Instances[index] is IShrinkModUnload unload) unload.OnUnload(loaded.Context);
loaded.LoadContext.Unload();
return true;
}
public void Dispose()
{
foreach (var path in _loaded.Keys.ToArray()) Unload(path);
}
private static Assembly? ResolveDependency(AssemblyLoadContext context, string directory, AssemblyName name)
{
var shared = AssemblyLoadContext.Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == name.Name);
if (shared != null) return shared;
var path = Path.Combine(directory, name.Name + ".dll");
return File.Exists(path) ? context.LoadFromAssemblyPath(path) : null;
}
}
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AssemblyName>ShrinkModFramework.Godot</AssemblyName>
<RootNamespace>ShrinkModFramework.Godot</RootNamespace>
<PackageId>ShrinkSDK.ModFramework.Godot</PackageId>
<Version>0.1.0</Version>
<Description>Collectible AssemblyLoadContext host for ShrinkSDK mods in Godot.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ShrinkSDK.ModFramework\ShrinkSDK.ModFramework.csproj" />
<ProjectReference Include="..\ShrinkSDK.Godot\ShrinkSDK.Godot.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,25 @@
#nullable enable
using System;
using System.Collections.Generic;
namespace ShrinkModFramework;
public sealed class ShrinkModContext
{
private readonly Dictionary<Type, object> _services = new();
public ShrinkModContext(string modDirectory) => ModDirectory = modDirectory ?? throw new ArgumentNullException(nameof(modDirectory));
public string ModDirectory { get; }
public void RegisterService<T>(T service) where T : class => _services[typeof(T)] = service ?? throw new ArgumentNullException(nameof(service));
public bool TryGetService<T>(out T? service) where T : class
{
service = _services.TryGetValue(typeof(T), out var value) ? value as T : null;
return service != null;
}
public T GetRequiredService<T>() where T : class => TryGetService<T>(out var value) ? value! : throw new InvalidOperationException($"Service is not registered: {typeof(T).FullName}");
}
public interface IShrinkModUnload
{
void OnUnload(ShrinkModContext context);
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkModFramework.Runtime</AssemblyName>
<RootNamespace>ShrinkModFramework</RootNamespace>
<PackageId>ShrinkSDK.ModFramework</PackageId>
<Version>0.3.0</Version>
<Description>Engine-neutral ShrinkSDK mod contracts and lifecycle.</Description>
<Nullable>disable</Nullable>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="Runtime\ShrinkModContext.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkModFramework\Runtime\Core\IShrinkMod.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkModFramework\Runtime\Core\ShrinkModBase.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkModFramework\Runtime\Core\ShrinkModHandle.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkModFramework\Runtime\Metadata\*.cs" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkNetwork.Integration.EventBus</AssemblyName>
<RootNamespace>ShrinkNetwork.Integration</RootNamespace>
<PackageId>ShrinkSDK.Network.Integration.EventBus</PackageId>
<Version>0.2.0</Version>
<Description>ShrinkNetwork and EventBus generated bridge.</Description>
<ShrinkCodeGenEnabled>true</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkNetwork.Integration.EventBus\*.cs" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
<ProjectReference Include="..\ShrinkSDK.Context.Core\ShrinkSDK.Context.Core.csproj" />
<ProjectReference Include="..\ShrinkSDK.EventBus\ShrinkSDK.EventBus.csproj" />
<ProjectReference Include="..\ShrinkSDK.Network\ShrinkSDK.Network.csproj" />
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
</ItemGroup>
</Project>
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkNetwork.Runtime</AssemblyName>
<RootNamespace>ShrinkNetwork</RootNamespace>
<PackageId>ShrinkSDK.Network</PackageId>
<Version>0.3.0</Version>
<Description>ShrinkSDK messaging, RPC, permission and transport runtime.</Description>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkNetwork\Runtime\**\*.cs" />
<PackageReference Include="Kcp-CSharp" Version="1.0.8" />
<PackageReference Include="MessagePack" Version="3.1.8" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="UniTask" Version="2.5.10" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
</ItemGroup>
</Project>
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<AssemblyName>ShrinkRuntime.Abstractions</AssemblyName>
<RootNamespace>ShrinkSDK.Runtime</RootNamespace>
<PackageId>ShrinkSDK.Runtime.Abstractions</PackageId>
<Version>0.1.0</Version>
<Description>Engine-neutral ShrinkSDK runtime contracts.</Description>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Assets\Modules\ShrinkRuntime.Abstractions\Runtime\ShrinkRuntimeServices.cs" Link="Runtime\ShrinkRuntimeServices.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,89 @@
#nullable enable
using Godot;
namespace ShrinkTutorial.Godot;
public partial class ShrinkGodotTutorialOverlay : Control
{
private readonly Label _title = new();
private readonly Label _body = new();
private ShrinkTutorialRunner? _runner;
private Control? _target;
public override void _Ready()
{
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
MouseFilter = MouseFilterEnum.Stop;
var panel = new PanelContainer { CustomMinimumSize = new Vector2(320, 100) };
panel.Position = new Vector2(24, 24);
var text = new VBoxContainer();
text.AddChild(_title);
text.AddChild(_body);
panel.AddChild(text);
AddChild(panel);
}
public void Bind(ShrinkTutorialRunner runner)
{
if (_runner != null) _runner.StepChanged -= ShowStep;
_runner = runner;
_runner.StepChanged += ShowStep;
if (_runner.CurrentStep != null) ShowStep(_runner.CurrentStep);
}
public override void _ExitTree()
{
if (_runner != null) _runner.StepChanged -= ShowStep;
_runner = null;
_target = null;
}
public override void _Process(double delta)
{
if (_runner?.CurrentStep is not { } step) return;
_target = ResolveTarget(step);
QueueRedraw();
}
public override void _Draw()
{
var viewport = GetViewportRect();
if (_target == null)
{
DrawRect(viewport, new Color(0, 0, 0, 0.72f));
return;
}
var hole = _target.GetGlobalRect().Grow(8);
var shade = new Color(0, 0, 0, 0.72f);
DrawRect(new Rect2(viewport.Position, new Vector2(viewport.Size.X, hole.Position.Y)), shade);
DrawRect(new Rect2(new Vector2(0, hole.End.Y), new Vector2(viewport.Size.X, viewport.Size.Y - hole.End.Y)), shade);
DrawRect(new Rect2(new Vector2(0, hole.Position.Y), new Vector2(hole.Position.X, hole.Size.Y)), shade);
DrawRect(new Rect2(new Vector2(hole.End.X, hole.Position.Y), new Vector2(viewport.Size.X - hole.End.X, hole.Size.Y)), shade);
}
public override void _GuiInput(InputEvent @event)
{
if (@event is not InputEventMouseButton { Pressed: true }) return;
var step = _runner?.CurrentStep;
if (step == null) return;
if (step.CompleteCondition == ShrinkTutorialCompleteCondition.AnyClick ||
step.CompleteCondition == ShrinkTutorialCompleteCondition.ClickTarget && _target?.GetGlobalRect().HasPoint(GetGlobalMousePosition()) == true)
_runner!.CompleteStep();
AcceptEvent();
}
private void ShowStep(ShrinkTutorialStep step)
{
_title.Text = step.Title;
_body.Text = step.Body;
Visible = true;
}
private Control? ResolveTarget(ShrinkTutorialStep step)
{
if (step.TargetMode == ShrinkTutorialTargetMode.Path) return GetTree().Root.GetNodeOrNull<Control>(step.Target);
if (step.TargetMode == ShrinkTutorialTargetMode.AnchorId) return GetTree().GetFirstNodeInGroup("shrink_tutorial_" + step.Target) as Control;
return null;
}
}
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AssemblyName>ShrinkTutorial.Godot</AssemblyName>
<RootNamespace>ShrinkTutorial.Godot</RootNamespace>
<PackageId>ShrinkSDK.Tutorial.Godot</PackageId>
<Version>0.1.0</Version>
<Description>Godot Control overlay and Resources for ShrinkSDK Tutorial.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="GodotSharp" Version="4.6.3" />
<ProjectReference Include="..\ShrinkSDK.Tutorial\ShrinkSDK.Tutorial.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
namespace ShrinkTutorial;
[Serializable]
public sealed class ShrinkTutorialStep
{
public string StepId = string.Empty;
public string Title = string.Empty;
public string Body = string.Empty;
public string Target = string.Empty;
public ShrinkTutorialTargetMode TargetMode;
public ShrinkTutorialCompleteCondition CompleteCondition = ShrinkTutorialCompleteCondition.ClickTarget;
public ShrinkTutorialDialogAnchor DialogAnchor = ShrinkTutorialDialogAnchor.Auto;
public ShrinkTutorialMaskShape MaskShape = ShrinkTutorialMaskShape.Rect;
public string CustomEventName = string.Empty;
public bool BlockInputOutsideTarget = true;
}
[Serializable]
public sealed class ShrinkTutorialData
{
public string TutorialId = string.Empty;
public List<ShrinkTutorialStep> Steps = new();
}
public sealed class ShrinkTutorialRunner
{
private readonly IShrinkTutorialStorage _storage;
private ShrinkTutorialProgress _progress;
public ShrinkTutorialRunner(IShrinkTutorialStorage storage)
{
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_progress = storage.Load() ?? new ShrinkTutorialProgress();
}
public ShrinkTutorialData Current { get; private set; }
public int StepIndex { get; private set; } = -1;
public ShrinkTutorialStep CurrentStep => Current != null && StepIndex >= 0 && StepIndex < Current.Steps.Count ? Current.Steps[StepIndex] : null;
public event Action<ShrinkTutorialStep> StepChanged;
public event Action<string> Completed;
public bool Start(ShrinkTutorialData tutorial)
{
if (tutorial == null || tutorial.Steps.Count == 0 || _progress.completedTutorials.Contains(tutorial.TutorialId)) return false;
Current = tutorial;
StepIndex = 0;
StepChanged?.Invoke(CurrentStep);
return true;
}
public bool CompleteStep(string customEventName = null)
{
var step = CurrentStep;
if (step == null) return false;
if (step.CompleteCondition == ShrinkTutorialCompleteCondition.CustomEvent &&
!string.Equals(step.CustomEventName, customEventName, StringComparison.Ordinal)) return false;
StepIndex++;
if (StepIndex < Current.Steps.Count) { StepChanged?.Invoke(CurrentStep); return true; }
_progress.completedTutorials.Add(Current.TutorialId);
_storage.Save(_progress);
var id = Current.TutorialId;
Current = null;
StepIndex = -1;
Completed?.Invoke(id);
return true;
}
public void Reset()
{
Current = null;
StepIndex = -1;
_storage.Reset();
_progress = new ShrinkTutorialProgress();
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkTutorial.Runtime</AssemblyName>
<RootNamespace>ShrinkTutorial</RootNamespace>
<PackageId>ShrinkSDK.Tutorial</PackageId>
<Version>0.2.0</Version>
<Description>Engine-neutral ShrinkSDK tutorial state and step runtime.</Description>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="Runtime\ShrinkTutorialCore.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkTutorial\Runtime\Core\ShrinkTutorialEnums.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkTutorial\Runtime\Core\ShrinkTutorialLocalization.cs" />
<Compile Include="..\..\..\Assets\Modules\ShrinkTutorial\Runtime\Storage\IShrinkTutorialStorage.cs" />
<ProjectReference Include="..\ShrinkSDK.Runtime.Abstractions\ShrinkSDK.Runtime.Abstractions.csproj" />
</ItemGroup>
</Project>