This commit is contained in:
2509_92447106 committed 2026-11-07 16:05:56 +08:00
commit 60113ab76e
81 files changed
+8520

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
bin/
obj/
dist/
build/
*.user
.DS_Store
.vs/
.venv/
venv/
env/
.idea/
.vscode/
__pycache__/
*.pyc
*.pyo
*.log
node_modules/
.pytest_cache/
.mypy_cache/
+40
View File
@@ -0,0 +1,40 @@
# 2026-11-07
## Earth Model Studio(新建项目)
- 用户要求:C#/.NET8(可切10),多目录结构(曾要求 gradle 命名,后明确改为标准 .NET 命名,勿再用 gradle 字样)
- 结构:src/main/dotnet + src/test/dotnet + src/main/resources + model/ + examples/ + dist/ + Directory.Build.props + build.sh/build.ps1
- 三平台一次性编译:`./build.sh publish` → dist/{mac-arm64(.app),win-x64,win-arm64},自包含单文件 + 内置 model/ + examples/
- 技术栈:Avalonia 11.3.9 + CommunityToolkit.Mvvm 8.2.2(本地 NuGet 已缓存);纯 CPU 球面像素渲染(SphereRaster + CelestialView)
- 模型格式:model/<id>/<id>.json + <id>.model/scene.json + land.json;模型源=git 仓库根的 model/ 目录(支持 github/gitlab/gitee zip 归档、git clone、本地目录)
- 内置模型:earth-rotation(自转)、earth-revolution(公转),land.json 手绘大陆轮廓已校验
- 校验:src/test/dotnet 用 Avalonia.Headless 渲染截图到 build/screenshots(页面+场景全通过,HUD 重叠已修)
- 已知小问题:RadialGradientBrush.Radius 过时警告;发布后 mac 单文件在沙箱内需 DOTNET_BUNDLE_EXTRACT_BASE_DIR 可写
## 修改(14:10 之后)
- 模型启动改为独立窗口:新增 Views/PlayerWindow.axaml(.cs),MainViewModel 只抛 PlayerRequested 事件,MainWindow 负责 Show(owner) 并维护 PlayerWindows 列表;PlayerViewModel 去掉 MainViewModel 依赖,改 CloseRequested + IDisposable;Esc/空格/F11 快捷键
- 分层:src=启动器(无模型数据、无预置模型源),model/=模型数据。移除 examples/,SettingsService 不再种内置源,AppPaths 去掉 ExamplesRoot 并新增 EMS_MODELS
- build.sh/build.ps1:publish 只建空 model/(仅 README),新增 pack-models → dist/models-1.0.0.zip
- model/README.md 写清模型格式规范
- 验证:离屏截图 page-player.png / page-main-while-playing.png,双窗口计数 2→关一个→1→0;三平台重新发布 + 模型 zip
## 架构重构(14:30 之后):启动器不再渲染,模型自带功能代码
- 新分层:src=启动器(扫描/下载/开窗,零渲染);model-sdk=契约;model-src=模型源码+封面工具;model=模型包(数据+dll+preview.png+i18n)
- 契约:IModelFactory(ApiVersion/Create) / IModelRuntime.CreateView(IModelContext) / IModelContext(ModelId/ModelDirectory/DataDirectory/Language/MemoryBudgetMb/RequestClose/Log)
- 加载:ModelHost + 可收集 AssemblyLoadContext,Sdk/Avalonia 走默认上下文,关窗 Unload
- 迁移:CelestialView/SphereRaster/LandMask/SceneDefinition/SceneRuntime → model-src/EarthModels(命名空间 NeoRF.EarthModels);PlayerView+PlayerViewModel 换成模型内 EarthModelView(C# 构建 UI)
- 模型包新增清单字段 assembly/type/preview/apiVersion;封面由 model-src/tools/PreviewGen 用模型渲染器生成
- 自转模型 views=["rotation"] → 无节气定位/无视图切换;公转 views=["revolution"] → 有节气、封面是公转场景
- 构建:./build.sh models 编译模型 dll + 生成封面;pack-models 先编译再打包
- 验证:EMS_SELFTEST=1 自检(dev + 发布包 /tmp 部署)两个模型均 OK;离屏截图含插件加载真实窗口
## 六项改动(15:00–15:35):真实贴图 / 缩放 / 拖动 / 动画 / 代码归位 / 进度条
- 目录:删除 model-src,根目录 model-sdk -> model/_sdk;现在根目录只有 src/ 与 model/。模型源码在 model/<id>/src/,共享引擎在 model/_engine/,契约在 model/_sdk/
- 清单 assembly 改为各模型自己的 dll:EarthRotationModel.dll / EarthRevolutionModel.dll(工厂仍是 NeoRF.EarthModels.*ModelFactory)
- 贴图:PlanetTexture 烘焙 1024×512 等经纬度纹理(海洋深度、沙漠/雨林/针叶林/苔原、极地冰盖、云层模糊、夜间辉光);反照率打包 uint[] Albedo
- 性能:地形梯度 SlopeEast/SlopeNorth 预烘焙(去掉每像素 4 次 SampleHeight + 6 次三角函数);海面高光 Pow 改乘法;运动时降分辨率 460 + 按帧耗时自适应 320–460,静止补 820 高清帧。实测公转播放 6ms、自转播放 ~18ms
- 交互:滚轮/工具栏 −100%+/⟲ 缩放 0.6–6×(缓动),暂停后拖动旋转地球或沿轨道移动、松手惯性;云层播放/暂停都缓慢漂移
- 动画:模型窗口淡入、按钮悬停 BrushTransition、教学面板滑入淡出;启动器页面切换淡入、按钮/卡片悬停过渡、进度条 DoubleTransition 平滑
- 进度条:契约新增 IModelRuntime.Prepare(后台)+ IModelContext.ReportProgress;ModelHost.LoadAsync 两阶段;LoadingWindow 显示真实阶段(读场景→烘焙纹理→构建界面)
- 打包:pack-models 排除 */bin/* */obj/*,避免把 107MB SkiaSharp native 打进包;模型包 356KB(含源码+dll+封面+i18n)
- 验证:离屏截图全部正常;反射校验缩放 1.00→1.25→1.00、暂停拖动=True、交互提示=True;自转无节气;发布包复制到 /tmp 自检两个模型 OK
- 产物:dist/mac-arm64 97M、win-x64 88M、win-arm64 94M(model/ 仅 README),dist/models-1.0.0.zip 356K
+22
View File
@@ -0,0 +1,22 @@
<Project>
<!--
多目录结构公共属性:
src/main/dotnet/<module> 生产代码
src/test/dotnet/<module> 测试 / 离屏渲染校验
TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0
-->
<PropertyGroup Condition="'$(TargetFramework)' == ''">
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<AvaloniaVersion>11.3.9</AvaloniaVersion>
<MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.0</Version>
<Company>NeoRF</Company>
<Product>Earth Model Studio</Product>
<NeutralLanguage>zh-Hans</NeutralLanguage>
</PropertyGroup>
</Project>
+127
View File
@@ -0,0 +1,127 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "main", "main", "{ABAA6554-252E-13CE-1B40-0464A7DBA771}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{F2BBD9FE-F148-5687-ED21-3ABA515A9B22}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio", "src\main\dotnet\EarthModelStudio\EarthModelStudio.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.Tests", "src\test\dotnet\EarthModelStudio.Tests\EarthModelStudio.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.ModelSdk", "model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "earth-rotation", "earth-rotation", "{EBCD2737-5E64-9C5F-5D8B-D0375EC50F43}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{13F93445-B061-AC9E-97CA-8C4FA55DC418}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRotationModel", "model\earth-rotation\src\EarthRotationModel.csproj", "{64556F71-7456-43B2-890C-CF01AD29D386}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "earth-revolution", "earth-revolution", "{0B92F86C-37C2-3C12-904C-85123CE34F4C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EADF0841-BEC2-9A74-4322-069D7B5A6EBB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|x64.ActiveCfg = Debug|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|x64.Build.0 = Debug|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|x86.ActiveCfg = Debug|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Debug|x86.Build.0 = Debug|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|Any CPU.Build.0 = Release|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x64.ActiveCfg = Release|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x64.Build.0 = Release|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x86.ActiveCfg = Release|Any CPU
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}.Release|x86.Build.0 = Release|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x64.ActiveCfg = Debug|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x64.Build.0 = Debug|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x86.ActiveCfg = Debug|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Debug|x86.Build.0 = Debug|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|Any CPU.Build.0 = Release|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x64.ActiveCfg = Release|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x64.Build.0 = Release|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x86.ActiveCfg = Release|Any CPU
{D15CB92F-5E5C-4516-8D07-C244FC0CD113}.Release|x86.Build.0 = Release|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x64.ActiveCfg = Debug|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x64.Build.0 = Debug|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x86.ActiveCfg = Debug|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Debug|x86.Build.0 = Debug|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|Any CPU.Build.0 = Release|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x64.ActiveCfg = Release|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x64.Build.0 = Release|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x86.ActiveCfg = Release|Any CPU
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}.Release|x86.Build.0 = Release|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x64.ActiveCfg = Debug|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x64.Build.0 = Debug|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x86.ActiveCfg = Debug|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Debug|x86.Build.0 = Debug|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|Any CPU.Build.0 = Release|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|x64.ActiveCfg = Release|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|x64.Build.0 = Release|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|x86.ActiveCfg = Release|Any CPU
{64556F71-7456-43B2-890C-CF01AD29D386}.Release|x86.Build.0 = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x64.ActiveCfg = Debug|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x64.Build.0 = Debug|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x86.ActiveCfg = Debug|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Debug|x86.Build.0 = Debug|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|Any CPU.Build.0 = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.ActiveCfg = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{ABAA6554-252E-13CE-1B40-0464A7DBA771} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{F2BBD9FE-F148-5687-ED21-3ABA515A9B22} = {ABAA6554-252E-13CE-1B40-0464A7DBA771}
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {F2BBD9FE-F148-5687-ED21-3ABA515A9B22}
{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}
{D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}
{EBCD2737-5E64-9C5F-5D8B-D0375EC50F43} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
{13F93445-B061-AC9E-97CA-8C4FA55DC418} = {EBCD2737-5E64-9C5F-5D8B-D0375EC50F43}
{64556F71-7456-43B2-890C-CF01AD29D386} = {13F93445-B061-AC9E-97CA-8C4FA55DC418}
{0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
{EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C}
{6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB}
EndGlobalSection
EndGlobal
+126
View File
@@ -0,0 +1,126 @@
# Earth Model Studio
天文教学模型**启动器**:主页管理/启动模型、从链接导入模型源并下载、设置模型源与启动内存分配。
> **分层约定(重要)**
> - `src/` = 启动器:扫描、下载、开窗口、显示启动进度。**不渲染、不含任何模型内容、不预置模型源**。
> - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。
>
> 结论:**模型相关代码全部直接存在模型目录里**,仓库根目录没有 `model-src/` / `model-sdk/` 这类旁路目录。
> 启动器只负责下载和启动;想加新内容 = 在 `model/<id>/` 里放模型,`src` 一行都不用改。
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**,一条命令全部编译
## 目录结构
```
EarthModelStudio/
├── EarthModelStudio.sln
├── Directory.Build.props # 公共构建属性(-p:TargetFramework=net10.0 可切 .NET 10)
├── build.sh / build.ps1 # 构建脚本(build/run/test/publish/models/pack-models)
├── src/ # ★ 启动器(没有渲染逻辑)
│ └── main/dotnet/EarthModelStudio/
│ ├── Models/ # 模型清单、设置(只有启动器需要的元数据)
│ ├── Services/ # 目录探测/设置/i18n/模型库/模型源/下载/内存预算/**ModelHost**
│ ├── ViewModels/ Views/ # 主页、下载、设置、模型窗口壳
│ └── Assets/i18n/ # 启动器界面语言包
├── src/test/dotnet/…Tests/ # 离屏校验(启动器页面 + 真实加载模型窗口)
├── model/ # ★ 模型的一切(源码 + 数据 + dll + 封面 + 语言包)
│ ├── _sdk/EarthModelStudio.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码)
│ ├── _engine/ # 共享引擎源码(渲染、界面、交互)
│ │ ├── src/ # CelestialView / PlanetTexture / EarthModelView …
│ │ └── PreviewGen/ # 用模型渲染器生成封面
│ ├── earth-rotation/
│ │ ├── earth-rotation.json # 清单
│ │ ├── src/ # 本模型源码(csproj + 入口工厂)
│ │ └── earth-rotation.model/ # dll + scene.json/land.json + preview.png + i18n
│ └── earth-revolution/ # 同上结构,封面是公转场景
└── dist/ # 发布产物(启动器 + 单独打包的模型)
```
模型库查找顺序:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 可执行文件旁 `model/` → 用户数据目录。
## 构建与运行
```bash
./build.sh build # 编译启动器
./build.sh models # 编译模型 dll + 生成封面(写进 model/)
./build.sh run # 运行
./build.sh test # 离屏校验:页面截图 + 真实加载模型窗口截图
./build.sh publish # 一次性编译三个平台(启动器,不含模型)
./build.sh pack-models # 编译模型后打包 -> dist/models-<version>.zip
./build.sh clean
```
Windows 用 `.\build.ps1`(参数相同)。
| 产物 | 平台 |
| --- | --- |
| `dist/mac-arm64/EarthModelStudio.app` | macOS Apple Silicon |
| `dist/win-x64/EarthModelStudio.exe` | Windows x64 |
| `dist/win-arm64/EarthModelStudio.exe` | Windows on ARM |
均为自包含单文件启动器,`model/` 目录为空(只有 README)。模型用 `pack-models` 单独分发。
## 模型契约
```csharp
public interface IModelFactory // 模型入口
{
int ApiVersion { get; } // 目前为 1
IModelRuntime Create();
}
public interface IModelRuntime : IDisposable
{
void Prepare(IModelContext context); // 后台线程:读数据、烘焙纹理、汇报进度
Control CreateView(IModelContext context); // UI 线程:模型自己做界面
}
public interface IModelContext
{
string ModelId { get; }
string ModelDirectory { get; }
string DataDirectory { get; }
string Language { get; }
int MemoryBudgetMb { get; }
void RequestClose();
void ReportProgress(double value, string? message = null);
void Log(string message);
}
```
启动器先弹进度窗,在后台调用 `Prepare`(模型用 `ReportProgress` 汇报真实进度),
再在 UI 线程调用 `CreateView`,把返回的控件直接铺满窗口 —— 除此之外什么都不做。
详细清单字段、数据格式、封面生成见 [`model/README.md`](model/README.md)。
## 模型窗口
- 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口
- 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集
- 快捷键 `Esc` 关闭、`F11` 全屏(其余快捷键由模型自己决定)
## 地球模型(model/_engine + model/<id>/src)
- **地表**:加载时烘焙 1024×512 等经纬度纹理 —— 海洋深度、沙漠/雨林/针叶林/苔原分带、极地冰盖、
山脉起伏(高度梯度参与光照)、云层、夜间城市辉光;每帧只做双线性采样 + 地形光照,60 FPS
- **自转**:球面像素渲染、晨昏线、大气边缘光、经纬网、地轴、太阳直射点;只有自转视角,
**没有节气定位**(节气属于公转)
- **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定位、HUD
- **交互**:滚轮 / 工具栏 −+ 缩放(0.6×–6×,带缓动);暂停后拖动可旋转地球或沿轨道拖动公转位置;
松手有惯性;缩放、视角、面板都有过渡动画
- 两个模型共用 `model/_engine` 的代码,各自 `src/` 只提供入口工厂;界面、文案、封面都在模型包里
## 模型源(git 仓库)
模型源就是普通 git 仓库,**仓库根目录下的 `model/` 文件夹即模型列表**。
支持 `https://github.com/<user>/<repo>.git`(GitLab / Gitee 同理,走 zip 归档,失败回退 `git clone --depth 1`)、
zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/<id>`,下载时把模型目录复制进本地 `model/`。
## 启动时运行内存分配
设置页的「启动时运行内存分配」类似启动器的 -Xmx:启动器把这份预算通过 `IModelContext.MemoryBudgetMb`
交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。
+110
View File
@@ -0,0 +1,110 @@
# ---------------------------------------------------------------------------
# Earth Model Studio 构建脚本(Windows PowerShell)
#
# .\build.ps1 编译
# .\build.ps1 run 运行
# .\build.ps1 test 离屏渲染校验
# .\build.ps1 publish 一次性编译三个平台 -> dist\
# .\build.ps1 models 编译模型功能程序集 + 生成封面
# .\build.ps1 pack-models 编译模型后整体打包 -> dist\models-x.y.z.zip
# .\build.ps1 clean 清理
#
# 分层约定:src\ 只是启动器,不含任何模型数据;模型全部放在 model\(外置数据)。
# ---------------------------------------------------------------------------
param(
[Parameter(Position = 0)]
[ValidateSet('build', 'run', 'test', 'publish', 'models', 'pack-models', 'clean', 'doctor')]
[string]$Task = 'build'
)
$ErrorActionPreference = 'Stop'
$Root = $PSScriptRoot
Set-Location $Root
$AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj'
$TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj'
$Sln = 'EarthModelStudio.sln'
$Version = '1.0.0'
function Publish-Rid([string]$Rid, [string]$OutDir) {
Write-Host "==> 编译 $Rid -> $OutDir"
dotnet publish $AppProj -c Release -r $Rid --self-contained true `
-p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true `
-p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false -o "$Root/$OutDir"
if (Test-Path "$Root/$OutDir/model") { Remove-Item -Recurse -Force "$Root/$OutDir/model" }
if (Test-Path "$Root/$OutDir/examples") { Remove-Item -Recurse -Force "$Root/$OutDir/examples" }
# 启动器不带模型:只建空的模型库目录,模型作为独立内容放置 / 下载
New-Item -ItemType Directory -Force -Path "$Root/$OutDir/model" | Out-Null
if (Test-Path "$Root/model/README.md") {
Copy-Item -Force "$Root/model/README.md" "$Root/$OutDir/model/README.md"
}
}
function Build-Models {
Write-Host '==> 编译模型功能程序集(源码就在各模型目录的 src\ 里)'
Get-ChildItem "$Root/model" -Directory | ForEach-Object {
$id = $_.Name
$src = Join-Path $_.FullName 'src'
if (-not (Test-Path $src)) { return }
$proj = Get-ChildItem $src -Filter *.csproj | Select-Object -First 1
if ($null -eq $proj) { return }
dotnet build $proj.FullName -c Release
$data = Join-Path $_.FullName "$id.model"
if (Test-Path $data) {
Get-ChildItem (Join-Path $src 'bin/Release/net8.0') -Filter *.dll | ForEach-Object {
if ($_.Name -eq 'EarthModelStudio.ModelSdk.dll') { return }
Copy-Item -Force $_.FullName $data
Write-Host " -> model/$id/$id.model/$($_.Name)"
}
}
}
Write-Host '==> 用模型自己的渲染器生成封面'
dotnet run --project $PreviewProj -c Release -- $Root
}
function Pack-Models {
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
$zip = "$Root/dist/models-$Version.zip"
if (Test-Path $zip) { Remove-Item -Force $zip }
Write-Host "==> 打包模型数据 -> dist/models-$Version.zip"
$stage = Join-Path $env:TEMP "ems-models-stage"
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
New-Item -ItemType Directory -Force -Path $stage | Out-Null
Get-ChildItem "$Root/model" -Recurse -File | Where-Object {
$_.FullName -notmatch '\\(bin|obj)\\' -and $_.Extension -ne '.user'
} | ForEach-Object {
$rel = $_.FullName.Substring("$Root/model".Length + 1)
$dest = Join-Path $stage $rel
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
Copy-Item -Force $_.FullName $dest
}
Compress-Archive -Path "$stage/*" -DestinationPath $zip -Force
Remove-Item -Recurse -Force $stage
}
switch ($Task) {
'build' { dotnet build $Sln -c Debug }
'run' { dotnet run --project $AppProj -c Debug }
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
'publish' {
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
Publish-Rid 'osx-arm64' 'dist/mac-arm64'
Publish-Rid 'win-x64' 'dist/win-x64'
Publish-Rid 'win-arm64' 'dist/win-arm64'
Write-Host '==> 三个平台编译完成(启动器不含模型数据),见 dist\' -ForegroundColor Green
Write-Host ' 模型数据用 .\build.ps1 pack-models 单独打包,或放进 <安装目录>\model 后再启动'
}
'models' {
Build-Models
}
'pack-models' {
Build-Models
Pack-Models
}
'clean' {
Remove-Item -Recurse -Force "$Root/build", "$Root/dist" -ErrorAction SilentlyContinue
Get-ChildItem "$Root/src" -Recurse -Directory -Include bin, obj |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
'doctor' { dotnet --info }
}
Executable
+159
View File
@@ -0,0 +1,159 @@
#!/bin/sh
# ---------------------------------------------------------------------------
# Earth Model Studio 构建脚本(macOS / Linux)
#
# ./build.sh build 编译(Debug)
# ./build.sh run 本机运行
# ./build.sh test 离屏渲染校验,截图输出到 build/screenshots
# ./build.sh publish 一次性编译三个平台 -> dist/
# ./build.sh models 编译模型功能程序集 + 生成模型封面(写进 model/<id>/<id>.model)
# ./build.sh pack-models 编译模型后把 model/ 整体打包 -> dist/models-x.y.z.zip
# ./build.sh clean 清理
#
# 分层约定:src/ 只是启动器,不含任何模型数据;模型全部放在 model/(外置数据)。
#
# publish 产出(启动器,模型库目录为空):
# dist/mac-arm64/EarthModelStudio.app macOS Apple Silicon
# dist/win-x64/EarthModelStudio.exe Windows x86_64
# dist/win-arm64/EarthModelStudio.exe Windows on ARM
# ---------------------------------------------------------------------------
set -e
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$ROOT_DIR"
APP_PROJ="src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj"
PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj"
SLN="EarthModelStudio.sln"
VERSION="1.0.0"
TASK="${1:-build}"
publish_rid() {
RID="$1"; OUT="$2"
echo ""
echo "==> 编译 ${RID} -> ${OUT}"
dotnet publish "$APP_PROJ" \
-c Release \
-r "$RID" \
--self-contained true \
-p:Version="$VERSION" \
-p:DebugType=none \
-p:PublishSingleFile=true \
-p:IncludeNativeLibrariesForSelfExtract=true \
-p:PublishTrimmed=false \
-o "$ROOT_DIR/$OUT"
# 启动器不带模型:只留一个空模型库目录,模型作为独立内容放置 / 下载
rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples"
mkdir -p "$ROOT_DIR/$OUT/model"
cp "$ROOT_DIR/model/README.md" "$ROOT_DIR/$OUT/model/README.md" 2>/dev/null || true
}
# 编译模型自己的功能程序集,并把 dll / 封面直接写进模型包
build_models() {
echo "==> 编译模型功能程序集(源码就在各模型目录的 src/ 里)"
for DIR in "$ROOT_DIR"/model/*/; do
ID=$(basename "$DIR")
[ -d "$DIR/src" ] || continue
PROJ=$(ls "$DIR"src/*.csproj 2>/dev/null | head -1)
[ -n "$PROJ" ] || continue
dotnet build "$PROJ" -c Release
if [ -d "$DIR$ID.model" ]; then
for DLL in "$DIR"src/bin/Release/net8.0/*.dll; do
[ -f "$DLL" ] || continue
NAME=$(basename "$DLL")
[ "$NAME" = "EarthModelStudio.ModelSdk.dll" ] && continue
cp "$DLL" "$DIR$ID.model/"
echo " -> model/$ID/$ID.model/$NAME"
done
fi
done
echo "==> 用模型自己的渲染器生成封面"
dotnet run --project "$PREVIEW_PROJ" -c Release -- "$ROOT_DIR"
}
# 把 model/ 里的模型数据单独打包(与启动器分开分发)
pack_models() {
mkdir -p "$ROOT_DIR/dist"
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
rm -f "$ZIP"
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
( cd "$ROOT_DIR" && zip -qr "$ZIP" model \
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
du -sh "$ZIP"
}
package_mac_app() {
DIST="$ROOT_DIR/dist/mac-arm64"
APP="$DIST/EarthModelStudio.app"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cat > "$APP/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key><string>Earth Model Studio</string>
<key>CFBundleDisplayName</key><string>Earth Model Studio</string>
<key>CFBundleIdentifier</key><string>cn.neorf.earthmodelstudio</string>
<key>CFBundleVersion</key><string>${VERSION}</string>
<key>CFBundleShortVersionString</key><string>${VERSION}</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleExecutable</key><string>EarthModelStudio</string>
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
<key>LSMinimumSystemVersion</key><string>11.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST
for f in "$DIST"/*; do
base=$(basename "$f")
[ "$base" = "EarthModelStudio.app" ] && continue
mv "$f" "$APP/Contents/MacOS/"
done
chmod +x "$APP/Contents/MacOS/EarthModelStudio"
echo "==> 已打包 $APP"
}
case "$TASK" in
build)
dotnet build "$SLN" -c Debug
;;
run)
dotnet run --project "$APP_PROJ" -c Debug
;;
test)
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots"
;;
publish)
mkdir -p "$ROOT_DIR/dist"
publish_rid "osx-arm64" "dist/mac-arm64"
publish_rid "win-x64" "dist/win-x64"
publish_rid "win-arm64" "dist/win-arm64"
package_mac_app
echo ""
echo "==> 三个平台编译完成(启动器不含模型数据):"
du -sh "$ROOT_DIR/dist"/* 2>/dev/null || true
echo " 模型数据用 ./build.sh pack-models 单独打包,或放进 <安装目录>/model 后再启动"
;;
models)
build_models
;;
pack-models)
build_models
pack_models
;;
clean)
rm -rf "$ROOT_DIR/build" "$ROOT_DIR/dist"
find "$ROOT_DIR/src" -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + 2>/dev/null || true
echo "==> 已清理"
;;
doctor)
dotnet --info | head -20
;;
*)
echo "未知任务: $TASK"
echo "可用: build | run | test | publish | models | pack-models | clean | doctor"
exit 1
;;
esac
+125
View File
@@ -0,0 +1,125 @@
# 模型库(model/)
这个目录是**模型**,包含模型自己的**源码 + 数据 + 功能程序集 + 封面 + 语言包**。
`src/`(启动器)只做三件事:扫描模型、下载模型、开窗口加载模型。**启动器没有任何渲染逻辑**。
> 模型相关的一切都在 `model/` 里:共享引擎源码 `model/_engine/`、契约源码 `model/_sdk/`、
> 每个模型自己的源码 `model/<id>/src/`,编译产物与数据 `model/<id>/<id>.model/`。
> 仓库根目录只有 `src/`(启动器)和 `model/`,没有任何旁路目录。
- 启动器查找模型库的顺序:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 可执行文件旁边 `model/` → 用户数据目录
- 一个模型 = 一个文件夹,文件夹名即模型 id;`_sdk/`、`_engine/` 是下划线开头的共享目录,不会被当成模型
- 模型可以单独打包、单独分发,也可以放进 git 仓库当模型源
## 目录结构
```
model/
_sdk/EarthModelStudio.ModelSdk/ # 模型契约(启动器与模型唯一的共享代码)
_engine/ # 共享引擎源码(可选,只有地球模型用)
src/ # CelestialView / PlanetTexture / EarthModelView / SphereRaster…
PreviewGen/ # 用模型渲染器生成封面的小工具
<模型 id>/
<模型 id>.json # 清单:名称、i18n、版本、程序集入口、封面
src/ # 模型自己的源码(csproj + IModelFactory 实现)
<模型 id>.model/ # 模型包(可分发的部分)
EarthRotationModel.dll # 功能程序集(实现 IModelFactory)
scene.json # 场景数据(内容由模型定义)
land.json # 贴图/轮廓数据(可选)
preview.png # 封面图(启动器只显示,不渲染)
i18n/zh-CN.json # 界面文案(模型自己读)
i18n/en.json
```
## `<id>.json`(模型清单,启动器只读它)
```json
{
"id": "earth-rotation",
"name": "Earth Rotation",
"nameI18n": { "zh-CN": "地球自转", "en": "Earth Rotation" },
"description": "……",
"descriptionI18n": { "zh-CN": "……", "en": "……" },
"version": "1.0.0",
"author": "NeoRF",
"tags": ["astronomy", "geography"],
"assembly": "EarthRotationModel.dll",
"type": "NeoRF.EarthModels.RotationModelFactory",
"preview": "preview.png",
"apiVersion": 1
}
```
| 字段 | 作用 |
| --- | --- |
| `assembly` | 功能程序集文件名,相对 `<id>.model`;留空按 `<id>.dll` 找 |
| `type` | 实现 `IModelFactory` 的完整类型名;留空则自动找第一个实现 |
| `preview` | 封面图,默认 `preview.png` |
| `apiVersion` | 模型契约版本,目前为 1 |
## 模型契约(model/_sdk)
模型只依赖一个极小的契约程序集 `EarthModelStudio.ModelSdk`(源码在 `model/_sdk/`):
```csharp
public interface IModelFactory
{
int ApiVersion { get; }
IModelRuntime Create();
}
public interface IModelRuntime : IDisposable
{
void Prepare(IModelContext context); // 后台线程:读数据、算纹理,可汇报进度
Control CreateView(IModelContext context); // UI 线程:构建界面
}
public interface IModelContext
{
string ModelId { get; }
string ModelDirectory { get; }
string DataDirectory { get; }
string Language { get; }
int MemoryBudgetMb { get; }
void RequestClose();
void ReportProgress(double value, string? message = null);
void Log(string message);
}
```
模型 `CreateView` 返回的控件会铺满窗口客户区 —— **工具栏、动画、文字、交互全由模型自己实现**。
启动器只提供窗口、语言、内存预算和关闭能力。
## `scene.json` / `land.json`
这两个文件的内容完全由模型自己定义(启动器不解析)。地球模型用的是:
- `scene.json`:`defaultView`、`views`、行星参数、颜色、轨道、`lessons` 教学要点
- `land.json`:大陆轮廓,`{ "polygons": [ { "name": "...", "points": [[lon,lat], ...] } ] }`
## 语言包
`<id>.model/i18n/<language>.json` 是扁平的 `键: 文案` 映射,模型自己读取。
地球模型用到的键:`title`、`view.rotation`、`play`、`pause`、`speed`、`reset`、`labels`、`orbit`、`grid`、`tilt`、
`lessons`、`seasons`、`close`、`sun`、`earth`、`north`、`south`、`subsolar`、`spinInfo`、`orbitInfo`、
`declinationInfo`、`dateInfo`、`season.*`。
## 封面
封面是 `preview.png`,由 `model/_engine/PreviewGen` 用**模型自己的渲染器**生成:
```bash
./build.sh models # 编译模型 dll + 生成所有模型封面
```
## 做一个新模型
1. 在 `model/<id>/src/` 里新建类库项目(可引用 `model/_engine/src` 的共享代码,也可完全自己写)
2. 写一个 `IModelFactory` 实现:`Prepare` 里读数据算纹理并 `ReportProgress`,`CreateView` 里返回控件
3. 在 `model/<id>/` 放清单和 `<id>.model/` 数据目录,用 `assembly` / `type` 指向你的 dll
4. `./build.sh models` 会自动编译每个模型、把 dll 复制进对应 `<id>.model/`,并生成封面
## 作为模型源分发
把 `model/` 放到任意 git 仓库根目录并推送,用户在「下载」页粘贴仓库链接即可;
启动器读取仓库里的 `model/` 文件夹,一栏一个模型。
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>NeoRF.EarthModels</RootNamespace>
<AssemblyName>EarthModelPreview</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<!-- 直接编译共享引擎源码:封面必须由模型自己的渲染器画 -->
<Compile Include="../src/**/*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" />
</ItemGroup>
</Project>
+113
View File
@@ -0,0 +1,113 @@
using System;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Media.Imaging;
using NeoRF.EarthModels;
namespace NeoRF.EarthModels.Preview;
/// <summary>
/// 封面生成工具:用模型自己的渲染器给每个模型画一张封面 preview.png。
/// 封面在模型包里,启动器只负责显示 —— 所以公转模型的封面一定就是公转场景。
/// 用法:dotnet run --project model-src/tools/PreviewGen -- &lt;仓库根&gt;
/// </summary>
internal static class Program
{
private const int Width = 768;
private const int Height = 316;
[STAThread]
public static int Main(string[] args)
{
var root = args.Length > 0 ? args[0] : Directory.GetCurrentDirectory();
var modelRoot = Path.Combine(root, "model");
if (!Directory.Exists(modelRoot))
{
Console.Error.WriteLine($"找不到模型库: {modelRoot}");
return 1;
}
var bench = args.Contains("--bench");
AppBuilder.Configure<Application>()
.UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting();
foreach (var modelDir in Directory.GetDirectories(modelRoot))
{
var id = Path.GetFileName(modelDir);
if (id.StartsWith(".")) continue;
var dataDir = Path.Combine(modelDir, id + ".model");
var sceneFile = Path.Combine(dataDir, "scene.json");
if (!File.Exists(sceneFile)) continue;
var runtime = SceneRuntime.Load(dataDir, 2048);
var texts = ModelStrings.Load(dataDir, "zh-CN");
var revolution = string.Equals(runtime.Scene.DefaultView, "revolution", StringComparison.OrdinalIgnoreCase);
var view = new CelestialView
{
Scene = runtime,
Texts = texts,
View = revolution ? SceneView.Revolution : SceneView.Rotation,
IsPlaying = false,
ShowHud = false,
ShowLabels = false,
ShowOrbit = true,
ShowGraticule = true,
Width = Width,
Height = Height
};
view.Measure(new Size(Width, Height));
view.Arrange(new Rect(0, 0, Width, Height));
view.JumpToOrbit(revolution ? 45 : 0);
view.JumpToSpin(20);
if (bench)
{
// 真实窗口尺寸下的帧耗时
view.Width = 1240;
view.Height = 820;
view.Measure(new Size(1240, 820));
view.Arrange(new Rect(0, 0, 1240, 820));
// 模拟播放态(运动时降分辨率),分别测静止高清帧与运动帧
var animField = typeof(NeoRF.EarthModels.CelestialView)
.GetField("_animating", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var sw = System.Diagnostics.Stopwatch.StartNew();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
var still = sw.Elapsed.TotalMilliseconds / 20;
animField?.SetValue(view, true);
sw.Restart();
for (var frame = 0; frame < 20; frame++)
{
view.JumpToSpin(20 + frame * 3);
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
tmp.Render(view);
}
sw.Stop();
Console.WriteLine($"{id}: 静止 {still:0.0} ms/frame · 播放 {sw.Elapsed.TotalMilliseconds / 20:0.0} ms/frame");
continue;
}
var outFile = Path.Combine(dataDir, "preview.png");
using (var bitmap = new RenderTargetBitmap(new PixelSize(Width, Height), new Vector(96, 96)))
{
bitmap.Render(view);
bitmap.Save(outFile);
}
Console.WriteLine($"preview -> {outFile}");
}
return 0;
}
}
File diff suppressed because it is too large. Load diff
+560
View File
@@ -0,0 +1,560 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels;
/// <summary>
/// 模型自己的界面:画布 + 工具栏 + 速度条 + 教学要点。
/// 带过渡动画、缩放控件与「暂停后可拖动」提示;启动器只负责开窗口。
/// </summary>
public sealed class EarthModelView : UserControl
{
private static readonly IBrush PanelBg = new SolidColorBrush(Color.Parse("#C40A1020"));
private static readonly IBrush ControlBg = new SolidColorBrush(Color.Parse("#16233C"));
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#2E6BE6"));
private static readonly IBrush TitleBrush = new SolidColorBrush(Color.Parse("#F2F6FF"));
private static readonly IBrush TextBrush = new SolidColorBrush(Color.Parse("#DCE7FA"));
private static readonly IBrush MutedBrush = new SolidColorBrush(Color.Parse("#7E93B8"));
private static readonly IBrush FaintBrush = new SolidColorBrush(Color.Parse("#61779C"));
private static readonly IBrush BodyBrush = new SolidColorBrush(Color.Parse("#8CA0C4"));
private static readonly TimeSpan HoverDuration = TimeSpan.FromMilliseconds(120);
private static readonly TimeSpan PanelDuration = TimeSpan.FromMilliseconds(190);
private readonly IModelContext _context;
private readonly ModelStrings _texts;
private readonly SceneRuntime _runtime;
private readonly List<string> _views;
private readonly List<ModelButton> _viewButtons = new();
private readonly CelestialView _canvas;
private Border? _viewSwitch;
private StackPanel? _seasonPanel;
private Border? _lessons;
private ModelButton? _playButton;
private TextBlock? _zoomText;
private bool _playing = true;
private bool _labels = true;
private bool _orbit = true;
private bool _grid = true;
private bool _tilt;
private bool _showLessons = true;
public EarthModelView(IModelContext context, SceneRuntime runtime)
{
_context = context;
_runtime = runtime;
_texts = ModelStrings.Load(context.DataDirectory, context.Language);
_views = ResolveViews(runtime.Scene);
Background = new SolidColorBrush(Color.Parse("#05070F"));
_canvas = new CelestialView
{
Scene = runtime,
Texts = _texts,
ShowLabels = true,
ShowOrbit = true,
ShowGraticule = true,
FrameRate = 60,
View = IsRevolution ? SceneView.Revolution : SceneView.Rotation
};
_canvas.JumpToOrbit(StartAngle);
_canvas.JumpToSpin(20);
_canvas.ZoomChanged += zoom =>
{
if (_zoomText != null) _zoomText.Text = $"{zoom * 100:0}%";
};
var root = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto") };
var top = BuildTopBar();
root.Children.Add(top);
var stage = new Grid();
stage.Children.Add(_canvas);
_lessons = BuildLessonsPanel();
stage.Children.Add(_lessons);
Grid.SetRow(stage, 1);
root.Children.Add(stage);
var bottom = BuildBottomBar();
Grid.SetRow(bottom, 2);
root.Children.Add(bottom);
Content = root;
ApplyVisibility();
// 打开时整窗淡入,避免“啪”地出现
Opacity = 0;
Transitions = new Transitions
{
new DoubleTransition
{
Property = OpacityProperty,
Duration = TimeSpan.FromMilliseconds(260),
Easing = new CubicEaseOut()
}
};
AttachedToVisualTree += (_, _) => Opacity = 1;
}
private string CurrentView { get; set; } = "rotation";
private double StartAngle => IsRevolution ? 60 : 0;
private bool IsRevolution => string.Equals(CurrentView, "revolution", StringComparison.OrdinalIgnoreCase);
private bool HasViewSwitch => _views.Count > 1;
private static string NormalizeView(string? view)
=> string.Equals(view, "revolution", StringComparison.OrdinalIgnoreCase) ? "revolution" : "rotation";
private List<string> ResolveViews(SceneDefinition scene)
{
var list = new List<string>();
foreach (var v in scene.Views)
{
var normalized = NormalizeView(v);
if (!list.Contains(normalized)) list.Add(normalized);
}
if (list.Count == 0) list.Add(NormalizeView(scene.DefaultView));
CurrentView = list[0];
return list;
}
// ---------------------------------------------------------------- 顶部
private Control BuildTopBar()
{
var close = MakeButton(_texts["close"], () => _context.RequestClose());
var title = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center };
title.Children.Add(new TextBlock
{
Text = _texts.Pick(_runtime.Scene.NameI18n, _texts["title"]),
Foreground = TitleBrush,
FontSize = 13,
FontWeight = FontWeight.SemiBold
});
title.Children.Add(new TextBlock
{
Text = _texts.Pick(_runtime.Scene.DescriptionI18n, ""),
Foreground = MutedBrush,
FontSize = 10.5,
MaxWidth = 330,
TextTrimming = TextTrimming.CharacterEllipsis
});
var switchPanel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };
switchPanel.Children.Add(MakeViewButton("rotation", _texts["view.rotation"]));
switchPanel.Children.Add(MakeViewButton("revolution", _texts["view.revolution"]));
_viewSwitch = new Border
{
Background = ControlBg,
CornerRadius = new CornerRadius(10),
Padding = new Thickness(3),
Margin = new Thickness(16, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
Child = switchPanel
};
var actions = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 7,
VerticalAlignment = VerticalAlignment.Center
};
// 缩放:− / 百分比 / + / 复位
actions.Children.Add(MakeButton("−", () => _canvas.ZoomBy(1 / 1.25), compact: true));
_zoomText = new TextBlock
{
Text = "100%",
Foreground = TextBrush,
FontSize = 11,
Width = 38,
VerticalAlignment = VerticalAlignment.Center,
TextAlignment = TextAlignment.Center
};
actions.Children.Add(_zoomText);
actions.Children.Add(MakeButton("+", () => _canvas.ZoomBy(1.25), compact: true));
actions.Children.Add(MakeButton("⟲", () =>
{
_canvas.ResetView();
_canvas.JumpToOrbit(StartAngle);
_canvas.JumpToSpin(20);
}, compact: true));
_playButton = MakeButton(_texts["pause"], TogglePlay);
actions.Children.Add(_playButton);
actions.Children.Add(MakeButton(_texts["reset"], () =>
{
_canvas.ResetAnimation();
_canvas.JumpToOrbit(StartAngle);
}));
actions.Children.Add(MakeToggle(_texts["labels"], _labels, on => { _labels = on; _canvas.ShowLabels = on; }));
actions.Children.Add(MakeToggle(_texts["orbit"], _orbit, on => { _orbit = on; _canvas.ShowOrbit = on; }));
actions.Children.Add(MakeToggle(_texts["grid"], _grid, on => { _grid = on; _canvas.ShowGraticule = on; }));
actions.Children.Add(MakeToggle(_texts["tilt"], _tilt, on => { _tilt = on; _canvas.ExaggerateTilt = on; }));
actions.Children.Add(MakeButton(_texts["lessons"], () => SetLessonsVisible(!_showLessons)));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") };
grid.Children.Add(close);
Grid.SetColumn(title, 1);
title.Margin = new Thickness(14, 0, 0, 0);
grid.Children.Add(title);
Grid.SetColumn(_viewSwitch, 2);
grid.Children.Add(_viewSwitch);
Grid.SetColumn(actions, 4);
grid.Children.Add(actions);
return new Border { Background = PanelBg, Padding = new Thickness(16, 11), Child = grid };
}
private ModelButton MakeViewButton(string view, string label)
{
var button = MakeButton(label, () => SwitchView(view));
button.SetBase(string.Equals(CurrentView, view, StringComparison.OrdinalIgnoreCase) ? Accent : ControlBg);
button.Tag = view;
button.IsVisible = _views.Contains(view);
_viewButtons.Add(button);
return button;
}
private ModelButton MakeToggle(string label, bool initial, Action<bool> changed)
{
var state = initial;
ModelButton? button = null;
button = MakeButton(label, () =>
{
state = !state;
changed(state);
button?.SetBase(state ? Accent : ControlBg);
});
button.SetBase(initial ? Accent : ControlBg);
return button;
}
private void SwitchView(string view)
{
CurrentView = NormalizeView(view);
_canvas.View = IsRevolution ? SceneView.Revolution : SceneView.Rotation;
_canvas.JumpToOrbit(StartAngle);
foreach (var button in _viewButtons)
button.SetBase(string.Equals(button.Tag as string, CurrentView, StringComparison.OrdinalIgnoreCase)
? Accent
: ControlBg);
ApplyVisibility();
}
// ---------------------------------------------------------------- 底部
private Control BuildBottomBar()
{
var speedLabel = new TextBlock
{
Text = _texts["speed"],
Foreground = new SolidColorBrush(Color.Parse("#9DB0D0")),
VerticalAlignment = VerticalAlignment.Center
};
var slider = new Slider
{
Minimum = 0.25,
Maximum = 4,
Value = 1,
Margin = new Thickness(12, 0, 0, 0),
Width = 180
};
var speedText = new TextBlock
{
Text = "1×",
Foreground = TextBrush,
VerticalAlignment = VerticalAlignment.Center,
Width = 46,
Margin = new Thickness(6, 0, 0, 0)
};
slider.ValueChanged += (_, e) =>
{
_canvas.Speed = e.NewValue;
speedText.Text = $"{e.NewValue:0.##}×";
};
var hint = new TextBlock
{
Text = _texts["hint"],
Foreground = FaintBrush,
FontSize = 10.5,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(22, 0, 0, 0),
TextTrimming = TextTrimming.CharacterEllipsis
};
_seasonPanel = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 6,
VerticalAlignment = VerticalAlignment.Center
};
_seasonPanel.Children.Add(new TextBlock
{
Text = _texts["seasons"],
Foreground = MutedBrush,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0)
});
_seasonPanel.Children.Add(MakeSeasonButton(0));
_seasonPanel.Children.Add(MakeSeasonButton(90));
_seasonPanel.Children.Add(MakeSeasonButton(180));
_seasonPanel.Children.Add(MakeSeasonButton(270));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") };
grid.Children.Add(speedLabel);
Grid.SetColumn(slider, 1);
grid.Children.Add(slider);
Grid.SetColumn(speedText, 2);
grid.Children.Add(speedText);
Grid.SetColumn(hint, 3);
grid.Children.Add(hint);
Grid.SetColumn(_seasonPanel, 4);
grid.Children.Add(_seasonPanel);
return new Border { Background = PanelBg, Padding = new Thickness(16, 10), Child = grid };
}
private ModelButton MakeSeasonButton(double angle)
{
var key = angle switch
{
0 => "season.springEquinox",
90 => "season.summerSolstice",
180 => "season.autumnEquinox",
_ => "season.winterSolstice"
};
return MakeButton(_texts[key], () =>
{
if (!IsRevolution) SwitchView("revolution");
_canvas.JumpToOrbit(angle);
});
}
// ---------------------------------------------------------------- 教学要点
private Border BuildLessonsPanel()
{
var header = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
header.Children.Add(new TextBlock
{
Text = _texts["lessons"],
Foreground = TitleBrush,
FontWeight = FontWeight.SemiBold,
FontSize = 12.5,
VerticalAlignment = VerticalAlignment.Center
});
var close = MakeButton("✕", () => SetLessonsVisible(false));
close.SetBase(Brushes.Transparent);
Grid.SetColumn(close, 1);
header.Children.Add(close);
var list = new StackPanel { Spacing = 2 };
foreach (var lesson in _runtime.Scene.Lessons)
{
var title = new TextBlock
{
Text = _texts.Pick(lesson.TitleI18n, ""),
Foreground = new SolidColorBrush(Color.Parse("#CFE0FF")),
FontSize = 12,
FontWeight = FontWeight.SemiBold,
TextWrapping = TextWrapping.Wrap
};
var body = new TextBlock
{
Text = _texts.Pick(lesson.BodyI18n, ""),
Foreground = BodyBrush,
FontSize = 11,
TextWrapping = TextWrapping.Wrap
};
var stack = new StackPanel { Spacing = 3 };
stack.Children.Add(title);
stack.Children.Add(body);
var button = new Button
{
Content = stack,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left,
Padding = new Thickness(8, 7),
Margin = new Thickness(0, 1),
Cursor = new Cursor(StandardCursorType.Hand),
Transitions = new Transitions
{
new BrushTransition { Property = BackgroundProperty, Duration = HoverDuration }
}
};
var captured = lesson;
button.Click += (_, _) => ApplyLesson(captured);
button.PointerEntered += (_, _) => button.Background = new SolidColorBrush(Color.Parse("#1B2A47"));
button.PointerExited += (_, _) => button.Background = Brushes.Transparent;
list.Children.Add(button);
}
var content = new StackPanel { Spacing = 8 };
content.Children.Add(header);
content.Children.Add(new ScrollViewer
{
Content = list,
MaxHeight = 380,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto
});
var panel = new Border
{
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Center,
Width = 272,
Margin = new Thickness(0, 58, 16, 80),
Background = new SolidColorBrush(Color.Parse("#D00B1226")),
CornerRadius = new CornerRadius(14),
Padding = new Thickness(13),
BorderBrush = new SolidColorBrush(Color.Parse("#26374F")),
BorderThickness = new Thickness(1),
Child = content,
RenderTransform = new TranslateTransform(0, 0)
};
panel.Transitions = new Transitions
{
new DoubleTransition { Property = OpacityProperty, Duration = PanelDuration, Easing = new CubicEaseOut() },
new DoubleTransition
{
Property = TranslateTransform.XProperty,
Duration = PanelDuration,
Easing = new CubicEaseOut()
}
};
return panel;
}
private void SetLessonsVisible(bool visible)
{
_showLessons = visible;
if (_lessons == null) return;
if (visible)
{
_lessons.IsVisible = true;
_lessons.Opacity = 1;
if (_lessons.RenderTransform is TranslateTransform transform) transform.X = 0;
return;
}
_lessons.Opacity = 0;
if (_lessons.RenderTransform is TranslateTransform hidden) hidden.X = 26;
var timer = new DispatcherTimer { Interval = PanelDuration };
timer.Tick += (_, _) =>
{
timer.Stop();
if (!_showLessons && _lessons != null) _lessons.IsVisible = false;
};
timer.Start();
}
private void ApplyLesson(Lesson lesson)
{
if (!string.IsNullOrWhiteSpace(lesson.View))
{
var view = NormalizeView(lesson.View);
if (!string.Equals(view, CurrentView, StringComparison.OrdinalIgnoreCase)) SwitchView(view);
}
if (lesson.AngleDeg.HasValue) _canvas.JumpToOrbit(lesson.AngleDeg.Value);
}
// ---------------------------------------------------------------- 工具
private ModelButton MakeButton(string text, Action onClick, bool compact = false)
{
var button = new ModelButton
{
Content = new TextBlock { Text = text, FontSize = 11.5 },
Foreground = TextBrush,
BorderThickness = new Thickness(0),
CornerRadius = new CornerRadius(8),
Padding = compact ? new Thickness(8, 4) : new Thickness(9, 5),
MinWidth = compact ? 26 : 0,
VerticalAlignment = VerticalAlignment.Center,
Cursor = new Cursor(StandardCursorType.Hand)
};
button.SetBase(ControlBg);
button.Click += (_, _) => onClick();
return button;
}
private void TogglePlay()
{
_playing = !_playing;
_canvas.IsPlaying = _playing;
if (_playButton?.Content is TextBlock block)
block.Text = _playing ? _texts["pause"] : _texts["play"];
}
private void ApplyVisibility()
{
if (_viewSwitch != null) _viewSwitch.IsVisible = HasViewSwitch;
if (_lessons != null) _lessons.IsVisible = _showLessons;
if (_seasonPanel != null) _seasonPanel.IsVisible = IsRevolution;
}
/// <summary>带悬停过渡的按钮:本地基础色 + 悬停提亮。</summary>
private sealed class ModelButton : Button
{
private IBrush _base = ControlBg;
private IBrush _hover = ControlBg;
public ModelButton()
{
Transitions = new Transitions
{
new BrushTransition { Property = BackgroundProperty, Duration = HoverDuration }
};
}
public void SetBase(IBrush brush)
{
_base = brush;
_hover = Lighten(brush);
Background = brush;
}
protected override void OnPointerEntered(PointerEventArgs e)
{
base.OnPointerEntered(e);
Background = _hover;
}
protected override void OnPointerExited(PointerEventArgs e)
{
base.OnPointerExited(e);
Background = _base;
}
private static IBrush Lighten(IBrush brush)
{
if (brush is not SolidColorBrush solid) return brush;
var c = solid.Color;
return new SolidColorBrush(Color.FromArgb(c.A,
(byte)Math.Min(255, c.R + 26),
(byte)Math.Min(255, c.G + 26),
(byte)Math.Min(255, c.B + 30)));
}
}
}
+37
View File
@@ -0,0 +1,37 @@
using System;
using Avalonia.Controls;
using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels;
/// <summary>
/// 地球模型共享运行时:读自己目录下的 scene.json / land.json / i18n,
/// 然后把自带界面交给启动器。启动器完全不知道“地球”“节气”这些东西。
/// </summary>
public sealed class EarthModelRuntime : IModelRuntime
{
public const int SupportedApiVersion = 1;
private SceneRuntime? _scene;
/// <summary>后台准备:读场景、生成地表纹理(耗时都花在这里,进度条能实时走)。</summary>
public void Prepare(IModelContext context)
{
context.ReportProgress(0.03, "读取场景数据");
_scene = SceneRuntime.Load(context.DataDirectory, context.MemoryBudgetMb, context.ReportProgress);
context.Log($"[{context.ModelId}] 场景已加载:{_scene.Scene.DefaultView}," +
$"地表纹理 {(_scene.Texture == null ? "无" : _scene.Texture.Width + "×" + _scene.Texture.Height)}");
}
/// <summary>UI 线程构建界面(很快)。</summary>
public Control CreateView(IModelContext context)
{
context.ReportProgress(0.78, "构建界面");
_scene ??= SceneRuntime.Load(context.DataDirectory, context.MemoryBudgetMb, context.ReportProgress);
var view = new EarthModelView(context, _scene);
context.ReportProgress(1.0, "准备就绪");
return view;
}
public void Dispose() => GC.SuppressFinalize(this);
}
+159
View File
@@ -0,0 +1,159 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NeoRF.EarthModels;
/// <summary>&lt;id&gt;.model/land.json —— 简化的大陆轮廓(经纬度多边形)。</summary>
public sealed class LandData
{
[JsonPropertyName("polygons")] public List<LandPolygon> Polygons { get; set; } = new();
public static LandData? Load(string path)
{
if (!File.Exists(path)) return null;
try
{
return JsonSerializer.Deserialize<LandData>(File.ReadAllText(path), ModelJson.Options);
}
catch (Exception ex)
{
Console.Error.WriteLine($"解析地表数据失败 {path}: {ex.Message}");
return null;
}
}
}
public sealed class LandPolygon
{
[JsonPropertyName("name")] public string? Name { get; set; }
/// <summary>[[lon, lat], ...]</summary>
[JsonPropertyName("points")] public List<double[]> Points { get; set; } = new();
}
/// <summary>
/// 等经纬度栅格地表掩膜(0=海洋 255=陆地),双线性采样。
/// 每个模型只生成一次,受内存预算约束。
/// </summary>
public sealed class LandMask
{
public int Width { get; init; }
public int Height { get; init; }
public byte[] Bits { get; init; } = Array.Empty<byte>();
public long ByteSize => Bits.LongLength;
public static LandMask Build(LandData data, int width = 1440, int height = 720)
{
var bits = new byte[width * height];
foreach (var poly in data.Polygons)
{
if (poly.Points.Count < 3) continue;
var pts = Unwrap(poly.Points);
if (pts.Count < 3) continue;
for (var shift = -1; shift <= 1; shift++)
Rasterize(bits, width, height, pts, shift * 360.0);
}
return new LandMask { Width = width, Height = height, Bits = bits };
}
private static List<(double Lon, double Lat)> Unwrap(List<double[]> points)
{
var result = new List<(double, double)>(points.Count);
if (points.Count == 0 || points[0].Length < 2) return result;
var prev = points[0][0];
result.Add((prev, points[0][1]));
for (var i = 1; i < points.Count; i++)
{
if (points[i].Length < 2) continue;
var lon = points[i][0];
while (lon - prev > 180) lon -= 360;
while (prev - lon > 180) lon += 360;
result.Add((lon, points[i][1]));
prev = lon;
}
return result;
}
private static void Rasterize(byte[] bits, int w, int h, List<(double Lon, double Lat)> pts, double lonShift)
{
var n = pts.Count;
var xs = new double[n];
var ys = new double[n];
double minY = double.MaxValue, maxY = double.MinValue;
for (var i = 0; i < n; i++)
{
xs[i] = (pts[i].Lon + lonShift + 180.0) / 360.0 * w;
ys[i] = (90.0 - pts[i].Lat) / 180.0 * h;
if (ys[i] < minY) minY = ys[i];
if (ys[i] > maxY) maxY = ys[i];
}
var y0 = Math.Max(0, (int)Math.Floor(minY));
var y1 = Math.Min(h - 1, (int)Math.Ceiling(maxY));
var crossings = new List<double>(16);
for (var y = y0; y <= y1; y++)
{
var sy = y + 0.5;
crossings.Clear();
for (var i = 0; i < n; i++)
{
var j = (i + 1) % n;
double ya = ys[i], yb = ys[j];
if (!((ya <= sy && yb > sy) || (yb <= sy && ya > sy))) continue;
var t = (sy - ya) / (yb - ya);
crossings.Add(xs[i] + t * (xs[j] - xs[i]));
}
if (crossings.Count < 2) continue;
crossings.Sort();
for (var k = 0; k + 1 < crossings.Count; k += 2)
{
var xa = (int)Math.Ceiling(crossings[k] - 0.5);
var xb = (int)Math.Floor(crossings[k + 1] - 0.5);
if (xb < xa) continue;
if (xb - xa >= w - 1)
{
for (var x = 0; x < w; x++) bits[y * w + x] = 255;
continue;
}
for (var x = xa; x <= xb; x++)
{
var mx = x % w;
if (mx < 0) mx += w;
bits[y * w + mx] = 255;
}
}
}
}
/// <summary>返回 0..1 的陆地覆盖度。</summary>
public double Sample(double lonDeg, double latDeg)
{
var u = (lonDeg + 180.0) / 360.0 * Width - 0.5;
var v = (90.0 - latDeg) / 180.0 * Height - 0.5;
var x0 = (int)Math.Floor(u);
var y0 = (int)Math.Floor(v);
var fx = u - x0;
var fy = v - y0;
double sum = 0;
for (var dy = 0; dy < 2; dy++)
{
var y = y0 + dy;
if (y < 0) y = 0;
if (y >= Height) y = Height - 1;
var wy = dy == 0 ? 1 - fy : fy;
for (var dx = 0; dx < 2; dx++)
{
var x = x0 + dx;
var mx = x % Width;
if (mx < 0) mx += Width;
var wx = dx == 0 ? 1 - fx : fx;
sum += Bits[y * Width + mx] * wx * wy;
}
}
return sum / 255.0;
}
}
+27
View File
@@ -0,0 +1,27 @@
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NeoRF.EarthModels;
/// <summary>模型自己的 JSON 读写(不依赖启动器)。</summary>
public static class ModelJson
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
public static T? Read<T>(string path)
{
if (!File.Exists(path)) return default;
return JsonSerializer.Deserialize<T>(File.ReadAllText(path), Options);
}
}
+182
View File
@@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.Json;
namespace NeoRF.EarthModels;
/// <summary>
/// 模型自己的一份文案。优先读模型数据目录里的 <c>i18n/&lt;language&gt;.json</c>,
/// 缺失时回退到代码内的默认文案,保证模型在没有语言包时也能完整显示。
/// 启动器不再持有任何模型相关文案。
/// </summary>
public sealed class ModelStrings
{
private readonly Dictionary<string, string> _texts;
public string Language { get; }
private ModelStrings(string language, Dictionary<string, string> texts)
{
Language = language;
_texts = texts;
}
public static ModelStrings Default { get; } = new("zh-CN", DefaultTexts.Zh);
public string this[string key]
=> _texts.TryGetValue(key, out var value) ? value
: DefaultTexts.Zh.TryGetValue(key, out var fallback) ? fallback
: key;
public string F(string key, params object[] args)
=> string.Format(CultureInfo.InvariantCulture, this[key], args);
public string Pick(Dictionary<string, string>? i18n, string fallback)
{
if (i18n == null) return fallback;
if (i18n.TryGetValue(Language, out var exact) && !string.IsNullOrWhiteSpace(exact)) return exact;
foreach (var pair in i18n)
{
if (Language.StartsWith(pair.Key, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(pair.Value))
return pair.Value;
}
if (i18n.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh;
return fallback;
}
public static ModelStrings Load(string dataDirectory, string language)
{
var zh = new Dictionary<string, string>(DefaultTexts.Zh);
var isEnglish = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
var chosen = isEnglish ? new Dictionary<string, string>(DefaultTexts.En) : new Dictionary<string, string>(zh);
// 语言包可以覆盖任意键:i18n/<language>.json
var dir = Path.Combine(dataDirectory, "i18n");
Overlay(Path.Combine(dir, language + ".json"), chosen);
if (!isEnglish) Overlay(Path.Combine(dir, "zh-CN.json"), chosen);
return new ModelStrings(isEnglish ? "en" : "zh-CN", chosen);
}
private static void Overlay(string path, Dictionary<string, string> target)
{
if (!File.Exists(path)) return;
try
{
var map = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(path), ModelJson.Options);
if (map == null) return;
foreach (var pair in map) target[pair.Key] = pair.Value;
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取模型语言包失败 {path}: {ex.Message}");
}
}
}
internal static class DefaultTexts
{
public static readonly Dictionary<string, string> Zh = new()
{
["title"] = "地球模型",
["view.rotation"] = "自转",
["view.revolution"] = "公转",
["play"] = "播放",
["pause"] = "暂停",
["speed"] = "速度",
["reset"] = "重置",
["labels"] = "标注",
["orbit"] = "轨道",
["grid"] = "经纬网",
["tilt"] = "夸张倾角",
["lessons"] = "教学要点",
["seasons"] = "节气定位",
["close"] = "关闭窗口",
["hint"] = "双指捏合或滚轮缩放 · 拖动可转动地球",
["shortcutHint"] = "空格 播放/暂停 · ←→ 步进 · 1–4 二分二至 · F 全屏",
["classroom"] = "课堂演示",
["directPoint"] = "太阳直射",
["frozen"] = "已定格",
["running"] = "播放中",
["step"] = "步进",
["closeup"] = "地球特写",
["overhead"] = "俯视",
["sideview"] = "侧视",
["zoom"] = "缩放",
["orbitTeach"] = "太阳直射点在南北回归线之间往返,形成四季更替。",
["lat.equator"] = "赤道",
["lat.tropicN"] = "北回归线 23.5°N",
["lat.tropicS"] = "南回归线 23.5°S",
["lat.polarN"] = "北极圈 66.5°N",
["lat.polarS"] = "南极圈 66.5°S",
["loading"] = "正在准备场景…",
["subsolar"] = "太阳直射点",
["north"] = "北极",
["south"] = "南极",
["northShort"] = "N",
["southShort"] = "S",
["sun"] = "太阳",
["earth"] = "地球",
["spinInfo"] = "自转 {0}° · 周期 {1} 小时",
["orbitInfo"] = "公转 {0}°",
["declinationInfo"] = "太阳直射 {0}",
["dateInfo"] = "日期 {0}",
["season.springEquinox"] = "春分",
["season.summerSolstice"] = "夏至",
["season.autumnEquinox"] = "秋分",
["season.winterSolstice"] = "冬至"
};
public static readonly Dictionary<string, string> En = new()
{
["title"] = "Earth model",
["view.rotation"] = "Rotation",
["view.revolution"] = "Revolution",
["play"] = "Play",
["pause"] = "Pause",
["speed"] = "Speed",
["reset"] = "Reset",
["labels"] = "Labels",
["orbit"] = "Orbit",
["grid"] = "Graticule",
["tilt"] = "Exaggerate tilt",
["lessons"] = "Teaching notes",
["seasons"] = "Solstices & equinoxes",
["close"] = "Close window",
["hint"] = "Pinch or scroll to zoom · drag to turn the Earth",
["shortcutHint"] = "Space play/pause · ←→ step · 1–4 solstices & equinoxes · F fullscreen",
["classroom"] = "Classroom",
["directPoint"] = "Subsolar",
["frozen"] = "Frozen",
["running"] = "Playing",
["step"] = "Step",
["closeup"] = "Earth close-up",
["overhead"] = "Top view",
["sideview"] = "Side view",
["zoom"] = "Zoom",
["orbitTeach"] = "The subsolar point travels between the tropics, producing the seasons.",
["lat.equator"] = "Equator",
["lat.tropicN"] = "Tropic of Cancer 23.5°N",
["lat.tropicS"] = "Tropic of Capricorn 23.5°S",
["lat.polarN"] = "Arctic Circle 66.5°N",
["lat.polarS"] = "Antarctic Circle 66.5°S",
["loading"] = "Preparing scene…",
["subsolar"] = "Subsolar point",
["north"] = "North pole",
["south"] = "South pole",
["northShort"] = "N",
["southShort"] = "S",
["sun"] = "Sun",
["earth"] = "Earth",
["spinInfo"] = "Rotation {0}° · period {1} h",
["orbitInfo"] = "Orbit {0}°",
["declinationInfo"] = "Subsolar {0}",
["dateInfo"] = "Date {0}",
["season.springEquinox"] = "Spring equinox",
["season.summerSolstice"] = "Summer solstice",
["season.autumnEquinox"] = "Autumn equinox",
["season.winterSolstice"] = "Winter solstice"
};
}
+74
View File
@@ -0,0 +1,74 @@
using System.Collections.Generic;
namespace NeoRF.EarthModels;
/// <summary>&lt;id&gt;.model/scene.json —— 模型数据(可视化场景描述)。</summary>
public sealed class SceneDefinition
{
public int SchemaVersion { get; set; } = 1;
public string Type { get; set; } = "planet";
/// <summary>rotation | revolution</summary>
public string DefaultView { get; set; } = "rotation";
/// <summary>模型支持的视图;为空表示只有 defaultView。</summary>
public List<string> Views { get; set; } = new();
public Dictionary<string, string>? NameI18n { get; set; }
public Dictionary<string, string>? DescriptionI18n { get; set; }
public StarDefinition Star { get; set; } = new();
public PlanetDefinition Planet { get; set; } = new();
public OrbitDefinition Orbit { get; set; } = new();
public List<Lesson> Lessons { get; set; } = new();
}
public sealed class StarDefinition
{
public string Name { get; set; } = "Sun";
public Dictionary<string, string>? NameI18n { get; set; }
public string Color { get; set; } = "#FFC24B";
/// <summary>相对行星半径的视觉倍率</summary>
public double RadiusScale { get; set; } = 0.5;
}
public sealed class PlanetDefinition
{
public string Name { get; set; } = "Earth";
public Dictionary<string, string>? NameI18n { get; set; }
/// <summary>黄赤交角:教材值 23.5°(23°26′),决定南北回归线纬度。</summary>
public double AxialTiltDeg { get; set; } = 23.5;
/// <summary>回归线纬度,默认与黄赤交角一致;极圈 = 90 − 回归线。</summary>
public double TropicDeg { get; set; } = 23.5;
public double RotationHours { get; set; } = 23.93;
public double OrbitDays { get; set; } = 365.26;
public string OceanColor { get; set; } = "#1B5FA8";
public string LandColor { get; set; } = "#4F8C4C";
public string? IceColor { get; set; } = "#E8EEF4";
public string? LandFile { get; set; } = "land.json";
public bool ShowGraticule { get; set; } = true;
}
public sealed class OrbitDefinition
{
public double SemiMajorAxis { get; set; } = 4.0;
public double Eccentricity { get; set; } = 0.0167;
public bool Show { get; set; } = true;
public List<SeasonPoint> Seasons { get; set; } = new();
}
public sealed class SeasonPoint
{
/// <summary>0=春分 90=夏至 180=秋分 270=冬至</summary>
public double AngleDeg { get; set; }
public string Key { get; set; } = "";
public string? Date { get; set; }
/// <summary>该节气的太阳直射纬度:春分/秋分 0,夏至 +23.5,冬至 −23.5。</summary>
public double? DeclinationDeg { get; set; }
/// <summary>课堂现象说明(写在模型数据里,启动器不参与)。</summary>
public Dictionary<string, string>? TeachingI18n { get; set; }
}
public sealed class Lesson
{
public Dictionary<string, string>? TitleI18n { get; set; }
public Dictionary<string, string>? BodyI18n { get; set; }
public string? View { get; set; }
public double? AngleDeg { get; set; }
}
+65
View File
@@ -0,0 +1,65 @@
using System;
using System.IO;
using Avalonia.Media;
namespace NeoRF.EarthModels;
/// <summary>
/// 模型自己的场景运行时:场景描述 + 预烘焙地表纹理 + 调色板。
/// 数据来自模型数据目录,不依赖启动器。
/// </summary>
public sealed class SceneRuntime
{
public SceneDefinition Scene { get; init; } = new();
public PlanetTexture? Texture { get; init; }
public Color Ocean { get; init; } = Color.Parse("#1B5FA8");
public Color Land { get; init; } = Color.Parse("#4F8C4C");
public Color Ice { get; init; } = Color.Parse("#E6EDF4");
public Color Star { get; init; } = Color.Parse("#FFC24B");
public long MemoryBytes => Texture?.ByteSize ?? 0;
public static SceneRuntime Load(string dataDirectory, int memoryBudgetMb,
Action<double, string?>? progress = null)
{
progress?.Invoke(0.06, "读取场景数据");
var scenePath = Path.Combine(dataDirectory, "scene.json");
var scene = ModelJson.Read<SceneDefinition>(scenePath) ?? new SceneDefinition();
var ocean = Parse(scene.Planet.OceanColor, "#1B5FA8");
var land = Parse(scene.Planet.LandColor, "#4F8C4C");
var ice = Parse(scene.Planet.IceColor, "#E6EDF4");
LandData? landData = null;
var landFile = scene.Planet.LandFile;
if (!string.IsNullOrWhiteSpace(landFile))
{
var path = Path.IsPathRooted(landFile!) ? landFile! : Path.Combine(dataDirectory, landFile!);
progress?.Invoke(0.12, "读取地表轮廓");
landData = LandData.Load(path);
}
// 内存预算决定纹理分辨率(1024 宽约 3 MB)
var width = memoryBudgetMb >= 1024 ? PlanetTexture.DefaultWidth
: memoryBudgetMb >= 512 ? 768
: 512;
progress?.Invoke(0.16, "生成地表纹理");
var texture = PlanetTexture.Build(landData, width, ocean, land, ice,
t => progress?.Invoke(0.16 + t * 0.48, "生成地表纹理"));
progress?.Invoke(0.68, "场景就绪");
return new SceneRuntime
{
Scene = scene,
Texture = texture,
Ocean = ocean,
Land = land,
Ice = ice,
Star = Parse(scene.Star.Color, "#FFC24B")
};
}
private static Color Parse(string? value, string fallback)
=> Color.TryParse(string.IsNullOrWhiteSpace(value) ? fallback : value, out var c) ? c : Color.Parse(fallback);
}
+476
View File
@@ -0,0 +1,476 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia.Media;
namespace NeoRF.EarthModels;
/// <summary>
/// 预烘焙的等经纬度地表贴图:反照率 + 高度 + 冰盖 + 云层 + 夜间灯光。
/// 只在模型加载时算一次,之后每帧只做采样 —— 比逐像素跑噪声快一个数量级,
/// 而且能画出「真实一点」的地表:海洋深度、沙漠/雨林/针叶林带、山脉阴影、极地冰盖。
/// </summary>
public sealed class PlanetTexture
{
public const int DefaultWidth = 1024;
public int Width { get; }
public int Height { get; }
/// <summary>打包的反照率(0xRRGGBB),每像素一次双线性即可拿三通道。</summary>
public uint[] Albedo { get; }
/// <summary>地形高度(0=海平面,255=高山)</summary>
public byte[] Elevation { get; }
/// <summary>云量</summary>
public byte[] Cloud { get; }
/// <summary>夜间灯光</summary>
public byte[] Lights { get; }
/// <summary>预烘焙的地形坡度:东向 / 北向高度梯度(加载时算一次,每帧直接采样)。</summary>
public float[] SlopeEast { get; }
public float[] SlopeNorth { get; }
public long ByteSize => (long)(Albedo.Length * 4 + Elevation.Length + Cloud.Length + Lights.Length
+ SlopeEast.Length * 4 + SlopeNorth.Length * 4);
private PlanetTexture(int width, int height)
{
Width = width;
Height = height;
var count = width * height;
Albedo = new uint[count];
Elevation = new byte[count];
Cloud = new byte[count];
Lights = new byte[count];
SlopeEast = new float[count];
SlopeNorth = new float[count];
}
public static PlanetTexture Build(LandData? landData, int width, Color ocean, Color land, Color ice,
Action<double>? progress = null)
{
width = Math.Clamp(width, 256, 2048);
var height = width / 2;
var texture = new PlanetTexture(width, height);
progress?.Invoke(0.08);
var mask = landData == null ? null : LandMask.Build(landData, width, height);
progress?.Invoke(0.28);
// 到海岸的距离:海里用来做深度,陆地上用来做大陆性(内陆更干)
var landDistance = new float[width * height];
var oceanDistance = new float[width * height];
ComputeDistances(mask, width, height, landDistance, oceanDistance);
progress?.Invoke(0.42);
Parallel.For(0, height, y =>
{
var lat = 90.0 - (y + 0.5) * 180.0 / height;
var latAbs = MathF.Abs((float)lat);
var rowBase = y * width;
for (var x = 0; x < width; x++)
{
var lon = (x + 0.5) * 360.0 / width - 180.0;
var index = rowBase + x;
var isLand = mask == null || mask.Bits[index] > 127;
var elevation = Fbm(lon * 2.1, lat * 2.1, 4, 0x51A3);
var moisture = Fbm(lon * 1.35 + 40, lat * 1.35 - 20, 3, 0x9E2B);
var detail = Fbm(lon * 0.85, lat * 0.85, 3, 0x2C77);
if (isLand)
{
// 内陆更干,靠海更湿
var inland = Math.Clamp(landDistance[index] / (width * 0.06f), 0f, 1f);
var wet = Math.Clamp(moisture * 0.78f + (1f - inland) * 0.16f
- MathF.Max(0f, latAbs - 45f) / 90f, 0f, 1f);
var (r, g, b) = LandPalette(latAbs, wet, inland, elevation, detail, land, ice);
texture.Albedo[index] = Pack(r, g, b);
texture.Elevation[index] = (byte)Math.Clamp(elevation * 235f + detail * 20f, 0, 255);
// 夜间灯光:沿海平原、中低纬,稀疏分布
// 夜间灯光:低频的城市群辉光(高频点会在小尺寸球面上变成噪点)
var cityGlow = Smooth(0.55f, 0.92f, Fbm(lon * 1.7, lat * 1.7, 3, 0x7A31));
if (latAbs < 60 && inland < 0.55f && elevation < 0.75f)
texture.Lights[index] = ToByte(cityGlow * 0.55f);
}
else
{
// 海洋:按离岸距离做深浅
var depth = Math.Clamp(oceanDistance[index] / (width * 0.09f), 0f, 1f);
depth = (float)Math.Pow(depth, 0.65);
var shallowR = Math.Min(1f, ocean.R / 255f + 0.16f);
var shallowG = Math.Min(1f, ocean.G / 255f + 0.22f);
var shallowB = Math.Min(1f, ocean.B / 255f + 0.16f);
var deepR = ocean.R / 255f * 0.32f;
var deepG = ocean.G / 255f * 0.40f;
var deepB = ocean.B / 255f * 0.52f;
var wave = (detail - 0.5f) * 0.035f;
texture.Albedo[index] = Pack(
ToByte(shallowR + (deepR - shallowR) * depth + wave),
ToByte(shallowG + (deepG - shallowG) * depth + wave),
ToByte(shallowB + (deepB - shallowB) * depth + wave));
texture.Elevation[index] = 0;
}
// 极地冰盖:纬度 + 噪声边界,海洋也能结冰
var iceEdge = 62f + (detail - 0.5f) * 9f;
var iceAmt = Smooth(iceEdge - 7f, iceEdge + 6f, latAbs);
if (iceAmt > 0.001f)
{
var iceR = ice.R / 255f;
var iceG = ice.G / 255f;
var iceB = ice.B / 255f;
var packed = texture.Albedo[index];
texture.Albedo[index] = Pack(
ToByte(Lerp(((packed >> 16) & 0xFF) / 255f, iceR, iceAmt)),
ToByte(Lerp(((packed >> 8) & 0xFF) / 255f, iceG, iceAmt)),
ToByte(Lerp((packed & 0xFF) / 255f, iceB, iceAmt)));
}
// 云:多个尺度的 fbm,赤道与中纬多云
var cloudBase = Fbm(lon * 0.55, lat * 0.7, 3, 0x1144);
var band = 0.5f + 0.5f * MathF.Cos(latAbs / 90f * MathF.PI * 3.1f);
var cloud = Smooth(0.48f, 0.84f, cloudBase * 0.86f + band * 0.14f);
texture.Cloud[index] = ToByte(cloud * 0.72f);
}
});
// 云层做一次模糊,避免小尺寸球面上采样出噪点
Blur(texture.Cloud, width, height, 2);
// 预烘焙地形坡度:渲染时不必每像素再取 4 次高度
BakeSlopes(texture, width, height);
progress?.Invoke(0.62);
return texture;
}
private static (byte R, byte G, byte B) LandPalette(float latAbs, float wet, float inland, float elevation,
float detail, Color landBase, Color ice)
{
// 基色随纬度:赤道雨林 -> 温带 -> 针叶林 -> 苔原
float r, g, b;
var tropical = (1f - Smooth(8f, 24f, latAbs));
var temperate = Smooth(20f, 34f, latAbs) * (1f - Smooth(46f, 60f, latAbs));
var boreal = Smooth(46f, 60f, latAbs) * (1f - Smooth(62f, 70f, latAbs));
var tundra = Smooth(60f, 72f, latAbs);
r = 0.13f; g = 0.36f; b = 0.17f; // 温带草原绿
r = Lerp(r, 0.10f, tropical); g = Lerp(g, 0.42f, tropical); b = Lerp(b, 0.19f, tropical);
r = Lerp(r, 0.17f, boreal); g = Lerp(g, 0.28f, boreal); b = Lerp(b, 0.17f, boreal);
r = Lerp(r, 0.34f, tundra); g = Lerp(g, 0.36f, tundra); b = Lerp(b, 0.31f, tundra);
// 湿润度:干 -> 沙漠/草原
var dry = Math.Clamp(1f - wet * 0.95f, 0f, 1f);
var desertBand = Math.Clamp(1f - MathF.Abs(latAbs - 24f) / 13f, 0f, 1f);
var desert = Math.Clamp(dry * 0.72f + desertBand * 0.62f, 0f, 1f);
r = Lerp(r, 0.72f, desert * 0.85f);
g = Lerp(g, 0.60f, desert * 0.85f);
b = Lerp(b, 0.38f, desert * 0.85f);
// 高原/山地:岩石和雪
var rock = Smooth(0.62f, 0.86f, elevation);
r = Lerp(r, 0.44f, rock * 0.7f);
g = Lerp(g, 0.40f, rock * 0.7f);
b = Lerp(b, 0.34f, rock * 0.7f);
var snow = Smooth(0.86f, 0.97f, elevation + (latAbs - 40f) / 220f);
r = Lerp(r, ice.R / 255f, snow);
g = Lerp(g, ice.G / 255f, snow);
b = Lerp(b, ice.B / 255f, snow);
// 细节扰动,避免大面积纯色
var grain = (detail - 0.5f) * 0.07f;
var baseMix = 0.25f;
return (
ToByte(Math.Clamp(r + grain + (landBase.R / 255f - 0.3f) * baseMix * 0.2f, 0f, 1f)),
ToByte(Math.Clamp(g + grain + (landBase.G / 255f - 0.45f) * baseMix * 0.2f, 0f, 1f)),
ToByte(Math.Clamp(b + grain + (landBase.B / 255f - 0.3f) * baseMix * 0.2f, 0f, 1f)));
}
/// <summary>可分离盒式模糊(原地),用于软化云层。</summary>
private static void Blur(byte[] data, int width, int height, int radius)
{
var temp = new byte[data.Length];
for (var y = 0; y < height; y++)
{
var row = y * width;
for (var x = 0; x < width; x++)
{
var sum = 0;
var count = 0;
for (var k = -radius; k <= radius; k++)
{
var sx = (x + k + width) % width;
sum += data[row + sx];
count++;
}
temp[row + x] = (byte)(sum / count);
}
}
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
var sum = 0;
var count = 0;
for (var k = -radius; k <= radius; k++)
{
var sy = Math.Clamp(y + k, 0, height - 1);
sum += temp[sy * width + x];
count++;
}
data[y * width + x] = (byte)(sum / count);
}
}
}
/// <summary>由高度图算东西/南北梯度,供球面光照直接使用。</summary>
private static void BakeSlopes(PlanetTexture t, int width, int height)
{
const float relief = 0.055f * 90f;
for (var y = 0; y < height; y++)
{
var row = y * width;
var up = Math.Max(0, y - 1) * width;
var down = Math.Min(height - 1, y + 1) * width;
for (var x = 0; x < width; x++)
{
var left = (x - 1 + width) % width;
var right = (x + 1) % width;
t.SlopeEast[row + x] = (t.Elevation[row + right] - t.Elevation[row + left]) / 255f * relief;
t.SlopeNorth[row + x] = (t.Elevation[up + x] - t.Elevation[down + x]) / 255f * relief;
}
}
}
// ---------------------------------------------------------------- 距离场
private static void ComputeDistances(LandMask? mask, int width, int height, float[] landDistance, float[] oceanDistance)
{
var count = width * height;
const float big = 1e6f;
for (var i = 0; i < count; i++)
{
var isLand = mask != null && mask.Bits[i] > 127;
landDistance[i] = isLand ? big : -big;
oceanDistance[i] = isLand ? -big : big;
}
// 两遍 chamfer:陆地到海洋的距离 / 海洋到陆地的距离
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var i = y * width + x;
if (mask != null && mask.Bits[i] > 127)
{
var best = big;
if (x > 0 && mask.Bits[i - 1] <= 127) best = 0.5f;
if (x < width - 1 && mask.Bits[i + 1] <= 127) best = Math.Min(best, 0.5f);
if (y > 0 && mask.Bits[i - width] <= 127) best = Math.Min(best, 0.5f);
if (y < height - 1 && mask.Bits[i + width] <= 127) best = Math.Min(best, 0.5f);
if (best < big) landDistance[i] = best;
}
if (mask != null && mask.Bits[i] <= 127)
{
var best = big;
if (x > 0 && mask.Bits[i - 1] > 127) best = 0.5f;
if (x < width - 1 && mask.Bits[i + 1] > 127) best = Math.Min(best, 0.5f);
if (y > 0 && mask.Bits[i - width] > 127) best = Math.Min(best, 0.5f);
if (y < height - 1 && mask.Bits[i + width] > 127) best = Math.Min(best, 0.5f);
if (best < big) oceanDistance[i] = best;
}
}
}
// 正向传递
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var i = y * width + x;
Propagate(landDistance, i, width, height, x, y, -1, 0, 1.4142f);
Propagate(oceanDistance, i, width, height, x, y, -1, 0, 1.4142f);
if (x > 0)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i - 1] + 1f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - 1] + 1f);
}
if (y > 0)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width] + 1f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width] + 1f);
if (x > 0)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width - 1] + 1.4142f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width - 1] + 1.4142f);
}
if (x < width - 1)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width + 1] + 1.4142f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width + 1] + 1.4142f);
}
}
}
}
// 反向传递
for (var y = height - 1; y >= 0; y--)
{
for (var x = width - 1; x >= 0; x--)
{
var i = y * width + x;
if (x < width - 1)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i + 1] + 1f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + 1] + 1f);
}
if (y < height - 1)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width] + 1f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width] + 1f);
if (x < width - 1)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width + 1] + 1.4142f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width + 1] + 1.4142f);
}
if (x > 0)
{
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width - 1] + 1.4142f);
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width - 1] + 1.4142f);
}
}
}
}
for (var i = 0; i < count; i++)
{
landDistance[i] = MathF.Max(0f, landDistance[i]);
oceanDistance[i] = MathF.Max(0f, oceanDistance[i]);
}
}
private static void Propagate(float[] map, int index, int width, int height, int x, int y, int dx, int dy, float w)
{
var nx = x + dx;
var ny = y + dy;
if (nx < 0 || nx >= width || ny < 0 || ny >= height) return;
var other = ny * width + nx;
map[index] = Math.Min(map[index], map[other] + w);
}
// ---------------------------------------------------------------- 噪声
/// <summary>值噪声 + 分形叠加(确定性,跨平台一致)。</summary>
public static float Fbm(double x, double y, int octaves, int seed)
{
var amplitude = 1.0;
var frequency = 1.0;
var sum = 0.0;
var norm = 0.0;
for (var i = 0; i < octaves; i++)
{
sum += amplitude * ValueNoise(x * frequency, y * frequency, seed + i * 101);
norm += amplitude;
amplitude *= 0.5;
frequency *= 2.07;
}
return (float)(sum / norm);
}
private static double ValueNoise(double x, double y, int seed)
{
var xi = (int)Math.Floor(x);
var yi = (int)Math.Floor(y);
var xf = x - xi;
var yf = y - yi;
var u = xf * xf * (3 - 2 * xf);
var v = yf * yf * (3 - 2 * yf);
var a = Hash(xi, yi, seed);
var b = Hash(xi + 1, yi, seed);
var c = Hash(xi, yi + 1, seed);
var d = Hash(xi + 1, yi + 1, seed);
return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v;
}
private static double Hash(int x, int y, int seed)
{
var h = (uint)(x * 374761393 + y * 668265263 + seed * 1442695041);
h = (h ^ (h >> 13)) * 1274126177u;
h ^= h >> 16;
return (h & 0xFFFFFF) / (double)0xFFFFFF;
}
// ---------------------------------------------------------------- 采样
public void Sample(double lon, double lat, out float r, out float g, out float b,
out float elevation, out float cloud, out float lights,
out float slopeEast, out float slopeNorth)
{
var u = (lon + 180.0) / 360.0 * Width - 0.5;
var v = (90.0 - lat) / 180.0 * Height - 0.5;
var x0 = (int)Math.Floor(u);
var y0 = (int)Math.Floor(v);
var fx = (float)(u - x0);
var fy = (float)(v - y0);
var x1 = x0 + 1;
var y1 = y0 + 1;
if (x0 < 0) x0 += Width; if (x1 < 0) x1 += Width;
if (x0 >= Width) x0 -= Width; if (x1 >= Width) x1 -= Width;
y0 = Math.Clamp(y0, 0, Height - 1);
y1 = Math.Clamp(y1, 0, Height - 1);
var i00 = y0 * Width + x0;
var i10 = y0 * Width + x1;
var i01 = y1 * Width + x0;
var i11 = y1 * Width + x1;
float w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy), w01 = (1 - fx) * fy, w11 = fx * fy;
var p00 = Albedo[i00];
var p10 = Albedo[i10];
var p01 = Albedo[i01];
var p11 = Albedo[i11];
var rr = ((p00 >> 16) & 0xFF) * w00 + ((p10 >> 16) & 0xFF) * w10 + ((p01 >> 16) & 0xFF) * w01 + ((p11 >> 16) & 0xFF) * w11;
var gg = ((p00 >> 8) & 0xFF) * w00 + ((p10 >> 8) & 0xFF) * w10 + ((p01 >> 8) & 0xFF) * w01 + ((p11 >> 8) & 0xFF) * w11;
var bb = (p00 & 0xFF) * w00 + (p10 & 0xFF) * w10 + (p01 & 0xFF) * w01 + (p11 & 0xFF) * w11;
r = rr / 255f;
g = gg / 255f;
b = bb / 255f;
elevation = (Elevation[i00] * w00 + Elevation[i10] * w10 + Elevation[i01] * w01 + Elevation[i11] * w11) / 255f;
cloud = (Cloud[i00] * w00 + Cloud[i10] * w10 + Cloud[i01] * w01 + Cloud[i11] * w11) / 255f;
lights = Lights[i00] / 255f;
slopeEast = SlopeEast[i00] * w00 + SlopeEast[i10] * w10 + SlopeEast[i01] * w01 + SlopeEast[i11] * w11;
slopeNorth = SlopeNorth[i00] * w00 + SlopeNorth[i10] * w10 + SlopeNorth[i01] * w01 + SlopeNorth[i11] * w11;
}
/// <summary>只采样高度(法线扰动用)。</summary>
public float SampleHeight(double lon, double lat)
{
var u = (lon + 180.0) / 360.0 * Width - 0.5;
var v = (90.0 - lat) / 180.0 * Height - 0.5;
var x = Math.Clamp((int)Math.Round(u), 0, Width - 1);
var y = Math.Clamp((int)Math.Round(v), 0, Height - 1);
return Elevation[y * Width + x] / 255f;
}
public float SampleCloud(double lon, double lat)
{
var u = (lon + 180.0) / 360.0 * Width - 0.5;
var v = (90.0 - lat) / 180.0 * Height - 0.5;
var x = Math.Clamp((int)Math.Round(u), 0, Width - 1);
var y = Math.Clamp((int)Math.Round(v), 0, Height - 1);
return Cloud[y * Width + x] / 255f;
}
public static byte ToByte(float v) => (byte)Math.Clamp((int)(v * 255f + 0.5f), 0, 255);
private static uint Pack(byte r, byte g, byte b) => ((uint)r << 16) | ((uint)g << 8) | b;
private static float Lerp(float a, float b, float t) => a + (b - a) * Math.Clamp(t, 0f, 1f);
private static float Smooth(float edge0, float edge1, float x)
{
if (edge1 <= edge0) return x >= edge1 ? 1f : 0f;
var t = Math.Clamp((x - edge0) / (edge1 - edge0), 0f, 1f);
return t * t * (3f - 2f * t);
}
}
+172
View File
@@ -0,0 +1,172 @@
using System;
using System.Numerics;
using System.Threading.Tasks;
using Avalonia.Media.Imaging;
namespace NeoRF.EarthModels;
/// <summary>
/// 球体像素级渲染:正交投影 + 预烘焙地表纹理 + 地形光照 + 云层 + 夜灯 + 大气边缘光。
/// 纯 CPU 光栅、按行并行,不依赖 GPU,三平台效果一致。
/// </summary>
public static unsafe class SphereRaster
{
/// <summary>把球体画进 WriteableBitmap(整张位图会被覆盖)。</summary>
public static void Draw(WriteableBitmap bitmap, int size, Matrix4x4 cam, Matrix4x4 planet,
Vector3 light, PlanetTexture texture, double cloudShift, bool showClouds)
{
using var framebuffer = bitmap.Lock();
var stride = framebuffer.RowBytes / 4;
Render((uint*)framebuffer.Address, stride, size, cam, planet, light, texture, cloudShift, showClouds);
}
public static void Render(uint* dst, int stride, int size, Matrix4x4 cam, Matrix4x4 planet,
Vector3 light, PlanetTexture texture, double cloudShift, bool showClouds)
{
var radius = size * 0.5f - 1.0f;
var center = size * 0.5f;
var inv = 1f / radius;
// 相机空间法线 -> 行星本地法线
var combined = Matrix4x4.Multiply(planet, cam);
var mt = Matrix4x4.Transpose(combined);
float m11 = mt.M11, m12 = mt.M12, m13 = mt.M13;
float m21 = mt.M21, m22 = mt.M22, m23 = mt.M23;
float m31 = mt.M31, m32 = mt.M32, m33 = mt.M33;
var lx = light.X; var ly = light.Y; var lz = light.Z;
Parallel.For(0, size, y =>
{
var ny = (center - y - 0.5f) * inv;
var row = dst + (long)y * stride;
for (var x = 0; x < size; x++)
{
var nx = (x + 0.5f - center) * inv;
var r2 = nx * nx + ny * ny;
if (r2 >= 1f)
{
row[x] = 0;
continue;
}
var nz = MathF.Sqrt(1f - r2);
// 本地法线(用于取经纬度)
var ux = nx * m11 + ny * m21 + nz * m31;
var uy = nx * m12 + ny * m22 + nz * m32;
var uz = nx * m13 + ny * m23 + nz * m33;
var lat = MathF.Asin(Math.Clamp(uy, -1f, 1f)) * 57.2957795f;
var lon = MathF.Atan2(ux, uz) * 57.2957795f;
var cloudLon = lon + cloudShift;
if (cloudLon > 180) cloudLon -= 360;
if (cloudLon < -180) cloudLon += 360;
texture.Sample(lon, lat, out var ar, out var ag, out var ab,
out var elevation, out var cloud, out var lights,
out var dEast, out var dNorth);
// ---- 地形法线:局部基向量可由球面法线直接推出,不必再算 6 次三角函数
// 点 P=(cosLat·sinLon, sinLat, cosLat·cosLon) = (ux,uy,uz)
// 东向 = (cosLon,0,-sinLon),北向 = (-sinLat·sinLon, cosLat, -sinLat·cosLon)
var cosLat = MathF.Sqrt(MathF.Max(ux * ux + uz * uz, 1e-6f));
var invCos = 1f / cosLat;
var eastX = uz * invCos;
var eastZ = -ux * invCos;
var northX = -uy * ux * invCos;
var northY = cosLat;
var northZ = -uy * uz * invCos;
var nLocalX = ux + eastX * dEast + northX * dNorth;
var nLocalY = uy + northY * dNorth;
var nLocalZ = uz + eastZ * dEast + northZ * dNorth;
var nLen = MathF.Sqrt(nLocalX * nLocalX + nLocalY * nLocalY + nLocalZ * nLocalZ);
if (nLen > 0.0001f) { nLocalX /= nLen; nLocalY /= nLen; nLocalZ /= nLen; }
var nCamX = nLocalX * combined.M11 + nLocalY * combined.M21 + nLocalZ * combined.M31;
var nCamY = nLocalX * combined.M12 + nLocalY * combined.M22 + nLocalZ * combined.M32;
var nCamZ = nLocalX * combined.M13 + nLocalY * combined.M23 + nLocalZ * combined.M33;
var lam = nx * lx + ny * ly + nz * lz; // 几何光照(晨昏线)
var bump = nCamX * lx + nCamY * ly + nCamZ * lz; // 地形光照
var day = Smooth(-0.18f, 0.22f, lam);
var terrainLight = 0.82f + 0.42f * MathF.Max(0f, bump - lam);
var shade = (0.055f + 0.945f * day) * terrainLight;
var br = ar * shade;
var bg = ag * shade;
var bb = ab * shade;
// 海面高光(高度为 0 视为水面)
if (elevation < 0.02f)
{
var t2 = MathF.Max(0f, lam);
var t4 = t2 * t2 * t2 * t2;
var t8 = t4 * t4;
var t16 = t8 * t8;
var spec = t16 * t8 * t4 * t2 * t2 * 0.62f;
br += spec * 0.95f;
bg += spec * 0.98f;
bb += spec;
}
// 云层(随经度缓慢漂移)
if (showClouds && cloud > 0.02f)
{
var cloudLight = 0.10f + 0.90f * day;
var c = Math.Clamp(cloud * 0.92f, 0f, 1f);
var cloudR = 0.98f * cloudLight;
var cloudG = 0.985f * cloudLight;
var cloudB = 1.0f * cloudLight;
br += (cloudR - br) * c;
bg += (cloudG - bg) * c;
bb += (cloudB - bb) * c;
}
// 夜间灯光
if (lights > 0.01f)
{
var night = 1f - day;
var glow = lights * night * 0.35f;
br += glow * 0.95f;
bg += glow * 0.72f;
bb += glow * 0.38f;
}
// 大气边缘散射
var rim = 1f - nz;
rim *= rim;
var litRim = rim * MathF.Max(0f, lam) * 0.98f;
br += 0.30f * litRim;
bg += 0.55f * litRim;
bb += 1.00f * litRim;
// 夜面极淡反照
var nightSide = 1f - day;
br += 0.008f * nightSide;
bg += 0.013f * nightSide;
bb += 0.028f * nightSide;
var coverage = 1f;
var edge = (1f - MathF.Sqrt(r2)) * radius;
if (edge < 1f) coverage = MathF.Max(0f, edge);
var a = (uint)(coverage * 255f);
var r8 = (uint)(Math.Clamp(br, 0f, 1f) * 255f * coverage);
var g8 = (uint)(Math.Clamp(bg, 0f, 1f) * 255f * coverage);
var b8 = (uint)(Math.Clamp(bb, 0f, 1f) * 255f * coverage);
row[x] = (a << 24) | (r8 << 16) | (g8 << 8) | b8;
}
});
}
private static float Smooth(float edge0, float edge1, float x)
{
if (edge1 <= edge0) return x >= edge1 ? 1f : 0f;
var t = Math.Clamp((x - edge0) / (edge1 - edge0), 0f, 1f);
return t * t * (3f - 2f * t);
}
}
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>EarthModelStudio.ModelSdk</RootNamespace>
<AssemblyName>EarthModelStudio.ModelSdk</AssemblyName>
<IsPackable>false</IsPackable>
<Description>Earth Model 模型契约:启动器与模型之间唯一的编译期依赖。</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
</Project>
@@ -0,0 +1,68 @@
using System;
using Avalonia.Controls;
namespace EarthModelStudio.ModelSdk;
/// <summary>
/// 模型入口契约。模型程序集里必须有一个公开、无参构造的 <see cref="IModelFactory"/> 实现,
/// 启动器按模型清单里的 <c>assembly</c> + <c>type</c> 定位并创建它。
/// </summary>
public interface IModelFactory
{
/// <summary>契约版本。启动器目前支持 1。</summary>
int ApiVersion { get; }
/// <summary>创建一个模型运行时实例(每个窗口一个实例)。</summary>
IModelRuntime Create();
}
/// <summary>
/// 模型运行时:负责把模型自己的界面交给启动器。
/// 启动器只负责开窗口,**不参与任何渲染**。
/// </summary>
public interface IModelRuntime : IDisposable
{
/// <summary>
/// 在**后台线程**准备数据(读文件、算纹理等),期间禁止创建或操作任何 UI 控件。
/// 启动器的进度窗会显示 <see cref="IModelContext.ReportProgress"/> 汇报的进度。
/// 默认空实现:模型也可以把准备工作留到 CreateView 里(那样会占用 UI 线程)。
/// </summary>
void Prepare(IModelContext context) { }
/// <summary>
/// 在 UI 线程创建模型窗口的内容。模型可以自由组合控件、自己画图、自己管动画。
/// 返回的控件会被直接放进窗口,铺满客户区。
/// </summary>
Control CreateView(IModelContext context);
}
/// <summary>启动器提供给模型的环境信息与能力。</summary>
public interface IModelContext
{
/// <summary>模型 id(即模型目录名)。</summary>
string ModelId { get; }
/// <summary>模型目录:<c>model/&lt;id&gt;</c>。</summary>
string ModelDirectory { get; }
/// <summary>模型数据目录:<c>model/&lt;id&gt;/&lt;id&gt;.model</c>,模型自己的场景数据、贴图、语言包都放这里。</summary>
string DataDirectory { get; }
/// <summary>界面语言(zh-CN / en)。模型应按它选择自己的文案。</summary>
string Language { get; }
/// <summary>用户在设置里分配的运行内存预算(MB),模型可据此控制缓存规模。</summary>
int MemoryBudgetMb { get; }
/// <summary>请求关闭承载此模型的窗口。</summary>
void RequestClose();
/// <summary>
/// 汇报加载进度(0–1)与当前阶段文案。启动器的加载进度条会实时显示,
/// 也可以在任何时候调用(例如切换数据集时)。
/// </summary>
void ReportProgress(double value, string? message = null);
/// <summary>输出日志(启动器会写到控制台)。</summary>
void Log(string message);
}
@@ -0,0 +1,28 @@
{
"schemaVersion": 1,
"id": "earth-revolution",
"name": "Earth Revolution",
"nameI18n": {
"zh-CN": "地球公转",
"en": "Earth Revolution"
},
"version": "1.0.0",
"author": "NeoRF",
"description": "四季更替、黄赤交角与二分二至",
"descriptionI18n": {
"zh-CN": "地球绕太阳公转一年:地轴指向不变,太阳直射点南北往返,形成四季。",
"en": "One year around the Sun: the fixed axial direction moves the subsolar point and creates the seasons."
},
"tags": [
"astronomy",
"geography",
"revolution"
],
"entry": "scene.json",
"license": "MIT",
"updatedAt": "2026-11-07",
"assembly": "EarthRevolutionModel.dll",
"type": "NeoRF.EarthModels.RevolutionModelFactory",
"preview": "preview.png",
"apiVersion": 1
}
@@ -0,0 +1,33 @@
{
"title": "Earth Revolution",
"view.rotation": "Rotation",
"view.revolution": "Revolution",
"play": "Play",
"pause": "Pause",
"speed": "Speed",
"reset": "Reset",
"labels": "Labels",
"orbit": "Orbit",
"grid": "Graticule",
"tilt": "Exaggerate tilt",
"lessons": "Teaching notes",
"seasons": "Solstices & equinoxes",
"close": "Close window",
"loading": "Preparing scene…",
"subsolar": "Subsolar point",
"north": "North pole",
"south": "South pole",
"northShort": "N",
"southShort": "S",
"sun": "Sun",
"earth": "Earth",
"spinInfo": "Rotation {0}° · period {1} h",
"orbitInfo": "Orbit {0}°",
"declinationInfo": "Subsolar {0}",
"dateInfo": "Date {0}",
"season.springEquinox": "Spring equinox",
"season.summerSolstice": "Summer solstice",
"season.autumnEquinox": "Autumn equinox",
"season.winterSolstice": "Winter solstice",
"hint": "Pinch or scroll to zoom · drag to turn the Earth"
}
@@ -0,0 +1,33 @@
{
"title": "地球自转",
"view.rotation": "自转",
"view.revolution": "公转",
"play": "播放",
"pause": "暂停",
"speed": "速度",
"reset": "重置",
"labels": "标注",
"orbit": "轨道",
"grid": "经纬网",
"tilt": "夸张倾角",
"lessons": "教学要点",
"seasons": "节气定位",
"close": "关闭窗口",
"loading": "正在准备场景…",
"subsolar": "太阳直射点",
"north": "北极",
"south": "南极",
"northShort": "N",
"southShort": "S",
"sun": "太阳",
"earth": "地球",
"spinInfo": "自转 {0}° · 周期 {1} 小时",
"orbitInfo": "公转 {0}°",
"declinationInfo": "太阳直射 {0}",
"dateInfo": "日期 {0}",
"season.springEquinox": "春分",
"season.summerSolstice": "夏至",
"season.autumnEquinox": "秋分",
"season.winterSolstice": "冬至",
"hint": "双指捏合或滚轮缩放 · 拖动可转动地球"
}
@@ -0,0 +1,98 @@
{
"schema": 1,
"note": "简化大陆轮廓(经度,纬度),用于教学演示,非测绘精度",
"polygons": [
{
"name": "north-america",
"points": [[-168,66],[-164,70],[-155,71],[-145,70],[-133,69],[-120,69],[-110,68],[-100,69],[-92,68],[-85,70],[-80,73],[-72,71],[-64,66],[-60,60],[-56,52],[-60,47],[-66,45],[-70,42],[-74,40],[-76,35],[-81,31],[-80,25],[-83,29],[-88,30],[-94,29],[-97,26],[-97,21],[-92,19],[-87,21],[-88,16],[-83,9],[-78,9],[-84,14],[-90,14],[-96,16],[-105,20],[-112,25],[-117,32],[-122,37],[-124,42],[-125,48],[-131,54],[-140,59],[-150,59],[-158,56],[-165,60],[-166,64]]
},
{
"name": "greenland",
"points": [[-45,60],[-52,64],[-55,68],[-60,72],[-63,76],[-56,80],[-42,82],[-28,80],[-21,74],[-23,70],[-31,66],[-38,62]]
},
{
"name": "south-america",
"points": [[-78,8],[-72,11],[-64,10],[-60,8],[-52,5],[-50,0],[-44,-2],[-38,-5],[-35,-8],[-39,-13],[-41,-22],[-48,-25],[-53,-34],[-57,-38],[-62,-40],[-65,-45],[-68,-50],[-70,-55],[-75,-52],[-74,-45],[-73,-37],[-71,-30],[-70,-23],[-70,-18],[-76,-14],[-81,-6],[-80,-2],[-79,2],[-77,6]]
},
{
"name": "africa",
"points": [[-17,15],[-16,20],[-13,28],[-9,32],[-5,36],[10,37],[20,32],[32,31],[35,28],[39,15],[43,11],[51,12],[48,2],[41,-2],[40,-10],[35,-18],[32,-25],[27,-33],[20,-35],[15,-28],[12,-17],[9,-1],[5,4],[-4,5],[-8,4],[-13,8],[-16,12]]
},
{
"name": "europe",
"points": [[-9,38],[-9,43],[-2,44],[0,48],[2,51],[5,53],[8,54],[9,57],[12,56],[13,54],[20,54],[21,57],[24,58],[28,60],[30,60],[29,64],[25,66],[22,69],[30,70],[40,68],[46,66],[55,68],[60,70],[68,68],[62,62],[58,56],[52,50],[48,46],[40,45],[36,44],[30,45],[28,41],[24,40],[23,37],[19,40],[16,41],[12,44],[7,44],[3,42],[-2,37]]
},
{
"name": "asia",
"points": [[60,70],[75,73],[90,75],[105,77],[115,74],[130,73],[145,72],[160,70],[170,68],[180,65],[172,62],[163,58],[155,52],[143,54],[137,50],[130,43],[126,40],[122,40],[120,36],[122,31],[118,25],[110,21],[105,10],[100,13],[98,8],[95,17],[90,22],[88,21],[80,16],[77,8],[73,18],[68,23],[62,25],[57,24],[52,28],[48,30],[44,13],[43,17],[39,21],[35,28],[34,31],[36,36],[30,41],[28,41],[30,45],[34,45],[40,45],[48,46],[52,50],[58,56],[62,62],[68,68]]
},
{
"name": "australia",
"points": [[113,-22],[114,-27],[116,-35],[129,-32],[138,-35],[146,-39],[150,-37],[153,-28],[146,-19],[142,-11],[132,-11],[126,-14],[122,-18]]
},
{
"name": "antarctica",
"points": [[-180,-72],[-150,-76],[-120,-74],[-90,-73],[-60,-64],[-30,-70],[0,-70],[30,-69],[60,-67],[90,-66],[120,-66],[150,-70],[180,-72],[180,-90],[-180,-90]]
},
{
"name": "madagascar",
"points": [[43,-12],[50,-15],[50,-25],[45,-25],[43,-20]]
},
{
"name": "japan",
"points": [[130,32],[136,35],[141,40],[145,44],[142,39],[137,34],[133,33]]
},
{
"name": "britain",
"points": [[-6,50],[-2,53],[-2,58],[-5,58],[-6,54]]
},
{
"name": "ireland",
"points": [[-10,52],[-6,53],[-6,55],[-10,55]]
},
{
"name": "iceland",
"points": [[-24,65],[-14,66],[-14,64],[-22,63]]
},
{
"name": "new-zealand",
"points": [[166,-46],[170,-44],[174,-41],[177,-38],[174,-35],[170,-38],[167,-42]]
},
{
"name": "sumatra",
"points": [[95,5],[100,1],[105,-6],[100,-4],[96,2]]
},
{
"name": "java",
"points": [[105,-6],[114,-8],[114,-9],[106,-7]]
},
{
"name": "borneo",
"points": [[109,2],[117,4],[119,-2],[115,-4],[110,-2]]
},
{
"name": "sulawesi",
"points": [[119,1],[125,1],[123,-5],[120,-3]]
},
{
"name": "new-guinea",
"points": [[131,-1],[141,-3],[150,-6],[147,-9],[140,-9],[134,-5]]
},
{
"name": "sri-lanka",
"points": [[80,9],[82,7],[81,6],[79,7]]
},
{
"name": "philippines",
"points": [[120,18],[124,13],[126,8],[122,6],[120,12]]
},
{
"name": "cuba",
"points": [[-85,22],[-77,20],[-74,20],[-80,23]]
},
{
"name": "taiwan",
"points": [[120,25],[122,24],[121,22],[120,23]]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

@@ -0,0 +1,138 @@
{
"schemaVersion": 1,
"type": "planet",
"defaultView": "revolution",
"views": [
"revolution"
],
"nameI18n": {
"zh-CN": "地球公转",
"en": "Earth Revolution"
},
"descriptionI18n": {
"zh-CN": "地球绕太阳公转一年:地轴指向不变,太阳直射点南北往返,形成四季。",
"en": "One year around the Sun: the fixed axial direction moves the subsolar point and creates the seasons."
},
"star": {
"name": "Sun",
"nameI18n": {
"zh-CN": "太阳",
"en": "Sun"
},
"color": "#FFC24B",
"radiusScale": 0.5
},
"planet": {
"name": "Earth",
"nameI18n": {
"zh-CN": "地球",
"en": "Earth"
},
"axialTiltDeg": 23.5,
"tropicDeg": 23.5,
"rotationHours": 23.93,
"orbitDays": 365.26,
"oceanColor": "#1C5FA8",
"landColor": "#4E8C4C",
"iceColor": "#E9EFF6",
"landFile": "land.json",
"showGraticule": false
},
"orbit": {
"semiMajorAxis": 4.0,
"eccentricity": 0.0167,
"show": true,
"seasons": [
{
"angleDeg": 0,
"key": "season.springEquinox",
"date": "3/21",
"declinationDeg": 0,
"teachingI18n": {
"zh-CN": "太阳直射赤道,全球昼夜平分。此后直射点由赤道向北移动。",
"en": "The Sun is overhead at the equator and day equals night everywhere. The subsolar point now moves north."
}
},
{
"angleDeg": 90,
"key": "season.summerSolstice",
"date": "6/22",
"declinationDeg": 23.5,
"teachingI18n": {
"zh-CN": "太阳直射北回归线 23.5°N。北半球昼最长、夜最短,北极圈内出现极昼。",
"en": "The Sun is overhead at the Tropic of Cancer (23.5°N). The northern hemisphere has its longest day."
}
},
{
"angleDeg": 180,
"key": "season.autumnEquinox",
"date": "9/23",
"declinationDeg": 0,
"teachingI18n": {
"zh-CN": "太阳再次直射赤道,全球昼夜平分。此后直射点向南移动。",
"en": "The Sun is overhead at the equator again. The subsolar point now moves south."
}
},
{
"angleDeg": 270,
"key": "season.winterSolstice",
"date": "12/22",
"declinationDeg": -23.5,
"teachingI18n": {
"zh-CN": "太阳直射南回归线 23.5°S。北半球昼最短、夜最长,北极圈内出现极夜。",
"en": "The Sun is overhead at the Tropic of Capricorn (23.5°S). The northern hemisphere has its shortest day."
}
}
]
},
"lessons": [
{
"titleI18n": {
"zh-CN": "一年绕太阳一圈",
"en": "One lap per year"
},
"bodyI18n": {
"zh-CN": "公转方向与自转相同,周期约 365.26 天;轨道接近圆形。",
"en": "The orbit takes about 365.26 days and runs the same direction as the spin."
},
"view": "revolution",
"angleDeg": 0
},
{
"titleI18n": {
"zh-CN": "地轴指向不变",
"en": "The axis keeps its direction"
},
"bodyI18n": {
"zh-CN": "公转过程中地轴始终指向北极星附近,黄赤交角 23.5° 保持不变。",
"en": "During the whole orbit the axis keeps pointing near Polaris, so the 23.5° tilt stays fixed in space."
},
"view": "revolution",
"angleDeg": 90
},
{
"titleI18n": {
"zh-CN": "夏至与冬至",
"en": "Solstices"
},
"bodyI18n": {
"zh-CN": "夏至太阳直射北回归线 23.5°N,北半球昼最长;冬至直射南回归线 23.5°S。",
"en": "At the June solstice the Sun is overhead at 23.5°N; at the December solstice at 23.5°S."
},
"view": "revolution",
"angleDeg": 90
},
{
"titleI18n": {
"zh-CN": "春分与秋分",
"en": "Equinoxes"
},
"bodyI18n": {
"zh-CN": "春分、秋分太阳直射赤道,全球昼夜平分,是四季的转折点。",
"en": "At the equinoxes the Sun is overhead at the equator and day equals night everywhere."
},
"view": "revolution",
"angleDeg": 180
}
]
}
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>NeoRF.EarthModels</RootNamespace>
<AssemblyName>EarthRevolutionModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<!-- 共享引擎源码就在 model/_engine 里(模型目录内),本模型直接编译进去 -->
<ItemGroup>
<Compile Include="../../_engine/src/**/*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
@@ -0,0 +1,11 @@
using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels;
/// <summary>地球公转模型入口(清单里的 type 指向这里)。</summary>
public sealed class RevolutionModelFactory : IModelFactory
{
public int ApiVersion => EarthModelRuntime.SupportedApiVersion;
public IModelRuntime Create() => new EarthModelRuntime();
}
+28
View File
@@ -0,0 +1,28 @@
{
"schemaVersion": 1,
"id": "earth-rotation",
"name": "Earth Rotation",
"nameI18n": {
"zh-CN": "地球自转",
"en": "Earth Rotation"
},
"version": "1.0.0",
"author": "NeoRF",
"description": "昼夜交替、晨昏线与太阳直射点",
"descriptionI18n": {
"zh-CN": "观察自转中的地球:昼夜半球、晨昏线与太阳直射点位置。",
"en": "Watch a rotating Earth: day/night hemispheres, terminator and the subsolar point."
},
"tags": [
"astronomy",
"geography",
"rotation"
],
"entry": "scene.json",
"license": "MIT",
"updatedAt": "2026-11-07",
"assembly": "EarthRotationModel.dll",
"type": "NeoRF.EarthModels.RotationModelFactory",
"preview": "preview.png",
"apiVersion": 1
}
@@ -0,0 +1,33 @@
{
"title": "Earth Rotation",
"view.rotation": "Rotation",
"view.revolution": "Revolution",
"play": "Play",
"pause": "Pause",
"speed": "Speed",
"reset": "Reset",
"labels": "Labels",
"orbit": "Orbit",
"grid": "Graticule",
"tilt": "Exaggerate tilt",
"lessons": "Teaching notes",
"seasons": "Solstices & equinoxes",
"close": "Close window",
"loading": "Preparing scene…",
"subsolar": "Subsolar point",
"north": "North pole",
"south": "South pole",
"northShort": "N",
"southShort": "S",
"sun": "Sun",
"earth": "Earth",
"spinInfo": "Rotation {0}° · period {1} h",
"orbitInfo": "Orbit {0}°",
"declinationInfo": "Subsolar {0}",
"dateInfo": "Date {0}",
"season.springEquinox": "Spring equinox",
"season.summerSolstice": "Summer solstice",
"season.autumnEquinox": "Autumn equinox",
"season.winterSolstice": "Winter solstice",
"hint": "Pinch or scroll to zoom · drag to turn the Earth"
}
@@ -0,0 +1,33 @@
{
"title": "地球自转",
"view.rotation": "自转",
"view.revolution": "公转",
"play": "播放",
"pause": "暂停",
"speed": "速度",
"reset": "重置",
"labels": "标注",
"orbit": "轨道",
"grid": "经纬网",
"tilt": "夸张倾角",
"lessons": "教学要点",
"seasons": "节气定位",
"close": "关闭窗口",
"loading": "正在准备场景…",
"subsolar": "太阳直射点",
"north": "北极",
"south": "南极",
"northShort": "N",
"southShort": "S",
"sun": "太阳",
"earth": "地球",
"spinInfo": "自转 {0}° · 周期 {1} 小时",
"orbitInfo": "公转 {0}°",
"declinationInfo": "太阳直射 {0}",
"dateInfo": "日期 {0}",
"season.springEquinox": "春分",
"season.summerSolstice": "夏至",
"season.autumnEquinox": "秋分",
"season.winterSolstice": "冬至",
"hint": "双指捏合或滚轮缩放 · 拖动可转动地球"
}
@@ -0,0 +1,98 @@
{
"schema": 1,
"note": "简化大陆轮廓(经度,纬度),用于教学演示,非测绘精度",
"polygons": [
{
"name": "north-america",
"points": [[-168,66],[-164,70],[-155,71],[-145,70],[-133,69],[-120,69],[-110,68],[-100,69],[-92,68],[-85,70],[-80,73],[-72,71],[-64,66],[-60,60],[-56,52],[-60,47],[-66,45],[-70,42],[-74,40],[-76,35],[-81,31],[-80,25],[-83,29],[-88,30],[-94,29],[-97,26],[-97,21],[-92,19],[-87,21],[-88,16],[-83,9],[-78,9],[-84,14],[-90,14],[-96,16],[-105,20],[-112,25],[-117,32],[-122,37],[-124,42],[-125,48],[-131,54],[-140,59],[-150,59],[-158,56],[-165,60],[-166,64]]
},
{
"name": "greenland",
"points": [[-45,60],[-52,64],[-55,68],[-60,72],[-63,76],[-56,80],[-42,82],[-28,80],[-21,74],[-23,70],[-31,66],[-38,62]]
},
{
"name": "south-america",
"points": [[-78,8],[-72,11],[-64,10],[-60,8],[-52,5],[-50,0],[-44,-2],[-38,-5],[-35,-8],[-39,-13],[-41,-22],[-48,-25],[-53,-34],[-57,-38],[-62,-40],[-65,-45],[-68,-50],[-70,-55],[-75,-52],[-74,-45],[-73,-37],[-71,-30],[-70,-23],[-70,-18],[-76,-14],[-81,-6],[-80,-2],[-79,2],[-77,6]]
},
{
"name": "africa",
"points": [[-17,15],[-16,20],[-13,28],[-9,32],[-5,36],[10,37],[20,32],[32,31],[35,28],[39,15],[43,11],[51,12],[48,2],[41,-2],[40,-10],[35,-18],[32,-25],[27,-33],[20,-35],[15,-28],[12,-17],[9,-1],[5,4],[-4,5],[-8,4],[-13,8],[-16,12]]
},
{
"name": "europe",
"points": [[-9,38],[-9,43],[-2,44],[0,48],[2,51],[5,53],[8,54],[9,57],[12,56],[13,54],[20,54],[21,57],[24,58],[28,60],[30,60],[29,64],[25,66],[22,69],[30,70],[40,68],[46,66],[55,68],[60,70],[68,68],[62,62],[58,56],[52,50],[48,46],[40,45],[36,44],[30,45],[28,41],[24,40],[23,37],[19,40],[16,41],[12,44],[7,44],[3,42],[-2,37]]
},
{
"name": "asia",
"points": [[60,70],[75,73],[90,75],[105,77],[115,74],[130,73],[145,72],[160,70],[170,68],[180,65],[172,62],[163,58],[155,52],[143,54],[137,50],[130,43],[126,40],[122,40],[120,36],[122,31],[118,25],[110,21],[105,10],[100,13],[98,8],[95,17],[90,22],[88,21],[80,16],[77,8],[73,18],[68,23],[62,25],[57,24],[52,28],[48,30],[44,13],[43,17],[39,21],[35,28],[34,31],[36,36],[30,41],[28,41],[30,45],[34,45],[40,45],[48,46],[52,50],[58,56],[62,62],[68,68]]
},
{
"name": "australia",
"points": [[113,-22],[114,-27],[116,-35],[129,-32],[138,-35],[146,-39],[150,-37],[153,-28],[146,-19],[142,-11],[132,-11],[126,-14],[122,-18]]
},
{
"name": "antarctica",
"points": [[-180,-72],[-150,-76],[-120,-74],[-90,-73],[-60,-64],[-30,-70],[0,-70],[30,-69],[60,-67],[90,-66],[120,-66],[150,-70],[180,-72],[180,-90],[-180,-90]]
},
{
"name": "madagascar",
"points": [[43,-12],[50,-15],[50,-25],[45,-25],[43,-20]]
},
{
"name": "japan",
"points": [[130,32],[136,35],[141,40],[145,44],[142,39],[137,34],[133,33]]
},
{
"name": "britain",
"points": [[-6,50],[-2,53],[-2,58],[-5,58],[-6,54]]
},
{
"name": "ireland",
"points": [[-10,52],[-6,53],[-6,55],[-10,55]]
},
{
"name": "iceland",
"points": [[-24,65],[-14,66],[-14,64],[-22,63]]
},
{
"name": "new-zealand",
"points": [[166,-46],[170,-44],[174,-41],[177,-38],[174,-35],[170,-38],[167,-42]]
},
{
"name": "sumatra",
"points": [[95,5],[100,1],[105,-6],[100,-4],[96,2]]
},
{
"name": "java",
"points": [[105,-6],[114,-8],[114,-9],[106,-7]]
},
{
"name": "borneo",
"points": [[109,2],[117,4],[119,-2],[115,-4],[110,-2]]
},
{
"name": "sulawesi",
"points": [[119,1],[125,1],[123,-5],[120,-3]]
},
{
"name": "new-guinea",
"points": [[131,-1],[141,-3],[150,-6],[147,-9],[140,-9],[134,-5]]
},
{
"name": "sri-lanka",
"points": [[80,9],[82,7],[81,6],[79,7]]
},
{
"name": "philippines",
"points": [[120,18],[124,13],[126,8],[122,6],[120,12]]
},
{
"name": "cuba",
"points": [[-85,22],[-77,20],[-74,20],[-80,23]]
},
{
"name": "taiwan",
"points": [[120,25],[122,24],[121,22],[120,23]]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

@@ -0,0 +1,138 @@
{
"schemaVersion": 1,
"type": "planet",
"defaultView": "rotation",
"views": [
"rotation"
],
"nameI18n": {
"zh-CN": "地球自转",
"en": "Earth Rotation"
},
"descriptionI18n": {
"zh-CN": "观察自转中的地球:昼夜半球、晨昏线与太阳直射点位置。",
"en": "Watch a rotating Earth: day/night hemispheres, terminator and the subsolar point."
},
"star": {
"name": "Sun",
"nameI18n": {
"zh-CN": "太阳",
"en": "Sun"
},
"color": "#FFC24B",
"radiusScale": 0.5
},
"planet": {
"name": "Earth",
"nameI18n": {
"zh-CN": "地球",
"en": "Earth"
},
"axialTiltDeg": 23.5,
"tropicDeg": 23.5,
"rotationHours": 23.93,
"orbitDays": 365.26,
"oceanColor": "#1C5FA8",
"landColor": "#4E8C4C",
"iceColor": "#E9EFF6",
"landFile": "land.json",
"showGraticule": true
},
"orbit": {
"semiMajorAxis": 4.0,
"eccentricity": 0.0167,
"show": true,
"seasons": [
{
"angleDeg": 0,
"key": "season.springEquinox",
"date": "3/21",
"declinationDeg": 0,
"teachingI18n": {
"zh-CN": "太阳直射赤道,全球昼夜平分。",
"en": "The Sun is overhead at the equator and day equals night everywhere."
}
},
{
"angleDeg": 90,
"key": "season.summerSolstice",
"date": "6/22",
"declinationDeg": 23.5,
"teachingI18n": {
"zh-CN": "太阳直射北回归线 23.5°N,北半球昼最长。",
"en": "The Sun is overhead at 23.5°N; the northern hemisphere has its longest day."
}
},
{
"angleDeg": 180,
"key": "season.autumnEquinox",
"date": "9/23",
"declinationDeg": 0,
"teachingI18n": {
"zh-CN": "太阳直射赤道,全球昼夜平分。",
"en": "The Sun is overhead at the equator and day equals night everywhere."
}
},
{
"angleDeg": 270,
"key": "season.winterSolstice",
"date": "12/22",
"declinationDeg": -23.5,
"teachingI18n": {
"zh-CN": "太阳直射南回归线 23.5°S,北半球昼最短。",
"en": "The Sun is overhead at 23.5°S; the northern hemisphere has its shortest day."
}
}
]
},
"lessons": [
{
"titleI18n": {
"zh-CN": "自西向东的自转",
"en": "Rotation from west to east"
},
"bodyI18n": {
"zh-CN": "从北极上空看,地球逆时针转动;转一圈用 23 小时 56 分 4 秒。",
"en": "Seen from above the north pole the Earth turns counter-clockwise, once every 23 h 56 min."
},
"view": "rotation",
"angleDeg": 0
},
{
"titleI18n": {
"zh-CN": "昼夜交替",
"en": "Day and night"
},
"bodyI18n": {
"zh-CN": "晨昏线(白色虚线)把地球分成昼半球与夜半球,交替周期 24 小时。",
"en": "The terminator (white dashes) splits the lit and dark hemispheres; one cycle takes 24 h."
},
"view": "rotation",
"angleDeg": 60
},
{
"titleI18n": {
"zh-CN": "太阳直射点",
"en": "Subsolar point"
},
"bodyI18n": {
"zh-CN": "黄色圆环标出太阳光垂直照射的位置,它随季节在南北回归线之间往返。",
"en": "The yellow ring marks where sunlight strikes vertically — it drifts between the tropics over a year."
},
"view": "rotation",
"angleDeg": 120
},
{
"titleI18n": {
"zh-CN": "地轴倾斜 23.5°",
"en": "Axial tilt 23.5°"
},
"bodyI18n": {
"zh-CN": "地轴与黄道面法线成 23.5°,倾斜方向不变,这是四季与五带划分的根本原因。",
"en": "The axis is tilted 23.5° from the ecliptic normal and keeps its direction — the root cause of seasons."
},
"view": "rotation",
"angleDeg": 200
}
]
}
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>NeoRF.EarthModels</RootNamespace>
<AssemblyName>EarthRotationModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<!-- 共享引擎源码就在 model/_engine 里(模型目录内),本模型直接编译进去 -->
<ItemGroup>
<Compile Include="../../_engine/src/**/*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
@@ -0,0 +1,11 @@
using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels;
/// <summary>地球自转模型入口(清单里的 type 指向这里)。</summary>
public sealed class RotationModelFactory : IModelFactory
{
public int ApiVersion => EarthModelRuntime.SupportedApiVersion;
public IModelRuntime Create() => new EarthModelRuntime();
}
@@ -0,0 +1,28 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:EarthModelStudio.ViewModels"
xmlns:views="using:EarthModelStudio.Views"
x:Class="EarthModelStudio.App"
RequestedThemeVariant="Light">
<Application.DataTemplates>
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<views:HomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:DownloadViewModel}">
<views:DownloadView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
<views:SettingsView />
</DataTemplate>
</Application.DataTemplates>
<Application.Resources>
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
</Application.Resources>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://EarthModelStudio/Styles/AppTheme.axaml" />
</Application.Styles>
</Application>
@@ -0,0 +1,70 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using EarthModelStudio.Services;
using EarthModelStudio.ViewModels;
using EarthModelStudio.Views;
namespace EarthModelStudio;
public partial class App : Application
{
public override void Initialize() => AvaloniaXamlLoader.Load(this);
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var services = AppServices.Create();
// 诊断模式:只验证模型程序集能否加载(发布包里也用它做冒烟测试)
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1")
{
var code = SelfTest(services);
Avalonia.Threading.Dispatcher.UIThread.Post(
() => desktop.Shutdown(code), Avalonia.Threading.DispatcherPriority.Background);
return;
}
var vm = new MainViewModel(services);
var window = new MainWindow { DataContext = vm };
vm.ConfirmHandler = async message =>
{
var dialog = new ConfirmWindow(message);
return await dialog.ShowDialog<bool>(window);
};
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
base.OnFrameworkInitializationCompleted();
}
/// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary>
private static int SelfTest(AppServices services)
{
var packages = services.Models.Scan();
Console.WriteLine($"模型库: {services.Paths.ModelRoot}");
Console.WriteLine($"模型数: {packages.Count}");
var failed = 0;
foreach (var package in packages)
{
try
{
using var loaded = services.ModelHost.Load(package, () => { });
Console.WriteLine($"OK {package.Id} -> {loaded.View.GetType().FullName}");
}
catch (Exception ex)
{
failed++;
Console.WriteLine($"FAIL {package.Id}: {ex.Message}");
}
}
return failed == 0 ? 0 : 1;
}
}
@@ -0,0 +1,139 @@
{
"app.name": "Earth Model Studio",
"app.tagline": "Astronomy teaching models · visual launcher",
"app.version": "Version",
"app.platform": "Platform",
"nav.home": "Home",
"nav.download": "Download",
"nav.settings": "Settings",
"home.title": "Model library",
"home.subtitle": "Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.",
"home.launch": "Launch model",
"home.download": "Get models",
"home.settings": "Settings",
"home.installed": "Installed models",
"home.count": "{0} models",
"home.empty": "No models yet",
"home.emptyHint": "Import a model source on the Download page, or drop a model folder into model/.",
"home.emptyAction": "Get models",
"home.open": "Open folder",
"home.delete": "Delete",
"home.deleteConfirm": "Delete the model \"{0}\"? Its files will be removed from the local library.",
"home.size": "Size",
"home.stats.models": "Installed",
"home.stats.sources": "Sources",
"home.stats.memory": "Memory budget",
"home.recent": "Select a model, then press Launch",
"home.getMore": "Get more models",
"home.launchHint": "Models open in their own window with play/pause, view controls and teaching notes.",
"dl.title": "Download",
"dl.subtitle": "Import a model source: git repository, zip archive or local folder. The model/ folder in the repo is the model list.",
"dl.import": "Import source",
"dl.importPlaceholder": "https://github.com/user/repo.git or /path/to/model-repo",
"dl.sources": "Sources",
"dl.refresh": "Refresh",
"dl.remove": "Remove",
"dl.noSource": "No sources yet",
"dl.pickSource": "Select a source to see available models",
"dl.available": "Available models",
"dl.download": "Download",
"dl.installed": "Installed",
"dl.reinstall": "Re-download",
"dl.background": "Background tasks",
"dl.bgEmpty": "No background tasks",
"dl.cancel": "Cancel",
"dl.retry": "Retry",
"dl.clearDone": "Clear finished",
"dl.removeTask": "Remove",
"dl.status.queued": "Queued",
"dl.status.downloading": "Downloading",
"dl.status.done": "Completed",
"dl.status.failed": "Failed",
"dl.status.canceled": "Canceled",
"dl.hint": "GitHub / GitLab / Gitee repository URLs, zip links and local folders are supported",
"dl.empty": "No models in this source",
"dl.emptyHint": "A source needs model/<model-id>/<model-id>.json layout",
"dl.syncing": "Reading model source…",
"dl.ready": "{0} models",
"dl.fromCache": "cached",
"dl.imported": "Source imported",
"dl.importFailed": "Import failed: {0}",
"dl.error.emptyUrl": "Please enter a source URL",
"dl.error.canceled": "Canceled",
"dl.error.unreachable": "Cannot reach this source, check the URL or network",
"dl.sourceDefault": "Source",
"set.title": "Settings",
"set.subtitle": "Model sources, startup memory allocation and local storage.",
"set.general": "General",
"set.language": "Language",
"set.language.auto": "System",
"set.fps": "Render frame rate",
"set.fps.desc": "Higher is smoother but uses more CPU.",
"set.memory": "Startup memory allocation",
"set.memory.desc": "The launcher hands this budget to each model; models decide how much data to cache with it.",
"set.memory.current": "In use",
"set.memory.unit": "MB",
"set.memory.hint": "2048 MB or more is recommended; 1024 MB for low-end devices.",
"set.preallocate": "Preload land data at startup",
"set.preallocate.desc": "Faster first frame, slightly slower startup.",
"set.sources": "Model sources",
"set.sources.desc": "Disabled sources are hidden from the Download page.",
"set.sourceEnabled": "Enabled",
"set.addSource": "Add source",
"set.sourceName": "Name",
"set.storage": "Storage",
"set.modelDir": "Model library",
"set.dataDir": "Data folder",
"set.openFolder": "Open folder",
"set.clearCache": "Clear cache",
"set.cacheCleared": "Cache cleared",
"set.about": "About",
"set.version": "Version",
"set.platform": "Platform",
"set.license": "License",
"set.licenseValue": "MIT",
"set.checkUpdate": "Check for updates",
"set.checkUpdate.desc": "Offline build — update by replacing the app folder.",
"set.modelFormat": "Model format",
"set.modelFormat.desc": "model/<model-id>/<model-id>.json + <model-id>.model/ scene data",
"player.back": "Close window",
"player.view.rotation": "Rotation",
"player.view.revolution": "Revolution",
"player.play": "Play",
"player.pause": "Pause",
"player.speed": "Speed",
"player.reset": "Reset",
"player.labels": "Labels",
"player.orbit": "Orbit",
"player.grid": "Graticule",
"player.tilt": "Exaggerate tilt",
"player.lessons": "Teaching notes",
"player.seasons": "Solstices & equinoxes",
"player.loading": "Preparing scene…",
"player.subsolar": "Subsolar point",
"player.north": "North pole",
"player.south": "South pole",
"player.northShort": "N",
"player.southShort": "S",
"player.spinInfo": "Rotation {0}° · period {1} h",
"player.orbitInfo": "Orbit {0}°",
"player.declinationInfo": "Subsolar {0}",
"player.dateInfo": "Date {0}",
"player.paused": "Paused",
"star.sun": "Sun",
"planet.earth": "Earth",
"season.springEquinox": "Spring equinox",
"season.summerSolstice": "Summer solstice",
"season.autumnEquinox": "Autumn equinox",
"season.winterSolstice": "Winter solstice",
"common.cancel": "Cancel",
"common.confirm": "Confirm",
"common.delete": "Delete",
"common.close": "Close",
"common.open": "Open",
"common.applied": "Applied",
"common.confirmTitle": "Please confirm",
"player.windowHint": "The model runs in its own window; close it to exit",
"player.errorTitle": "Failed to launch \"{0}\"",
"player.errorHint": "The model package has no usable assembly. Make sure <id>.model contains the model dll, or re-download it."
}
@@ -0,0 +1,139 @@
{
"app.name": "地球模型工作室",
"app.tagline": "天文教学模型 · 可视化启动器",
"app.version": "版本",
"app.platform": "平台",
"nav.home": "主页",
"nav.download": "下载",
"nav.settings": "设置",
"home.title": "模型库",
"home.subtitle": "选择模型,用可交互的三维演示讲清自转、公转与四季成因。",
"home.launch": "启动模型",
"home.download": "下载模型",
"home.settings": "设置",
"home.installed": "已安装模型",
"home.count": "{0} 个模型",
"home.empty": "模型库还是空的",
"home.emptyHint": "在「下载」页从链接导入模型源,或把模型直接放进 model 目录。",
"home.emptyAction": "去下载模型",
"home.open": "打开目录",
"home.delete": "删除",
"home.deleteConfirm": "删除模型「{0}」?模型文件会从本地模型库移除。",
"home.size": "体积",
"home.stats.models": "已安装",
"home.stats.sources": "模型源",
"home.stats.memory": "内存预算",
"home.recent": "选择模型后点击「启动模型」",
"home.getMore": "获取更多模型",
"home.launchHint": "模型在自己的窗口里运行,可播放/暂停、切换视角并使用教学要点。",
"dl.title": "下载模型",
"dl.subtitle": "从链接导入模型源:git 仓库、zip 压缩包或本地目录。仓库里的 model/ 文件夹就是模型列表。",
"dl.import": "导入模型源",
"dl.importPlaceholder": "https://github.com/user/repo.git 或 /本地/模型仓库",
"dl.sources": "模型源",
"dl.refresh": "刷新",
"dl.remove": "移除",
"dl.noSource": "还没有模型源",
"dl.pickSource": "选择一个模型源,查看可下载的模型",
"dl.available": "可用模型",
"dl.download": "下载",
"dl.installed": "已安装",
"dl.reinstall": "重新下载",
"dl.background": "后台任务",
"dl.bgEmpty": "暂无后台任务",
"dl.cancel": "取消",
"dl.retry": "重试",
"dl.clearDone": "清除已完成",
"dl.removeTask": "移除",
"dl.status.queued": "排队中",
"dl.status.downloading": "下载中",
"dl.status.done": "已完成",
"dl.status.failed": "失败",
"dl.status.canceled": "已取消",
"dl.hint": "支持 GitHub / GitLab / Gitee 仓库地址、zip 直链、本地目录",
"dl.empty": "这个源里没有模型",
"dl.emptyHint": "仓库需要包含 model/<模型ID>/<模型ID>.json 结构",
"dl.syncing": "正在读取模型源…",
"dl.ready": "共 {0} 个模型",
"dl.fromCache": "本地缓存",
"dl.imported": "已导入模型源",
"dl.importFailed": "导入失败:{0}",
"dl.error.emptyUrl": "请填写模型源链接",
"dl.error.canceled": "已取消",
"dl.error.unreachable": "无法访问该模型源,请检查链接或网络",
"dl.sourceDefault": "模型源",
"set.title": "设置",
"set.subtitle": "模型源、启动时内存分配与本地存储。",
"set.general": "通用",
"set.language": "界面语言",
"set.language.auto": "跟随系统",
"set.fps": "渲染帧率",
"set.fps.desc": "越高越顺滑,CPU 占用也越高。",
"set.memory": "启动时运行内存分配",
"set.memory.desc": "启动器把这份预算交给模型:模型自己决定用它缓存多少数据(贴图分辨率、缓冲等)。",
"set.memory.current": "当前占用",
"set.memory.unit": "MB",
"set.memory.hint": "建议 2048 MB 以上,低配设备可选 1024 MB。",
"set.preallocate": "启动时预加载模型地表数据",
"set.preallocate.desc": "打开后首帧更快,启动耗时略增。",
"set.sources": "模型源",
"set.sources.desc": "停用的模型源不会出现在下载页。",
"set.sourceEnabled": "启用",
"set.addSource": "添加模型源",
"set.sourceName": "名称",
"set.storage": "存储",
"set.modelDir": "模型库目录",
"set.dataDir": "数据目录",
"set.openFolder": "打开文件夹",
"set.clearCache": "清理缓存",
"set.cacheCleared": "缓存已清理",
"set.about": "关于",
"set.version": "版本",
"set.platform": "平台",
"set.license": "许可",
"set.licenseValue": "MIT",
"set.checkUpdate": "检查更新",
"set.checkUpdate.desc": "当前为离线构建,更新请替换程序目录。",
"set.modelFormat": "模型格式",
"set.modelFormat.desc": "model/<模型ID>/<模型ID>.json + <模型ID>.model/ 场景数据",
"player.back": "关闭窗口",
"player.view.rotation": "自转",
"player.view.revolution": "公转",
"player.play": "播放",
"player.pause": "暂停",
"player.speed": "速度",
"player.reset": "重置",
"player.labels": "标注",
"player.orbit": "轨道",
"player.grid": "经纬网",
"player.tilt": "夸张倾角",
"player.lessons": "教学要点",
"player.seasons": "节气定位",
"player.loading": "正在准备场景…",
"player.subsolar": "太阳直射点",
"player.north": "北极",
"player.south": "南极",
"player.northShort": "N",
"player.southShort": "S",
"player.spinInfo": "自转 {0}° · 周期 {1} 小时",
"player.orbitInfo": "公转 {0}°",
"player.declinationInfo": "太阳直射 {0}",
"player.dateInfo": "日期 {0}",
"player.paused": "已暂停",
"star.sun": "太阳",
"planet.earth": "地球",
"season.springEquinox": "春分",
"season.summerSolstice": "夏至",
"season.autumnEquinox": "秋分",
"season.winterSolstice": "冬至",
"common.cancel": "取消",
"common.confirm": "确定",
"common.delete": "删除",
"common.close": "关闭",
"common.open": "打开",
"common.applied": "已应用",
"common.confirmTitle": "请确认",
"player.windowHint": "模型在独立窗口中运行,关闭窗口即退出模型",
"player.errorTitle": "模型「{0}」启动失败",
"player.errorHint": "模型包里没有可用的功能程序集。请确认 <id>.model 目录内有模型 dll,或重新下载该模型。"
}
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>EarthModelStudio</RootNamespace>
<AssemblyName>EarthModelStudio</AssemblyName>
<ApplicationManifest>app.manifest</ApplicationManifest>
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<InvariantGlobalization>false</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="Assets\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
</ItemGroup>
<!-- 模型契约:启动器与模型唯一的共享代码(不含任何渲染/业务) -->
<ItemGroup>
<ProjectReference Include="..\..\..\..\model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace EarthModelStudio.Models;
/// <summary>应用设置,持久化到 data/settings.json。</summary>
public sealed class AppSettings
{
/// <summary>auto | zh-CN | en</summary>
public string Language { get; set; } = "auto";
/// <summary>light | dark</summary>
public string Theme { get; set; } = "light";
/// <summary>渲染帧率:24 / 30 / 60</summary>
public int RenderFps { get; set; } = 30;
/// <summary>启动时运行内存分配(MB)——决定场景缓存/纹理预算。</summary>
public int MemoryMb { get; set; } = 2048;
/// <summary>启动时检查模型源更新。</summary>
public bool CheckSourceOnStartup { get; set; }
/// <summary>模型库目录覆盖(留空则自动探测)。</summary>
public string? ModelRootOverride { get; set; }
public List<ModelSource> Sources { get; set; } = new();
public List<string> RecentModels { get; set; } = new();
}
/// <summary>模型源:一个满足 Earth Model 规范的 git 仓库 / zip / 本地目录。</summary>
public sealed class ModelSource
{
public string Id { get; set; } = Guid.NewGuid().ToString("N")[..8];
public string Name { get; set; } = "";
public string Url { get; set; } = "";
public string? Branch { get; set; }
public bool Enabled { get; set; } = true;
public bool BuiltIn { get; set; }
public string? LastSynced { get; set; }
[JsonIgnore]
public string DisplayHost
{
get
{
if (string.IsNullOrWhiteSpace(Url)) return "";
if (Url.StartsWith("file:", StringComparison.OrdinalIgnoreCase) || System.IO.Path.IsPathRooted(Url))
return "local";
return Uri.TryCreate(Url, UriKind.Absolute, out var u) ? u.Host : Url;
}
}
}
@@ -0,0 +1,98 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace EarthModelStudio.Models;
/// <summary>model/&lt;id&gt;/&lt;id&gt;.json 的内容。</summary>
public sealed class ModelManifest
{
public int SchemaVersion { get; set; } = 1;
public string Id { get; set; } = "";
public string Name { get; set; } = "";
public Dictionary<string, string>? NameI18n { get; set; }
public string Version { get; set; } = "1.0.0";
public string Author { get; set; } = "";
public string Description { get; set; } = "";
public Dictionary<string, string>? DescriptionI18n { get; set; }
public List<string>? Tags { get; set; }
/// <summary>相对 &lt;id&gt;.model 目录的入口文件,默认 scene.json</summary>
public string? Entry { get; set; }
/// <summary>模型自带的界面程序集(相对 &lt;id&gt;.model),默认 &lt;id&gt;.dll</summary>
public string? Assembly { get; set; }
/// <summary>实现 IModelFactory 的类型全名;留空则自动查找</summary>
public string? Type { get; set; }
/// <summary>封面图文件名,默认 preview.png</summary>
public string? Preview { get; set; }
/// <summary>模型契约版本</summary>
public int ApiVersion { get; set; } = 1;
public string? License { get; set; }
public string? UpdatedAt { get; set; }
public string? MinAppVersion { get; set; }
}
public sealed class ModelPackage
{
public ModelManifest Manifest { get; init; } = new();
public string Directory { get; init; } = "";
public long SizeBytes { get; set; }
public string Id => Manifest.Id;
public string DataDirectory => System.IO.Path.Combine(Directory, Id + ".model");
public string ScenePath
{
get
{
var entry = string.IsNullOrWhiteSpace(Manifest.Entry) ? "scene.json" : Manifest.Entry!;
if (entry.StartsWith(Id + ".model")) return System.IO.Path.Combine(Directory, entry);
return System.IO.Path.Combine(DataDirectory, entry);
}
}
/// <summary>模型自带的界面程序集路径。</summary>
public string AssemblyPath
{
get
{
var file = string.IsNullOrWhiteSpace(Manifest.Assembly) ? Id + ".dll" : Manifest.Assembly!;
return System.IO.Path.IsPathRooted(file) ? file : System.IO.Path.Combine(DataDirectory, file);
}
}
/// <summary>封面图路径(launcher 只显示,不渲染)。</summary>
public string PreviewPath
{
get
{
var file = string.IsNullOrWhiteSpace(Manifest.Preview) ? "preview.png" : Manifest.Preview!;
return System.IO.Path.IsPathRooted(file) ? file : System.IO.Path.Combine(DataDirectory, file);
}
}
public string LocalizedName => Services.L.I.Pick(Manifest.NameI18n,
string.IsNullOrWhiteSpace(Manifest.Name) ? Id : Manifest.Name);
public string LocalizedDescription => Services.L.I.Pick(Manifest.DescriptionI18n, Manifest.Description);
}
public sealed class RemoteModel
{
public ModelManifest Manifest { get; init; } = new();
public string Directory { get; init; } = "";
public long SizeBytes { get; init; }
public string SourceId { get; init; } = "";
public string Id => Manifest.Id;
public string LocalizedName => Services.L.I.Pick(Manifest.NameI18n,
string.IsNullOrWhiteSpace(Manifest.Name) ? Id : Manifest.Name);
public string LocalizedDescription => Services.L.I.Pick(Manifest.DescriptionI18n, Manifest.Description);
}
public sealed class SourceIndex
{
public string SourceId { get; init; } = "";
public string Root { get; init; } = "";
public bool FromCache { get; init; }
public List<RemoteModel> Models { get; init; } = new();
public string? Error { get; init; }
public string ResolvedFrom { get; init; } = "";
}
@@ -0,0 +1,15 @@
using System;
using Avalonia;
namespace EarthModelStudio;
internal static class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
}
@@ -0,0 +1,93 @@
using System;
using System.IO;
namespace EarthModelStudio.Services;
/// <summary>
/// 目录探测。启动器本身不含任何模型数据,模型一律从外部模型库目录读取:
/// 1) 开发态:从 bin 目录向上找到 EarthModelStudio.sln,模型库用仓库根 model/
/// 2) 绿色态:可执行文件旁边有 model/ 目录(发布包默认只建空目录)
/// 3) 安装态:模型库放到用户数据目录
/// 也可用环境变量 EMS_HOME / EMS_MODELS 显式指定。
/// </summary>
public sealed class AppPaths
{
public string AppRoot { get; private init; } = "";
public string ModelRoot { get; private init; } = "";
public string DataRoot { get; private init; } = "";
public bool IsPortableModelRoot { get; private init; }
public string CacheRoot => Path.Combine(DataRoot, "cache");
public string SettingsFile => Path.Combine(DataRoot, "settings.json");
public static AppPaths Discover()
{
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
var dataRoot = Environment.GetEnvironmentVariable("EMS_DATA")
?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EarthModelStudio");
// 显式指定模型库(模型是外置数据,可放在任意磁盘/网络盘)
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
if (!string.IsNullOrWhiteSpace(envModels))
{
return new AppPaths
{
AppRoot = baseDir,
ModelRoot = envModels!,
DataRoot = dataRoot,
IsPortableModelRoot = false
};
}
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
repoRoot = FindRepoRoot(baseDir);
var exeModelDir = Path.Combine(baseDir, "model");
string appRoot, modelRoot;
bool portable = false;
if (!string.IsNullOrEmpty(repoRoot) && Directory.Exists(Path.Combine(repoRoot!, "model")))
{
appRoot = repoRoot!;
modelRoot = Path.Combine(appRoot, "model");
}
else if (Directory.Exists(exeModelDir))
{
appRoot = baseDir;
modelRoot = exeModelDir;
portable = true;
}
else
{
appRoot = baseDir;
modelRoot = Path.Combine(dataRoot, "model");
}
return new AppPaths
{
AppRoot = appRoot,
ModelRoot = modelRoot,
DataRoot = dataRoot,
IsPortableModelRoot = portable
};
}
private static string? FindRepoRoot(string start)
{
var dir = new DirectoryInfo(start);
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
{
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName;
}
return null;
}
public void EnsureCreated()
{
Directory.CreateDirectory(DataRoot);
Directory.CreateDirectory(CacheRoot);
Directory.CreateDirectory(ModelRoot);
}
}
@@ -0,0 +1,49 @@
using System;
namespace EarthModelStudio.Services;
/// <summary>组合根:一处初始化所有服务。</summary>
public sealed class AppServices
{
public static AppServices Current { get; private set; } = null!;
public AppPaths Paths { get; }
public SettingsService Settings { get; }
public ModelRepository Models { get; }
public DownloadCenter Downloads { get; }
public MemoryBudget Memory { get; }
public ModelSourceClient Sources { get; }
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
public ModelHost ModelHost { get; }
private AppServices(AppPaths paths)
{
Paths = paths;
Settings = new SettingsService(paths);
Models = new ModelRepository(paths);
Sources = new ModelSourceClient(paths);
Downloads = new DownloadCenter(paths, Models);
Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory);
}
public static AppServices Create()
{
var paths = AppPaths.Discover();
paths.EnsureCreated();
var services = new AppServices(paths);
services.Settings.Load();
L.I.Initialize(services.Settings.Current.Language);
services.Memory.Apply(services.Settings.Current.MemoryMb);
Current = services;
return services;
}
public static AppServices Ensure()
{
if (Current == null) Create();
return Current;
}
}
@@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
public enum DownloadState
{
Queued,
Running,
Completed,
Failed,
Canceled
}
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
public sealed partial class DownloadJob : ObservableObject
{
public RemoteModel Model { get; }
public string Id => Model.Id;
public string Name => Model.LocalizedName;
public string Version => Model.Manifest.Version;
public CancellationTokenSource Cts { get; } = new();
[ObservableProperty] private DownloadState _state = DownloadState.Queued;
[ObservableProperty] private double _progress;
[ObservableProperty] private string _statusText = "";
[ObservableProperty] private string _detailText = "";
[ObservableProperty] private string? _error;
public DownloadJob(RemoteModel model)
{
Model = model;
RefreshText();
}
public bool IsActive => State is DownloadState.Queued or DownloadState.Running;
public bool CanRetry => State is DownloadState.Failed or DownloadState.Canceled;
public bool IsDone => State == DownloadState.Completed;
public void RefreshText()
{
StatusText = State switch
{
DownloadState.Queued => L.I["dl.status.queued"],
DownloadState.Running => L.I["dl.status.downloading"],
DownloadState.Completed => L.I["dl.status.done"],
DownloadState.Failed => L.I["dl.status.failed"],
_ => L.I["dl.status.canceled"]
};
DetailText = State == DownloadState.Failed && !string.IsNullOrEmpty(Error)
? Error!
: ModelScanner.HumanSize(Model.SizeBytes);
OnPropertyChanged(nameof(IsActive));
OnPropertyChanged(nameof(CanRetry));
OnPropertyChanged(nameof(IsDone));
}
partial void OnStateChanged(DownloadState value) => RefreshText();
partial void OnErrorChanged(string? value) => RefreshText();
}
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
public sealed class DownloadCenter
{
private readonly ModelRepository _repository;
private readonly AppPaths _paths;
private readonly SemaphoreSlim _slots = new(2);
public ObservableCollection<DownloadJob> Jobs { get; } = new();
public event Action? Installed;
public DownloadCenter(AppPaths paths, ModelRepository repository)
{
_paths = paths;
_repository = repository;
}
public DownloadJob Enqueue(RemoteModel model)
{
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
if (running != null) return running;
var job = new DownloadJob(model);
Jobs.Insert(0, job);
_ = RunAsync(job);
return job;
}
private async Task RunAsync(DownloadJob job)
{
// 在 UI 线程构造,回调自动回到 UI 线程
var progress = new Progress<(long Done, long Total)>(p =>
{
job.Progress = p.Total > 0 ? Math.Clamp((double)p.Done / p.Total, 0, 1) : 0;
});
try
{
await _slots.WaitAsync(job.Cts.Token).ConfigureAwait(true);
}
catch (OperationCanceledException)
{
job.State = DownloadState.Canceled;
return;
}
try
{
job.State = DownloadState.Running;
await ModelInstaller.InstallAsync(job.Model, _paths.ModelRoot, progress, job.Cts.Token)
.ConfigureAwait(true);
job.Progress = 1;
job.State = DownloadState.Completed;
_repository.NotifyChanged();
Installed?.Invoke();
}
catch (OperationCanceledException)
{
job.State = DownloadState.Canceled;
}
catch (Exception ex)
{
job.Error = ex.Message;
job.State = DownloadState.Failed;
}
finally
{
_slots.Release();
}
}
public void Cancel(DownloadJob job)
{
try { job.Cts.Cancel(); } catch { }
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
}
public void Retry(DownloadJob job)
{
if (job.IsActive) return;
Jobs.Remove(job);
Enqueue(job.Model);
}
public void Remove(DownloadJob job)
{
Cancel(job);
Jobs.Remove(job);
}
public void ClearFinished()
{
for (var i = Jobs.Count - 1; i >= 0; i--)
{
if (Jobs[i].State is DownloadState.Completed or DownloadState.Canceled)
Jobs.RemoveAt(i);
}
}
public int ActiveCount => Jobs.Count(j => j.IsActive);
}
@@ -0,0 +1,34 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace EarthModelStudio.Services;
public static class Json
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
public static T? Read<T>(string path)
{
if (!System.IO.File.Exists(path)) return default;
return JsonSerializer.Deserialize<T>(System.IO.File.ReadAllText(path), Options);
}
public static void Write<T>(string path, T value)
{
var dir = System.IO.Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir);
var tmp = path + ".tmp";
System.IO.File.WriteAllText(tmp, JsonSerializer.Serialize(value, Options));
System.IO.File.Move(tmp, path, true);
}
}
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text.Json;
using Avalonia.Markup.Xaml;
using Avalonia.Data;
using Avalonia.Platform;
namespace EarthModelStudio.Services;
/// <summary>轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。</summary>
public sealed class L : INotifyPropertyChanged
{
private static readonly L _instance = new();
public static L I => _instance;
private Dictionary<string, string> _map = new(StringComparer.OrdinalIgnoreCase);
private readonly List<WeakReference<LocalizedString>> _watchers = new();
public string Language { get; private set; } = "zh-CN";
public event PropertyChangedEventHandler? PropertyChanged;
public event Action? LanguageChanged;
public static readonly (string Code, string Label)[] Supported =
{
("zh-CN", "简体中文"),
("en", "English")
};
public void Initialize(string? preference)
{
var code = Resolve(preference);
LoadLanguage(code, force: true);
}
public static string Resolve(string? pref)
{
if (!string.IsNullOrWhiteSpace(pref) && !pref.Equals("auto", StringComparison.OrdinalIgnoreCase))
return pref!.StartsWith("en", StringComparison.OrdinalIgnoreCase) ? "en" : "zh-CN";
var ui = CultureInfo.CurrentUICulture;
return ui.TwoLetterISOLanguageName.Equals("zh", StringComparison.OrdinalIgnoreCase) ? "zh-CN" : "en";
}
public void SetLanguage(string code)
{
code = Resolve(code);
if (code == Language) return;
LoadLanguage(code, force: false);
}
private void LoadLanguage(string code, bool force)
{
var loaded = ReadTable(code) ?? ReadTable("en") ?? new Dictionary<string, string>();
if (code != "zh-CN")
{
// 中文兜底,避免缺键出现空白
foreach (var kv in ReadTable("zh-CN") ?? new Dictionary<string, string>())
loaded.TryAdd(kv.Key, kv.Value);
}
_map = loaded;
if (!force && code == Language) return;
Language = code;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language)));
foreach (var w in _watchers)
if (w.TryGetTarget(out var ls)) ls.Refresh();
LanguageChanged?.Invoke();
}
private static Dictionary<string, string>? ReadTable(string code)
{
try
{
var uri = new Uri($"avares://EarthModelStudio/Assets/i18n/{code}.json");
using var stream = AssetLoader.Open(uri);
using var reader = new StreamReader(stream);
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
}
catch
{
return null;
}
}
public string this[string key]
{
get
{
if (string.IsNullOrEmpty(key)) return "";
return _map.TryGetValue(key, out var v) ? v : key;
}
}
public string F(string key, params object?[] args)
{
var fmt = this[key];
try { return string.Format(fmt, args); }
catch (FormatException) { return fmt; }
}
public LocalizedString For(string key)
{
var ls = new LocalizedString(key);
_watchers.Add(new WeakReference<LocalizedString>(ls));
return ls;
}
/// <summary>按 i18n 字典取值:当前语言 -> 英文 -> zh-CN -> 默认名。</summary>
public string Pick(Dictionary<string, string>? dict, string fallback)
{
if (dict == null || dict.Count == 0) return fallback;
if (dict.TryGetValue(Language, out var v) && !string.IsNullOrWhiteSpace(v)) return v;
if (Language != "en" && dict.TryGetValue("en", out var en) && !string.IsNullOrWhiteSpace(en)) return en;
if (dict.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh;
foreach (var kv in dict) if (!string.IsNullOrWhiteSpace(kv.Value)) return kv.Value;
return fallback;
}
}
public sealed class LocalizedString : INotifyPropertyChanged
{
public string Key { get; }
public LocalizedString(string key) => Key = key;
public string Value => L.I[Key];
public event PropertyChangedEventHandler? PropertyChanged;
internal void Refresh() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
}
/// <summary>XAML 用法:Text="{loc:Loc nav.home}"</summary>
public sealed class LocExtension : MarkupExtension
{
public LocExtension() { }
public LocExtension(string key) => Key = key;
public string Key { get; set; } = "";
public override object ProvideValue(IServiceProvider serviceProvider)
=> new Binding(nameof(LocalizedString.Value)) { Source = L.I.For(Key) };
}
@@ -0,0 +1,30 @@
using System;
namespace EarthModelStudio.Services;
/// <summary>
/// 启动时运行内存分配(类似启动器的 -Xmx)。
/// 启动器只负责把这份预算通过 <c>IModelContext.MemoryBudgetMb</c> 交给模型,
/// 具体怎么用(贴图分辨率、缓存大小)由模型自己决定。
/// </summary>
public sealed class MemoryBudget
{
public int BudgetMb { get; private set; } = 2048;
public long BudgetBytes => (long)BudgetMb * 1024L * 1024L;
public long ManagedBytes => GC.GetTotalMemory(false);
public event Action? Changed;
public void Apply(int mb)
{
BudgetMb = Math.Clamp(mb, 256, 16384);
Changed?.Invoke();
}
/// <summary>内存情况变化(例如模型窗口开关)时刷新展示。</summary>
public void Refresh() => Changed?.Invoke();
public double UsageRatio => BudgetBytes <= 0 ? 0 : Math.Clamp((double)ManagedBytes / BudgetBytes, 0, 1);
public string UsageText => $"{ModelScanner.HumanSize(ManagedBytes)} / {BudgetMb} MB";
}
@@ -0,0 +1,233 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Avalonia.Controls;
using EarthModelStudio.Models;
using EarthModelStudio.ModelSdk;
namespace EarthModelStudio.Services;
/// <summary>
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
/// 启动器对“场景 / 行星 / 节气”一无所知,只认契约。
/// </summary>
public sealed class ModelHost
{
public const int SupportedApiVersion = 1;
private readonly AppPaths _paths;
private readonly SettingsService _settings;
private readonly MemoryBudget _memory;
public ModelHost(AppPaths paths, SettingsService settings, MemoryBudget memory)
{
_paths = paths;
_settings = settings;
_memory = memory;
}
/// <summary>同步加载(全部在 UI 线程,用于自检 / 命令行)。</summary>
public LoadedModel Load(ModelPackage package, Action requestClose, Action<double, string?>? progress = null)
{
var session = CreateSession(package, requestClose, progress);
try
{
session.Runtime.Prepare(session.Context);
var view = session.Runtime.CreateView(session.Context)
?? throw new InvalidOperationException("模型没有返回界面");
return session.Complete(view);
}
catch
{
session.Dispose();
throw;
}
}
/// <summary>
/// 异步加载:数据准备放在后台线程(<see cref="IModelRuntime.Prepare"/>),
/// 界面构建回到 UI 线程,进度通过 <paramref name="progress"/> 实时汇报。
/// </summary>
public async Task<LoadedModel> LoadAsync(ModelPackage package, Action requestClose,
Action<double, string?>? progress = null)
{
var session = CreateSession(package, requestClose, progress);
try
{
await Task.Run(() => session.Runtime.Prepare(session.Context)).ConfigureAwait(true);
var view = session.Runtime.CreateView(session.Context)
?? throw new InvalidOperationException("模型没有返回界面");
return session.Complete(view);
}
catch
{
session.Dispose();
throw;
}
}
private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? progress)
{
var assemblyPath = package.AssemblyPath;
if (!File.Exists(assemblyPath))
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
var directory = Path.GetDirectoryName(assemblyPath)!;
var context = new ModelLoadContext(directory);
try
{
var assembly = context.LoadFromAssemblyPath(assemblyPath);
var type = ResolveFactoryType(assembly, package.Manifest.Type);
if (type == null)
throw new InvalidOperationException("模型程序集里没有找到 IModelFactory 实现");
if (Activator.CreateInstance(type) is not IModelFactory factory)
throw new InvalidOperationException($"无法创建模型入口:{type.FullName}");
if (factory.ApiVersion != SupportedApiVersion)
throw new InvalidOperationException(
$"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致");
var runtime = factory.Create();
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
return new Session(context, runtime, modelContext);
}
catch
{
context.Unload();
throw;
}
}
private static Type? ResolveFactoryType(Assembly assembly, string? typeName)
{
if (!string.IsNullOrWhiteSpace(typeName))
{
var exact = assembly.GetType(typeName!, throwOnError: false);
if (exact != null) return exact;
}
foreach (var type in assembly.GetTypes())
{
if (type.IsAbstract || type.IsInterface) continue;
if (typeof(IModelFactory).IsAssignableFrom(type)) return type;
}
return null;
}
private sealed class Session : IDisposable
{
private readonly ModelLoadContext _context;
public Session(ModelLoadContext context, IModelRuntime runtime, ModelContext modelContext)
{
_context = context;
Runtime = runtime;
Context = modelContext;
}
public IModelRuntime Runtime { get; }
public ModelContext Context { get; }
public LoadedModel Complete(Control view) => new(_context, Runtime, view);
public void Dispose()
{
try { Runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
}
}
/// <summary>一次性模型实例:窗口关闭后释放视图、卸载程序集。</summary>
public sealed class LoadedModel : IDisposable
{
private readonly ModelLoadContext _context;
private readonly IModelRuntime _runtime;
private bool _disposed;
public LoadedModel(ModelLoadContext context, IModelRuntime runtime, Control view)
{
_context = context;
_runtime = runtime;
View = view;
}
public Control View { get; }
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
}
/// <summary>模型程序集加载上下文:契约与 Avalonia 一律回到默认上下文,保证类型一致。</summary>
public sealed class ModelLoadContext : AssemblyLoadContext
{
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
{
"EarthModelStudio.ModelSdk",
"Avalonia",
"Avalonia.Base",
"Avalonia.Controls",
"Avalonia.Desktop",
"Avalonia.Skia",
"Avalonia.Themes.Fluent",
"SkiaSharp",
"HarfBuzzSharp"
};
private readonly string _directory;
public ModelLoadContext(string directory) : base("model:" + Path.GetFileName(directory), isCollectible: true)
=> _directory = directory;
protected override Assembly? Load(AssemblyName assemblyName)
{
var name = assemblyName.Name;
if (string.IsNullOrEmpty(name)) return null;
if (Shared.Contains(name)) return null; // 用启动器已加载的那份
if (name.StartsWith("System.", StringComparison.OrdinalIgnoreCase)) return null;
if (name is "System" or "netstandard" or "mscorlib") return null;
var candidate = Path.Combine(_directory, name + ".dll");
return File.Exists(candidate) ? LoadFromAssemblyPath(candidate) : null;
}
}
/// <summary>启动器提供给模型的环境。</summary>
public sealed class ModelContext : IModelContext
{
private readonly Action _requestClose;
private readonly Action<double, string?>? _progress;
public ModelContext(ModelPackage package, string language, int memoryMb, Action requestClose,
Action<double, string?>? progress)
{
_progress = progress;
ModelId = package.Id;
ModelDirectory = package.Directory;
DataDirectory = package.DataDirectory;
Language = language;
MemoryBudgetMb = memoryMb;
_requestClose = requestClose;
}
public string ModelId { get; }
public string ModelDirectory { get; }
public string DataDirectory { get; }
public string Language { get; }
public int MemoryBudgetMb { get; }
public void RequestClose() => _requestClose();
public void ReportProgress(double value, string? message = null) => _progress?.Invoke(value, message);
public void Log(string message) => Console.WriteLine(message);
}
@@ -0,0 +1,71 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
public static class ModelInstaller
{
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
{
var target = Path.Combine(modelRoot, model.Id);
var staging = target + ".installing";
if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging);
long total = 0;
var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
try { total += new FileInfo(file).Length; } catch { }
}
long done = 0;
try
{
foreach (var file in files)
{
ct.ThrowIfCancellationRequested();
var relative = Path.GetRelativePath(model.Directory, file);
var dest = Path.Combine(staging, relative);
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await using (var src = File.OpenRead(file))
await using (var dst = File.Create(dest))
{
await src.CopyToAsync(dst, 81920, ct);
}
long length = 0;
try { length = new FileInfo(dest).Length; } catch { }
done += length;
progress?.Report((done, total <= 0 ? done : total));
}
if (Directory.Exists(target))
{
var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
Directory.Move(target, backup);
Directory.Move(staging, target);
try { Directory.Delete(backup, true); } catch { }
}
else
{
Directory.Move(staging, target);
}
progress?.Report((total, total));
return target;
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
throw;
}
}
}
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
/// <summary>
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
/// 场景、贴图、界面都由模型自己的程序集负责。
/// </summary>
public sealed class ModelRepository
{
private readonly AppPaths _paths;
public ModelRepository(AppPaths paths) => _paths = paths;
public event Action? Changed;
public IReadOnlyList<ModelPackage> Scan()
{
var result = new List<ModelPackage>();
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
{
result.Add(new ModelPackage
{
Manifest = manifest,
Directory = dir,
SizeBytes = ModelScanner.DirectorySize(dir)
});
}
return result;
}
public ModelPackage? Find(string id) => Scan().FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
public bool Delete(string id)
{
var package = Find(id);
if (package == null) return false;
try
{
Directory.Delete(package.Directory, true);
Changed?.Invoke();
return true;
}
catch (Exception ex)
{
Console.Error.WriteLine($"删除模型失败: {ex.Message}");
return false;
}
}
public void NotifyChanged() => Changed?.Invoke();
}
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.IO;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
public static class ModelScanner
{
/// <summary>扫描模型库:model/&lt;id&gt;/&lt;id&gt;.json + &lt;id&gt;.model/</summary>
public static List<(ModelManifest Manifest, string Dir)> Scan(string modelRoot)
{
var list = new List<(ModelManifest, string)>();
if (!Directory.Exists(modelRoot)) return list;
foreach (var dir in Directory.GetDirectories(modelRoot))
{
var folder = Path.GetFileName(dir);
if (folder.StartsWith(".")) continue;
var manifestPath = Path.Combine(dir, folder + ".json");
if (!File.Exists(manifestPath))
{
var candidates = Directory.GetFiles(dir, "*.json", SearchOption.TopDirectoryOnly);
if (candidates.Length == 0) continue;
manifestPath = candidates[0];
}
ModelManifest? manifest;
try { manifest = Json.Read<ModelManifest>(manifestPath); }
catch (Exception ex)
{
Console.Error.WriteLine($"模型清单解析失败 {manifestPath}: {ex.Message}");
continue;
}
if (manifest == null) continue;
if (string.IsNullOrWhiteSpace(manifest.Id)) manifest.Id = folder;
list.Add((manifest, dir));
}
list.Sort((a, b) => string.Compare(a.Item1.Id, b.Item1.Id, StringComparison.OrdinalIgnoreCase));
return list;
}
public static long DirectorySize(string dir)
{
if (!Directory.Exists(dir)) return 0;
long total = 0;
try
{
foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
{
try { total += new FileInfo(file).Length; }
catch { /* 忽略被占用的文件 */ }
}
}
catch { /* 忽略权限问题 */ }
return total;
}
public static string HumanSize(long bytes)
{
string[] units = { "B", "KB", "MB", "GB" };
double value = bytes;
var unit = 0;
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
return unit == 0 ? $"{bytes} B" : $"{value:0.#} {units[unit]}";
}
}
@@ -0,0 +1,252 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
/// <summary>
/// 从链接导入模型源。
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/&lt;id&gt;。
/// </summary>
public sealed class ModelSourceClient
{
private readonly AppPaths _paths;
private static readonly HttpClient Http = CreateHttp();
public ModelSourceClient(AppPaths paths) => _paths = paths;
private static HttpClient CreateHttp()
{
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0 (+model-source)");
return client;
}
public async Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(source.Url))
return new SourceIndex { SourceId = source.Id, Error = "dl.error.emptyUrl" };
try
{
var (root, fromCache) = await ResolveRootAsync(source, force, log, ct);
var models = new List<RemoteModel>();
foreach (var (manifest, dir) in ModelScanner.Scan(Path.Combine(root, "model")))
{
models.Add(new RemoteModel
{
Manifest = manifest,
Directory = dir,
SizeBytes = ModelScanner.DirectorySize(dir),
SourceId = source.Id
});
}
return new SourceIndex
{
SourceId = source.Id,
Root = root,
Models = models,
FromCache = fromCache,
ResolvedFrom = root
};
}
catch (OperationCanceledException)
{
return new SourceIndex { SourceId = source.Id, Error = "dl.error.canceled" };
}
catch (Exception ex)
{
return new SourceIndex { SourceId = source.Id, Error = ex.Message };
}
}
private async Task<(string Root, bool FromCache)> ResolveRootAsync(ModelSource source, bool force,
IProgress<string>? log, CancellationToken ct)
{
var raw = source.Url.Trim();
// 1) 本地目录(开发模型源最方便)
var localPath = raw.StartsWith("file://", StringComparison.OrdinalIgnoreCase)
? new Uri(raw).LocalPath
: raw;
if (Directory.Exists(localPath))
{
log?.Report("local");
return (localPath, true);
}
var cacheDir = Path.Combine(_paths.CacheRoot, "sources", source.Id);
if (!force && Directory.Exists(Path.Combine(cacheDir, "model")))
{
log?.Report("cache");
return (cacheDir, true);
}
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
Directory.CreateDirectory(cacheDir);
// 2) zip 直链 / 托管平台归档
foreach (var url in ArchiveCandidates(raw, source.Branch))
{
ct.ThrowIfCancellationRequested();
try
{
log?.Report("zip:" + url);
await DownloadZipAsync(url, cacheDir, ct);
if (Directory.Exists(Path.Combine(cacheDir, "model")))
return (cacheDir, false);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
log?.Report("zip-failed:" + ex.Message);
}
}
// 3) git clone(需要本机安装 git)
log?.Report("git");
if (await TryGitCloneAsync(raw, cacheDir, source.Branch, ct))
return (cacheDir, false);
throw new InvalidOperationException("dl.error.unreachable");
}
private static IEnumerable<string> ArchiveCandidates(string url, string? branch)
{
if (url.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
yield return url;
yield break;
}
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) yield break;
var segments = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 2) yield break;
var owner = segments[0];
var repo = segments[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? segments[1][..^4]
: segments[1];
var host = uri.Host.ToLowerInvariant();
var branches = new List<string>();
if (!string.IsNullOrWhiteSpace(branch)) branches.Add(branch!);
else if (host.Contains("gitee")) { branches.Add("master"); branches.Add("main"); }
else { branches.Add("main"); branches.Add("master"); }
foreach (var b in branches)
{
if (host.Contains("github.com"))
yield return $"https://codeload.github.com/{owner}/{repo}/zip/refs/heads/{b}";
else if (host.Contains("gitlab"))
yield return $"https://gitlab.com/{owner}/{repo}/-/archive/{b}/{repo}-{b}.zip";
else if (host.Contains("gitee.com"))
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
else
yield break;
}
}
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
{
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tmpRoot);
var zipPath = Path.Combine(tmpRoot, "source.zip");
try
{
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
{
response.EnsureSuccessStatusCode();
await using var input = await response.Content.ReadAsStreamAsync(ct);
await using var output = File.Create(zipPath);
await input.CopyToAsync(output, 81920, ct);
}
var extractDir = Path.Combine(tmpRoot, "extract");
Directory.CreateDirectory(extractDir);
ZipFile.ExtractToDirectory(zipPath, extractDir, true);
var root = FindModelRoot(extractDir) ?? extractDir;
foreach (var entry in Directory.GetFileSystemEntries(root))
{
var name = Path.GetFileName(entry);
var dest = Path.Combine(cacheDir, name);
if (Directory.Exists(dest)) Directory.Delete(dest, true);
else if (File.Exists(dest)) File.Delete(dest);
if (Directory.Exists(entry)) Directory.Move(entry, dest);
else File.Move(entry, dest);
}
}
finally
{
try { if (Directory.Exists(tmpRoot)) Directory.Delete(tmpRoot, true); } catch { }
}
}
private static string? FindModelRoot(string dir, int depth = 0)
{
if (Directory.Exists(Path.Combine(dir, "model"))) return dir;
if (depth >= 2) return null;
foreach (var child in Directory.GetDirectories(dir))
{
var found = FindModelRoot(child, depth + 1);
if (found != null) return found;
}
return null;
}
private static async Task<bool> TryGitCloneAsync(string url, string cacheDir, string? branch, CancellationToken ct)
{
if (cacheDir.Length > 0 && Directory.Exists(cacheDir))
{
foreach (var f in Directory.GetFileSystemEntries(cacheDir))
{
if (Directory.Exists(f)) Directory.Delete(f, true);
else File.Delete(f);
}
}
var args = new List<string> { "clone", "--depth", "1" };
if (!string.IsNullOrWhiteSpace(branch)) { args.Add("--branch"); args.Add(branch!); }
args.Add(url);
args.Add(cacheDir);
try
{
var psi = new ProcessStartInfo("git")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
foreach (var a in args) psi.ArgumentList.Add(a);
using var process = Process.Start(psi);
if (process == null) return false;
var stderrTask = process.StandardError.ReadToEndAsync(ct);
await process.WaitForExitAsync(ct);
var stderr = await stderrTask;
if (process.ExitCode != 0)
{
Console.Error.WriteLine($"git clone 失败: {stderr}");
return false;
}
return Directory.Exists(Path.Combine(cacheDir, "model")) || Directory.Exists(cacheDir);
}
catch (Exception ex)
{
Console.Error.WriteLine($"git clone 异常: {ex.Message}");
return false;
}
}
}
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.IO;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
public sealed class SettingsService
{
private readonly AppPaths _paths;
public AppSettings Current { get; private set; } = new();
public event Action? Changed;
public SettingsService(AppPaths paths) => _paths = paths;
public void Load()
{
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
if (Current.Sources.Count == 0) SeedSources();
if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
}
/// <summary>
/// 首次启动不预置任何模型源:启动器只做适配,模型内容由用户从链接导入。
/// 这里只给一条空的自定义源占位。
/// </summary>
private void SeedSources()
{
Current.Sources.Add(new ModelSource
{
Id = "custom",
Name = "自定义源",
Url = "",
Enabled = false
});
Save();
}
public void Save()
{
try
{
Json.Write(_paths.SettingsFile, Current);
}
catch (Exception ex)
{
Console.Error.WriteLine($"保存设置失败: {ex.Message}");
}
}
public void Apply(Action<AppSettings> mutate)
{
mutate(Current);
Save();
Changed?.Invoke();
}
public void Notify()
{
Save();
Changed?.Invoke();
}
}
@@ -0,0 +1,30 @@
using System;
using System.Diagnostics;
using System.IO;
namespace EarthModelStudio.Services;
public static class Shell
{
public static void OpenFolder(string path)
{
if (string.IsNullOrWhiteSpace(path)) return;
try
{
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var info = new ProcessStartInfo
{
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
: OperatingSystem.IsMacOS() ? "open"
: "xdg-open",
UseShellExecute = false
};
info.ArgumentList.Add(path);
Process.Start(info);
}
catch (Exception ex)
{
Console.Error.WriteLine($"打开目录失败: {ex.Message}");
}
}
}
@@ -0,0 +1,249 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Styles.Resources>
<SolidColorBrush x:Key="AppBg" Color="#F4F6FB" />
<SolidColorBrush x:Key="Surface" Color="#FFFFFF" />
<SolidColorBrush x:Key="SurfaceAlt" Color="#F7F9FE" />
<SolidColorBrush x:Key="Line" Color="#E3E8F3" />
<SolidColorBrush x:Key="LineStrong" Color="#D2DAEA" />
<SolidColorBrush x:Key="Ink" Color="#111A2E" />
<SolidColorBrush x:Key="InkDim" Color="#5B6A86" />
<SolidColorBrush x:Key="InkFaint" Color="#8A97B1" />
<SolidColorBrush x:Key="Accent" Color="#2F6BFF" />
<SolidColorBrush x:Key="AccentDark" Color="#1F4FD0" />
<SolidColorBrush x:Key="AccentSoft" Color="#EAF1FF" />
<SolidColorBrush x:Key="SideBg" Color="#0D1526" />
<SolidColorBrush x:Key="SideLine" Color="#1B2740" />
<SolidColorBrush x:Key="SideInk" Color="#A9B8D4" />
<SolidColorBrush x:Key="Success" Color="#1F9D6B" />
<SolidColorBrush x:Key="Danger" Color="#D64545" />
<SolidColorBrush x:Key="Warn" Color="#D98613" />
<LinearGradientBrush x:Key="HeroBg" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Color="#12203C" Offset="0" />
<GradientStop Color="#1A3057" Offset="0.55" />
<GradientStop Color="#0E1A31" Offset="1" />
</LinearGradientBrush>
</Styles.Resources>
<Style Selector="Window">
<Setter Property="FontSize" Value="13" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<!-- 文本 -->
<Style Selector="TextBlock.h1">
<Setter Property="FontSize" Value="26" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.h2">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.h3">
<Setter Property="FontSize" Value="13.5" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.muted">
<Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
</Style>
<Style Selector="TextBlock.faint">
<Setter Property="FontSize" Value="11.5" />
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
</Style>
<Style Selector="TextBlock.eyebrow">
<Setter Property="FontSize" Value="11" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
</Style>
<Style Selector="TextBlock.onDark">
<Setter Property="Foreground" Value="#EAF1FF" />
</Style>
<Style Selector="TextBlock.onDarkDim">
<Setter Property="Foreground" Value="#9DB0D0" />
</Style>
<!-- 容器 -->
<!-- 容器:卡片悬停浮起,阴影与位移都有过渡 -->
<Style Selector="Border.card">
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="16" />
<Setter Property="Transitions">
<Transitions>
<BoxShadowsTransition Property="BoxShadow" Duration="0:0:0.2" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.2" />
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.2" />
</Transitions>
</Setter>
</Style>
<Style Selector="Border.card:pointerover">
<Setter Property="BoxShadow" Value="0 10 26 0 #1A213C70" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
<Setter Property="RenderTransform" Value="translateY(-2px)" />
</Style>
<Style Selector="Border.panel">
<Setter Property="Background" Value="{DynamicResource SurfaceAlt}" />
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="12" />
</Style>
<Style Selector="Border.hero">
<Setter Property="Background" Value="{DynamicResource HeroBg}" />
<Setter Property="CornerRadius" Value="20" />
<Setter Property="BoxShadow" Value="0 12 32 0 #1A0B1A3A" />
</Style>
<Style Selector="Border.chip">
<Setter Property="Background" Value="{DynamicResource AccentSoft}" />
<Setter Property="CornerRadius" Value="999" />
<Setter Property="Padding" Value="8,2" />
</Style>
<Style Selector="Border.tag">
<Setter Property="Background" Value="#F0F3FA" />
<Setter Property="CornerRadius" Value="6" />
<Setter Property="Padding" Value="7,2" />
</Style>
<!-- 按钮 -->
<!-- 全局过渡:悬停、选中、进度都不再「啪」地跳变 -->
<Style Selector="Button /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Background" Duration="0:0:0.14" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.14" />
<BrushTransition Property="Foreground" Duration="0:0:0.14" />
</Transitions>
</Setter>
</Style>
<Style Selector="Button">
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Transitions">
<Transitions>
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.12" />
</Transitions>
</Setter>
</Style>
<Style Selector="Button:pointerover">
<Setter Property="RenderTransform" Value="translateY(-1px)" />
</Style>
<Style Selector="Button:pressed">
<Setter Property="RenderTransform" Value="translateY(1px)" />
</Style>
<Style Selector="Button.primary">
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.primary /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
<Setter Property="CornerRadius" Value="9" />
</Style>
<Style Selector="Button.primary:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{DynamicResource AccentDark}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentDark}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.ghost">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
</Style>
<Style Selector="Button.ghost /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
</Style>
<Style Selector="Button.ghost:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#EEF2FA" />
</Style>
<Style Selector="Button.danger">
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.danger:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#FDECEC" />
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.small">
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="10,4" />
<Setter Property="MinHeight" Value="28" />
<Setter Property="CornerRadius" Value="8" />
</Style>
<Style Selector="Button.onDark">
<Setter Property="Background" Value="#1B2740" />
<Setter Property="BorderBrush" Value="#2A3A57" />
<Setter Property="Foreground" Value="#DCE7FA" />
</Style>
<Style Selector="Button.onDark:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#233351" />
</Style>
<Style Selector="Button.onDark.active /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
</Style>
<!-- 侧栏 -->
<Style Selector="Button.nav">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{DynamicResource SideInk}" />
<Setter Property="Padding" Value="14,10" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="FontSize" Value="13.5" />
<Setter Property="MinHeight" Value="40" />
</Style>
<Style Selector="Button.nav /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
</Style>
<Style Selector="Button.nav:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#16213A" />
<Setter Property="Foreground" Value="#E8EFFF" />
</Style>
<Style Selector="Button.nav.active /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#1C2C4C" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<!-- 输入 -->
<Style Selector="TextBox">
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Padding" Value="11,8" />
<Setter Property="MinHeight" Value="36" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
</Style>
<Style Selector="ComboBox">
<Setter Property="CornerRadius" Value="9" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Padding" Value="10,4" />
</Style>
<Style Selector="ProgressBar">
<Setter Property="Height" Value="5" />
<Setter Property="CornerRadius" Value="3" />
<Setter Property="MinHeight" Value="5" />
</Style>
<Style Selector="CheckBox">
<Setter Property="FontSize" Value="12.5" />
</Style>
</Styles>
@@ -0,0 +1,372 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models;
using EarthModelStudio.Services;
namespace EarthModelStudio.ViewModels;
public partial class DownloadViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly MainViewModel _main;
private bool _initialized;
public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
public ObservableCollection<DownloadJob> Jobs => _services.Downloads.Jobs;
[ObservableProperty] private SourceItemViewModel? _selectedSource;
[ObservableProperty] private string _importUrl = "";
[ObservableProperty] private bool _isBusy;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _hasModels;
[ObservableProperty] private bool _isBackgroundOpen = true;
[ObservableProperty] private string _jobSummary = "";
[ObservableProperty] private bool _hasJobs;
[ObservableProperty] private bool _isSourceEmpty;
public DownloadViewModel(AppServices services, MainViewModel main)
{
_services = services;
_main = main;
Jobs.CollectionChanged += OnJobsChanged;
foreach (var job in Jobs) job.PropertyChanged += OnJobPropertyChanged;
L.I.LanguageChanged += RefreshLanguage;
RebuildSources();
UpdateJobState();
}
public string BackgroundTitle => L.I["dl.background"];
public string ImportHint => L.I["dl.hint"];
// ------------------------------------------------------------ 页面生命周期
public void OnShown()
{
if (_initialized) return;
_initialized = true;
if (SelectedSource == null)
SelectedSource = Sources.FirstOrDefault(s => s.Model.Enabled && !string.IsNullOrWhiteSpace(s.Model.Url))
?? Sources.FirstOrDefault();
}
// ------------------------------------------------------------ 模型源
private void RebuildSources()
{
var keepId = SelectedSource?.Model.Id;
Sources.Clear();
foreach (var source in _services.Settings.Current.Sources)
Sources.Add(new SourceItemViewModel(source, this, _services));
SelectedSource = Sources.FirstOrDefault(s => s.Model.Id == keepId) ?? SelectedSource;
}
partial void OnSelectedSourceChanged(SourceItemViewModel? value)
{
if (value == null) return;
if (string.IsNullOrWhiteSpace(value.Model.Url))
{
Models.Clear();
HasModels = false;
IsSourceEmpty = true;
StatusMessage = L.I["dl.pickSource"];
return;
}
_ = LoadAsync(value, force: false);
}
internal void OnSourceEnabledChanged(SourceItemViewModel source)
{
if (!source.Model.Enabled && SelectedSource == source) Models.Clear();
}
internal void RemoveSource(SourceItemViewModel source)
{
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
var wasSelected = SelectedSource == source;
Sources.Remove(source);
if (wasSelected)
{
SelectedSource = Sources.FirstOrDefault();
if (SelectedSource == null)
{
Models.Clear();
HasModels = false;
}
}
}
[RelayCommand]
private async Task ImportAsync()
{
var url = ImportUrl.Trim();
if (string.IsNullOrWhiteSpace(url))
{
StatusMessage = L.I["dl.error.emptyUrl"];
return;
}
var source = new ModelSource
{
Name = DeriveName(url),
Url = url,
Enabled = true
};
_services.Settings.Current.Sources.Add(source);
_services.Settings.Save();
var item = new SourceItemViewModel(source, this, _services);
Sources.Add(item);
ImportUrl = "";
SelectedSource = item;
await LoadAsync(item, force: true);
}
private static string DeriveName(string url)
{
var trimmed = url.TrimEnd('/', '\\');
var slash = trimmed.LastIndexOfAny(new[] { '/', '\\' });
var name = slash >= 0 ? trimmed[(slash + 1)..] : trimmed;
if (name.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
if (name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
return string.IsNullOrWhiteSpace(name) ? url : name;
}
[RelayCommand]
private async Task RefreshAsync()
{
if (SelectedSource == null) return;
await LoadAsync(SelectedSource, force: true);
}
internal async Task RefreshFromSource(SourceItemViewModel source)
{
SelectedSource = source;
await LoadAsync(source, force: true);
}
private async Task LoadAsync(SourceItemViewModel source, bool force)
{
if (!source.Model.Enabled) return;
IsBusy = true;
StatusMessage = L.I["dl.syncing"];
try
{
var index = await _services.Sources.FetchAsync(source.Model, force, null, CancellationToken.None);
if (SelectedSource != source) return;
if (index.Error != null)
{
Models.Clear();
HasModels = false;
IsSourceEmpty = true;
StatusMessage = DescribeError(index.Error);
return;
}
var installedIds = new HashSet<string>(
_services.Models.Scan().Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
Models.Clear();
foreach (var model in index.Models)
{
Models.Add(new RemoteModelRowViewModel(model, source,
installedIds.Contains(model.Id), DownloadCommand));
}
HasModels = Models.Count > 0;
IsSourceEmpty = Models.Count == 0;
StatusMessage = index.FromCache
? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}"
: L.I.F("dl.ready", Models.Count);
}
catch (Exception ex)
{
StatusMessage = ex.Message;
}
finally
{
IsBusy = false;
}
}
private static string DescribeError(string error)
{
if (error.StartsWith("dl.", StringComparison.Ordinal))
{
var text = L.I[error];
return text == error ? error : text;
}
return error;
}
// ------------------------------------------------------------ 下载
[RelayCommand]
private async Task DownloadAsync(RemoteModelRowViewModel row)
{
if (row == null) return;
row.RowOpacity = 0;
row.RowHeight = 0;
IsBackgroundOpen = true;
_services.Downloads.Enqueue(row.Model);
await Task.Delay(240);
Models.Remove(row);
HasModels = Models.Count > 0;
IsSourceEmpty = Models.Count == 0;
}
[RelayCommand]
private void CancelJob(DownloadJob? job)
{
if (job != null) _services.Downloads.Cancel(job);
}
[RelayCommand]
private void RetryJob(DownloadJob? job)
{
if (job != null) _services.Downloads.Retry(job);
}
[RelayCommand]
private void RemoveJob(DownloadJob? job)
{
if (job != null) _services.Downloads.Remove(job);
}
[RelayCommand]
private void ClearFinished() => _services.Downloads.ClearFinished();
[RelayCommand]
private void ToggleBackground() => IsBackgroundOpen = !IsBackgroundOpen;
// ------------------------------------------------------------ 任务展示
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (DownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
if (e.OldItems != null)
foreach (DownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
UpdateJobState();
}
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(DownloadJob.State))
{
if (sender is DownloadJob { State: DownloadState.Completed })
_services.Models.NotifyChanged();
}
UpdateJobState();
}
private void UpdateJobState()
{
HasJobs = Jobs.Count > 0;
JobSummary = $"{L.I["dl.background"]} ({Jobs.Count})";
OnPropertyChanged(nameof(JobSummary));
}
private void RefreshLanguage()
{
foreach (var source in Sources) source.RefreshLanguage();
foreach (var model in Models) model.RefreshLanguage();
foreach (var job in Jobs) job.RefreshText();
OnPropertyChanged(nameof(BackgroundTitle));
OnPropertyChanged(nameof(ImportHint));
UpdateJobState();
}
}
public partial class SourceItemViewModel : ObservableObject
{
private readonly DownloadViewModel _owner;
private readonly AppServices _services;
public ModelSource Model { get; }
public SourceItemViewModel(ModelSource model, DownloadViewModel owner, AppServices services)
{
Model = model;
_owner = owner;
_services = services;
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
RefreshCommand = new AsyncRelayCommand(async () => await _owner.RefreshFromSource(this));
}
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost;
public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url);
public bool Enabled
{
get => Model.Enabled;
set
{
if (Model.Enabled == value) return;
Model.Enabled = value;
_services.Settings.Save();
OnPropertyChanged();
_owner.OnSourceEnabledChanged(this);
}
}
public ICommand RemoveCommand { get; }
public ICommand RefreshCommand { get; }
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(HostText));
}
}
public partial class RemoteModelRowViewModel : ObservableObject
{
public RemoteModel Model { get; }
public SourceItemViewModel Source { get; }
public RemoteModelRowViewModel(RemoteModel model, SourceItemViewModel source, bool installed, ICommand downloadCommand)
{
Model = model;
Source = source;
Installed = installed;
DownloadCommand = downloadCommand;
}
public string Name => Model.LocalizedName;
public string Description => Model.LocalizedDescription;
public string VersionText => "v" + Model.Manifest.Version;
public string SizeText => ModelScanner.HumanSize(Model.SizeBytes);
public string MetaText => $"{VersionText} · {SizeText}";
public string TagsText => string.Join(" · ", Model.Manifest.Tags ?? new List<string>());
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
[ObservableProperty] private bool _installed;
[ObservableProperty] private double _rowHeight = 92;
[ObservableProperty] private double _rowOpacity = 1;
public string ButtonText => Installed ? L.I["dl.reinstall"] : L.I["dl.download"];
public ICommand DownloadCommand { get; }
partial void OnInstalledChanged(bool value) => OnPropertyChanged(nameof(ButtonText));
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(MetaText));
OnPropertyChanged(nameof(TagsText));
OnPropertyChanged(nameof(ButtonText));
}
}
@@ -0,0 +1,148 @@
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models;
using Avalonia.Media.Imaging;
using EarthModelStudio.Services;
namespace EarthModelStudio.ViewModels;
public partial class HomeViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly MainViewModel _main;
public ObservableCollection<ModelCardViewModel> Models { get; } = new();
[ObservableProperty] private ModelCardViewModel? _selected;
[ObservableProperty] private bool _isEmpty;
public string CountText => L.I.F("home.count", Models.Count);
public string SourceCountText => _services.Settings.Current.Sources
.Count(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url)).ToString();
public string MemoryText => $"{_services.Memory.BudgetMb} MB";
public string SelectedHint => Selected == null ? L.I["home.recent"] : L.I["home.launchHint"];
public HomeViewModel(AppServices services, MainViewModel main)
{
_services = services;
_main = main;
_services.Models.Changed += Refresh;
L.I.LanguageChanged += RefreshLanguage;
Refresh();
}
public void Refresh()
{
var keepId = Selected?.Package.Id;
Models.Clear();
foreach (var package in _services.Models.Scan())
Models.Add(new ModelCardViewModel(package, _services, this));
Selected = Models.FirstOrDefault(m => m.Package.Id == keepId) ?? Models.FirstOrDefault();
IsEmpty = Models.Count == 0;
RefreshLanguage();
}
private void RefreshLanguage()
{
OnPropertyChanged(nameof(CountText));
OnPropertyChanged(nameof(SourceCountText));
OnPropertyChanged(nameof(MemoryText));
OnPropertyChanged(nameof(SelectedHint));
foreach (var model in Models) model.RefreshLanguage();
}
public void LaunchModel(ModelCardViewModel card)
{
Selected = card;
_main.PlayModel(card.Package);
}
public async Task DeleteAsync(ModelCardViewModel card)
{
if (!await _main.ConfirmAsync(L.I.F("home.deleteConfirm", card.Name))) return;
_services.Models.Delete(card.Package.Id);
_services.Models.NotifyChanged();
Refresh();
}
[RelayCommand]
private void Launch()
{
var card = Selected ?? Models.FirstOrDefault();
if (card != null) _main.PlayModel(card.Package);
}
[RelayCommand]
private void OpenDownload() => _main.GoDownload();
[RelayCommand]
private void OpenSettings() => _main.GoSettings();
[RelayCommand]
private void OpenFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
}
public partial class ModelCardViewModel : ObservableObject
{
private readonly AppServices _services;
private Bitmap? _preview;
public ModelPackage Package { get; }
public ModelCardViewModel(ModelPackage package, AppServices services, HomeViewModel home)
{
Package = package;
_services = services;
LaunchCommand = new RelayCommand(() => home.LaunchModel(this));
DeleteCommand = new AsyncRelayCommand(() => home.DeleteAsync(this));
OpenFolderCommand = new RelayCommand(() => Shell.OpenFolder(package.Directory));
}
public string Name => Package.LocalizedName;
public string Description => Package.LocalizedDescription;
public string VersionText => "v" + Package.Manifest.Version;
public string SizeText => ModelScanner.HumanSize(Package.SizeBytes);
public string MetaText => $"{VersionText} · {SizeText}";
public string TagsText => string.Join(" · ", Package.Manifest.Tags ?? new());
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
public string AuthorText => string.IsNullOrWhiteSpace(Package.Manifest.Author) ? "" : Package.Manifest.Author;
/// <summary>封面图来自模型包自带的 preview.png —— 启动器只显示,不渲染。</summary>
public Bitmap? Preview
{
get
{
if (_preview != null) return _preview;
try
{
if (File.Exists(Package.PreviewPath)) _preview = new Bitmap(Package.PreviewPath);
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取模型封面失败 {Package.Id}: {ex.Message}");
}
return _preview;
}
}
public bool HasPreview => Preview != null;
public ICommand LaunchCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand OpenFolderCommand { get; }
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(MetaText));
OnPropertyChanged(nameof(TagsText));
}
}
@@ -0,0 +1,87 @@
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models;
using EarthModelStudio.Services;
using EarthModelStudio.ViewModels;
namespace EarthModelStudio.ViewModels;
public partial class MainViewModel : ObservableObject
{
private readonly AppServices _services;
public HomeViewModel Home { get; }
public DownloadViewModel Download { get; }
public SettingsViewModel Settings { get; }
/// <summary>模型宿主:按清单加载模型自带的功能程序集。</summary>
public ModelHost Models { get; }
[ObservableProperty] private ObservableObject _current = null!;
[ObservableProperty] private bool _isHomeActive = true;
[ObservableProperty] private bool _isDownloadActive;
[ObservableProperty] private bool _isSettingsActive;
/// <summary>由主窗口注入的确认对话框。</summary>
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
/// <summary>
/// 请求为新模型开一个独立窗口。真正创建窗口的是主窗口,
/// 因此同一个模型可以同时开多份,主界面也不会被替换。
/// </summary>
public event Action<ModelPackage>? PlayerRequested;
public string VersionText => "v1.0.0";
public string PlatformText => RuntimeInformation.RuntimeIdentifier;
public MainViewModel(AppServices services)
{
_services = services;
Models = services.ModelHost;
Home = new HomeViewModel(services, this);
Download = new DownloadViewModel(services, this);
Settings = new SettingsViewModel(services);
Current = Home;
}
partial void OnCurrentChanged(ObservableObject value)
{
IsHomeActive = value is HomeViewModel;
IsDownloadActive = value is DownloadViewModel;
IsSettingsActive = value is SettingsViewModel;
}
[RelayCommand]
public void GoHome()
{
Home.Refresh();
Current = Home;
}
[RelayCommand]
public void GoDownload()
{
Current = Download;
Download.OnShown();
}
[RelayCommand]
public void GoSettings()
{
Settings.Refresh();
Current = Settings;
}
/// <summary>启动模型:交给模型自己的程序集,在独立窗口中运行。</summary>
public void PlayModel(ModelPackage package)
{
_services.Memory.Refresh();
PlayerRequested?.Invoke(package);
}
public async Task<bool> ConfirmAsync(string message)
=> ConfirmHandler == null || await ConfirmHandler(message);
}
@@ -0,0 +1,176 @@
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models;
using EarthModelStudio.Services;
namespace EarthModelStudio.ViewModels;
public sealed class LanguageOption
{
public string Code { get; init; } = "auto";
public string Label { get; set; } = "";
public override string ToString() => Label;
}
public partial class SettingsViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _loading = true;
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
public ObservableCollection<LanguageOption> Languages { get; } = new();
public int[] FrameRates { get; } = { 24, 30, 60 };
[ObservableProperty] private LanguageOption? _selectedLanguage;
[ObservableProperty] private int _selectedFps = 30;
[ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private string _statusMessage = "";
public string MemoryValueText => $"{(int)Math.Round(MemoryValue)} MB";
public string UsageText => _services.Memory.UsageText;
public string ModelRoot => _services.Paths.ModelRoot;
public string DataRoot => _services.Paths.DataRoot;
public string PlatformText => $"{RuntimeInformation.OSDescription} · {RuntimeInformation.RuntimeIdentifier}";
public string VersionText => "v1.0.0";
public string MemoryHint => L.I["set.memory.hint"];
public SettingsViewModel(AppServices services)
{
_services = services;
L.I.LanguageChanged += OnLanguageChanged;
Refresh();
_loading = false;
}
public void Refresh()
{
_loading = true;
BuildLanguages();
var settings = _services.Settings.Current;
SelectedFps = settings.RenderFps;
MemoryValue = settings.MemoryMb;
Sources.Clear();
foreach (var source in settings.Sources)
Sources.Add(new SettingsSourceViewModel(source, _services, this));
_loading = false;
OnPropertyChanged(nameof(UsageText));
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(MemoryHint));
OnPropertyChanged(nameof(ModelRoot));
OnPropertyChanged(nameof(DataRoot));
}
private void BuildLanguages()
{
var current = _services.Settings.Current.Language;
Languages.Clear();
Languages.Add(new LanguageOption { Code = "auto", Label = L.I["set.language.auto"] });
foreach (var (code, label) in L.Supported)
Languages.Add(new LanguageOption { Code = code, Label = label });
SelectedLanguage = Languages.FirstOrDefault(l => l.Code == current) ?? Languages[0];
}
private void OnLanguageChanged()
{
_loading = true;
BuildLanguages();
_loading = false;
Refresh();
}
partial void OnSelectedLanguageChanged(LanguageOption? value)
{
if (_loading || value == null) return;
_services.Settings.Apply(s => s.Language = value.Code);
L.I.SetLanguage(value.Code);
}
partial void OnSelectedFpsChanged(int value)
{
if (_loading) return;
_services.Settings.Apply(s => s.RenderFps = Math.Clamp(value, 12, 120));
}
partial void OnMemoryValueChanged(double value)
{
if (_loading) return;
var mb = (int)Math.Round(value);
_services.Settings.Apply(s => s.MemoryMb = mb);
_services.Memory.Apply(mb);
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand]
private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
[RelayCommand]
private void OpenDataFolder() => Shell.OpenFolder(_services.Paths.DataRoot);
[RelayCommand]
private void ClearCache()
{
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
GC.Collect();
GC.WaitForPendingFinalizers();
_services.Memory.Refresh();
StatusMessage = L.I["set.cacheCleared"];
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand]
private void ApplyMemory()
{
_services.Memory.Apply((int)Math.Round(MemoryValue));
StatusMessage = L.I["common.applied"];
OnPropertyChanged(nameof(UsageText));
}
internal void RemoveSource(SettingsSourceViewModel source)
{
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
Sources.Remove(source);
_services.Settings.Notify();
}
}
public partial class SettingsSourceViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly SettingsViewModel _owner;
public ModelSource Model { get; }
public SettingsSourceViewModel(ModelSource model, AppServices services, SettingsViewModel owner)
{
Model = model;
_services = services;
_owner = owner;
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
}
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url;
public bool Enabled
{
get => Model.Enabled;
set
{
if (Model.Enabled == value) return;
Model.Enabled = value;
_services.Settings.Save();
OnPropertyChanged();
}
}
public ICommand RemoveCommand { get; }
}
@@ -0,0 +1,19 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services"
x:Class="EarthModelStudio.Views.ConfirmWindow"
Title="{loc:Loc app.name}"
Width="440" SizeToContent="Height"
CanResize="False" ShowInTaskbar="False"
WindowStartupLocation="CenterOwner"
Background="{DynamicResource Surface}">
<StackPanel Margin="24,20,24,20" Spacing="14">
<TextBlock Classes="h2" Text="{loc:Loc common.confirmTitle}" />
<TextBlock x:Name="MessageText" Classes="muted" TextWrapping="Wrap" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,6,0,0">
<Button Content="{loc:Loc common.cancel}" Click="OnCancel" />
<Button Classes="primary" Content="{loc:Loc common.confirm}" Click="OnConfirm" />
</StackPanel>
</StackPanel>
</Window>
@@ -0,0 +1,21 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views;
public partial class ConfirmWindow : Window
{
public ConfirmWindow() : this("") { }
public ConfirmWindow(string message)
{
AvaloniaXamlLoader.Load(this);
var text = this.FindControl<TextBlock>("MessageText");
if (text != null) text.Text = message;
}
private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
private void OnConfirm(object? sender, RoutedEventArgs e) => Close(true);
}
@@ -0,0 +1,155 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services"
x:Class="EarthModelStudio.Views.DownloadView">
<Grid ColumnDefinitions="316,*" Margin="24,22,24,24">
<!-- 模型源 -->
<Border Grid.Column="0" Classes="card" Padding="18" Margin="0,0,16,0">
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto">
<TextBlock Classes="h2" Text="{loc:Loc dl.sources}" />
<StackPanel Grid.Row="1" Margin="0,12,0,0" Spacing="8">
<TextBox Text="{Binding ImportUrl}" Watermark="{loc:Loc dl.importPlaceholder}" />
<Button Classes="primary" Content="{loc:Loc dl.import}"
Command="{Binding ImportCommand}" HorizontalAlignment="Stretch" />
</StackPanel>
<TextBlock Grid.Row="2" Classes="faint" Text="{loc:Loc dl.hint}"
TextWrapping="Wrap" Margin="0,9,0,12" />
<ScrollViewer Grid.Row="3" VerticalScrollBarVisibility="Auto">
<ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}"
Background="Transparent" BorderThickness="0" Padding="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*,Auto" Margin="0,3">
<StackPanel Spacing="2" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
<Button Grid.Column="1" Classes="ghost small" Content="✕"
Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
<Border Grid.Row="4" Classes="panel" Padding="12,9" Margin="0,10,0,0">
<StackPanel Spacing="3">
<TextBlock Classes="eyebrow" Text="{loc:Loc dl.available}" />
<TextBlock Classes="faint" Text="{Binding StatusMessage}" TextWrapping="Wrap" />
</StackPanel>
</Border>
</Grid>
</Border>
<!-- 可用模型 + 后台任务 -->
<Border Grid.Column="1" Classes="card" Padding="20">
<Grid RowDefinitions="Auto,*,Auto">
<Grid ColumnDefinitions="*,Auto,Auto">
<StackPanel>
<TextBlock Classes="h2" Text="{loc:Loc dl.available}" />
<TextBlock Classes="muted" Text="{Binding StatusMessage}" Margin="0,3,0,0" />
</StackPanel>
<ProgressBar Grid.Column="1" IsIndeterminate="True" Width="90" Height="4"
IsVisible="{Binding IsBusy}" VerticalAlignment="Center" Margin="12,0" />
<Button Grid.Column="2" Classes="small" Content="{loc:Loc dl.refresh}"
Command="{Binding RefreshCommand}" VerticalAlignment="Center" />
</Grid>
<ScrollViewer Grid.Row="1" Margin="0,14,0,0" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Models}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Height="{Binding RowHeight}" Opacity="{Binding RowOpacity}"
ClipToBounds="True" Margin="0,0,0,10">
<Border.Transitions>
<Transitions>
<DoubleTransition Property="Height" Duration="0:0:0.24" Easing="CubicEaseOut" />
<DoubleTransition Property="Opacity" Duration="0:0:0.18" />
</Transitions>
</Border.Transitions>
<Border Classes="panel" Padding="14,11">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="3" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBlock Text="{Binding Name}" FontSize="13" FontWeight="SemiBold" />
<Border Classes="tag" VerticalAlignment="Center">
<TextBlock Text="{Binding VersionText}" Classes="faint" />
</Border>
<TextBlock Text="{Binding SizeText}" Classes="faint" VerticalAlignment="Center" />
</StackPanel>
<TextBlock Text="{Binding Description}" Classes="muted"
MaxLines="1" TextTrimming="CharacterEllipsis" MaxWidth="520" />
<TextBlock Text="{Binding TagsText}" Classes="faint" IsVisible="{Binding HasTags}" />
</StackPanel>
<Button Grid.Column="1" Classes="primary small" Content="{Binding ButtonText}"
Command="{Binding DownloadCommand}" CommandParameter="{Binding}"
VerticalAlignment="Center" Margin="12,0,0,0" />
</Grid>
</Border>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<!-- 后台任务(下载时折叠到这里) -->
<Border Grid.Row="2" Classes="panel" Margin="0,12,0,0" Padding="6" IsVisible="{Binding HasJobs}">
<StackPanel>
<Grid ColumnDefinitions="*,Auto">
<Button Classes="ghost" Content="{Binding JobSummary}" Command="{Binding ToggleBackgroundCommand}"
HorizontalContentAlignment="Left" FontSize="12" FontWeight="SemiBold" Padding="10,7" />
<Button Grid.Column="1" Classes="ghost small" Content="{loc:Loc dl.clearDone}"
Command="{Binding ClearFinishedCommand}" VerticalAlignment="Center" Margin="0,0,6,0" />
</Grid>
<ScrollViewer MaxHeight="200" IsVisible="{Binding IsBackgroundOpen}">
<ItemsControl ItemsSource="{Binding Jobs}" Margin="6,0,6,6">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="{DynamicResource Surface}" CornerRadius="9" Padding="10,8" Margin="0,4,0,0">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="4">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Text="{Binding Name}" FontSize="12" FontWeight="SemiBold" />
<TextBlock Grid.Column="1" Text="{Binding StatusText}" Classes="faint" />
</Grid>
<ProgressBar Value="{Binding Progress}" Maximum="1" IsVisible="{Binding IsActive}" />
<TextBlock Text="{Binding DetailText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="2"
VerticalAlignment="Center" Margin="10,0,0,0">
<Button Classes="ghost small" Content="{loc:Loc dl.cancel}"
IsVisible="{Binding IsActive}"
Command="{Binding $parent[ItemsControl].DataContext.CancelJobCommand}"
CommandParameter="{Binding}" />
<Button Classes="ghost small" Content="{loc:Loc dl.retry}"
IsVisible="{Binding CanRetry}"
Command="{Binding $parent[ItemsControl].DataContext.RetryJobCommand}"
CommandParameter="{Binding}" />
<Button Classes="ghost small" Content="{loc:Loc dl.removeTask}"
Command="{Binding $parent[ItemsControl].DataContext.RemoveJobCommand}"
CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</StackPanel>
</Border>
</Grid>
</Border>
</Grid>
</UserControl>
@@ -0,0 +1,9 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views;
public partial class DownloadView : UserControl
{
public DownloadView() => AvaloniaXamlLoader.Load(this);
}
@@ -0,0 +1,111 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services"
xmlns:controls="using:EarthModelStudio.Controls"
x:Class="EarthModelStudio.Views.HomeView">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Margin="26,24,26,28" Spacing="18">
<!-- 主视觉 -->
<Border Classes="hero" Padding="26,24">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="9" MaxWidth="560">
<TextBlock Classes="h1 onDark" Text="{loc:Loc home.title}" />
<TextBlock Text="{loc:Loc home.subtitle}" Foreground="#A9BEDF" FontSize="12.5"
TextWrapping="Wrap" MaxWidth="500" />
<StackPanel Orientation="Horizontal" Spacing="10" Margin="0,12,0,0">
<Button Classes="primary" Content="{loc:Loc home.launch}" Command="{Binding LaunchCommand}" />
<Button Classes="onDark" Content="{loc:Loc home.download}" Command="{Binding OpenDownloadCommand}" />
<Button Classes="onDark" Content="{loc:Loc home.settings}" Command="{Binding OpenSettingsCommand}" />
</StackPanel>
<TextBlock Text="{Binding SelectedHint}" Foreground="#7E93B8" FontSize="11" Margin="2,2,0,0" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="96">
<StackPanel Spacing="2">
<TextBlock Text="{Binding Models.Count}" Foreground="#FFFFFF" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.models}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="96">
<StackPanel Spacing="2">
<TextBlock Text="{Binding SourceCountText}" Foreground="#FFFFFF" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.sources}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="112">
<StackPanel Spacing="2">
<TextBlock Text="{Binding MemoryText}" Foreground="#FFFFFF" FontSize="16" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.memory}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
</StackPanel>
</Grid>
</Border>
<!-- 列表标题 -->
<Grid ColumnDefinitions="*,Auto" Margin="2,4,2,0">
<TextBlock Classes="h2" Text="{loc:Loc home.installed}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding CountText}" VerticalAlignment="Center" />
</Grid>
<!-- 模型卡片 -->
<ItemsControl ItemsSource="{Binding Models}" IsVisible="{Binding !IsEmpty}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Classes="card" Width="336" Margin="0,0,16,16" ClipToBounds="True">
<StackPanel>
<Border Height="138" Background="#0B1226" ClipToBounds="True">
<Panel>
<TextBlock Text="◎" FontSize="34" Foreground="#1B2A47"
HorizontalAlignment="Center" VerticalAlignment="Center" />
<Image Source="{Binding Preview}" Stretch="UniformToFill" />
</Panel>
</Border>
<StackPanel Margin="16,13,16,15" Spacing="7">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="h3" Text="{Binding Name}" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="1" Classes="faint" Text="{Binding MetaText}"
VerticalAlignment="Center" Margin="8,0,0,0" />
</Grid>
<TextBlock Classes="muted" Text="{Binding Description}" TextWrapping="Wrap"
MaxLines="2" Height="32" TextTrimming="CharacterEllipsis" />
<TextBlock Classes="faint" Text="{Binding TagsText}" IsVisible="{Binding HasTags}" />
<Grid ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,6,0,0">
<Button Classes="primary small" Content="{loc:Loc home.launch}"
Command="{Binding LaunchCommand}" />
<Button Grid.Column="2" Classes="ghost small" Content="{loc:Loc home.open}"
Command="{Binding OpenFolderCommand}" Margin="0,0,4,0" />
<Button Grid.Column="3" Classes="ghost small danger" Content="{loc:Loc home.delete}"
Command="{Binding DeleteCommand}" />
</Grid>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- 空状态 -->
<Border Classes="card" Padding="30,34" IsVisible="{Binding IsEmpty}">
<StackPanel Spacing="10" HorizontalAlignment="Center">
<TextBlock Classes="h2" Text="{loc:Loc home.empty}" HorizontalAlignment="Center" />
<TextBlock Classes="muted" Text="{loc:Loc home.emptyHint}" TextWrapping="Wrap"
MaxWidth="420" TextAlignment="Center" />
<Button Classes="primary" Content="{loc:Loc home.emptyAction}"
Command="{Binding OpenDownloadCommand}" HorizontalAlignment="Center" Margin="0,6,0,0" />
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
@@ -0,0 +1,9 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views;
public partial class HomeView : UserControl
{
public HomeView() => AvaloniaXamlLoader.Load(this);
}
@@ -0,0 +1,107 @@
using System;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
namespace EarthModelStudio.Views;
/// <summary>
/// 模型启动进度窗:加载模型程序集、生成地表纹理、构建界面的真实进度。
/// 只显示进度,不做任何渲染。
/// </summary>
public sealed class LoadingWindow : Window
{
private readonly ProgressBar _bar;
private readonly TextBlock _stage;
private readonly TextBlock _percent;
public LoadingWindow(string modelName)
{
Title = modelName;
Width = 460;
Height = 172;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Background = new SolidColorBrush(Color.Parse("#0B1226"));
SystemDecorations = SystemDecorations.BorderOnly;
var title = new TextBlock
{
Text = modelName,
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
FontSize = 15,
FontWeight = FontWeight.SemiBold
};
_stage = new TextBlock
{
Text = "正在准备模型…",
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
FontSize = 12
};
_bar = new ProgressBar
{
Minimum = 0,
Maximum = 1,
Value = 0,
Height = 6,
IsIndeterminate = true,
CornerRadius = new CornerRadius(3),
Foreground = new SolidColorBrush(Color.Parse("#3B7BFF")),
Background = new SolidColorBrush(Color.Parse("#1B2740")),
Transitions = new Transitions
{
// 进度平滑增长,不会一跳一跳
new DoubleTransition
{
Property = RangeBase.ValueProperty,
Duration = TimeSpan.FromMilliseconds(240),
Easing = new CubicEaseOut()
}
}
};
_percent = new TextBlock
{
Text = "",
Foreground = new SolidColorBrush(Color.Parse("#6E86AD")),
FontSize = 11,
HorizontalAlignment = HorizontalAlignment.Right
};
var panel = new StackPanel
{
Margin = new Thickness(22, 20),
Spacing = 12
};
panel.Children.Add(title);
panel.Children.Add(_bar);
panel.Children.Add(_stage);
panel.Children.Add(_percent);
Content = panel;
}
/// <summary>任意线程调用都可以。</summary>
public void Report(double value, string? message)
{
if (!Dispatcher.UIThread.CheckAccess())
{
Dispatcher.UIThread.Post(() => Report(value, message));
return;
}
var clamped = Math.Clamp(value, 0, 1);
_bar.IsIndeterminate = false;
_bar.Value = clamped;
_percent.Text = $"{clamped * 100:0}%";
if (!string.IsNullOrWhiteSpace(message)) _stage.Text = message;
}
}
@@ -0,0 +1,50 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services"
x:Class="EarthModelStudio.Views.MainWindow"
Title="{loc:Loc app.name}"
Width="1220" Height="800"
MinWidth="1040" MinHeight="700"
Background="{DynamicResource AppBg}"
WindowStartupLocation="CenterScreen">
<Grid ColumnDefinitions="236,*">
<!-- 侧栏 -->
<Border Grid.Column="0" Background="{DynamicResource SideBg}">
<Grid RowDefinitions="Auto,*,Auto" Margin="16,22,16,18">
<StackPanel Orientation="Horizontal" Spacing="11">
<Border Width="38" Height="38" CornerRadius="12" Background="#1C2C4C">
<TextBlock Text="◎" FontSize="20" Foreground="#8FB6FF"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="13.5" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc app.tagline}" Foreground="#7C90B4" FontSize="10" />
</StackPanel>
</StackPanel>
<StackPanel Grid.Row="1" Margin="0,30,0,0" Spacing="6">
<TextBlock Text="MENU" Foreground="#4C5F80" FontSize="9.5" FontWeight="SemiBold" Margin="14,0,0,4" />
<Button Classes="nav" Classes.active="{Binding IsHomeActive}"
Command="{Binding GoHomeCommand}" Content="{loc:Loc nav.home}" />
<Button Classes="nav" Classes.active="{Binding IsDownloadActive}"
Command="{Binding GoDownloadCommand}" Content="{loc:Loc nav.download}" />
<Button Classes="nav" Classes.active="{Binding IsSettingsActive}"
Command="{Binding GoSettingsCommand}" Content="{loc:Loc nav.settings}" />
</StackPanel>
<StackPanel Grid.Row="2" Spacing="4">
<Border Height="1" Background="{DynamicResource SideLine}" Margin="0,0,0,10" />
<TextBlock Text="{Binding VersionText}" Foreground="#6F82A6" FontSize="10.5" Margin="14,0,0,0" />
<TextBlock Text="{Binding PlatformText}" Foreground="#4F6080" FontSize="10" Margin="14,0,0,0" />
</StackPanel>
</Grid>
</Border>
<!-- 内容:页面切换由 MainWindow 做淡入过渡,避免硬切 -->
<ContentControl x:Name="PageHost" Grid.Column="1" Content="{Binding Current}" />
</Grid>
</Window>
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Threading;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using EarthModelStudio.Models;
using EarthModelStudio.Services;
using EarthModelStudio.ViewModels;
namespace EarthModelStudio.Views;
public partial class MainWindow : Window
{
private readonly List<PlayerWindow> _players = new();
private MainViewModel? _viewModel;
private ContentControl? _pageHost;
public MainWindow()
{
InitializeComponent();
_pageHost = this.FindControl<ContentControl>("PageHost");
if (_pageHost != null)
{
// 页面切换:淡入过渡,避免瞬间硬切
_pageHost.Transitions = new Transitions
{
new DoubleTransition
{
Property = Visual.OpacityProperty,
Duration = TimeSpan.FromMilliseconds(200),
Easing = new CubicEaseOut()
}
};
}
DataContextChanged += OnDataContextChanged;
Closed += OnClosed;
}
/// <summary>当前打开的模型窗口(每个模型一个独立窗口)。</summary>
public IReadOnlyList<PlayerWindow> PlayerWindows => _players;
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
private void OnDataContextChanged(object? sender, EventArgs e)
{
if (_viewModel != null)
{
_viewModel.PlayerRequested -= OpenPlayerWindow;
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
_viewModel = DataContext as MainViewModel;
if (_viewModel != null)
{
_viewModel.PlayerRequested += OpenPlayerWindow;
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
}
}
/// <summary>切换页面时让内容淡入,避免「一卡一卡」的硬切。</summary>
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(MainViewModel.Current) || _pageHost == null) return;
_pageHost.Opacity = 0.55;
// 下一帧回到 1,OpacityTransition 会自动插值
Dispatcher.UIThread.Post(() =>
{
if (_pageHost != null) _pageHost.Opacity = 1;
}, DispatcherPriority.Render);
}
private async void OpenPlayerWindow(ModelPackage package)
{
if (_viewModel == null) return;
// 启动进度窗:模型加载、地表纹理生成、界面构建的真实进度
var loading = new LoadingWindow(package.LocalizedName);
loading.Show(this);
loading.Report(0, "正在加载模型…");
// 让进度窗先画出来(用调度器让出一帧,测试环境也能推进)
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
PlayerWindow? window = null;
LoadedModel? loaded = null;
Exception? error = null;
try
{
loaded = await _viewModel.Models.LoadAsync(package, () => window?.Close(),
(value, message) => loading.Report(value, message));
}
catch (Exception ex)
{
error = ex;
}
loading.Close();
if (loaded == null || error != null)
{
var message = error?.Message ?? L.I["player.errorHint"];
var dialog = new ModelErrorWindow(
L.I.F("player.errorTitle", package.LocalizedName),
$"{message}\n\n{L.I["player.errorHint"]}");
dialog.Show(this);
return;
}
window = new PlayerWindow(package, loaded);
window.Closed += (_, _) => _players.Remove(window);
_players.Add(window);
window.Show(this);
window.Activate();
}
private void OnClosed(object? sender, EventArgs e)
{
if (_viewModel != null)
{
_viewModel.PlayerRequested -= OpenPlayerWindow;
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
foreach (var window in _players.ToList()) window.Close();
_players.Clear();
}
}
@@ -0,0 +1,106 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using System.Collections.Generic;
using EarthModelStudio.Models;
using EarthModelStudio.Services;
namespace EarthModelStudio.Views;
/// <summary>
/// 模型窗口:**只做窗口宿主**。
/// 内容完全来自模型程序集(<see cref="LoadedModel.View"/>),启动器不渲染任何东西。
/// 快捷键:Esc 关闭窗口,F11 全屏。
/// </summary>
public sealed class PlayerWindow : Window
{
private LoadedModel? _model;
public PlayerWindow(ModelPackage package, LoadedModel model)
{
_model = model;
Title = package.LocalizedName;
Width = 1240;
Height = 820;
MinWidth = 1000;
MinHeight = 680;
Background = new SolidColorBrush(Color.Parse("#05070F"));
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Content = model.View;
KeyDown += OnKeyDown;
Closed += OnClosed;
}
private void OnKeyDown(object? sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Escape:
Close();
e.Handled = true;
break;
case Key.F11:
WindowState = WindowState == WindowState.FullScreen
? WindowState.Normal
: WindowState.FullScreen;
e.Handled = true;
break;
}
}
private void OnClosed(object? sender, EventArgs e)
{
Content = null;
_model?.Dispose();
_model = null;
}
}
/// <summary>模型加载失败时显示的提示窗口(不含任何渲染逻辑)。</summary>
public sealed class ModelErrorWindow : Window
{
public ModelErrorWindow(string title, string message)
{
Title = title;
Width = 560;
Height = 340;
Background = new SolidColorBrush(Color.Parse("#0B1226"));
WindowStartupLocation = WindowStartupLocation.CenterOwner;
var lines = new List<Control>
{
new TextBlock
{
Text = title,
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
FontSize = 16,
FontWeight = FontWeight.SemiBold
},
new TextBlock
{
Text = message,
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
FontSize = 12,
TextWrapping = TextWrapping.Wrap
},
new Button
{
Content = "确定",
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
Padding = new Thickness(18, 6)
}
};
var panel = new StackPanel
{
Margin = new Thickness(24),
Spacing = 14
};
foreach (var line in lines) panel.Children.Add(line);
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
Content = panel;
}
}
@@ -0,0 +1,141 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:EarthModelStudio.Services"
x:Class="EarthModelStudio.Views.SettingsView">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Margin="26,24,26,32" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
<StackPanel Spacing="4">
<TextBlock Classes="h1" Text="{loc:Loc set.title}" />
<TextBlock Classes="muted" Text="{loc:Loc set.subtitle}" />
</StackPanel>
<!-- 通用 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="16">
<TextBlock Classes="h2" Text="{loc:Loc set.general}" />
<Grid ColumnDefinitions="200,*">
<StackPanel VerticalAlignment="Center" Spacing="2">
<TextBlock Classes="h3" Text="{loc:Loc set.language}" />
</StackPanel>
<ComboBox Grid.Column="1" ItemsSource="{Binding Languages}"
SelectedItem="{Binding SelectedLanguage}" Width="220" HorizontalAlignment="Left">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Label}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
<Grid ColumnDefinitions="200,*">
<StackPanel VerticalAlignment="Center" Spacing="2">
<TextBlock Classes="h3" Text="{loc:Loc set.fps}" />
<TextBlock Classes="faint" Text="{loc:Loc set.fps.desc}" TextWrapping="Wrap" />
</StackPanel>
<ComboBox Grid.Column="1" ItemsSource="{Binding FrameRates}"
SelectedItem="{Binding SelectedFps}" Width="120" HorizontalAlignment="Left" />
</Grid>
</StackPanel>
</Border>
<!-- 内存 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="12">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="h2" Text="{loc:Loc set.memory}" />
<TextBlock Grid.Column="1" Text="{Binding MemoryValueText}" Classes="h3"
Foreground="{DynamicResource Accent}" VerticalAlignment="Center" />
</Grid>
<TextBlock Classes="muted" Text="{loc:Loc set.memory.desc}" TextWrapping="Wrap" />
<Slider Minimum="512" Maximum="8192" TickFrequency="256" IsSnapToTickEnabled="False"
Value="{Binding MemoryValue}" Margin="0,4,0,0" />
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="faint" Text="{loc:Loc set.memory.hint}" TextWrapping="Wrap" />
<TextBlock Grid.Column="1" Classes="faint" Text="{Binding UsageText}" Margin="16,0,0,0" />
</Grid>
</StackPanel>
</Border>
<!-- 模型源 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="10">
<TextBlock Classes="h2" Text="{loc:Loc set.sources}" />
<TextBlock Classes="muted" Text="{loc:Loc set.sources.desc}" TextWrapping="Wrap" />
<ItemsControl ItemsSource="{Binding Sources}" Margin="0,4,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Classes="panel" Padding="12,9" Margin="0,0,0,8">
<Grid ColumnDefinitions="Auto,*,Auto">
<CheckBox IsChecked="{Binding Enabled}" VerticalAlignment="Center" Margin="0,0,10,0" />
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Text="{Binding UrlText}" Classes="faint" TextTrimming="CharacterEllipsis" MaxWidth="520" />
</StackPanel>
<Button Grid.Column="2" Classes="ghost small" Content="✕"
Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<!-- 存储 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="14">
<TextBlock Classes="h2" Text="{loc:Loc set.storage}" />
<Grid ColumnDefinitions="200,*,Auto">
<TextBlock Classes="h3" Text="{loc:Loc set.modelDir}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding ModelRoot}"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="0,0,10,0" />
<Button Grid.Column="2" Classes="small" Content="{loc:Loc set.openFolder}"
Command="{Binding OpenModelFolderCommand}" />
</Grid>
<Grid ColumnDefinitions="200,*,Auto">
<TextBlock Classes="h3" Text="{loc:Loc set.dataDir}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding DataRoot}"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="0,0,10,0" />
<Button Grid.Column="2" Classes="small" Content="{loc:Loc set.openFolder}"
Command="{Binding OpenDataFolderCommand}" />
</Grid>
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="faint" Text="{Binding StatusMessage}" VerticalAlignment="Center" />
<Button Grid.Column="1" Classes="small" Content="{loc:Loc set.clearCache}"
Command="{Binding ClearCacheCommand}" />
</Grid>
</StackPanel>
</Border>
<!-- 关于 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="12">
<TextBlock Classes="h2" Text="{loc:Loc set.about}" />
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.version}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.platform}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding PlatformText}" TextWrapping="Wrap" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.modelFormat}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.modelFormat.desc}" TextWrapping="Wrap" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.license}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.licenseValue}" />
</Grid>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
@@ -0,0 +1,9 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views;
public partial class SettingsView : UserControl
{
public SettingsView() => AvaloniaXamlLoader.Load(this);
}
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="EarthModelStudio.Desktop" />
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 / 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
</assembly>
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>EarthModelStudio.Tests</RootNamespace>
<AssemblyName>EarthModelStudio.Tests</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../main/dotnet/EarthModelStudio/EarthModelStudio.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,221 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Threading;
using Avalonia.VisualTree;
using EarthModelStudio;
using EarthModelStudio.Services;
using EarthModelStudio.ViewModels;
using EarthModelStudio.Views;
namespace EarthModelStudio.Tests;
/// <summary>
/// 离屏校验工具:把启动器页面和模型窗口渲染成 PNG。
/// 用法:dotnet run --project src/test/dotnet/EarthModelStudio.Tests -- build/screenshots
/// </summary>
internal static class Program
{
private static string _outDir = "screenshots";
[STAThread]
public static int Main(string[] args)
{
_outDir = args.Length > 0 ? args[0] : "screenshots";
Directory.CreateDirectory(_outDir);
Environment.SetEnvironmentVariable("EMS_HOME", FindRepoRoot());
Environment.SetEnvironmentVariable("EMS_DATA", Path.Combine(_outDir, ".data"));
AppBuilder.Configure<App>()
.UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting();
var services = AppServices.Create();
RenderPages(services);
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
return 0;
}
private static string FindRepoRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
{
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName;
}
return Directory.GetCurrentDirectory();
}
private static void RenderPages(AppServices services)
{
var vm = new MainViewModel(services);
var window = new MainWindow { DataContext = vm };
window.Show();
Dispatcher.UIThread.RunJobs();
Capture(window, "page-home.png");
vm.GoDownloadCommand.Execute(null);
Dispatcher.UIThread.RunJobs();
Capture(window, "page-download.png");
vm.GoSettingsCommand.Execute(null);
Dispatcher.UIThread.RunJobs();
Capture(window, "page-settings.png");
// 启动进度窗(单独截图)
var demoLoading = new LoadingWindow("地球自转");
demoLoading.Show(window);
demoLoading.Report(0.42, "生成地表纹理");
Dispatcher.UIThread.RunJobs();
Capture(demoLoading, "page-loading.png");
demoLoading.Close();
var packages = services.Models.Scan();
Console.WriteLine($"模型数: {packages.Count}");
foreach (var p in packages)
Console.WriteLine($" {p.Id}: 程序集={Path.GetFileName(p.AssemblyPath)} 存在={File.Exists(p.AssemblyPath)} 封面={File.Exists(p.PreviewPath)}");
// 启动模型:应当新开窗口,主窗口保持原页面
for (var i = 0; i < packages.Count && i < 2; i++)
{
var before = window.PlayerWindows.Count;
vm.PlayModel(packages[i]);
// 加载是异步的(带进度窗),这里泵一下调度器等它完成
var appeared = WaitFor(() => window.PlayerWindows.Count > before);
var player = window.PlayerWindows.LastOrDefault();
Console.WriteLine($"player windows = {window.PlayerWindows.Count} ({packages[i].Id}) appeared={appeared}");
if (player == null) continue;
if (i == 0)
{
Dispatcher.UIThread.RunJobs();
Capture(player, "page-player.png");
}
else
{
Capture(player, "page-player-rotation.png");
}
// 节气定位 / 视图切换只属于公转模型;自转模型不该出现
var hasSeasons = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("节气定位", StringComparison.Ordinal) && ShownInTree(t));
var hasViewSwitch = Descendants(player).OfType<Button>()
.Any(b => b.Tag is string tag && (tag == "rotation" || tag == "revolution") && ShownInTree(b));
Console.WriteLine($" {packages[i].Id}: 节气定位={hasSeasons} 视图切换={hasViewSwitch}");
// 缩放 / 拖动能力:模型画布由模型程序集提供,这里用反射验证接口存在且可用
var canvas = Descendants(player).FirstOrDefault(c => c.GetType().Name == "CelestialView");
if (canvas != null)
{
var type = canvas.GetType();
var zoomProp = type.GetProperty("Zoom");
var zoomBy = type.GetMethod("ZoomBy");
var resetView = type.GetMethod("ResetView");
var beforeZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
zoomBy?.Invoke(canvas, new object[] { 1.25 });
var afterZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
resetView?.Invoke(canvas, null);
var resetZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
var hasPointerOverride = type.GetMethod("OnPointerMoved",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) != null;
Console.WriteLine($" {packages[i].Id}: 缩放={beforeZoom:0.00}→{afterZoom:0.00}→{resetZoom:0.00} 暂停拖动={hasPointerOverride}");
}
// 底部提示:滚轮缩放 / 暂停后可拖动
var hasHint = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("拖动", StringComparison.Ordinal) && ShownInTree(t));
Console.WriteLine($" {packages[i].Id}: 交互提示={hasHint}");
}
// 关掉第二个窗口,只留一个继续验证主窗口
var second = window.PlayerWindows.LastOrDefault();
if (second != null) second.Close();
Dispatcher.UIThread.RunJobs();
Console.WriteLine($"window after closing second = {window.PlayerWindows.Count}");
// 主窗口仍停留在设置页 —— 说明没有被模型画面覆盖
Capture(window, "page-main-while-playing.png");
foreach (var player in window.PlayerWindows.ToList()) player.Close();
Dispatcher.UIThread.RunJobs();
window.Close();
}
private static bool WaitFor(Func<bool> condition, int timeoutMs = 20000)
{
var watch = Stopwatch.StartNew();
while (watch.ElapsedMilliseconds < timeoutMs)
{
Dispatcher.UIThread.RunJobs();
if (condition()) return true;
Thread.Sleep(15);
}
return condition();
}
private static bool ShownInTree(Control control)
{
Visual? current = control;
while (current != null)
{
if (current is Control c && !c.IsVisible) return false;
current = current.GetVisualParent();
}
return true;
}
private static IEnumerable<Control> Descendants(Control root)
{
var stack = new Stack<Control>();
stack.Push(root);
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current;
switch (current)
{
case Panel panel:
foreach (var child in panel.Children) stack.Push(child);
break;
case Border { Child: Control only }:
stack.Push(only);
break;
case ScrollViewer { Content: Control scrolled }:
stack.Push(scrolled);
break;
case ContentControl { Content: Control content }:
stack.Push(content);
break;
}
}
}
private static void Capture(Window window, string fileName)
{
try
{
var frame = window.CaptureRenderedFrame();
if (frame == null)
{
Console.WriteLine("capture failed: " + fileName);
return;
}
var path = Path.Combine(_outDir, fileName);
frame.Save(path);
Console.WriteLine($"page -> {path}");
}
catch (Exception ex)
{
Console.WriteLine($"capture error {fileName}: {ex.Message}");
}
}
}