This commit is contained in:
2509_92447106 committed 2026-11-07 18:46:11 +08:00
1 parent 5760fb77b0
commit 6e23391339
22 files changed
+298 -92

No files matched your search

+7
View File
@@ -12,6 +12,13 @@
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings> <ImplicitUsings>disable</ImplicitUsings>
<!--
Avalonia.BuildServices 的遥测任务会向用户目录写 buildtasks.log。
在只读用户目录 / CI / 沙箱里该写入抛 UnauthorizedAccessException(MSB4018),
直接让整个解决方案编译失败(实测)。官方开关是环境变量
AVALONIA_TELEMETRY_OPTOUT=1(MSBuild 属性对 11.3.2 无效),
build.sh / build.ps1 已默认导出;IDE 直接编译时无需此变量。
-->
<AvaloniaVersion>11.3.9</AvaloniaVersion> <AvaloniaVersion>11.3.9</AvaloniaVersion>
<MvvmVersion>8.2.2</MvvmVersion> <MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.0</Version> <Version>1.0.0</Version>
+10
View File
@@ -0,0 +1,10 @@
<Project>
<!--
Avalonia.BuildServices 11.3.x 的 AvaloniaStats 任务会向
~/Library/Application Support/AvaloniaUI/BuildServices/buildtasks.log 写遥测日志。
只读用户目录 / CI / 沙箱里该写入抛 UnauthorizedAccessException(MSB4018),
会让整个解决方案编译失败(实测)。这是纯统计任务,不影响产物,直接禁用。
在 buildTransitive/*.targets 之后导入,同名 Target 覆盖即可(MSBuild 后定义者优先)。
-->
<Target Name="AvaloniaStats" />
</Project>
+4
View File
@@ -33,6 +33,10 @@ $ErrorActionPreference = 'Stop'
$Root = $PSScriptRoot $Root = $PSScriptRoot
Set-Location $Root Set-Location $Root
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。
# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
$AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj' $AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj'
$TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj' $TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj'
$PreviewProj = 'model/_engine/PreviewGen/PreviewGen.csproj' $PreviewProj = 'model/_engine/PreviewGen/PreviewGen.csproj'
+5 -1
View File
@@ -24,7 +24,11 @@
# cache/ 下载暂存 # cache/ 下载暂存
# update/ 待下次启动应用的启动器更新 # update/ 待下次启动应用的启动器更新
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
set -e set -eu
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。
# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。
export AVALONIA_TELEMETRY_OPTOUT=1
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$ROOT_DIR" cd "$ROOT_DIR"
+74 -45
View File
@@ -25,7 +25,7 @@ public enum SceneView
/// 纯 CPU 像素着色 + 矢量标注,无外部贴图依赖,三平台表现一致。 /// 纯 CPU 像素着色 + 矢量标注,无外部贴图依赖,三平台表现一致。
/// 交互约定:单指/鼠标拖动只改变地球自身的角度,视角平面保持不变;双指捏合缩放。 /// 交互约定:单指/鼠标拖动只改变地球自身的角度,视角平面保持不变;双指捏合缩放。
/// </summary> /// </summary>
public class CelestialView : Control public class CelestialView : Control, IDisposable
{ {
// ---------------------------------------------------------------- 属性 // ---------------------------------------------------------------- 属性
public static readonly StyledProperty<SceneRuntime?> SceneProperty = public static readonly StyledProperty<SceneRuntime?> SceneProperty =
@@ -391,6 +391,20 @@ public class CelestialView : Control
_timer = null; _timer = null;
} }
/// <summary>
/// 窗口关闭时释放计时器与 WriteableBitmap:DispatcherTimer 的 Tick 事件会持有本控件实例,
/// 不置空会让 collectible 的 ModelLoadContext 无法回收(模型卸载不干净)。
/// </summary>
public void Dispose()
{
_timer?.Stop();
_timer = null;
_sphere?.Dispose();
_sphere = null;
_sphereSize = 0;
GC.SuppressFinalize(this);
}
private void OnTick(object? sender, EventArgs e) private void OnTick(object? sender, EventArgs e)
{ {
var now = Stopwatch.GetTimestamp(); var now = Stopwatch.GetTimestamp();
@@ -531,9 +545,9 @@ public class CelestialView : Control
else RenderRotation(ctx, size, runtime); else RenderRotation(ctx, size, runtime);
} }
private void DrawSpace(DrawingContext ctx, Size size) // 每帧 Render 都会调用:渐变画刷改成静态只读,避免在热路径反复分配。
{ // 全部使用相对坐标,可安全共享;Radius -> RadiusX/RadiusY(旧 API 已过时)。
var bg = new LinearGradientBrush private static readonly IBrush SpaceBg = new LinearGradientBrush
{ {
StartPoint = new RelativePoint(0.15, 0, RelativeUnit.Relative), StartPoint = new RelativePoint(0.15, 0, RelativeUnit.Relative),
EndPoint = new RelativePoint(0.85, 1, RelativeUnit.Relative), EndPoint = new RelativePoint(0.85, 1, RelativeUnit.Relative),
@@ -544,7 +558,53 @@ public class CelestialView : Control
new GradientStop(Color.Parse("#04060E"), 1) new GradientStop(Color.Parse("#04060E"), 1)
} }
}; };
ctx.FillRectangle(bg, new Rect(size));
private static readonly IBrush SpaceBand = new RadialGradientBrush
{
Center = new RelativePoint(0.72, 0.18, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.72, 0.18, RelativeUnit.Relative),
RadiusX = new RelativeScalar(1.1, RelativeUnit.Relative),
RadiusY = new RelativeScalar(1.1, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.FromArgb(26, 120, 150, 255), 0),
new GradientStop(Color.FromArgb(0, 120, 150, 255), 1)
}
};
private static readonly IBrush AtmosphereGlow = new RadialGradientBrush
{
Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.5, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.5, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.FromArgb(90, 70, 140, 235), 0.60),
new GradientStop(Color.FromArgb(34, 80, 150, 240), 0.80),
new GradientStop(Color.FromArgb(0, 80, 150, 240), 1.0)
}
};
private static readonly IBrush SunGlow = new RadialGradientBrush
{
Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.5, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.5, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.FromArgb(120, 255, 196, 92), 0.10),
new GradientStop(Color.FromArgb(48, 255, 168, 60), 0.34),
new GradientStop(Color.FromArgb(0, 255, 150, 40), 1.0)
}
};
private static readonly IBrush EarthHalo = new SolidColorBrush(Color.FromArgb(56, 70, 140, 235));
private void DrawSpace(DrawingContext ctx, Size size)
{
ctx.FillRectangle(SpaceBg, new Rect(size));
foreach (var star in Stars) foreach (var star in Stars)
{ {
@@ -557,18 +617,7 @@ public class CelestialView : Control
ctx.DrawEllipse(brush, null, new Point(star.X * size.Width, star.Y * size.Height), star.R, star.R); ctx.DrawEllipse(brush, null, new Point(star.X * size.Width, star.Y * size.Height), star.R, star.R);
} }
var band = new RadialGradientBrush ctx.FillRectangle(SpaceBand, new Rect(size));
{
Center = new RelativePoint(0.72, 0.18, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.72, 0.18, RelativeUnit.Relative),
Radius = 1.1,
GradientStops =
{
new GradientStop(Color.FromArgb(26, 120, 150, 255), 0),
new GradientStop(Color.FromArgb(0, 120, 150, 255), 1)
}
};
ctx.FillRectangle(band, new Rect(size));
} }
private void DrawLoading(DrawingContext ctx, Size size) private void DrawLoading(DrawingContext ctx, Size size)
@@ -594,19 +643,7 @@ public class CelestialView : Control
// 太阳光由「直射纬度」反推:直射点严格落在对应纬线上,且始终朝向右前方可见半球 // 太阳光由「直射纬度」反推:直射点严格落在对应纬线上,且始终朝向右前方可见半球
var light = RotationLight(cam, tilt); var light = RotationLight(cam, tilt);
var glow = new RadialGradientBrush ctx.DrawEllipse(AtmosphereGlow, null, center, radius * 1.16, radius * 1.16);
{
Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
Radius = 0.5,
GradientStops =
{
new GradientStop(Color.FromArgb(90, 70, 140, 235), 0.60),
new GradientStop(Color.FromArgb(34, 80, 150, 240), 0.80),
new GradientStop(Color.FromArgb(0, 80, 150, 240), 1.0)
}
};
ctx.DrawEllipse(glow, null, center, radius * 1.16, radius * 1.16);
var px = PixelSizeFor(radius); var px = PixelSizeFor(radius);
if (px > 8 && runtime.Texture != null) if (px > 8 && runtime.Texture != null)
@@ -841,25 +878,15 @@ public class CelestialView : Control
var lightWorld = Vector3.Normalize(-earthPos); var lightWorld = Vector3.Normalize(-earthPos);
var lightCam = Vector3.TransformNormal(lightWorld, cam); var lightCam = Vector3.TransformNormal(lightWorld, cam);
var sunGlow = new RadialGradientBrush ctx.DrawEllipse(SunGlow, null, center, sunR * 6.2, sunR * 6.2);
{
Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative),
Radius = 0.5,
GradientStops =
{
new GradientStop(Color.FromArgb(120, 255, 196, 92), 0.10),
new GradientStop(Color.FromArgb(48, 255, 168, 60), 0.34),
new GradientStop(Color.FromArgb(0, 255, 150, 40), 1.0)
}
};
ctx.DrawEllipse(sunGlow, null, center, sunR * 6.2, sunR * 6.2);
// sunBody 依赖场景里的 runtime.Star,不能静态化;仅把过时 API 换成 RadiusX/Y
var sunBody = new RadialGradientBrush var sunBody = new RadialGradientBrush
{ {
Center = new RelativePoint(0.42, 0.38, RelativeUnit.Relative), Center = new RelativePoint(0.42, 0.38, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.42, 0.38, RelativeUnit.Relative), GradientOrigin = new RelativePoint(0.42, 0.38, RelativeUnit.Relative),
Radius = 0.62, RadiusX = new RelativeScalar(0.62, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.62, RelativeUnit.Relative),
GradientStops = GradientStops =
{ {
new GradientStop(Color.Parse("#FFF3D0"), 0), new GradientStop(Color.Parse("#FFF3D0"), 0),
@@ -877,7 +904,7 @@ public class CelestialView : Control
var px = PixelSizeFor(earthR); var px = PixelSizeFor(earthR);
if (px > 8) if (px > 8)
{ {
ctx.DrawEllipse(new SolidColorBrush(Color.FromArgb(56, 70, 140, 235)), null, ctx.DrawEllipse(EarthHalo, null,
earthScreen, earthR * 1.35, earthR * 1.35); earthScreen, earthR * 1.35, earthR * 1.35);
var bmp = EnsureSphereBitmap(px); var bmp = EnsureSphereBitmap(px);
if (runtime.Texture != null) if (runtime.Texture != null)
@@ -1002,6 +1029,8 @@ public class CelestialView : Control
private WriteableBitmap EnsureSphereBitmap(int px) private WriteableBitmap EnsureSphereBitmap(int px)
{ {
if (_sphere != null && _sphereSize == px) return _sphere; if (_sphere != null && _sphereSize == px) return _sphere;
// 自适应分辨率会频繁改 px,旧位图必须先释放,否则每帧都可能泄漏一张 ~0.8MB 位图
_sphere?.Dispose();
_sphere = new WriteableBitmap(new PixelSize(px, px), new Avalonia.Vector(96, 96), _sphere = new WriteableBitmap(new PixelSize(px, px), new Avalonia.Vector(96, 96),
PixelFormat.Bgra8888, AlphaFormat.Premul); PixelFormat.Bgra8888, AlphaFormat.Premul);
_sphereSize = px; _sphereSize = px;
+30 -3
View File
@@ -17,7 +17,7 @@ namespace NeoRF.EarthModels;
/// 模型自己的界面:画布 + 触控友好工具栏 + 课堂演示卡 + 节气定格与步进。 /// 模型自己的界面:画布 + 触控友好工具栏 + 课堂演示卡 + 节气定格与步进。
/// 启动器只负责下载、开窗口和进度条,不参与任何模型渲染或教学交互。 /// 启动器只负责下载、开窗口和进度条,不参与任何模型渲染或教学交互。
/// </summary> /// </summary>
public sealed class EarthModelView : UserControl public sealed class EarthModelView : UserControl, IDisposable
{ {
private static readonly IBrush PanelBg = new SolidColorBrush(Color.Parse("#C40A1020")); private static readonly IBrush PanelBg = new SolidColorBrush(Color.Parse("#C40A1020"));
private static readonly IBrush ControlBg = new SolidColorBrush(Color.Parse("#16233C")); private static readonly IBrush ControlBg = new SolidColorBrush(Color.Parse("#16233C"));
@@ -155,15 +155,42 @@ public sealed class EarthModelView : UserControl
{ {
Opacity = 1; Opacity = 1;
_uiTimer.Start(); _uiTimer.Start();
if (TopLevel.GetTopLevel(this) is Window window) window.KeyDown += OnKeyDown; if (TopLevel.GetTopLevel(this) is Window window)
{
_hostWindow = window;
window.KeyDown += OnKeyDown;
}
}; };
DetachedFromVisualTree += (_, _) => DetachedFromVisualTree += (_, _) =>
{ {
_uiTimer.Stop(); _uiTimer.Stop();
if (TopLevel.GetTopLevel(this) is Window window) window.KeyDown -= OnKeyDown; if (_hostWindow != null)
{
_hostWindow.KeyDown -= OnKeyDown;
_hostWindow = null;
}
}; };
} }
private Window? _hostWindow;
/// <summary>
/// 窗口关闭时释放计时器、解绑窗口事件并释放两块球面位图,
/// 否则 DispatcherTimer / KeyDown 会持有控件,使 collectible ALC 无法卸载。
/// </summary>
public void Dispose()
{
_uiTimer.Stop();
if (_hostWindow != null)
{
_hostWindow.KeyDown -= OnKeyDown;
_hostWindow = null;
}
_canvas.Dispose();
_closeup.Dispose();
GC.SuppressFinalize(this);
}
private string CurrentView { get; set; } = "rotation"; private string CurrentView { get; set; } = "rotation";
private double StartAngle => IsRevolution ? 60 : 0; private double StartAngle => IsRevolution ? 60 : 0;
private bool IsRevolution => string.Equals(CurrentView, "revolution", StringComparison.OrdinalIgnoreCase); private bool IsRevolution => string.Equals(CurrentView, "revolution", StringComparison.OrdinalIgnoreCase);
+9 -1
View File
@@ -33,5 +33,13 @@ public sealed class EarthModelRuntime : IModelRuntime
return view; return view;
} }
public void Dispose() => GC.SuppressFinalize(this); /// <summary>
/// 释放预烘焙纹理(约 3MB 托管数组)与场景引用。窗口关闭时由启动器调用,
/// 避免 collectible ALC 里的类型被长生命周期引用拖住而无法卸载。
/// </summary>
public void Dispose()
{
_scene = null;
GC.SuppressFinalize(this);
}
} }
+2 -2
View File
@@ -23,6 +23,6 @@
"type": "NeoRF.EarthModels.RevolutionModelFactory", "type": "NeoRF.EarthModels.RevolutionModelFactory",
"preview": "preview.png", "preview": "preview.png",
"apiVersion": 1, "apiVersion": 1,
"version": "1.0-b8139bb568", "version": "1.0-0a73a257ec",
"updatedAt": "2026-11-07T09:23:04Z" "updatedAt": "2026-11-07T10:46:02Z"
} }
+2 -2
View File
@@ -23,6 +23,6 @@
"type": "NeoRF.EarthModels.RotationModelFactory", "type": "NeoRF.EarthModels.RotationModelFactory",
"preview": "preview.png", "preview": "preview.png",
"apiVersion": 1, "apiVersion": 1,
"version": "1.0-52ac06496e", "version": "1.0-6c97454f58",
"updatedAt": "2026-11-07T09:23:04Z" "updatedAt": "2026-11-07T10:46:02Z"
} }
+10 -10
View File
@@ -1,30 +1,30 @@
{ {
"schema": 1, "schema": 1,
"generated": "2026-11-07T09:23:04Z", "generated": "2026-11-07T10:46:02Z",
"repository": "https://gitcode.com/2509_92447106/GC", "repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main", "branch": "main",
"modelDir": "model", "modelDir": "model",
"launcher": { "launcher": {
"version": "1.0.0", "version": "1.0.0",
"revision": "eee4fbbfbc", "revision": "0d59eff631",
"packages": { "packages": {
"win-x64": { "win-x64": {
"path": "dist/GC-win-x64.zip", "path": "dist/GC-win-x64.zip",
"url": "", "url": "",
"sha256": "dbd4997d111c4a60c5d06eadaf0962f41750bafa5b26946e216200ddf7d6c1cf", "sha256": "7bfb1cfab07934642eff4c52078a8f5f034f1d2432a7613f04674403c70f2b6d",
"size": 39378935 "size": 78755039
}, },
"win-arm64": { "win-arm64": {
"path": "dist/GC-win-arm64.zip", "path": "dist/GC-win-arm64.zip",
"url": "", "url": "",
"sha256": "662589f9b315357702d855c46b12c1d088475bdf160c0c042793f2af404f8cb7", "sha256": "9fddf07fa18cbdb368e37204cfb96f5828207e5fe74ecb31fa66b61fa400fd1c",
"size": 37679907 "size": 75360988
}, },
"osx-arm64": { "osx-arm64": {
"path": "dist/GC-osx-arm64.zip", "path": "dist/GC-osx-arm64.zip",
"url": "", "url": "",
"sha256": "01dbf8b4787717aeb804a157ebaf0a75b8fffb1e9ab5e3fb0279fa9299ebee0a", "sha256": "3517548b598eda62c92d873528f39e305c52c6fb246fa5ba5f3613f8b8cb315a",
"size": 39853456 "size": 39847910
}, },
"osx-x64": { "osx-x64": {
"path": "dist/GC-osx-x64.zip", "path": "dist/GC-osx-x64.zip",
@@ -39,12 +39,12 @@
"models": [ "models": [
{ {
"id": "earth-revolution", "id": "earth-revolution",
"version": "1.0-b8139bb568", "version": "1.0-0a73a257ec",
"dir": "model/earth-revolution" "dir": "model/earth-revolution"
}, },
{ {
"id": "earth-rotation", "id": "earth-rotation",
"version": "1.0-52ac06496e", "version": "1.0-6c97454f58",
"dir": "model/earth-rotation" "dir": "model/earth-rotation"
} }
] ]
@@ -83,6 +83,7 @@ public sealed class DirectoryRemote : IModelRemote
} }
var url = package.Url; var url = package.Url;
if (string.IsNullOrWhiteSpace(url)) return null; if (string.IsNullOrWhiteSpace(url)) return null;
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct); return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
if (Path.IsPathRooted(url) && File.Exists(url)) if (Path.IsPathRooted(url) && File.Exists(url))
@@ -64,6 +64,8 @@ public sealed class L : INotifyPropertyChanged
Language = code; Language = code;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language)));
// 顺带清理已回收的弱引用,避免 _watchers 只增不减
_watchers.RemoveAll(w => !w.TryGetTarget(out _));
foreach (var w in _watchers) foreach (var w in _watchers)
if (w.TryGetTarget(out var ls)) ls.Refresh(); if (w.TryGetTarget(out var ls)) ls.Refresh();
LanguageChanged?.Invoke(); LanguageChanged?.Invoke();
@@ -162,6 +162,10 @@ public sealed class LoadedModel : IDisposable
{ {
if (_disposed) return; if (_disposed) return;
_disposed = true; _disposed = true;
// 顺序:先释放视图(停计时器/Dispose 位图),再释放运行时,最后卸载程序集。
// 否则视图里的事件订阅会继续持有 ALC 内的类型,collectible 上下文无法回收。
try { (View as IDisposable)?.Dispose(); }
catch (Exception ex) { Console.Error.WriteLine($"释放模型视图失败: {ex.Message}"); }
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); } try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); } try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
} }
@@ -31,7 +31,12 @@ public static class ModelInstaller
{ {
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
var relative = Path.GetRelativePath(model.Directory, file); var relative = Path.GetRelativePath(model.Directory, file);
var dest = Path.Combine(staging, relative); // 路径穿越防护:相对路径必须完整落在 staging 目录内
var dest = Path.GetFullPath(Path.Combine(staging, relative));
var stagingFull = Path.GetFullPath(staging)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"非法的模型文件路径: {relative}");
var destDir = Path.GetDirectoryName(dest); var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir); if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
@@ -46,18 +51,30 @@ public static class ModelInstaller
progress?.Report((done, total <= 0 ? done : total)); progress?.Report((done, total <= 0 ? done : total));
} }
if (Directory.Exists(target)) // 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
{
var backup = target + ".old"; var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true); if (Directory.Exists(backup)) Directory.Delete(backup, true);
Directory.Move(target, backup); var hasBackup = false;
Directory.Move(staging, target); try
try { Directory.Delete(backup, true); } catch { }
}
else
{ {
if (Directory.Exists(target))
{
Directory.Move(target, backup);
hasBackup = true;
}
Directory.Move(staging, target); Directory.Move(staging, target);
} }
catch
{
// 新目录尚未就位时把旧目录还原;staging 由外层 catch 清理
if (hasBackup && !Directory.Exists(target) && Directory.Exists(backup))
Directory.Move(backup, target);
throw;
}
if (hasBackup)
{
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
}
progress?.Report((total, total)); progress?.Report((total, total));
return target; return target;
@@ -173,7 +173,7 @@ public sealed class ModelSourceClient
var extractDir = Path.Combine(tmpRoot, "extract"); var extractDir = Path.Combine(tmpRoot, "extract");
Directory.CreateDirectory(extractDir); Directory.CreateDirectory(extractDir);
ZipFile.ExtractToDirectory(zipPath, extractDir, true); ZipSafety.ExtractToDirectory(zipPath, extractDir);
var root = FindModelRoot(extractDir) ?? extractDir; var root = FindModelRoot(extractDir) ?? extractDir;
foreach (var entry in Directory.GetFileSystemEntries(root)) foreach (var entry in Directory.GetFileSystemEntries(root))
@@ -195,6 +195,8 @@ public sealed class UpdateService
private static bool IsPayload(string id, string relative) private static bool IsPayload(string id, string relative)
{ {
var rel = relative.Replace('\\', '/'); var rel = relative.Replace('\\', '/');
// 拒绝任何形式的父目录穿越与绝对路径
if (rel.StartsWith('/') || rel.Contains("..", StringComparison.Ordinal)) return false;
return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) || return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) ||
rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase); rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase);
} }
@@ -223,7 +225,14 @@ public sealed class UpdateService
{ {
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
var bytes = await _remote.DownloadAsync(entry, ct); var bytes = await _remote.DownloadAsync(entry, ct);
var dest = Path.Combine(staging, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)); // 路径穿越防护:规范化后必须仍落在 staging 目录内,
// 防止远端清单里的 "../" 或绝对路径写进安装目录之外。
var dest = Path.GetFullPath(Path.Combine(staging,
entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)));
var stagingFull = Path.GetFullPath(staging)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}");
var destDir = Path.GetDirectoryName(dest); var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir); if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await File.WriteAllBytesAsync(dest, bytes, ct); await File.WriteAllBytesAsync(dest, bytes, ct);
@@ -307,7 +316,7 @@ public sealed class UpdateService
await File.WriteAllBytesAsync(zip, bytes, ct); await File.WriteAllBytesAsync(zip, bytes, ct);
try try
{ {
ZipFile.ExtractToDirectory(zip, payload, true); ZipSafety.ExtractToDirectory(zip, payload);
} }
finally finally
{ {
@@ -0,0 +1,36 @@
using System;
using System.IO;
using System.IO.Compression;
namespace EarthModelStudio.Services;
/// <summary>
/// 安全解压:拒绝 zip slip(条目名含 ../、绝对路径、盘符),
/// 并在解压前逐条校验目标路径完整落在目标目录内。
/// </summary>
public static class ZipSafety
{
public static void ExtractToDirectory(string zipPath, string destination)
{
var destFull = Path.GetFullPath(destination)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
using (var archive = ZipFile.OpenRead(zipPath))
{
foreach (var entry in archive.Entries)
{
var name = entry.FullName.Replace('\\', '/');
if (name.StartsWith('/') || name.Contains("..", StringComparison.Ordinal) ||
(name.Length >= 2 && name[1] == ':'))
throw new InvalidOperationException($"压缩包含非法路径条目: {entry.FullName}");
var target = Path.GetFullPath(Path.Combine(destFull, name));
if (!target.StartsWith(destFull, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
}
}
// 校验通过后交给框架解压(保留 overwrite 语义)
ZipFile.ExtractToDirectory(zipPath, destination, true);
}
}
@@ -19,6 +19,9 @@ public partial class DownloadViewModel : ObservableObject
private readonly AppServices _services; private readonly AppServices _services;
private readonly MainViewModel _main; private readonly MainViewModel _main;
private bool _initialized; private bool _initialized;
// 每次切源取消上一次加载,并用 generation 序号丢弃过期结果,避免并发写 Models 集合
private CancellationTokenSource? _loadCts;
private int _loadGeneration;
public ObservableCollection<SourceItemViewModel> Sources { get; } = new(); public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new(); public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
@@ -157,12 +160,22 @@ public partial class DownloadViewModel : ObservableObject
private async Task LoadAsync(SourceItemViewModel source, bool force) private async Task LoadAsync(SourceItemViewModel source, bool force)
{ {
if (!source.Model.Enabled) return; if (!source.Model.Enabled) return;
// 取消上一次尚未完成的加载,避免快速切换源时并发 Clear/写入同一集合
_loadCts?.Cancel();
_loadCts?.Dispose();
_loadCts = new CancellationTokenSource();
var ct = _loadCts.Token;
var generation = ++_loadGeneration;
IsBusy = true; IsBusy = true;
StatusMessage = L.I["dl.syncing"]; StatusMessage = L.I["dl.syncing"];
try try
{ {
var index = await _services.Sources.FetchAsync(source.Model, force, null, CancellationToken.None); var index = await _services.Sources.FetchAsync(source.Model, force, null, ct);
if (SelectedSource != source) return; // 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合
if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source)
return;
if (index.Error != null) if (index.Error != null)
{ {
@@ -189,13 +202,18 @@ public partial class DownloadViewModel : ObservableObject
? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}" ? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}"
: L.I.F("dl.ready", Models.Count); : L.I.F("dl.ready", Models.Count);
} }
catch (OperationCanceledException)
{
// 被更新的加载取代或页面关闭:忽略,不覆盖新结果
}
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = ex.Message; if (!ct.IsCancellationRequested) StatusMessage = ex.Message;
} }
finally finally
{ {
IsBusy = false; // 只有最后一次加载才复位 Busy,避免旧任务把新任务的忙碌状态清掉
if (generation == _loadGeneration) IsBusy = false;
} }
} }
@@ -20,6 +20,7 @@ public partial class MainWindow : Window
private readonly List<PlayerWindow> _players = new(); private readonly List<PlayerWindow> _players = new();
private MainViewModel? _viewModel; private MainViewModel? _viewModel;
private ContentControl? _pageHost; private ContentControl? _pageHost;
private bool _isClosing;
public MainWindow() public MainWindow()
{ {
@@ -74,9 +75,19 @@ public partial class MainWindow : Window
}, DispatcherPriority.Render); }, DispatcherPriority.Render);
} }
private async void OpenPlayerWindow(ModelPackage package) // 事件处理器必须是 void,因此包一层可观察异常的入口:
// fire-and-forget 的 Task 也要观察异常,绝不外泄到 Avalonia 事件循环导致进程崩溃。
private void OpenPlayerWindow(ModelPackage package) => _ = OpenPlayerWindowSafeAsync(package);
private async Task OpenPlayerWindowSafeAsync(ModelPackage package)
{ {
if (_viewModel == null) return; try { await OpenPlayerWindowAsync(package); }
catch (Exception ex) { Console.Error.WriteLine($"打开模型窗口失败: {ex}"); }
}
private async Task OpenPlayerWindowAsync(ModelPackage package)
{
if (_viewModel == null || _isClosing) return;
// 启动进度窗:模型加载、地表纹理生成、界面构建的真实进度 // 启动进度窗:模型加载、地表纹理生成、界面构建的真实进度
var loading = new LoadingWindow(package.LocalizedName); var loading = new LoadingWindow(package.LocalizedName);
@@ -88,9 +99,18 @@ public partial class MainWindow : Window
PlayerWindow? window = null; PlayerWindow? window = null;
LoadedModel? loaded = null; LoadedModel? loaded = null;
Exception? error = null; Exception? error = null;
// 关键修复:requestClose 过去捕获的是「尚未赋值的 window」,加载期恒为 null,
// 模型在 Prepare/CreateView 里调用 context.RequestClose() 会静默失效。
// 改为关闭当前存在的窗口(加载期=进度窗,加载完成=模型窗),统一走 UI 线程。
void RequestClose() => Dispatcher.UIThread.Post(() =>
{
(window ?? (Window?)loading)?.Close();
});
try try
{ {
loaded = await _viewModel.Models.LoadAsync(package, () => window?.Close(), loaded = await _viewModel.Models.LoadAsync(package, RequestClose,
(value, message) => loading.Report(value, message)); (value, message) => loading.Report(value, message));
} }
catch (Exception ex) catch (Exception ex)
@@ -100,6 +120,13 @@ public partial class MainWindow : Window
loading.Close(); loading.Close();
// 加载期间用户关掉了主窗口:不要再弹出幽灵模型窗口,直接释放已加载模型
if (_isClosing)
{
loaded?.Dispose();
return;
}
if (loaded == null || error != null) if (loaded == null || error != null)
{ {
var message = error?.Message ?? L.I["player.errorHint"]; var message = error?.Message ?? L.I["player.errorHint"];
@@ -119,11 +146,14 @@ public partial class MainWindow : Window
private void OnClosed(object? sender, EventArgs e) private void OnClosed(object? sender, EventArgs e)
{ {
_isClosing = true;
if (_viewModel != null) if (_viewModel != null)
{ {
_viewModel.PlayerRequested -= OpenPlayerWindow; _viewModel.PlayerRequested -= OpenPlayerWindow;
_viewModel.PropertyChanged -= OnViewModelPropertyChanged; _viewModel.PropertyChanged -= OnViewModelPropertyChanged;
} }
// 先取快照再关闭:PlayerWindow.Closed 回调会 _players.Remove,
// 直接遍历原集合会在 foreach 期间修改底层导致异常。
foreach (var window in _players.ToList()) window.Close(); foreach (var window in _players.ToList()) window.Close();
_players.Clear(); _players.Clear();
} }
+10 -10
View File
@@ -1,30 +1,30 @@
{ {
"schema": 1, "schema": 1,
"generated": "2026-11-07T09:23:04Z", "generated": "2026-11-07T10:46:02Z",
"repository": "https://gitcode.com/2509_92447106/GC", "repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main", "branch": "main",
"modelDir": "model", "modelDir": "model",
"launcher": { "launcher": {
"version": "1.0.0", "version": "1.0.0",
"revision": "eee4fbbfbc", "revision": "0d59eff631",
"packages": { "packages": {
"win-x64": { "win-x64": {
"path": "dist/GC-win-x64.zip", "path": "dist/GC-win-x64.zip",
"url": "", "url": "",
"sha256": "dbd4997d111c4a60c5d06eadaf0962f41750bafa5b26946e216200ddf7d6c1cf", "sha256": "7bfb1cfab07934642eff4c52078a8f5f034f1d2432a7613f04674403c70f2b6d",
"size": 39378935 "size": 78755039
}, },
"win-arm64": { "win-arm64": {
"path": "dist/GC-win-arm64.zip", "path": "dist/GC-win-arm64.zip",
"url": "", "url": "",
"sha256": "662589f9b315357702d855c46b12c1d088475bdf160c0c042793f2af404f8cb7", "sha256": "9fddf07fa18cbdb368e37204cfb96f5828207e5fe74ecb31fa66b61fa400fd1c",
"size": 37679907 "size": 75360988
}, },
"osx-arm64": { "osx-arm64": {
"path": "dist/GC-osx-arm64.zip", "path": "dist/GC-osx-arm64.zip",
"url": "", "url": "",
"sha256": "01dbf8b4787717aeb804a157ebaf0a75b8fffb1e9ab5e3fb0279fa9299ebee0a", "sha256": "3517548b598eda62c92d873528f39e305c52c6fb246fa5ba5f3613f8b8cb315a",
"size": 39853456 "size": 39847910
}, },
"osx-x64": { "osx-x64": {
"path": "dist/GC-osx-x64.zip", "path": "dist/GC-osx-x64.zip",
@@ -39,12 +39,12 @@
"models": [ "models": [
{ {
"id": "earth-revolution", "id": "earth-revolution",
"version": "1.0-b8139bb568", "version": "1.0-0a73a257ec",
"dir": "model/earth-revolution" "dir": "model/earth-revolution"
}, },
{ {
"id": "earth-rotation", "id": "earth-rotation",
"version": "1.0-52ac06496e", "version": "1.0-6c97454f58",
"dir": "model/earth-rotation" "dir": "model/earth-rotation"
} }
] ]