Compare commits
10
Commits
a24f39d4fd
...
v0.2.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eedafac0f2
|
||
|
|
6c2cca5735
|
||
|
|
e355bbfd35
|
||
|
|
77adb61b3b
|
||
|
|
3f92962215
|
||
|
|
c8830f945b
|
||
|
|
fdf0057e77
|
||
|
|
d7e218f105
|
||
|
|
c82e04fccb
|
||
|
|
228570aca6
|
No files matched your search
@@ -1,4 +1,4 @@
|
||||
name: Publish NuGet package
|
||||
name: Publish NuGet packages
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -14,32 +14,110 @@ jobs:
|
||||
packages: write
|
||||
env:
|
||||
NUGET_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: '1'
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||
LD_LIBRARY_PATH: /opt/dotnet-libs/usr/lib/x86_64-linux-gnu
|
||||
SSL_CERT_FILE: /opt/ca-certificates.crt
|
||||
steps:
|
||||
- name: Checkout tagged source
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: Validate tag and pack
|
||||
- name: Fetch exact tagged source
|
||||
env:
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag="${GITEA_REF#refs/tags/}"
|
||||
version="$(dotnet msbuild ShrinkSDK.Godot.csproj -getProperty:Version -nologo)"
|
||||
test "$tag" = "v$version"
|
||||
dotnet restore ShrinkSDK.Godot.csproj --configfile NuGet.Config
|
||||
dotnet pack ShrinkSDK.Godot.csproj --configuration Release --no-restore --output packages --include-symbols --include-source
|
||||
case "$tag" in
|
||||
v[0-9]*) ;;
|
||||
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
|
||||
esac
|
||||
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/${GITEA_REPOSITORY}/archive/${tag}.tar.gz"
|
||||
node --input-type=module <<'NODE'
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
- name: Publish package
|
||||
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
|
||||
NODE
|
||||
mkdir release
|
||||
tar -xzf release.tar.gz --strip-components=1 -C release
|
||||
rm -f release.tar.gz
|
||||
printf '%s' "$tag" > release/.shrink-sdk-release-tag
|
||||
|
||||
- name: Install .NET 8 SDK
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node --input-type=module <<'NODE'
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { rootCertificates } from 'node:tls';
|
||||
|
||||
await writeFile('/opt/ca-certificates.crt', rootCertificates.join('\n'));
|
||||
|
||||
const metadataResponse = await fetch('https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/8.0/releases.json');
|
||||
if (!metadataResponse.ok) throw new Error(`Release metadata download failed: ${metadataResponse.status}`);
|
||||
const metadata = await metadataResponse.json();
|
||||
const sdkVersion = metadata['latest-sdk'];
|
||||
const release = metadata.releases.find(item => item.sdk?.version === sdkVersion);
|
||||
const file = release?.sdk?.files?.find(item => item.rid === 'linux-x64' && item.name.endsWith('.tar.gz'));
|
||||
if (!file) throw new Error(`Linux x64 SDK archive not found for ${sdkVersion}`);
|
||||
const archiveUrl = `https://dotnetcli.blob.core.windows.net/dotnet/Sdk/${sdkVersion}/dotnet-sdk-${sdkVersion}-linux-x64.tar.gz`;
|
||||
const archiveResponse = await fetch(archiveUrl);
|
||||
if (!archiveResponse.ok) throw new Error(`SDK download failed: ${archiveResponse.status}`);
|
||||
await writeFile('/tmp/dotnet-sdk.tar.gz', new Uint8Array(await archiveResponse.arrayBuffer()));
|
||||
|
||||
const poolUrl = 'https://deb.debian.org/debian-security/pool/updates/main/o/openssl/';
|
||||
const poolResponse = await fetch(poolUrl);
|
||||
if (!poolResponse.ok) throw new Error(`OpenSSL package index download failed: ${poolResponse.status}`);
|
||||
const poolIndex = await poolResponse.text();
|
||||
const packages = [...poolIndex.matchAll(/href="(libssl3_[^"]+_amd64\.deb)"/g)].map(match => match[1]).sort();
|
||||
const packageName = packages.at(-1);
|
||||
if (!packageName) throw new Error('Debian libssl3 package was not found');
|
||||
const packageResponse = await fetch(poolUrl + packageName);
|
||||
if (!packageResponse.ok) throw new Error(`OpenSSL package download failed: ${packageResponse.status}`);
|
||||
await writeFile('/tmp/libssl3.deb', new Uint8Array(await packageResponse.arrayBuffer()));
|
||||
NODE
|
||||
mkdir -p /opt/dotnet
|
||||
tar -xzf /tmp/dotnet-sdk.tar.gz -C /opt/dotnet
|
||||
mkdir -p /opt/dotnet-libs
|
||||
dpkg-deb -x /tmp/libssl3.deb /opt/dotnet-libs
|
||||
rm -f /tmp/dotnet-sdk.tar.gz
|
||||
rm -f /tmp/libssl3.deb
|
||||
/opt/dotnet/dotnet --info
|
||||
|
||||
- name: Validate, pack and publish
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
: "${NUGET_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
||||
export PATH="/opt/dotnet:$PATH"
|
||||
cd release
|
||||
tag="$(cat .shrink-sdk-release-tag)"
|
||||
projects=()
|
||||
if [[ -d DotNet~ ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find DotNet~ -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
if [[ -d Godot~ ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find Godot~ -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
if [[ "${#projects[@]}" -eq 0 ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find . -maxdepth 1 -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
test "${#projects[@]}" -gt 0
|
||||
if [[ -f package.json ]]; then
|
||||
version="$(node -p "require('./package.json').version")"
|
||||
else
|
||||
version="$(sed -n 's:.*<Version>\([^<]*\)</Version>.*:\1:p' "${projects[0]}" | head -n 1)"
|
||||
fi
|
||||
test "$tag" = "v$version"
|
||||
mkdir -p packages
|
||||
for project in "${projects[@]}"; do
|
||||
dotnet restore "$project" --configfile NuGet.Config
|
||||
dotnet pack "$project" --configuration Release --no-restore --output "$PWD/packages" --include-symbols --include-source
|
||||
done
|
||||
find packages -maxdepth 1 -name '*.nupkg' -type f | grep -q .
|
||||
dotnet nuget push 'packages/*.nupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||
if compgen -G 'packages/*.snupkg' > /dev/null; then
|
||||
dotnet nuget push 'packages/*.snupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
# ShrinkSDK.Godot
|
||||
|
||||
Godot 4.6 C# 宿主与平台服务适配包。
|
||||
Godot 4.7 C# 宿主与平台服务适配包。
|
||||
|
||||
```powershell
|
||||
dotnet add package ShrinkSDK.Godot --version 0.1.0
|
||||
dotnet add package ShrinkSDK.Godot --version 0.2.1
|
||||
```
|
||||
|
||||
主场景根节点继承 `ShrinkGodotHost`,在 `_Ready` 中先调用 `base._Ready()`,再调用 `StartAppAsync()`。CodeGen 由依赖模块的 `buildTransitive` 自动启用。
|
||||
主场景根节点继承 `ShrinkGodotHost`,在 `_Ready` 中先调用 `base._Ready()`,再调用 `StartAppAsync()`。`Runtime` 属性暴露 `ShrinkGodotRuntime`,可在非节点入口中复用同一套平台服务、派发队列和网络泵。`ShutdownAppAsync()` 只停止 App;`ShutdownAsync()` 关闭整个运行时。CodeGen 由依赖模块的 `buildTransitive` 自动启用。
|
||||
|
||||
## 可复用能力
|
||||
|
||||
<!-- shrink:capabilities -->
|
||||
Capability: Godot 宿主生命周期、主线程派发与网络每帧处理预算
|
||||
Aliases: Godot 主线程 派发 队列 预算
|
||||
Limits: Godot C# 需要 .NET SDK;Unity 编译输入不包含此宿主,符号查询使用 --project Godot/Packages/ShrinkSDK.Godot/ShrinkSDK.Godot.csproj
|
||||
Extension: ShrinkGodotRuntime 与 ShrinkGodotHost.NetworkDispatchBudgetPerFrame、TryPost
|
||||
Evidence: [ShrinkGodotRuntime](ShrinkGodotRuntime.cs); [ShrinkGodotHost](ShrinkGodotHost.cs)
|
||||
<!-- /shrink:capabilities -->
|
||||
+101
-112
@@ -1,15 +1,11 @@
|
||||
#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;
|
||||
@@ -17,138 +13,131 @@ using ShrinkSDK.Runtime;
|
||||
namespace ShrinkSDK.Godot;
|
||||
|
||||
public partial class ShrinkGodotHost : Node, IShrinkMainThreadDispatcher,
|
||||
IShrinkLogger, IShrinkClock, IShrinkPathProvider, IShrinkScreenshotProvider,
|
||||
IShrinkApplicationLifecycle
|
||||
IShrinkDeferredMainThreadDispatcher, 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;
|
||||
private readonly ShrinkGodotRuntime _runtime = new();
|
||||
private SceneTree? _tree;
|
||||
private ulong _lastTickFrame = ulong.MaxValue;
|
||||
private bool _signalsConnected;
|
||||
|
||||
public event Action? Paused;
|
||||
public event Action? Resumed;
|
||||
public event Action? Exiting;
|
||||
public ShrinkGodotRuntime Runtime => _runtime;
|
||||
|
||||
[Export] public int DispatchBudgetPerFrame { get; set; } = 256;
|
||||
[Export] public int NetworkDispatchBudgetPerFrame { get; set; } = 256;
|
||||
[Export]
|
||||
public int DispatchBudgetPerFrame
|
||||
{
|
||||
get => _runtime.DispatchBudgetPerFrame;
|
||||
set => _runtime.DispatchBudgetPerFrame = value;
|
||||
}
|
||||
|
||||
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();
|
||||
[Export]
|
||||
public int NetworkDispatchBudgetPerFrame
|
||||
{
|
||||
get => _runtime.NetworkDispatchBudgetPerFrame;
|
||||
set => _runtime.NetworkDispatchBudgetPerFrame = value;
|
||||
}
|
||||
|
||||
public event Action? Paused
|
||||
{
|
||||
add => _runtime.Paused += value;
|
||||
remove => _runtime.Paused -= value;
|
||||
}
|
||||
|
||||
public event Action? Resumed
|
||||
{
|
||||
add => _runtime.Resumed += value;
|
||||
remove => _runtime.Resumed -= value;
|
||||
}
|
||||
|
||||
public event Action? Exiting
|
||||
{
|
||||
add => _runtime.Exiting += value;
|
||||
remove => _runtime.Exiting -= value;
|
||||
}
|
||||
|
||||
public bool IsMainThread => _runtime.IsMainThread;
|
||||
public bool IsInitialized => _runtime.IsInitialized;
|
||||
public bool IsShutdown => _runtime.IsShutdown;
|
||||
public DateTimeOffset UtcNow => _runtime.UtcNow;
|
||||
public double UnscaledTimeSeconds => _runtime.UnscaledTimeSeconds;
|
||||
public string PersistentDataPath => _runtime.PersistentDataPath;
|
||||
public string TemporaryDataPath => _runtime.TemporaryDataPath;
|
||||
|
||||
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);
|
||||
_runtime.Initialize(this);
|
||||
SetProcess(true);
|
||||
if (_signalsConnected || !IsInsideTree())
|
||||
return;
|
||||
_tree = GetTree();
|
||||
_tree.ProcessFrame += OnProcessFrame;
|
||||
TreeExiting += OnTreeExiting;
|
||||
TreeExited += OnTreeExited;
|
||||
_signalsConnected = true;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
public override void _Process(double delta) => Tick(delta);
|
||||
|
||||
public override void _Notification(int what) => _runtime.Notify(what);
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
var budget = Math.Max(1, DispatchBudgetPerFrame);
|
||||
while (budget-- > 0 && _dispatchQueue.TryDequeue(out var action))
|
||||
action();
|
||||
PumpNetworkAsync().Forget();
|
||||
if (_runtime.IsInitialized && !_runtime.IsShutdown)
|
||||
_runtime.ShutdownAsync().Forget();
|
||||
}
|
||||
|
||||
public override void _Notification(int what)
|
||||
private void OnProcessFrame() => Tick(GetProcessDeltaTime());
|
||||
|
||||
private void Tick(double delta)
|
||||
{
|
||||
switch ((long)what)
|
||||
var frame = Engine.GetProcessFrames();
|
||||
if (frame == _lastTickFrame)
|
||||
return;
|
||||
_lastTickFrame = frame;
|
||||
_runtime.Tick(delta);
|
||||
}
|
||||
|
||||
private void OnTreeExiting()
|
||||
{
|
||||
if (_runtime.IsInitialized && !_runtime.IsShutdown)
|
||||
_runtime.ShutdownAsync().Forget();
|
||||
}
|
||||
|
||||
private void OnTreeExited()
|
||||
{
|
||||
if (_tree != null)
|
||||
{
|
||||
case NotificationApplicationPaused:
|
||||
case NotificationApplicationFocusOut:
|
||||
Paused?.Invoke();
|
||||
break;
|
||||
case NotificationApplicationResumed:
|
||||
case NotificationApplicationFocusIn:
|
||||
Resumed?.Invoke();
|
||||
break;
|
||||
case NotificationWMCloseRequest:
|
||||
case NotificationPredelete:
|
||||
Exiting?.Invoke();
|
||||
break;
|
||||
_tree.ProcessFrame -= OnProcessFrame;
|
||||
_tree = null;
|
||||
}
|
||||
TreeExiting -= OnTreeExiting;
|
||||
TreeExited -= OnTreeExited;
|
||||
_signalsConnected = false;
|
||||
if (_runtime.IsInitialized && !_runtime.IsShutdown)
|
||||
_runtime.ShutdownAsync().Forget();
|
||||
}
|
||||
|
||||
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 UniTask<ShrinkAppRuntime> StartAppAsync(ShrinkAppSettings? settings = null,
|
||||
ShrinkAppServices? services = null) => _runtime.StartAppAsync(settings, services);
|
||||
|
||||
public async UniTask ShutdownAppAsync()
|
||||
{
|
||||
if (_appRuntime == null) return;
|
||||
await _appRuntime.ShutdownAsync();
|
||||
_appRuntime = null;
|
||||
}
|
||||
public UniTask ShutdownAsync() => _runtime.ShutdownAsync();
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (action == null) throw new ArgumentNullException(nameof(action));
|
||||
_dispatchQueue.Enqueue(action);
|
||||
return true;
|
||||
}
|
||||
public UniTask ShutdownAppAsync() => _runtime.StopAppAsync();
|
||||
|
||||
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 TryPost(Action action) => _runtime.TryPost(action);
|
||||
|
||||
public bool RemoveNetworkService(ShrinkNetworkService service)
|
||||
{
|
||||
if (!_networkServices.Remove(service, out var queue)) return false;
|
||||
service.DispatchScheduler = ShrinkNetworkDispatchSchedulers.Inline;
|
||||
queue.Dispose();
|
||||
return true;
|
||||
}
|
||||
public bool TryPostDeferred(Action action) => _runtime.TryPostDeferred(action);
|
||||
|
||||
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 AddNetworkService(ShrinkNetworkService service) => _runtime.AddNetworkService(service);
|
||||
|
||||
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 bool RemoveNetworkService(ShrinkNetworkService service) => _runtime.RemoveNetworkService(service);
|
||||
|
||||
public ValueTask<byte[]> CapturePngAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var image = GetViewport().GetTexture().GetImage();
|
||||
return ValueTask.FromResult(image.SavePngToBuffer());
|
||||
}
|
||||
public static ShrinkCodeGenWovenAttribute RequireWoven(Assembly assembly) =>
|
||||
ShrinkGodotRuntime.RequireWoven(assembly);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
public void Log(ShrinkLogLevel level, string message, Exception? exception = null) =>
|
||||
_runtime.Log(level, message, exception);
|
||||
|
||||
public ValueTask<byte[]> CapturePngAsync(CancellationToken cancellationToken = default) =>
|
||||
_runtime.CapturePngAsync(cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
#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 ShrinkApp;
|
||||
using ShrinkDataSaver;
|
||||
using ShrinkEventBus;
|
||||
using ShrinkNetwork;
|
||||
using ShrinkSDK.Runtime;
|
||||
|
||||
namespace ShrinkSDK.Godot;
|
||||
|
||||
public sealed class ShrinkGodotRuntime : IShrinkMainThreadDispatcher, IShrinkDeferredMainThreadDispatcher,
|
||||
IShrinkLogger, IShrinkClock, IShrinkPathProvider, IShrinkScreenshotProvider,
|
||||
IShrinkApplicationLifecycle
|
||||
{
|
||||
private readonly ConcurrentQueue<Action> _dispatchQueue = new();
|
||||
private readonly Dictionary<ShrinkNetworkService, ShrinkNetworkDispatchQueue> _networkServices = new();
|
||||
private readonly object _dispatchGate = new();
|
||||
private KeyValuePair<ShrinkNetworkService, ShrinkNetworkDispatchQueue>[] _networkSnapshot = [];
|
||||
private readonly SemaphoreSlim _lifecycleGate = new(1, 1);
|
||||
private Node? _owner;
|
||||
private int _mainThreadId;
|
||||
private volatile bool _initialized;
|
||||
private volatile bool _shutdown;
|
||||
private bool _networkPumpRunning;
|
||||
private ShrinkAppRuntime? _appRuntime;
|
||||
|
||||
public event Action? Paused;
|
||||
public event Action? Resumed;
|
||||
public event Action? Exiting;
|
||||
|
||||
public int DispatchBudgetPerFrame { get; set; } = 256;
|
||||
public int NetworkDispatchBudgetPerFrame { get; set; } = 256;
|
||||
|
||||
public bool IsInitialized => _initialized;
|
||||
public bool IsShutdown => _shutdown;
|
||||
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 void Initialize(Node owner)
|
||||
{
|
||||
if (owner == null)
|
||||
throw new ArgumentNullException(nameof(owner));
|
||||
if (_shutdown)
|
||||
throw new InvalidOperationException("ShrinkGodotRuntime has already shut down.");
|
||||
if (_initialized)
|
||||
{
|
||||
if (!ReferenceEquals(_owner, owner))
|
||||
throw new InvalidOperationException("ShrinkGodotRuntime is already bound to another owner.");
|
||||
return;
|
||||
}
|
||||
|
||||
_owner = owner;
|
||||
_mainThreadId = Thread.CurrentThread.ManagedThreadId;
|
||||
ShrinkRuntimeServices.Configure(this, this, this, this, this, this);
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(this);
|
||||
ShrinkDataSaverPlatform.Configure(this, this, this, this);
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
public void Tick(double delta)
|
||||
{
|
||||
if (!_initialized || _shutdown) return;
|
||||
RequireMainThread();
|
||||
|
||||
var budget = Math.Max(1, DispatchBudgetPerFrame);
|
||||
var count = Math.Min(budget, _dispatchQueue.Count);
|
||||
while (count-- > 0 && _dispatchQueue.TryDequeue(out var action))
|
||||
{
|
||||
try
|
||||
{
|
||||
action();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Log(ShrinkLogLevel.Error, "Godot dispatch callback failed.", exception);
|
||||
}
|
||||
}
|
||||
|
||||
PumpNetworkAsync().Forget();
|
||||
}
|
||||
|
||||
public void Notify(int what)
|
||||
{
|
||||
if (_shutdown)
|
||||
return;
|
||||
switch ((long)what)
|
||||
{
|
||||
case MainLoop.NotificationApplicationPaused:
|
||||
case MainLoop.NotificationApplicationFocusOut:
|
||||
Paused?.Invoke();
|
||||
break;
|
||||
case MainLoop.NotificationApplicationResumed:
|
||||
case MainLoop.NotificationApplicationFocusIn:
|
||||
Resumed?.Invoke();
|
||||
break;
|
||||
case Node.NotificationWMCloseRequest:
|
||||
case Node.NotificationPredelete:
|
||||
Exiting?.Invoke();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public async UniTask<ShrinkAppRuntime> StartAppAsync(ShrinkAppSettings? settings = null,
|
||||
ShrinkAppServices? services = null)
|
||||
{
|
||||
await _lifecycleGate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (!_initialized)
|
||||
throw new InvalidOperationException("Initialize the Godot runtime before starting the app.");
|
||||
if (_shutdown)
|
||||
throw new InvalidOperationException("ShrinkGodotRuntime has already shut down.");
|
||||
if (_appRuntime?.IsRunning == true)
|
||||
return _appRuntime;
|
||||
if (_appRuntime != null)
|
||||
{
|
||||
await _appRuntime.ShutdownAsync();
|
||||
_appRuntime = null;
|
||||
}
|
||||
|
||||
_appRuntime = new ShrinkAppRuntime(_owner, settings, services);
|
||||
await _appRuntime.StartAsync();
|
||||
return _appRuntime;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lifecycleGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async UniTask ShutdownAsync()
|
||||
{
|
||||
await _lifecycleGate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (_shutdown)
|
||||
return;
|
||||
var appRuntime = _appRuntime;
|
||||
_appRuntime = null;
|
||||
try
|
||||
{
|
||||
if (appRuntime != null)
|
||||
await appRuntime.ShutdownAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_dispatchGate)
|
||||
{
|
||||
_shutdown = true;
|
||||
while (_dispatchQueue.TryDequeue(out _)) { }
|
||||
}
|
||||
|
||||
foreach (var pair in _networkServices)
|
||||
{
|
||||
pair.Key.DispatchScheduler = ShrinkNetworkDispatchSchedulers.Inline;
|
||||
pair.Value.Dispose();
|
||||
}
|
||||
_networkServices.Clear();
|
||||
_networkSnapshot = [];
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lifecycleGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async UniTask StopAppAsync()
|
||||
{
|
||||
await _lifecycleGate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (_shutdown || _appRuntime == null)
|
||||
return;
|
||||
var appRuntime = _appRuntime;
|
||||
_appRuntime = null;
|
||||
await appRuntime.ShutdownAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lifecycleGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
lock (_dispatchGate)
|
||||
{
|
||||
if (!_initialized || _shutdown) return false;
|
||||
_dispatchQueue.Enqueue(action);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryPostDeferred(Action action) => TryPost(action);
|
||||
|
||||
public bool AddNetworkService(ShrinkNetworkService service)
|
||||
{
|
||||
if (service == null)
|
||||
throw new ArgumentNullException(nameof(service));
|
||||
if (!_initialized || _shutdown) return false;
|
||||
RequireMainThread();
|
||||
if (_networkServices.ContainsKey(service))
|
||||
return true;
|
||||
var queue = new ShrinkNetworkDispatchQueue(Math.Max(1, NetworkDispatchBudgetPerFrame * 4));
|
||||
service.DispatchScheduler = queue;
|
||||
_networkServices.Add(service, queue);
|
||||
UpdateNetworkSnapshot();
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool RemoveNetworkService(ShrinkNetworkService service)
|
||||
{
|
||||
if (service == null)
|
||||
throw new ArgumentNullException(nameof(service));
|
||||
RequireMainThread();
|
||||
if (!_networkServices.Remove(service, out var queue))
|
||||
return false;
|
||||
service.DispatchScheduler = ShrinkNetworkDispatchSchedulers.Inline;
|
||||
queue.Dispose();
|
||||
UpdateNetworkSnapshot();
|
||||
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();
|
||||
if (_owner == null || !GodotObject.IsInstanceValid(_owner))
|
||||
throw new InvalidOperationException("ShrinkGodotRuntime has no valid owner viewport.");
|
||||
var image = _owner.GetViewport().GetTexture().GetImage();
|
||||
return ValueTask.FromResult(image.SavePngToBuffer());
|
||||
}
|
||||
|
||||
private void RequireMainThread()
|
||||
{
|
||||
if (!IsMainThread) throw new InvalidOperationException("Godot lifecycle and network registration require the owner thread.");
|
||||
}
|
||||
|
||||
private void UpdateNetworkSnapshot()
|
||||
{
|
||||
_networkSnapshot = new KeyValuePair<ShrinkNetworkService, ShrinkNetworkDispatchQueue>[_networkServices.Count];
|
||||
((ICollection<KeyValuePair<ShrinkNetworkService, ShrinkNetworkDispatchQueue>>)_networkServices).CopyTo(_networkSnapshot, 0);
|
||||
}
|
||||
|
||||
private async UniTaskVoid PumpNetworkAsync()
|
||||
{
|
||||
if (_networkPumpRunning || _shutdown)
|
||||
return;
|
||||
_networkPumpRunning = true;
|
||||
try
|
||||
{
|
||||
foreach (var pair in _networkSnapshot)
|
||||
{
|
||||
if (_shutdown) break;
|
||||
if (_networkServices.TryGetValue(pair.Key, out var queue) && ReferenceEquals(queue, pair.Value))
|
||||
await queue.PumpAsync(Math.Max(1, NetworkDispatchBudgetPerFrame));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_networkPumpRunning = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.IO;
|
||||
using ShrinkDataSaver;
|
||||
|
||||
namespace ShrinkSDK.Godot;
|
||||
|
||||
public static class ShrinkGodotStorage
|
||||
{
|
||||
public static LocalStorageProvider CreateRenameOnly(string rootPath) =>
|
||||
new(rootPath, LocalStorageCommitStrategy.RenameOnly,
|
||||
(source, destination) => File.Move(source, destination, overwrite: true));
|
||||
}
|
||||
@@ -4,17 +4,17 @@
|
||||
<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>
|
||||
<Version>0.2.1</Version>
|
||||
<Description>Godot 4.7 host and platform services for ShrinkSDK.</Description>
|
||||
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="GodotSharp" Version="4.6.3" />
|
||||
<PackageReference Include="GodotSharp" Version="4.7.2" />
|
||||
<PackageReference Include="UniTask" Version="2.5.10" />
|
||||
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.1.0" />
|
||||
<PackageReference Include="ShrinkSDK.EventBus" Version="2.1.0" />
|
||||
<PackageReference Include="ShrinkSDK.Network" Version="0.3.0" />
|
||||
<PackageReference Include="ShrinkSDK.DataSaver" Version="2.3.0" />
|
||||
<PackageReference Include="ShrinkSDK.App.Core" Version="0.2.0" />
|
||||
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.2.0" />
|
||||
<PackageReference Include="ShrinkSDK.EventBus" Version="2.3.1" />
|
||||
<PackageReference Include="ShrinkSDK.Network" Version="0.4.3" />
|
||||
<PackageReference Include="ShrinkSDK.DataSaver" Version="2.5.0" />
|
||||
<PackageReference Include="ShrinkSDK.App.Core" Version="0.2.4" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Reference in new issue
Block a user