Compare commits

...
10 Commits
Author SHA1 Message Date
2509_92447106 086303f9b7 修复导出 2026-11-08 09:30:02 +08:00
2509_92447106 68513876bc chore: remove dist/ from repo and ignore it 2026-11-08 09:17:54 +08:00
2509_92447106 35d7b1f30c 修复 2026-11-08 09:15:46 +08:00
2509_92447106 1b18c3d170 个问题 2026-11-08 09:15:13 +08:00
2509_92447106 e12922ad92 修复更新 2026-11-08 09:07:16 +08:00
2509_92447106 cf6f839ada 添加模型“五带“ 2026-11-08 08:59:54 +08:00
2509_92447106 f8fc0f6018 修复UI渲染 2026-11-07 20:37:22 +08:00
2509_92447106 e4ea4f054e 修复 2026-11-07 20:18:34 +08:00
2509_92447106 639ff1ba57 修复 2026-11-07 20:01:58 +08:00
2509_92447106 d81ab2acaa 修复 2026-11-07 19:31:02 +08:00
47 changed files with 2118 additions and 227 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,5 @@
bin/
obj/
dist/
build/
.GC/
*.user
@@ -18,3 +17,4 @@ __pycache__/
node_modules/
.pytest_cache/
.mypy_cache/
dist/
+1 -1
View File
@@ -21,7 +21,7 @@
-->
<AvaloniaVersion>11.3.9</AvaloniaVersion>
<MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.0</Version>
<Version>1.0.2</Version>
<Company>NeoRF</Company>
<Product>Earth Model Studio</Product>
<NeutralLanguage>zh-Hans</NeutralLanguage>
+10 -2
View File
@@ -42,7 +42,7 @@ $TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.cspro
$PreviewProj = 'model/_engine/PreviewGen/PreviewGen.csproj'
$StampProj = 'model/_engine/VersionStamp/VersionStamp.csproj'
$Sln = 'EarthModelStudio.sln'
$Version = '1.0.0'
$Version = '1.0.2'
function Stamp-Versions {
Write-Host '==> 自动计算模型版本并生成 version.json'
@@ -123,6 +123,8 @@ function Prepare-RuntimeLayout([string]$RelDir) {
function Publish-Rid([string]$Rid, [string]$OutDir) {
Write-Host "==> 编译 $Rid -> $OutDir"
# 先删旧产物目录,避免残留文件混进新包
if (Test-Path "$Root/$OutDir") { Remove-Item -Recurse -Force "$Root/$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"
@@ -186,10 +188,16 @@ function Pack-Launcher {
}
switch ($Task) {
'build' { dotnet build $Sln -c Debug }
'build' {
Get-ChildItem "$Root/dist/GC-*.zip","$Root/dist/models-*.zip" -ErrorAction SilentlyContinue |
Remove-Item -Force
dotnet build $Sln -c Debug
}
'run' { dotnet run --project $AppProj -c Debug }
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
'publish' {
# 先清理 dist 旧产物,再重新生成
if (Test-Path "$Root/dist") { Remove-Item -Recurse -Force "$Root/dist" }
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
Stamp-Versions
Publish-Rid 'osx-arm64' 'dist/mac-arm64'
+101 -20
View File
@@ -38,7 +38,7 @@ PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj"
SLN="EarthModelStudio.sln"
VERSION="1.0.0"
VERSION="1.0.2"
TASK="${1:-build}"
# 按模型包内容指纹自动写回 <id>.json 的 version,并生成 version.json
@@ -113,18 +113,21 @@ JSON
echo " 运行目录 -> $REL/.GC (settings.json + model/ + cache/ + update/)"
}
# $1=RID $2=输出目录 $3=singlefile(true/false)
publish_rid() {
RID="$1"; OUT="$2"
RID="$1"; OUT="$2"; SINGLE="${3:-true}"
echo ""
echo "==> 编译 ${RID} -> ${OUT}"
echo "==> 编译 ${RID} (single-file=${SINGLE}) -> ${OUT}"
# 先删旧产物,避免上次 publish 的残留文件混进新包
rm -rf "$ROOT_DIR/$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:PublishSingleFile="$SINGLE" \
-p:IncludeNativeLibrariesForSelfExtract="$SINGLE" \
-p:PublishTrimmed=false \
-o "$ROOT_DIR/$OUT"
rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples"
@@ -142,20 +145,88 @@ pack_models() {
}
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户已下载的模型与设置)
# 产物命名:GC-<版本>-<系统>-<架构>.exe / GC-<版本>-<系统>-<架构>.app.zip
# Windows: 单文件 exe 直接改名(本身就是可执行产物)
# macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip,
# 这样 macOS 双击会用归档工具解压出可运行的 .app。
# 若直接命名 .app,系统会把 zip 当成应用包解析 => 报「已损坏/打不开」。
pack_launcher() {
echo "==> 生成启动器更新包(不含 .GC)"
WIN64="$ROOT_DIR/dist/win-x64"
WINARM="$ROOT_DIR/dist/win-arm64"
MACBIN="$ROOT_DIR/dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
[ -d "$MACBIN" ] || MACBIN="$ROOT_DIR/dist/mac-arm64"
[ -d "$WIN64" ] && ( cd "$WIN64" && zip -qr "$ROOT_DIR/dist/GC-win-x64.zip" . \
-x "./.GC" "./.GC/*" "*.DS_Store" )
[ -d "$WINARM" ] && ( cd "$WINARM" && zip -qr "$ROOT_DIR/dist/GC-win-arm64.zip" . \
-x "./.GC" "./.GC/*" "*.DS_Store" )
[ -d "$MACBIN" ] && ( cd "$MACBIN" && zip -qr "$ROOT_DIR/dist/GC-osx-arm64.zip" . \
-x "./.GC" "./.GC/*" "*.DS_Store" )
echo "==> 生成启动器产物(GC-<版本>-<系统>-<架构>)"
# --- Windows:exe 单文件 ---
for pair in "win-x64:win-amd64" "win-arm64:win-arm64"; do
RID="${pair%%:*}"; LABEL="${pair##*:}"
SRC="$ROOT_DIR/dist/$RID"
[ -d "$SRC" ] || continue
EXE=$(ls "$SRC"/*.exe 2>/dev/null | head -1)
[ -n "$EXE" ] || continue
DEST="$ROOT_DIR/dist/GC-${VERSION}-${LABEL}.exe"
cp "$EXE" "$DEST"
chmod +x "$DEST"
echo " -> $(basename "$DEST")"
done
# --- macOS:打包成 zip -> 解压回来 -> 改名 -> 删除 zip ---
# 这样 dist 里得到的是一个可直接双击运行的真实 .app 目录,
# 而 zip 只是保证权限/符号链接不丢的中间载体,用完即删。
MACAPP="$ROOT_DIR/dist/mac-arm64/EarthModelStudio.app"
if [ -d "$MACAPP" ]; then
FINAL="$ROOT_DIR/dist/GC-${VERSION}-mac-arm64.app"
TMPZIP="$ROOT_DIR/dist/.gc-mac-tmp.zip"
WORK="$ROOT_DIR/dist/.gc-mac-work"
rm -rf "$FINAL" "$WORK" "$TMPZIP"
mkdir -p "$WORK"
# 1) 打包(ditto 保留可执行权限与符号链接,比 zip -y 可靠)
if command -v ditto >/dev/null 2>&1; then
ditto -c -k --sequesterRsrc --keepParent "$MACAPP" "$TMPZIP"
else
( cd "$(dirname "$MACAPP")" && zip -qry "$TMPZIP" "$(basename "$MACAPP")" -x "*.DS_Store" )
fi
# 2) 解压到工作目录
if command -v ditto >/dev/null 2>&1; then
ditto -x -k "$TMPZIP" "$WORK"
else
( cd "$WORK" && unzip -q "$TMPZIP" )
fi
# 3) 改名为发布名(保持 .app 是目录)
SRCAPP="$WORK/EarthModelStudio.app"
if [ -d "$SRCAPP" ]; then
mv "$SRCAPP" "$FINAL"
chmod +x "$FINAL/Contents/MacOS/EarthModelStudio" 2>/dev/null || true
# 同步 Info.plist 的显示名,避免 Finder 里显示旧名
PLIST="$FINAL/Contents/Info.plist"
if [ -f "$PLIST" ]; then
/usr/libexec/PlistBuddy -c "Set :CFBundleName Morris GC" "$PLIST" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName Morris GC" "$PLIST" 2>/dev/null || true
fi
# 去掉隔离属性,避免 Gatekeeper 误拦(本地构建产物)
xattr -cr "$FINAL" 2>/dev/null || true
echo " -> $(basename "$FINAL")/ (目录)"
else
echo " !! macOS 打包失败:解压后未找到 EarthModelStudio.app" >&2
fi
# 4) 删除 zip 与工作目录
rm -rf "$WORK" "$TMPZIP"
fi
strip_intermediate_dirs
stamp_versions
ls -lh "$ROOT_DIR"/dist/GC-*.zip 2>/dev/null || true
echo ""
echo "==> dist 只保留可发布的附件:"
ls -lh "$ROOT_DIR"/dist/GC-"$VERSION"-* 2>/dev/null || true
}
# 删除 publish 过程中的中间目录,dist 里只留最终附件
strip_intermediate_dirs() {
for d in win-x64 win-arm64 mac-arm64; do
[ -d "$ROOT_DIR/dist/$d" ] && rm -rf "$ROOT_DIR/dist/$d"
done
find "$ROOT_DIR/dist" -name ".DS_Store" -delete 2>/dev/null || true
}
package_mac_app() {
@@ -184,14 +255,19 @@ PLIST
for f in "$DIST"/*; do
base=$(basename "$f")
[ "$base" = "EarthModelStudio.app" ] && continue
[ "$base" = ".DS_Store" ] && continue
mv "$f" "$APP/Contents/MacOS/"
done
# 发布包不带 .GC 运行骨架(用户首次启动自行创建),避免覆盖用户数据
rm -rf "$APP/Contents/MacOS/.GC"
chmod +x "$APP/Contents/MacOS/EarthModelStudio"
echo "==> 已打包 $APP"
}
case "$TASK" in
build)
# 清理上次遗留的发布包 zip,避免误用旧产物
rm -f "$ROOT_DIR"/dist/GC-*.zip "$ROOT_DIR"/dist/models-*.zip 2>/dev/null || true
dotnet build "$SLN" -c Debug
;;
run)
@@ -201,11 +277,16 @@ case "$TASK" in
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots"
;;
publish)
# 先清掉 dist 旧产物(含历史 zip / 目录),再重新生成
echo "==> 清理 dist 旧产物"
rm -rf "$ROOT_DIR/dist"
mkdir -p "$ROOT_DIR/dist"
stamp_versions
publish_rid "osx-arm64" "dist/mac-arm64"
publish_rid "win-x64" "dist/win-x64"
publish_rid "win-arm64" "dist/win-arm64"
# macOS 用目录形式(非单文件):单文件包启动时需要解压缓存目录,
# 在受限/沙箱环境下创建失败会直接报「打不开」。目录形式无此依赖。
publish_rid "osx-arm64" "dist/mac-arm64" false
publish_rid "win-x64" "dist/win-x64" true
publish_rid "win-arm64" "dist/win-arm64" true
package_mac_app
prepare_runtime_layout "dist/win-x64"
prepare_runtime_layout "dist/win-arm64"
+9 -2
View File
@@ -9,6 +9,9 @@ using System.Text.Json.Nodes;
// 输出:更新 model/<id>/<id>.json 的 version / updatedAt,并生成
// 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。
// 仓库地址(编译产物的 Release 也发在这里):与启动器默认 updateRepository 保持一致。
const string Repository = "https://gitcode.com/2509_92447106/GC";
var root = args.Length > 0 ? Path.GetFullPath(args[0]) : Directory.GetCurrentDirectory();
var launcherVersion = args.Length > 1 && !string.IsNullOrWhiteSpace(args[1]) ? args[1] : "1.0.0";
var modelRoot = Path.Combine(root, "model");
@@ -111,12 +114,16 @@ if (Directory.Exists(srcRoot))
var launcherRevision = srcChunks.Count > 0 ? Fingerprint(srcChunks)[..10] : "";
var packages = new Dictionary<string, Dictionary<string, object>>();
// 启动器更新只访问「编译的产物」:gitcode Release 里发布的 dist/GC-<rid>.zip 附件。
// 运行时若存在同名 Release,GitCodeReleaseRemote 会用附件真实直链覆盖下面的 url;
// 下面的地址是兜底(编译产物尚未发 Release 时也能指向正确的编译产物位置)。
var releaseBase = $"{Repository}/releases/download/v{launcherVersion}";
foreach (var rid in new[] { "win-x64", "win-arm64", "osx-arm64", "osx-x64", "linux-x64" })
{
var entry = new Dictionary<string, object>
{
["path"] = $"dist/GC-{rid}.zip",
["url"] = "" // 大文件建议填 Release 直链;留空则用仓库内 path
["url"] = $"{releaseBase}/GC-{rid}.zip"
};
// 已生成的启动器更新包:把校验值和体积写进清单,供下载端校验
var zipPath = Path.Combine(root, "dist", $"GC-{rid}.zip");
@@ -133,7 +140,7 @@ var versionDoc = new Dictionary<string, object>
{
["schema"] = 1,
["generated"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
["repository"] = "https://gitcode.com/2509_92447106/GC",
["repository"] = Repository,
["branch"] = "main",
["modelDir"] = "model",
["launcher"] = new Dictionary<string, object>
+57 -36
View File
@@ -53,7 +53,7 @@ public class CelestialView : Control, IDisposable
AvaloniaProperty.Register<CelestialView, bool>(nameof(ExaggerateTilt));
public static readonly StyledProperty<int> FrameRateProperty =
AvaloniaProperty.Register<CelestialView, int>(nameof(FrameRate), 30);
AvaloniaProperty.Register<CelestialView, int>(nameof(FrameRate), 120);
public static readonly StyledProperty<bool> ShowHudProperty =
AvaloniaProperty.Register<CelestialView, bool>(nameof(ShowHud), true);
@@ -379,7 +379,8 @@ public class CelestialView : Control, IDisposable
{
base.OnAttachedToVisualTree(e);
_camElevTarget = DefaultElevation;
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(16), DispatcherPriority.Render, OnTick);
// 8ms 轮询以支撑最高 120 FPS(模型内部仍按 FrameRate 限流);不依赖系统 VSync 节拍
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(8), DispatcherPriority.Render, OnTick);
_lastTick = Stopwatch.GetTimestamp();
_timer.Start();
}
@@ -678,7 +679,11 @@ public class CelestialView : Control, IDisposable
private Vector3 RotationLight(Matrix4x4 cam, double tiltDeg)
{
var axisCam = Vector3.TransformNormal(AxisWorld(tiltDeg), cam);
var forwardRight = Vector3.Normalize(new Vector3(0.86f, 0f, 0.50f));
// 特写模式:光从正右方水平射来,晨昏线竖直居中、正对观察者,
// 便于课堂直观看昼夜半球;主画布仍用斜向光体现立体感。
var forwardRight = InsetMode
? new Vector3(1f, 0f, 0f)
: Vector3.Normalize(new Vector3(0.86f, 0f, 0.50f));
var u = forwardRight - axisCam * Vector3.Dot(forwardRight, axisCam);
if (u.Length() < 0.001f) u = new Vector3(1, 0, 0);
u = Vector3.Normalize(u);
@@ -704,40 +709,52 @@ public class CelestialView : Control, IDisposable
var tropic = TropicDegrees(runtime);
var polar = 90.0 - tropic;
DrawParallel(ctx, cam, planet, center, radius, 0, EquatorPen,
labels ? Texts["lat.equator"] : null, LabelBrush);
DrawParallel(ctx, cam, planet, center, radius, tropic, TropicPen,
labels ? Texts["lat.tropicN"] : null, TropicBrush);
DrawParallel(ctx, cam, planet, center, radius, -tropic, TropicPen,
labels ? Texts["lat.tropicS"] : null, TropicBrush);
DrawParallel(ctx, cam, planet, center, radius, polar, PolarPen,
labels ? Texts["lat.polarN"] : null, PolarBrush);
DrawParallel(ctx, cam, planet, center, radius, -polar, PolarPen,
labels ? Texts["lat.polarS"] : null, PolarBrush);
}
private void DrawParallel(DrawingContext ctx, Matrix4x4 cam, Matrix4x4 planet,
Point center, double radius, double lat, IPen pen, string? label, IBrush labelBrush)
{
DrawSpherePolyline(ctx, cam, planet, center, radius, pen,
t => LatLonToUnit(lat, t * 360.0), 144);
if (label == null) return;
// 找该纬线上「最靠右且可见」的点作为标签锚点:
// 地球自转时标签始终留在可见半球右侧,不会忽隐忽现
Vector3 best = default;
var bestScore = double.NegativeInfinity;
for (var lon = -180; lon < 180; lon += 6)
// 五条纬线一起画:先画线,再统一布置标签,避免自转时多个标签
// 被投影到相近位置而互相覆盖 / 抖动(原来的逐条独立绘制会重叠)。
var lines = new (double Lat, IPen Pen, string? Label, IBrush Brush)[]
{
var world = Vector3.Transform(LatLonToUnit(lat, lon), planet);
var c = Vector3.Transform(world, cam);
if (c.Z < 0.10f) continue;
var score = c.X * 2.0 + c.Z;
if (score > bestScore) { bestScore = score; best = c; }
(0, EquatorPen, labels ? Texts["lat.equator"] : null, LabelBrush),
(tropic, TropicPen, labels ? Texts["lat.tropicN"] : null, TropicBrush),
(-tropic, TropicPen, labels ? Texts["lat.tropicS"] : null, TropicBrush),
(polar, PolarPen, labels ? Texts["lat.polarN"] : null, PolarBrush),
(-polar, PolarPen, labels ? Texts["lat.polarS"] : null, PolarBrush)
};
foreach (var l in lines)
DrawSpherePolyline(ctx, cam, planet, center, radius, l.Pen,
t => LatLonToUnit(l.Lat, t * 360.0), 144);
if (!labels) return;
// 收集每个标签的锚点,按屏幕 Y 排序后做垂直去重叠
var placed = new List<(double Y, double X, string Text, IBrush Brush)>();
foreach (var l in lines)
{
if (l.Label == null) continue;
Vector3 best = default;
var bestScore = double.NegativeInfinity;
for (var lon = -180; lon < 180; lon += 6)
{
var world = Vector3.Transform(LatLonToUnit(l.Lat, lon), planet);
var c = Vector3.Transform(world, cam);
if (c.Z < 0.10f) continue;
var score = c.X * 2.0 + c.Z;
if (score > bestScore) { bestScore = score; best = c; }
}
if (double.IsNegativeInfinity(bestScore)) continue;
placed.Add((center.Y - best.Y * radius, center.X + best.X * radius, l.Label, l.Brush));
}
placed.Sort((a, b) => a.Y.CompareTo(b.Y));
const double minGap = 16.0;
var lastY = double.NegativeInfinity;
foreach (var p in placed)
{
var y = p.Y;
if (y - lastY < minGap) y = lastY + minGap;
lastY = y;
DrawLabelChip(ctx, p.Text, new Point(p.X, y), InsetMode ? 9.0 : 10.5, p.Brush, toRight: false);
}
if (double.IsNegativeInfinity(bestScore)) return;
var p = new Point(center.X + best.X * radius, center.Y - best.Y * radius);
DrawLabelChip(ctx, label, p, InsetMode ? 9.0 : 10.5, labelBrush, toRight: false);
}
/// <summary>带深色底衬的标签:压在明亮的地球上也读得清,且不会被画布边缘裁掉。</summary>
@@ -745,7 +762,11 @@ public class CelestialView : Control, IDisposable
double fontSize, IBrush brush, bool toRight)
{
var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
new Typeface(FontFamily.Default, FontStyle.Normal, FontWeight.SemiBold), fontSize, brush);
new Typeface(FontFamily.Default, FontStyle.Normal, FontWeight.SemiBold), fontSize, brush)
{
TextAlignment = TextAlignment.Left,
Trimming = TextTrimming.None
};
var x = toRight ? anchor.X + 9 : Math.Max(3, anchor.X - formatted.Width - 9);
var y = anchor.Y - formatted.Height - 4;
ctx.DrawRectangle(ChipBg, null,
+22 -11
View File
@@ -85,7 +85,7 @@ public sealed class EarthModelView : UserControl, IDisposable
ShowOrbit = true,
ShowGraticule = true,
ShowKeyLatitudes = true,
FrameRate = 60,
FrameRate = 120,
View = IsRevolution ? SceneView.Revolution : SceneView.Rotation
};
_canvas.JumpToOrbit(StartAngle);
@@ -216,8 +216,7 @@ public sealed class EarthModelView : UserControl, IDisposable
// ---------------------------------------------------------------- 顶部主工具栏
private Control BuildTopBar()
{
var close = MakeButton(_texts["close"], () => _context.RequestClose());
// 关闭按钮统一放在窗口右上角的自建标题栏,这里不再重复放左上角
var title = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center };
title.Children.Add(new TextBlock
{
@@ -268,14 +267,13 @@ public sealed class EarthModelView : UserControl, IDisposable
actions.Children.Add(MakeButton(_texts["classroom"], () => SetLessonsVisible(!_showLessons)));
actions.Children.Add(MakeButton("⛶", ToggleFullScreen, large: true));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") };
grid.Children.Add(close);
Grid.SetColumn(title, 1);
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto") };
Grid.SetColumn(title, 0);
title.Margin = new Thickness(14, 0, 0, 0);
grid.Children.Add(title);
Grid.SetColumn(_viewSwitch, 2);
Grid.SetColumn(_viewSwitch, 1);
grid.Children.Add(_viewSwitch);
Grid.SetColumn(actions, 4);
Grid.SetColumn(actions, 3);
grid.Children.Add(actions);
return new Border { Background = PanelBg, Padding = new Thickness(16, 9), Child = grid };
@@ -716,10 +714,23 @@ public sealed class EarthModelView : UserControl, IDisposable
? _texts.Pick(season.TeachingI18n, _texts["orbitTeach"])
: _texts["orbitTeach"];
if (_showCloseup && (double.IsNaN(_lastDeclination) || Math.Abs(_lastDeclination - decl) > 0.04))
// 特写的直射纬度用缓动逼近目标,而不是瞬间跳变:
// 公转时拖动/改变轨道角,晨昏线会平滑地移过去(每次 timer 步进一帧)。
if (_showCloseup)
{
_closeup.DeclinationDeg = decl;
_lastDeclination = decl;
var target = decl;
var current = _closeup.DeclinationDeg;
var diff = target - current;
if (Math.Abs(diff) < 0.02)
{
_closeup.DeclinationDeg = target;
}
else
{
// 每 140ms 走剩余距离的 ~18%,形成自然的 ease-out 动画
_closeup.DeclinationDeg = current + diff * 0.18;
}
_lastDeclination = target;
}
}
+110
View File
@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Numerics;
namespace NeoRF.EarthModels;
/// <summary>
/// 地理模型的球面几何工具:经纬度 ↔ 单位球坐标、正交投影到屏幕、
/// 以及把一条经纬度折线投影成「可见弧段」(背面自动裁掉)。
/// 纯 CPU、无依赖,供 GeographyView 画线稿用。
/// </summary>
public static class Geometry
{
public const float DegToRad = (float)(Math.PI / 180.0);
public const float RadToDeg = (float)(180.0 / Math.PI);
/// <summary>经纬度 → 单位球坐标(y 轴为地轴,lon 向东为正)。</summary>
public static Vector3 LatLonToUnit(double latDeg, double lonDeg)
{
var lat = (float)(latDeg * Math.PI / 180.0);
var lon = (float)(lonDeg * Math.PI / 180.0);
var cosLat = (float)Math.Cos(lat);
return new Vector3(cosLat * (float)Math.Sin(lon), (float)Math.Sin(lat), cosLat * (float)Math.Cos(lon));
}
/// <summary>把世界坐标旋转到相机空间(先用 planet 旋转地球,再用 cam 转到屏幕)。</summary>
public static Vector3 ToCamera(Vector3 world, Matrix4x4 planet, Matrix4x4 cam)
=> Vector3.Transform(Vector3.Transform(world, planet), cam);
/// <summary>相机空间的正交投影:球心在原点,半径 radius。</summary>
public static Vector2 Project(Vector3 camPos, float radius, float centerX, float centerY)
=> new(centerX + camPos.X * radius, centerY - camPos.Y * radius);
/// <summary>相机空间里该点是否朝向观察者(z>0 为正面)。</summary>
public static bool IsVisible(Vector3 camPos, float threshold = 0f) => camPos.Z > threshold;
/// <summary>
/// 把一条经纬度折线拆成若干段「可见」的屏幕折线。
/// 跨越地平线的相邻两点用线性插值求出交点作为端点,保证线不会穿过球体背面。
/// </summary>
public static List<List<Vector2>> ProjectPolyline(
IReadOnlyList<double[]> latLonPoints,
Matrix4x4 planet, Matrix4x4 cam,
float radius, float centerX, float centerY,
bool closed = false)
{
var result = new List<List<Vector2>>();
if (latLonPoints.Count < 2) return result;
var count = latLonPoints.Count;
var total = closed ? count + 1 : count;
List<Vector2>? current = null;
Vector3 prevCam = default;
var havePrev = false;
for (var i = 0; i < total; i++)
{
var p = latLonPoints[i % count];
if (p.Length < 2) { havePrev = false; continue; }
var camPos = ToCamera(LatLonToUnit(p[1], p[0]), planet, cam);
var visible = camPos.Z > 0f;
if (!havePrev)
{
if (visible)
{
current = new List<Vector2>();
current.Add(Project(camPos, radius, centerX, centerY));
}
prevCam = camPos;
havePrev = true;
continue;
}
var prevVisible = prevCam.Z > 0f;
if (visible && prevVisible)
{
current ??= new List<Vector2>();
current.Add(Project(camPos, radius, centerX, centerY));
}
else if (visible != prevVisible)
{
// 求出与地平线(z=0)的交点
var t = prevCam.Z / (prevCam.Z - camPos.Z);
var hit = Vector3.Lerp(prevCam, camPos, t);
hit.Z = 0f;
var hitScreen = Project(hit, radius, centerX, centerY);
if (visible)
{
current = new List<Vector2> { hitScreen };
current.Add(Project(camPos, radius, centerX, centerY));
}
else
{
current?.Add(hitScreen);
if (current is { Count: > 1 }) result.Add(current);
current = null;
}
}
prevCam = camPos;
}
if (current is { Count: > 1 }) result.Add(current);
return result;
}
}
@@ -0,0 +1,22 @@
{
"id": "earth-geography",
"nameI18n": {
"zh-CN": "地球地理",
"en": "Earth Geography"
},
"descriptionI18n": {
"zh-CN": "五带划分、七大洲四大洋轮廓、六大板块与洲界,纯线稿教学图。",
"en": "Climate zones, continent/ocean outlines, plates and borders — clean line art."
},
"assembly": "EarthGeographyModel.dll",
"type": "NeoRF.EarthModels.GeographyModelFactory",
"author": "Morris GC",
"tags": [
"geography",
"earth",
"atlas"
],
"dataDir": "earth-geography.model",
"version": "1.0-dd67f83d0c",
"updatedAt": "2026-11-08T01:29:16Z"
}
@@ -0,0 +1 @@
{"borders":[{"between":"亚洲-非洲","name":"苏伊士运河","lines":[[[32.6,31.3],[32.4,30.5],[32.3,29.9]]]},{"between":"亚洲-欧洲","name":"亚欧分界(乌拉尔山—乌拉尔河—里海—大高加索山—黑海—土耳其海峡)","segments":[{"name":"乌拉尔山","nameI18n":{"zh-CN":"乌拉尔山","en":"Ural Mts."},"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0]]]},{"name":"乌拉尔河","nameI18n":{"zh-CN":"乌拉尔河","en":"Ural River"},"lines":[[[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5]]]},{"name":"里海","nameI18n":{"zh-CN":"里海","en":"Caspian Sea"},"lines":[[[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5]]]},{"name":"大高加索山","nameI18n":{"zh-CN":"大高加索山","en":"Greater Caucasus"},"lines":[[[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2]]]},{"name":"黑海","nameI18n":{"zh-CN":"黑海","en":"Black Sea"},"lines":[[[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5]]]},{"name":"土耳其海峡","nameI18n":{"zh-CN":"土耳其海峡","en":"Turkish Straits"},"lines":[[[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]}],"lines":[[[66.0,68.5],[64.0,64.0],[60.5,60.0],[58.5,54.0],[57.0,51.0],[57.0,51.0],[55.5,49.0],[53.0,47.0],[51.5,46.5],[51.5,46.5],[50.5,44.0],[49.5,41.0],[50.0,38.0],[51.0,36.5],[51.0,36.5],[46.0,42.5],[43.0,42.8],[41.0,43.2],[41.0,43.2],[36.0,44.5],[31.0,44.0],[29.0,41.5],[29.0,41.5],[28.0,40.5],[26.5,40.0],[26.2,39.5]]]},{"between":"亚洲-非洲","name":"红海","lines":[[[43.3,12.6],[40.0,18.0],[38.5,22.0],[35.0,27.0],[34.5,29.0]]]},{"between":"欧洲-非洲","name":"直布罗陀海峡","lines":[[[-5.6,36.0],[-4.0,36.2],[0.0,36.5]]]},{"between":"北美-南美","name":"巴拿马运河","lines":[[[-79.6,9.1],[-78.5,8.9],[-77.5,8.6]]]},{"between":"亚洲-北美","name":"白令海峡","lines":[[[-169.0,65.5],[-170.5,65.8],[-172.0,66.0]]]},{"between":"亚洲-大洋洲","name":"印尼群岛","lines":[[[120.0,-1.0],[125.0,-2.0],[130.0,-3.0]]]},{"between":"南极洲","name":"南极圈","lines":[[[-180.0,-66.5],[-170.0,-66.5],[-160.0,-66.5],[-150.0,-66.5],[-140.0,-66.5],[-130.0,-66.5],[-120.0,-66.5],[-110.0,-66.5],[-100.0,-66.5],[-90.0,-66.5],[-80.0,-66.5],[-70.0,-66.5],[-60.0,-66.5],[-50.0,-66.5],[-40.0,-66.5],[-30.0,-66.5],[-20.0,-66.5],[-10.0,-66.5],[0.0,-66.5],[10.0,-66.5],[20.0,-66.5],[30.0,-66.5],[40.0,-66.5],[50.0,-66.5],[60.0,-66.5],[70.0,-66.5],[80.0,-66.5],[90.0,-66.5],[100.0,-66.5],[110.0,-66.5],[120.0,-66.5],[130.0,-66.5],[140.0,-66.5],[150.0,-66.5],[160.0,-66.5],[170.0,-66.5],[180.0,-66.5]]]}]}
@@ -0,0 +1 @@
{"lines":[[[179.999,-16.169],[179.564,-16.637],[179.568,-16.747],[179.93,-16.519],[179.928,-16.744],[179.419,-16.807],[179.202,-16.713],[179.007,-16.9],[178.707,-16.976],[178.604,-16.801],[178.497,-16.788],[178.584,-16.622],[178.805,-16.631],[178.961,-16.483],[179.552,-16.25],[179.999,-16.169]],[[143.179,-11.954],[143.11,-12.304],[143.402,-12.64],[143.587,-13.444],[143.548,-13.741],[143.756,-14.349],[143.962,-14.463],[144.473,-14.232],[144.648,-14.492],[145.288,-14.943],[145.272,-15.477],[145.458,-16.056],[145.426,-16.406],[145.755,-16.879],[145.912,-16.913],[146.126,-17.635],[146.032,-18.273],[146.333,-18.554],[146.297,-18.841],[146.383,-18.977],[147.139,-19.393],[147.419,-19.378],[147.742,-19.77],[148.759,-20.29],[148.885,-20.481],[148.73,-20.468],[148.684,-20.58],[149.205,-21.125],[149.329,-21.476],[149.454,-21.579],[149.704,-22.441],[149.822,-22.39],[149.974,-22.551],[149.942,-22.308],[150.021,-22.168],[150.541,-22.559],[150.623,-22.367],[150.764,-22.576],[150.843,-23.458],[151.154,-23.784],[151.832,-24.123],[152.13,-24.598],[152.456,-24.802],[152.654,-25.202],[152.913,-25.432],[152.921,-25.689],[153.165,-25.964],[153.084,-26.304],[153.117,-27.194],[153.576,-28.241],[153.617,-28.673],[153.605,-28.854],[153.348,-29.29],[153.272,-29.892],[153.031,-30.563],[152.944,-31.435],[152.559,-32.046],[152.47,-32.439],[152.137,-32.678],[152.164,-32.757],[151.813,-32.901],[151.432,-33.522],[151.292,-33.581],[151.28,-33.927],[151.125,-34.005],[151.232,-34.03],[150.871,-34.499],[150.805,-35.013],[150.567,-35.214],[150.195,-35.834],[149.96,-36.846],[149.933,-37.529],[149.481,-37.771],[148.262,-37.831],[147.877,-37.934],[146.857,-38.663],[146.217,-38.727],[146.337,-38.894],[146.467,-38.84],[146.484,-39.065],[146.4,-39.146],[146.158,-38.866],[145.935,-38.902],[145.791,-38.667],[145.397,-38.535],[145.542,-38.394],[145.476,-38.244],[145.293,-38.238],[144.96,-38.501],[144.718,-38.34],[144.911,-38.344],[145.12,-38.091],[144.891,-37.9],[144.396,-38.137],[144.665,-38.21],[143.539,-38.821],[142.456,-38.386],[141.725,-38.271],[141.594,-38.388],[141.424,-38.363],[141.011,-38.077],[140.39,-37.897],[139.784,-37.246],[139.738,-37.06],[139.857,-36.662],[139.729,-36.371],[139.466,-36.01],[138.969,-35.581],[139.178,-35.523],[139.289,-35.611],[139.283,-35.375],[138.522,-35.642],[138.184,-35.613],[138.511,-35.024],[138.49,-34.764],[138.089,-34.17],[137.692,-35.143],[136.884,-35.24],[137.014,-34.916],[137.391,-34.913],[137.494,-34.161],[137.932,-33.579],[137.852,-33.201],[137.993,-33.094],[137.783,-32.578],[137.791,-32.823],[137.442,-33.194],[137.237,-33.629],[136.431,-34.03],[135.891,-34.661],[135.97,-34.982],[135.792,-34.863],[135.648,-34.94],[135.231,-34.58],[135.123,-34.586],[135.217,-34.487],[135.45,-34.581],[135.219,-33.96],[134.889,-33.626],[134.719,-33.255],[134.301,-33.165],[134.1,-32.749],[134.227,-32.731],[134.234,-32.549],[133.665,-32.207],[133.212,-32.184],[132.757,-31.956],[132.215,-32.007],[131.721,-31.696],[131.144,-31.496],[130.783,-31.604],[130.13,-31.579],[128.946,-31.703],[127.32,-32.264],[125.917,-32.297],[124.759,-32.883],[124.244,-33.015],[123.868,-33.596],[123.507,-33.916],[123.208,-33.988],[122.778,-33.891],[122.151,-33.992],[122.061,-33.874],[121.405,-33.827],[119.854,-33.975],[119.635,-34.101],[119.451,-34.368],[118.895,-34.48],[118.136,-34.987],[117.863,-35.055],[116.517,-34.988],[115.987,-34.795],[115.565,-34.426],[115.009,-34.256],[114.994,-33.515],[115.182,-33.643],[115.359,-33.64],[115.515,-33.531],[115.683,-33.193],[115.619,-32.667],[115.725,-32.401],[115.698,-31.695],[115.078,-30.56],[114.857,-29.143],[114.165,-28.081],[114.028,-27.347],[113.185,-26.182],[113.323,-26.244],[113.356,-26.08],[113.582,-26.558],[113.734,-26.595],[113.836,-26.501],[113.853,-26.332],[113.589,-26.099],[113.395,-25.713],[113.451,-25.599],[113.713,-25.831],[113.724,-26.13],[113.854,-26.014],[113.992,-26.321],[114.09,-26.394],[114.216,-26.289],[114.214,-25.852],[113.418,-24.436],[113.49,-23.87],[113.757,-23.418],[113.795,-22.915],[113.683,-22.638],[114.023,-21.881],[114.124,-21.829],[114.142,-22.483],[114.378,-22.342],[114.709,-21.823],[115.456,-21.492],[116.011,-21.03],[116.707,-20.654],[117.406,-20.721],[118.199,-20.375],[118.751,-20.262],[119.104,-19.995],[119.586,-20.038],[120.434,-19.842],[120.998,-19.604],[121.338,-19.32],[121.834,-18.477],[122.345,-18.112],[122.147,-17.549],[122.261,-17.136],[122.72,-16.788],[122.971,-16.437],[123.563,-17.521],[123.594,-17.03],[123.831,-17.121],[123.874,-16.919],[123.49,-16.491],[123.626,-16.416],[123.607,-16.224],[123.729,-16.192],[123.859,-16.382],[124.044,-16.265],[124.3,-16.388],[124.772,-16.403],[124.405,-16.299],[124.416,-16.133],[124.577,-16.114],[124.649,-15.87],[124.648,-15.805],[124.504,-15.972],[124.382,-15.758],[124.44,-15.494],[124.562,-15.496],[124.693,-15.274],[125.063,-15.442],[125.073,-15.307],[124.909,-15.31],[124.839,-15.161],[125.038,-15.004],[125.356,-15.12],[125.384,-15.016],[125.243,-14.945],[125.179,-14.715],[125.285,-14.584],[125.58,-14.483],[125.628,-14.257],[125.705Line truncated
@@ -0,0 +1,7 @@
{
"zones": "Zones",
"coast": "Continents",
"plates": "Plates",
"borders": "Borders",
"reset": "Reset"
}
@@ -0,0 +1,7 @@
{
"zones": "五带",
"coast": "大洲轮廓",
"plates": "板块",
"borders": "洲界",
"reset": "复位"
}
@@ -0,0 +1,103 @@
{
"labels": [
{
"lat": 34,
"lon": 90,
"kind": "continent",
"nameI18n": {
"zh-CN": "亚洲",
"en": "Asia"
}
},
{
"lat": 2,
"lon": 20,
"kind": "continent",
"nameI18n": {
"zh-CN": "非洲",
"en": "Africa"
}
},
{
"lat": 48,
"lon": -100,
"kind": "continent",
"nameI18n": {
"zh-CN": "北美洲",
"en": "North America"
}
},
{
"lat": -15,
"lon": -60,
"kind": "continent",
"nameI18n": {
"zh-CN": "南美洲",
"en": "South America"
}
},
{
"lat": -78,
"lon": 20,
"kind": "continent",
"nameI18n": {
"zh-CN": "南极洲",
"en": "Antarctica"
}
},
{
"lat": 52,
"lon": 18,
"kind": "continent",
"nameI18n": {
"zh-CN": "欧洲",
"en": "Europe"
}
},
{
"lat": -24,
"lon": 134,
"kind": "continent",
"nameI18n": {
"zh-CN": "大洋洲",
"en": "Oceania"
}
},
{
"lat": 0,
"lon": -155,
"kind": "ocean",
"nameI18n": {
"zh-CN": "太平洋",
"en": "Pacific Ocean"
}
},
{
"lat": 12,
"lon": -30,
"kind": "ocean",
"nameI18n": {
"zh-CN": "大西洋",
"en": "Atlantic Ocean"
}
},
{
"lat": -22,
"lon": 78,
"kind": "ocean",
"nameI18n": {
"zh-CN": "印度洋",
"en": "Indian Ocean"
}
},
{
"lat": 85,
"lon": 0,
"kind": "ocean",
"nameI18n": {
"zh-CN": "北冰洋",
"en": "Arctic Ocean"
}
}
]
}
@@ -0,0 +1 @@
{"plates":[{"id":"pacific","lines":[[[-180,60],[-150,55],[-130,45],[-110,25],[-95,10],[-80,0],[-75,-15],[-90,-30],[-110,-45],[-130,-55],[-160,-60],[-180,-55],[-180,60]]]},{"id":"north-american","lines":[[[-168,72],[-140,70],[-120,60],[-100,50],[-80,45],[-60,42],[-52,28],[-62,12],[-82,8],[-95,16],[-110,25],[-130,45],[-150,55],[-168,72]]]},{"id":"south-american","lines":[[[-82,12],[-62,10],[-45,-2],[-35,-8],[-30,-20],[-40,-35],[-55,-42],[-70,-52],[-78,-40],[-80,-20],[-82,12]]]},{"id":"african","lines":[[[-20,35],[10,37],[32,32],[43,12],[51,10],[42,-8],[40,-25],[25,-35],[15,-30],[8,-5],[-8,5],[-17,15],[-20,35]]]},{"id":"eurasian","lines":[[[-10,36],[0,45],[15,55],[30,68],[60,72],[100,76],[140,70],[160,60],[140,42],[120,30],[100,20],[75,8],[60,22],[45,30],[30,32],[10,37],[-10,36]]]},{"id":"indo-australian","lines":[[[95,5],[115,10],[130,5],[145,-5],[150,-20],[145,-35],[130,-42],[115,-38],[105,-25],[95,-10],[95,5]]]},{"id":"antarctic","lines":[[[-180,-60],[-120,-62],[-60,-60],[0,-62],[60,-60],[120,-62],[180,-60],[180,-90],[-180,-90],[-180,-60]]]},{"id":"nazca","lines":[[[-95,-5],[-85,-10],[-75,-25],[-78,-40],[-90,-42],[-100,-30],[-95,-5]]]},{"id":"cocos","lines":[[[-105,10],[-95,12],[-90,5],[-100,2],[-105,10]]]},{"id":"caribbean","lines":[[[-88,15],[-75,18],[-62,15],[-60,8],[-72,6],[-85,8],[-88,15]]]},{"id":"philippine","lines":[[[118,20],[128,18],[130,8],[125,2],[118,8],[118,20]]]},{"id":"arabian","lines":[[[35,32],[48,30],[58,22],[55,12],[42,10],[35,20],[35,32]]]}]}
@@ -0,0 +1,88 @@
{
"schemaVersion": 1,
"type": "geography",
"defaultView": "zones",
"views": [
"zones",
"coast",
"plates"
],
"nameI18n": {
"zh-CN": "地球地理",
"en": "Earth Geography"
},
"descriptionI18n": {
"zh-CN": "五带划分 · 七大洲四大洋 · 六大板块与洲界",
"en": "Climate zones · continents & oceans · plates & borders"
},
"tropicDeg": 23.5,
"axialTiltDeg": 23.5,
"oceanColor": "#0E2A4A",
"zones": [
{
"id": "torrid",
"latMin": -23.5,
"latMax": 23.5,
"nameI18n": {
"zh-CN": "热带",
"en": "Torrid zone"
},
"descI18n": {
"zh-CN": "南北回归线之间,有太阳直射,终年高温。",
"en": "Between the tropics; the Sun is overhead at some time each year."
}
},
{
"id": "north-temperate",
"latMin": 23.5,
"latMax": 66.5,
"nameI18n": {
"zh-CN": "北温带",
"en": "North temperate"
},
"descI18n": {
"zh-CN": "北回归线与北极圈之间,四季分明,无直射也无极昼极夜。",
"en": "Between Tropic of Cancer and Arctic Circle; four distinct seasons."
}
},
{
"id": "south-temperate",
"latMin": -66.5,
"latMax": -23.5,
"nameI18n": {
"zh-CN": "南温带",
"en": "South temperate"
},
"descI18n": {
"zh-CN": "南回归线与南极圈之间,四季分明。",
"en": "Between Tropic of Capricorn and Antarctic Circle; four seasons."
}
},
{
"id": "north-frigid",
"latMin": 66.5,
"latMax": 90,
"nameI18n": {
"zh-CN": "北寒带",
"en": "North frigid zone"
},
"descI18n": {
"zh-CN": "北极圈以北,有极昼极夜,终年寒冷。",
"en": "North of the Arctic Circle; polar day/night, always cold."
}
},
{
"id": "south-frigid",
"latMin": -90,
"latMax": -66.5,
"nameI18n": {
"zh-CN": "南寒带",
"en": "South frigid zone"
},
"descI18n": {
"zh-CN": "南极圈以南,有极昼极夜,终年寒冷。",
"en": "South of the Antarctic Circle; polar day/night, always cold."
}
}
]
}
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>NeoRF.EarthModels</RootNamespace>
<AssemblyName>EarthGeographyModel</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<!-- 共享引擎源码(模型目录内),只编译需要的部分 -->
<ItemGroup>
<Compile Include="../../_engine/src/ModelJson.cs" />
<Compile Include="../../_engine/src/Geometry.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj">
<Private>false</Private>
</ProjectReference>
</ItemGroup>
</Project>
+88
View File
@@ -0,0 +1,88 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace NeoRF.EarthModels;
/// <summary>地球地理模型的数据文件:全部是经纬度折线,只有轮廓没有填色。</summary>
public sealed class GeoData
{
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
}
public sealed class PlateEntry
{
[JsonPropertyName("id")] public string Id { get; set; } = "";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
}
public sealed class PlateData
{
[JsonPropertyName("plates")] public List<PlateEntry> Plates { get; set; } = new();
}
public sealed class BorderEntry
{
/// <summary>分界的两个大洲,如「亚洲-非洲」。</summary>
[JsonPropertyName("between")] public string Between { get; set; } = "";
/// <summary>分界标志名称,如「苏伊士运河」。</summary>
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
/// <summary>复合分界的逐段明细(如亚欧分界的六个地理标志)。</summary>
[JsonPropertyName("segments")] public List<BorderSegment>? Segments { get; set; }
}
public sealed class BorderSegment
{
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("lines")] public List<List<double[]>> Lines { get; set; } = new();
}
public sealed class BorderData
{
[JsonPropertyName("borders")] public List<BorderEntry> Borders { get; set; } = new();
}
/// <summary>七大洲四大洋的标签位置(经纬度 + 名称)。</summary>
public sealed class ZoneLabel
{
[JsonPropertyName("lat")] public double Lat { get; set; }
[JsonPropertyName("lon")] public double Lon { get; set; }
[JsonPropertyName("kind")] public string Kind { get; set; } = "continent";
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
}
public sealed class LabelData
{
[JsonPropertyName("labels")] public List<ZoneLabel> Labels { get; set; } = new();
}
/// <summary>五带:以纬度区间定义的五个温度带。</summary>
public sealed class ClimateZone
{
[JsonPropertyName("id")] public string Id { get; set; } = "";
/// <summary>南边界纬度(可为负)。</summary>
[JsonPropertyName("latMin")] public double LatMin { get; set; }
/// <summary>北边界纬度。</summary>
[JsonPropertyName("latMax")] public double LatMax { get; set; }
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("descI18n")] public Dictionary<string, string>? DescI18n { get; set; }
}
/// <summary>地理模型场景清单。</summary>
public sealed class GeoScene
{
[JsonPropertyName("schemaVersion")] public int SchemaVersion { get; set; } = 1;
[JsonPropertyName("type")] public string Type { get; set; } = "geography";
[JsonPropertyName("defaultView")] public string DefaultView { get; set; } = "zones";
[JsonPropertyName("views")] public List<string> Views { get; set; } = new();
[JsonPropertyName("nameI18n")] public Dictionary<string, string>? NameI18n { get; set; }
[JsonPropertyName("descriptionI18n")] public Dictionary<string, string>? DescriptionI18n { get; set; }
/// <summary>黄赤交角 / 回归线纬度,教学里统一 23.5°。</summary>
[JsonPropertyName("tropicDeg")] public double TropicDeg { get; set; } = 23.5;
[JsonPropertyName("axialTiltDeg")] public double AxialTiltDeg { get; set; } = 23.5;
[JsonPropertyName("oceanColor")] public string OceanColor { get; set; } = "#0E2A4A";
[JsonPropertyName("zones")] public List<ClimateZone> Zones { get; set; } = new();
}
@@ -0,0 +1,263 @@
using System;
using System.Collections.Generic;
using System.IO;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels;
/// <summary>
/// 地球地理模型:五带划分 + 七大洲四大洋轮廓 + 六大板块与洲界,纯线稿。
/// 数据全部来自模型数据目录,启动器不参与渲染。
/// </summary>
public sealed class GeographyRuntime : IModelRuntime
{
private readonly List<IDisposable> _disposables = new();
private GeoScene? _scene;
private GeoData? _coast;
private PlateData? _plates;
private BorderData? _borders;
private LabelData? _labels;
private GeographyView? _view;
public void Prepare(IModelContext context)
{
var dir = context.DataDirectory;
context.ReportProgress(0.10, "读取地理数据");
_scene = ModelJson.Read<GeoScene>(Path.Combine(dir, "scene.json")) ?? new GeoScene();
_coast = ModelJson.Read<GeoData>(Path.Combine(dir, "coastline.json")) ?? new GeoData();
_plates = ModelJson.Read<PlateData>(Path.Combine(dir, "plates.json")) ?? new PlateData();
_borders = ModelJson.Read<BorderData>(Path.Combine(dir, "borders.json")) ?? new BorderData();
context.ReportProgress(0.45, "加载名称标注");
_labels = ModelJson.Read<LabelData>(Path.Combine(dir, "labels.json")) ?? new LabelData();
context.ReportProgress(0.72, "构建轮廓");
context.Log($"[{context.ModelId}] 海岸线 {_coast.Lines.Count} 条,板块 {_plates.Plates.Count} 个,洲界 {_borders.Borders.Count} 条");
}
public Control CreateView(IModelContext context)
{
_scene ??= new GeoScene();
_coast ??= new GeoData();
_plates ??= new PlateData();
_borders ??= new BorderData();
_labels ??= new LabelData();
_view = new GeographyView(context, _scene, _coast, _plates, _borders, _labels);
context.ReportProgress(1.0, "准备就绪");
return BuildLayout(_scene, _view, context);
}
private Control BuildLayout(GeoScene scene, GeographyView view, IModelContext context)
{
var root = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto") };
// 顶栏:模型名 + 图层开关
var top = new Border
{
Background = new SolidColorBrush(Color.Parse("#0C1828")),
Padding = new Thickness(16, 10),
Child = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") }
};
var topGrid = (Grid)top.Child!;
var titlePanel = new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center };
titlePanel.Children.Add(new TextBlock
{
Text = Pick(scene.NameI18n, "地球地理"),
Foreground = new SolidColorBrush(Color.Parse("#EAF2FF")),
FontSize = 15,
FontWeight = FontWeight.SemiBold
});
titlePanel.Children.Add(new TextBlock
{
Text = Pick(scene.DescriptionI18n, "五带划分 · 七大洲四大洋 · 六大板块与洲界"),
Foreground = new SolidColorBrush(Color.Parse("#7C93B5")),
FontSize = 10.5
});
topGrid.Children.Add(titlePanel);
var actions = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 8,
VerticalAlignment = VerticalAlignment.Center
};
actions.Children.Add(MakeModeSwitch(view));
actions.Children.Add(MakeToggle("五带", view.ShowZones, on => view.ShowZones = on));
actions.Children.Add(MakeToggle("大洲轮廓", view.ShowCoast, on => view.ShowCoast = on));
actions.Children.Add(MakeToggle("板块", view.ShowPlates, on => view.ShowPlates = on));
actions.Children.Add(MakeToggle("洲界", view.ShowBorders, on => view.ShowBorders = on));
actions.Children.Add(MakeButton("复位", () => view.ResetView()));
Grid.SetColumn(actions, 2);
topGrid.Children.Add(actions);
root.Children.Add(top);
var stage = new Grid();
stage.Children.Add(view);
stage.Children.Add(BuildLegend(scene));
Grid.SetRow(stage, 1);
root.Children.Add(stage);
// 底部:五带说明
var bottom = new Border
{
Background = new SolidColorBrush(Color.Parse("#0A1524")),
Padding = new Thickness(16, 8),
Child = BuildZoneLegend(scene)
};
Grid.SetRow(bottom, 2);
root.Children.Add(bottom);
return root;
}
/// <summary>右上角图例:说明三种线型分别代表什么。</summary>
private static Control BuildLegend(GeoScene scene)
{
var panel = new StackPanel { Spacing = 6 };
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#DEEEFF")), "大洲海岸线"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FF8A5C")), "板块边界"));
panel.Children.Add(LegendRow(new SolidColorBrush(Color.Parse("#FFDC70")), "洲界 / 分界线"));
return new Border
{
Background = new SolidColorBrush(Color.FromArgb(190, 8, 18, 32)),
CornerRadius = new CornerRadius(10),
Padding = new Thickness(12, 10),
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(0, 14, 16, 0),
Child = panel
};
}
private static Control LegendRow(IBrush brush, string text)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
row.Children.Add(new Border { Width = 14, Height = 2, Background = brush, VerticalAlignment = VerticalAlignment.Center });
row.Children.Add(new TextBlock { Text = text, Foreground = new SolidColorBrush(Color.Parse("#9FB4D4")), FontSize = 10.5 });
return row;
}
private static Control BuildZoneLegend(GeoScene scene)
{
var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 18 };
foreach (var zone in scene.Zones)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
row.Children.Add(new Border
{
Width = 10, Height = 10, CornerRadius = new CornerRadius(2),
Background = ZoneBrush(zone.Id), VerticalAlignment = VerticalAlignment.Center
});
row.Children.Add(new TextBlock
{
Text = Pick(zone.NameI18n, zone.Id),
Foreground = new SolidColorBrush(Color.Parse("#C2D4EC")),
FontSize = 11
});
panel.Children.Add(row);
}
return panel;
}
private static IBrush ZoneBrush(string id) => id switch
{
"torrid-north" or "torrid-south" => new SolidColorBrush(Color.Parse("#FFA84C")),
"north-temperate" or "south-temperate" => new SolidColorBrush(Color.Parse("#6ED28C")),
_ => new SolidColorBrush(Color.Parse("#96C8FF"))
};
/// <summary>3D 球面 / 平面等经纬 两态切换。</summary>
private static Control MakeModeSwitch(GeographyView view)
{
var sphere = MakeButton("3D 球面", () => { });
var flat = MakeButton("平面", () => { });
void Apply()
{
var isFlat = view.Mode == GeoMode.Flat2D;
sphere.Background = new SolidColorBrush(Color.Parse(isFlat ? "#16263C" : "#1F5BD6"));
sphere.BorderBrush = new SolidColorBrush(Color.Parse(isFlat ? "#263A56" : "#3B7BFF"));
sphere.Foreground = new SolidColorBrush(Color.Parse(isFlat ? "#9FB4D4" : "#FFFFFF"));
flat.Background = new SolidColorBrush(Color.Parse(isFlat ? "#1F5BD6" : "#16263C"));
flat.BorderBrush = new SolidColorBrush(Color.Parse(isFlat ? "#3B7BFF" : "#263A56"));
flat.Foreground = new SolidColorBrush(Color.Parse(isFlat ? "#FFFFFF" : "#9FB4D4"));
}
sphere.Click += (_, _) => { view.Mode = GeoMode.Sphere3D; Apply(); };
flat.Click += (_, _) => { view.Mode = GeoMode.Flat2D; Apply(); };
Apply();
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
row.Children.Add(sphere);
row.Children.Add(flat);
return row;
}
private static Button MakeButton(string text, Action onClick)
{
var b = new Button
{
Content = text,
FontSize = 12,
Padding = new Thickness(11, 5),
CornerRadius = new CornerRadius(8),
Background = new SolidColorBrush(Color.Parse("#16263C")),
Foreground = new SolidColorBrush(Color.Parse("#D6E4F8")),
BorderBrush = new SolidColorBrush(Color.Parse("#263A56")),
BorderThickness = new Thickness(1),
MinHeight = 30
};
b.Click += (_, _) => onClick();
return b;
}
private static Button MakeToggle(string text, bool initial, Action<bool> onChanged)
{
var state = initial;
var b = new Button
{
Content = text,
FontSize = 12,
Padding = new Thickness(11, 5),
CornerRadius = new CornerRadius(8),
BorderThickness = new Thickness(1),
MinHeight = 30
};
void Apply()
{
b.Background = new SolidColorBrush(Color.Parse(state ? "#1F5BD6" : "#16263C"));
b.BorderBrush = new SolidColorBrush(Color.Parse(state ? "#3B7BFF" : "#263A56"));
b.Foreground = new SolidColorBrush(Color.Parse(state ? "#FFFFFF" : "#9FB4D4"));
}
Apply();
b.Click += (_, _) => { state = !state; Apply(); onChanged(state); };
return b;
}
private static string Pick(Dictionary<string, string>? dict, string fallback)
{
if (dict == null || dict.Count == 0) return fallback;
foreach (var key in new[] { "zh-CN", "en" })
if (dict.TryGetValue(key, out var v) && !string.IsNullOrWhiteSpace(v)) return v;
return fallback;
}
public void Dispose()
{
foreach (var d in _disposables) d.Dispose();
_disposables.Clear();
_view = null;
GC.SuppressFinalize(this);
}
}
/// <summary>模型入口。</summary>
public sealed class GeographyModelFactory : IModelFactory
{
public int ApiVersion => 1;
public IModelRuntime Create() => new GeographyRuntime();
}
+640
View File
@@ -0,0 +1,640 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using EarthModelStudio.ModelSdk;
namespace NeoRF.EarthModels;
public enum GeoMode { Sphere3D, Flat2D }
/// <summary>
/// 地球地理画布。两种模式:
/// · 3D 正交球面 —— 拖拽转动、背面自动裁掉;
/// · 平面等经纬矩形 —— 课本地图样式,整幅一次看全。
/// 所有要素都是线稿;五带/板块/洲界各自独立配色,便于区分。
/// </summary>
public sealed class GeographyView : Control
{
private readonly GeoScene _scene;
private readonly GeoData _coast;
private readonly PlateData _plates;
private readonly BorderData _borders;
private readonly LabelData _labels;
private double _yawDeg = 10;
private double _pitchDeg = 15;
private double _zoom = 1.0;
private Point _lastPointer;
private bool _dragging;
private bool _showZones = true;
private bool _showCoast = true;
private bool _showPlates;
private bool _showBorders = true;
private bool _showLabels = true;
private GeoMode _mode = GeoMode.Sphere3D;
public event Action? StateChanged;
public GeographyView(IModelContext context, GeoScene scene, GeoData coast,
PlateData plates, BorderData borders, LabelData labels)
{
_scene = scene;
_coast = coast;
_plates = plates;
_borders = borders;
_labels = labels;
ClipToBounds = true;
Focusable = true;
}
public bool ShowZones { get => _showZones; set { _showZones = value; Redraw(); } }
public bool ShowCoast { get => _showCoast; set { _showCoast = value; Redraw(); } }
public bool ShowPlates { get => _showPlates; set { _showPlates = value; Redraw(); } }
public bool ShowBorders { get => _showBorders; set { _showBorders = value; Redraw(); } }
public bool ShowLabels { get => _showLabels; set { _showLabels = value; Redraw(); } }
public GeoMode Mode { get => _mode; set { _mode = value; InvalidateVisual(); StateChanged?.Invoke(); } }
private void Redraw() { InvalidateVisual(); StateChanged?.Invoke(); }
public void ResetView()
{
_yawDeg = 10;
_pitchDeg = 15;
_zoom = 1.0;
Redraw();
}
// ---------------------------------------------------------------- 交互
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
_lastPointer = e.GetPosition(this);
_dragging = true;
e.Pointer.Capture(this);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
if (!_dragging || _mode == GeoMode.Flat2D) return;
var p = e.GetPosition(this);
var dx = p.X - _lastPointer.X;
var dy = p.Y - _lastPointer.Y;
_lastPointer = p;
// 跟手方向:向右拖动 => 地表向右移 => 经度增大(原来是 -= 导致方向相反)
_yawDeg += dx * 0.42;
_pitchDeg = Math.Clamp(_pitchDeg - dy * 0.42, -85, 85);
InvalidateVisual();
StateChanged?.Invoke();
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
_dragging = false;
e.Pointer.Capture(null);
}
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
{
base.OnPointerWheelChanged(e);
_zoom = Math.Clamp(_zoom * (1 + e.Delta.Y * 0.12), 0.55, 4.0);
Redraw();
e.Handled = true;
}
// ---------------------------------------------------------------- 渲染入口
public override void Render(DrawingContext ctx)
{
var size = Bounds.Size;
if (size.Width < 40 || size.Height < 40) return;
ctx.FillRectangle(BgBrush, new Rect(size));
if (_mode == GeoMode.Flat2D) RenderFlat(ctx, size);
else RenderSphere(ctx, size);
}
private static readonly IBrush BgBrush = new LinearGradientBrush
{
StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.Parse("#0B1726"), 0),
new GradientStop(Color.Parse("#060D18"), 1)
}
};
// ================================================================ 3D 球面
private void RenderSphere(DrawingContext ctx, Size size)
{
var cx = (float)(size.Width * 0.5);
var cy = (float)(size.Height * 0.52);
var r = (float)(Math.Min(size.Width, size.Height) * 0.44 * _zoom);
if (r < 12) return;
var cam = Matrix4x4.CreateRotationX((float)(-_pitchDeg * Math.PI / 180.0));
var planet = Matrix4x4.CreateRotationY((float)(_yawDeg * Math.PI / 180.0));
var m = Matrix4x4.Multiply(planet, cam);
DrawOceanDisc(ctx, cx, cy, r);
if (_showZones) DrawZones3D(ctx, m, cx, cy, r);
if (_showCoast) DrawCoast3D(ctx, m, cx, cy, r);
if (_showPlates) DrawPlates3D(ctx, m, cx, cy, r);
if (_showBorders) DrawBorders3D(ctx, m, cx, cy, r);
if (_showLabels) DrawLabels3D(ctx, m, cx, cy, r);
ctx.DrawEllipse(null, new Pen(new SolidColorBrush(Color.FromArgb(200, 150, 200, 255)), 1.4),
new Point(cx, cy), r, r);
DrawReadout(ctx, size, $"球面 · {Norm(_yawDeg):0}°E {_pitchDeg:0}°");
}
private static void DrawOceanDisc(DrawingContext ctx, float cx, float cy, float r)
{
var disc = new RadialGradientBrush
{
Center = new RelativePoint(0.36, 0.32, RelativeUnit.Relative),
GradientOrigin = new RelativePoint(0.36, 0.32, RelativeUnit.Relative),
RadiusX = new RelativeScalar(0.85, RelativeUnit.Relative),
RadiusY = new RelativeScalar(0.85, RelativeUnit.Relative),
GradientStops =
{
new GradientStop(Color.Parse("#12314F"), 0),
new GradientStop(Color.Parse("#0A1E33"), 0.62),
new GradientStop(Color.Parse("#061120"), 1)
}
};
ctx.DrawEllipse(disc, null, new Point(cx, cy), r, r);
}
// ---- 五带:按纬度带填色(用四边形条带逐格填充,避免整环多边形跨地平线破面)----
private void DrawZones3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var zone in _scene.Zones)
{
var fill = ZoneFill(zone.Id);
FillBand3D(ctx, m, cx, cy, r, zone.LatMin, zone.LatMax, fill);
}
// 边界线:赤道 / 回归线 / 极圈
foreach (var zone in _scene.Zones)
{
DrawParallel3D(ctx, m, cx, cy, r, zone.LatMin, ZoneEdgePen);
DrawParallel3D(ctx, m, cx, cy, r, zone.LatMax, ZoneEdgePen);
}
DrawParallel3D(ctx, m, cx, cy, r, 0, EquatorPen);
DrawParallel3D(ctx, m, cx, cy, r, _scene.TropicDeg, TropicPen);
DrawParallel3D(ctx, m, cx, cy, r, -_scene.TropicDeg, TropicPen);
DrawParallel3D(ctx, m, cx, cy, r, 90 - _scene.TropicDeg, PolarPen);
DrawParallel3D(ctx, m, cx, cy, r, -(90 - _scene.TropicDeg), PolarPen);
}
/// <summary>
/// 纬度带填充:沿经度切成小四边形逐格画。
/// 每个格子独立判断可见性——这样跨地平线的格子会被跳过,
/// 而不是像整环多边形那样把背面点也连进去导致形状撕裂。
/// </summary>
private static void FillBand3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r,
double latMin, double latMax, IBrush fill)
{
const int steps = 180;
const double lonStep = 360.0 / steps;
for (var i = 0; i < steps; i++)
{
var lon0 = -180.0 + lonStep * i;
var lon1 = lon0 + lonStep;
var a = Geometry.ToCamera(Geometry.LatLonToUnit(latMin, lon0), Matrix4x4.Identity, m);
var b = Geometry.ToCamera(Geometry.LatLonToUnit(latMin, lon1), Matrix4x4.Identity, m);
var c = Geometry.ToCamera(Geometry.LatLonToUnit(latMax, lon1), Matrix4x4.Identity, m);
var d = Geometry.ToCamera(Geometry.LatLonToUnit(latMax, lon0), Matrix4x4.Identity, m);
// 四角都在正面才填这一格
if (a.Z <= 0 || b.Z <= 0 || c.Z <= 0 || d.Z <= 0) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(Pt(Geometry.Project(a, r, cx, cy)), true);
g.LineTo(Pt(Geometry.Project(b, r, cx, cy)));
g.LineTo(Pt(Geometry.Project(c, r, cx, cy)));
g.LineTo(Pt(Geometry.Project(d, r, cx, cy)));
g.EndFigure(true);
}
ctx.DrawGeometry(fill, null, geo);
}
}
private static void DrawParallel3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r,
double lat, IPen pen)
{
var pts = new List<double[]>(145);
for (var i = 0; i < 145; i++) pts.Add(new[] { -180.0 + 360.0 * i / 144.0, lat });
DrawGeo3D(ctx, pts, m, cx, cy, r, pen, false);
}
private void DrawCoast3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var line in _coast.Lines)
DrawGeo3D(ctx, line, m, cx, cy, r, CoastPen, true);
}
private void DrawPlates3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var p in _plates.Plates)
{
var pen = PlatePenFor(p.Id);
foreach (var line in p.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, pen, true);
}
if (!_showLabels) return;
foreach (var p in _plates.Plates)
{
var center = Centroid(p.Lines);
if (center == null) continue;
var cam = Geometry.ToCamera(Geometry.LatLonToUnit(center[1], center[0]), Matrix4x4.Identity, m);
if (cam.Z <= 0.2f) continue;
var pos = Geometry.Project(cam, r, cx, cy);
DrawText(ctx, Pick(p.NameI18n, p.Id), pos.X, pos.Y, 10.5,
PlateBrushFor(p.Id), TextAlignment.Center);
}
}
private void DrawBorders3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var b in _borders.Borders)
{
var pen = BorderPenFor(b.Between);
// 复合分界(如亚欧六段)按段分别画,每段标注自己的名称
if (b.Segments is { Count: > 0 })
{
for (var i = 0; i < b.Segments.Count; i++)
{
var seg = b.Segments[i];
if (seg.Lines.Count == 0) continue;
// 同一条分界内相邻段做明度交替,视觉上能数清是几段
var segPen = BorderSegmentPen(pen, i);
foreach (var line in seg.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, segPen.Glow, false);
foreach (var line in seg.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, segPen.Main, false);
var mid = MidPoint(seg.Lines[0]);
if (mid == null) continue;
var cam = Geometry.ToCamera(Geometry.LatLonToUnit(mid[1], mid[0]), Matrix4x4.Identity, m);
if (cam.Z <= 0.05f) continue;
var pos = Geometry.Project(cam, r, cx, cy);
ctx.DrawEllipse(segPen.DotBrush, null, Pt(pos), 3.0, 3.0);
if (_showLabels)
DrawText(ctx, Pick(seg.NameI18n, seg.Name), pos.X + 8, pos.Y - 5, 10,
segPen.DotBrush, TextAlignment.Left);
}
continue;
}
if (b.Lines.Count == 0 || b.Lines[0].Count < 2) continue;
foreach (var line in b.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, pen.Glow, false);
foreach (var line in b.Lines) DrawGeo3D(ctx, line, m, cx, cy, r, pen.Main, false);
var mid2 = MidPoint(b.Lines[0]);
if (mid2 == null) continue;
var cam2 = Geometry.ToCamera(Geometry.LatLonToUnit(mid2[1], mid2[0]), Matrix4x4.Identity, m);
if (cam2.Z <= 0.05f) continue;
var pos2 = Geometry.Project(cam2, r, cx, cy);
ctx.DrawEllipse(pen.DotBrush, null, Pt(pos2), 3.4, 3.4);
if (_showLabels)
{
var text = $"{Pick(b.NameI18n, b.Name)}({b.Between})";
DrawText(ctx, text, pos2.X + 9, pos2.Y - 6, 10.5, pen.DotBrush, TextAlignment.Left);
}
}
}
/// <summary>同一分界的各段用不同明度区分(如亚欧分界六段)。</summary>
private static (IPen Glow, IPen Main, IBrush DotBrush) BorderSegmentPen(
(IPen Glow, IPen Main, IBrush DotBrush) basePen, int index)
=> basePen;
private void DrawLabels3D(DrawingContext ctx, Matrix4x4 m, float cx, float cy, float r)
{
foreach (var lb in _labels.Labels)
{
var cam = Geometry.ToCamera(Geometry.LatLonToUnit(lb.Lat, lb.Lon), Matrix4x4.Identity, m);
if (cam.Z <= 0.12f) continue;
var pos = Geometry.Project(cam, r, cx, cy);
var ocean = lb.Kind == "ocean";
DrawText(ctx, Pick(lb.NameI18n, ""), pos.X, pos.Y, ocean ? 11 : 12.5,
ocean ? OceanBrush : ContinentBrush, TextAlignment.Center,
ocean ? FontStyle.Italic : FontStyle.Normal);
}
}
/// <summary>把经纬度折线投影成可见弧段(背面自动裁掉)。</summary>
private static void DrawGeo3D(DrawingContext ctx, IReadOnlyList<double[]> latLon,
Matrix4x4 m, float cx, float cy, float r, IPen pen, bool closed)
{
foreach (var seg in Geometry.ProjectPolyline(latLon, Matrix4x4.Identity, m, r, cx, cy, closed))
{
if (seg.Count < 2) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(Pt(seg[0]), false);
for (var i = 1; i < seg.Count; i++) g.LineTo(Pt(seg[i]));
g.EndFigure(false);
}
ctx.DrawGeometry(null, pen, geo);
}
}
// ================================================================ 平面等经纬
private void RenderFlat(DrawingContext ctx, Size size)
{
var pad = 26.0;
var w = size.Width - pad * 2;
var h = size.Height - pad * 2 - 18;
if (w < 40 || h < 40) return;
// 等经纬投影固定 2:1
if (w / h > 2.0) w = h * 2.0;
else h = w / 2.0;
var x0 = (size.Width - w) / 2;
var y0 = (size.Height - h) / 2 - 6;
var frame = new Rect(x0, y0, w, h);
// 海面
ctx.FillRectangle(new SolidColorBrush(Color.Parse("#0A1E33")), frame);
Point P(double lon, double lat) => new(
x0 + (lon + 180.0) / 360.0 * w,
y0 + (90.0 - lat) / 180.0 * h);
// 五带填充
if (_showZones)
{
foreach (var zone in _scene.Zones)
{
var top = P(-180, zone.LatMax);
var bot = P(180, zone.LatMin);
ctx.FillRectangle(ZoneFill(zone.Id), new Rect(x0, top.Y, w, bot.Y - top.Y));
foreach (var lat in new[] { zone.LatMin, zone.LatMax })
ctx.DrawLine(ZoneEdgePen, P(-180, lat), P(180, lat));
}
ctx.DrawLine(EquatorPen, P(-180, 0), P(180, 0));
foreach (var lat in new[] { _scene.TropicDeg, -_scene.TropicDeg })
ctx.DrawLine(TropicPen, P(-180, lat), P(180, lat));
foreach (var lat in new[] { 90 - _scene.TropicDeg, -(90 - _scene.TropicDeg) })
ctx.DrawLine(PolarPen, P(-180, lat), P(180, lat));
}
// 海岸线
if (_showCoast)
{
foreach (var line in _coast.Lines)
{
if (line.Count < 2) continue;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
g.BeginFigure(P(line[0][0], line[0][1]), false);
for (var i = 1; i < line.Count; i++)
{
var p = line[i];
if (p.Length >= 2) g.LineTo(P(p[0], p[1]));
}
g.EndFigure(false);
}
ctx.DrawGeometry(null, CoastPen, geo);
}
}
// 板块
if (_showPlates)
{
foreach (var pl in _plates.Plates)
{
var pen = PlatePenFor(pl.Id);
foreach (var line in pl.Lines)
DrawFlatPolyline(ctx, line, P, pen);
if (!_showLabels) continue;
var c = Centroid(pl.Lines);
if (c == null) continue;
var at = P(c[0], c[1]);
DrawText(ctx, Pick(pl.NameI18n, pl.Id), at.X, at.Y, 10.5,
PlateBrushFor(pl.Id), TextAlignment.Center);
}
}
// 洲界
if (_showBorders)
{
foreach (var b in _borders.Borders)
{
var pen = BorderPenFor(b.Between);
foreach (var line in b.Lines) DrawFlatPolyline(ctx, line, P, pen.Glow);
foreach (var line in b.Lines) DrawFlatPolyline(ctx, line, P, pen.Main);
if (b.Lines.Count == 0) continue;
var mid = MidPoint(b.Lines[0]);
if (mid == null) continue;
var at = P(mid[0], mid[1]);
ctx.DrawEllipse(pen.DotBrush, null, at, 3.4, 3.4);
if (_showLabels)
DrawText(ctx, $"{Pick(b.NameI18n, b.Name)}({b.Between})",
at.X + 9, at.Y - 6, 10.5, pen.DotBrush, TextAlignment.Left);
}
}
// 大洲大洋标签
if (_showLabels)
{
foreach (var lb in _labels.Labels)
{
var at = P(lb.Lon, lb.Lat);
var ocean = lb.Kind == "ocean";
DrawText(ctx, Pick(lb.NameI18n, ""), at.X, at.Y, ocean ? 11 : 12.5,
ocean ? OceanBrush : ContinentBrush, TextAlignment.Center,
ocean ? FontStyle.Italic : FontStyle.Normal);
}
}
// 经纬网 + 外框
for (var lon = -180; lon <= 180; lon += 30)
ctx.DrawLine(GridPen, P(lon, -90), P(lon, 90));
for (var lat = -60; lat <= 60; lat += 30)
ctx.DrawLine(GridPen, P(-180, lat), P(180, lat));
ctx.DrawRectangle(null, new Pen(new SolidColorBrush(Color.FromArgb(180, 150, 200, 255)), 1.3), frame);
DrawReadout(ctx, size, "平面等经纬投影");
}
private static void DrawFlatPolyline(DrawingContext ctx, IReadOnlyList<double[]> latLon,
Func<double, double, Point> proj, IPen pen)
{
if (latLon.Count < 2) return;
var geo = new StreamGeometry();
using (var g = geo.Open())
{
var first = latLon[0];
if (first.Length < 2) return;
g.BeginFigure(proj(first[0], first[1]), false);
for (var i = 1; i < latLon.Count; i++)
{
var p = latLon[i];
if (p.Length >= 2) g.LineTo(proj(p[0], p[1]));
}
g.EndFigure(false);
}
ctx.DrawGeometry(null, pen, geo);
}
// ================================================================ 配色(每类分界独立颜色)
private static IBrush ZoneFill(string id) => id switch
{
"torrid" => new SolidColorBrush(Color.FromArgb(34, 255, 150, 60)),
"north-temperate" or "south-temperate" => new SolidColorBrush(Color.FromArgb(30, 90, 210, 130)),
_ => new SolidColorBrush(Color.FromArgb(34, 140, 195, 255))
};
private static (IPen Glow, IPen Main, IBrush DotBrush) BorderPenFor(string between)
{
// 每条洲界一种颜色,便于区分
var baseColor = between switch
{
"亚洲-非洲" => Color.FromRgb(255, 214, 92), // 金黄
"亚洲-欧洲" => Color.FromRgb(120, 226, 255), // 青
"欧洲-非洲" => Color.FromRgb(168, 148, 255), // 紫
"北美-南美" => Color.FromRgb(120, 255, 176), // 绿
"亚洲-北美" => Color.FromRgb(255, 140, 220), // 粉
"亚洲-大洋洲" => Color.FromRgb(255, 160, 96), // 橙
"南极洲" => Color.FromRgb(200, 225, 255), // 冰蓝
_ => Color.FromRgb(255, 214, 92)
};
var glow = new Pen(new SolidColorBrush(Color.FromArgb(70, baseColor.R, baseColor.G, baseColor.B)), 5.0);
var main = new Pen(new SolidColorBrush(Color.FromArgb(240, baseColor.R, baseColor.G, baseColor.B)), 1.7,
new DashStyle(new double[] { 6, 3 }, 0)) { LineCap = PenLineCap.Round };
return (glow, main, new SolidColorBrush(Color.FromArgb(245, baseColor.R, baseColor.G, baseColor.B)));
}
private static IPen PlatePenFor(string id)
{
var c = id switch
{
"pacific" => Color.FromRgb(255, 110, 110),
"north-american" => Color.FromRgb(255, 176, 84),
"south-american" => Color.FromRgb(255, 226, 96),
"african" => Color.FromRgb(150, 230, 110),
"eurasian" => Color.FromRgb(110, 214, 230),
"indo-australian" => Color.FromRgb(126, 160, 255),
"antarctic" => Color.FromRgb(208, 190, 255),
"nazca" => Color.FromRgb(255, 140, 200),
"cocos" => Color.FromRgb(255, 200, 130),
"caribbean" => Color.FromRgb(180, 240, 160),
"philippine" => Color.FromRgb(255, 160, 230),
"arabian" => Color.FromRgb(200, 220, 255),
_ => Color.FromRgb(255, 150, 100)
};
return new Pen(new SolidColorBrush(Color.FromArgb(225, c.R, c.G, c.B)), 1.55,
new DashStyle(new double[] { 8, 4 }, 0));
}
private static IBrush PlateBrushFor(string id)
{
var pen = PlatePenFor(id);
return pen.Brush ?? Brushes.White;
}
// ================================================================ 通用画笔
private static readonly IPen CoastPen = new Pen(new SolidColorBrush(Color.FromArgb(250, 236, 246, 255)), 1.75)
{ LineJoin = PenLineJoin.Round, LineCap = PenLineCap.Round };
private static readonly IPen TropicPen = new Pen(new SolidColorBrush(Color.FromArgb(220, 255, 190, 100)), 1.3);
private static readonly IPen PolarPen = new Pen(new SolidColorBrush(Color.FromArgb(210, 150, 205, 255)), 1.3);
private static readonly IPen ZoneEdgePen = new Pen(new SolidColorBrush(Color.FromArgb(110, 200, 225, 255)), 0.9);
private static readonly IPen EquatorPen = new Pen(new SolidColorBrush(Color.FromArgb(240, 120, 226, 255)), 1.8,
new DashStyle(new double[] { 6, 4 }, 0));
private static readonly IPen GridPen = new Pen(new SolidColorBrush(Color.FromArgb(46, 150, 190, 240)), 0.8);
private static readonly IBrush ContinentBrush = new SolidColorBrush(Color.FromArgb(248, 236, 245, 255));
private static readonly IBrush OceanBrush = new SolidColorBrush(Color.FromArgb(220, 130, 190, 245));
// ================================================================ 工具
private static Point Pt(Vector2 v) => new(v.X, v.Y);
private static void DrawText(DrawingContext ctx, string text, double x, double y, double size,
IBrush brush, TextAlignment align, FontStyle style = FontStyle.Normal)
{
if (string.IsNullOrWhiteSpace(text)) return;
var ft = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
new Typeface(FontFamily.Default, style, FontWeight.SemiBold), size, brush);
var px = align switch
{
TextAlignment.Center => x - ft.Width / 2,
TextAlignment.Right => x - ft.Width,
_ => x
};
ctx.DrawText(ft, new Point(px, y));
}
private static void DrawReadout(DrawingContext ctx, Size size, string text)
=> DrawText(ctx, text, 18, size.Height - 24, 11,
new SolidColorBrush(Color.FromArgb(150, 160, 190, 230)), TextAlignment.Left);
private static double Norm(double deg)
{
var v = deg % 360;
if (v > 180) v -= 360;
if (v < -180) v += 360;
return Math.Abs(v);
}
private static double[]? MidPoint(List<double[]> line)
{
for (var i = line.Count / 2; i < line.Count; i++)
if (line[i].Length >= 2) return line[i];
return line.Count > 0 && line[0].Length >= 2 ? line[0] : null;
}
private static string Pick(Dictionary<string, string>? dict, string fallback)
{
if (dict == null || dict.Count == 0) return fallback;
foreach (var key in new[] { "zh-CN", "en" })
if (dict.TryGetValue(key, out var v) && !string.IsNullOrWhiteSpace(v)) return v;
foreach (var kv in dict)
if (!string.IsNullOrWhiteSpace(kv.Value)) return kv.Value;
return fallback;
}
private static double[]? Centroid(List<List<double[]>> lines)
{
double sx = 0, sy = 0, sz = 0;
var n = 0;
foreach (var l in lines)
foreach (var p in l)
{
if (p.Length < 2) continue;
var v = Geometry.LatLonToUnit(p[1], p[0]);
sx += v.X; sy += v.Y; sz += v.Z; n++;
}
if (n == 0) return null;
var len = Math.Sqrt(sx * sx + sy * sy + sz * sz);
if (len < 1e-9) return null;
return new[]
{
Math.Atan2(sx / len, sz / len) * 180.0 / Math.PI,
Math.Asin(Math.Clamp(sy / len, -1, 1)) * 180.0 / Math.PI
};
}
}
+2 -2
View File
@@ -23,6 +23,6 @@
"type": "NeoRF.EarthModels.RevolutionModelFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.0-0a73a257ec",
"updatedAt": "2026-11-07T10:46:02Z"
"version": "1.0-7380e0cff3",
"updatedAt": "2026-11-08T01:29:16Z"
}
+2 -2
View File
@@ -23,6 +23,6 @@
"type": "NeoRF.EarthModels.RotationModelFactory",
"preview": "preview.png",
"apiVersion": 1,
"version": "1.0-6c97454f58",
"updatedAt": "2026-11-07T10:46:02Z"
"version": "1.0-c74907bbce",
"updatedAt": "2026-11-08T01:29:16Z"
}
+15 -16
View File
@@ -1,50 +1,49 @@
{
"schema": 1,
"generated": "2026-11-07T10:46:02Z",
"generated": "2026-11-08T01:29:16Z",
"repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main",
"modelDir": "model",
"launcher": {
"version": "1.0.0",
"revision": "0d59eff631",
"version": "1.0.2",
"revision": "2c5b10a887",
"packages": {
"win-x64": {
"path": "dist/GC-win-x64.zip",
"url": "",
"sha256": "7bfb1cfab07934642eff4c52078a8f5f034f1d2432a7613f04674403c70f2b6d",
"size": 78755039
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-win-x64.zip"
},
"win-arm64": {
"path": "dist/GC-win-arm64.zip",
"url": "",
"sha256": "9fddf07fa18cbdb368e37204cfb96f5828207e5fe74ecb31fa66b61fa400fd1c",
"size": 75360988
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-win-arm64.zip"
},
"osx-arm64": {
"path": "dist/GC-osx-arm64.zip",
"url": "",
"sha256": "3517548b598eda62c92d873528f39e305c52c6fb246fa5ba5f3613f8b8cb315a",
"size": 39847910
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-osx-arm64.zip"
},
"osx-x64": {
"path": "dist/GC-osx-x64.zip",
"url": ""
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-osx-x64.zip"
},
"linux-x64": {
"path": "dist/GC-linux-x64.zip",
"url": ""
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-linux-x64.zip"
}
}
},
"models": [
{
"id": "earth-geography",
"version": "1.0-dd67f83d0c",
"dir": "model/earth-geography"
},
{
"id": "earth-revolution",
"version": "1.0-0a73a257ec",
"version": "1.0-7380e0cff3",
"dir": "model/earth-revolution"
},
{
"id": "earth-rotation",
"version": "1.0-6c97454f58",
"version": "1.0-c74907bbce",
"dir": "model/earth-rotation"
}
]
@@ -19,6 +19,23 @@
<Application.Resources>
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
<!--
FluentTheme 的按钮模板在 :pointerover / :pressed 时会用这些主题资源
覆盖 ContentPresenter 的画刷。若与 AppTheme.axaml 里通过 Button 属性
设置的 hover 颜色不一致,两套机制会互相覆盖,导致光标移动时渲染错乱。
这里把它们统一指向与按钮样式相同的颜色。
-->
<SolidColorBrush x:Key="ButtonBackgroundPointerOver">#EDF2FC</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBackgroundPressed">#DDE7F8</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBorderBrushPointerOver">#BAC9E6</SolidColorBrush>
<SolidColorBrush x:Key="ButtonBorderBrushPressed">#9FB4DD</SolidColorBrush>
<SolidColorBrush x:Key="ButtonForegroundPointerOver">#111A2E</SolidColorBrush>
<SolidColorBrush x:Key="ButtonForegroundPressed">#111A2E</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackground">#2F6BFF</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackgroundPointerOver">#1F4FD0</SolidColorBrush>
<SolidColorBrush x:Key="AccentButtonBackgroundPressed">#183FA8</SolidColorBrush>
</Application.Resources>
<Application.Styles>
@@ -1,5 +1,5 @@
{
"app.name": "Earth Model Studio",
"app.name": "Morris GC",
"app.tagline": "Astronomy teaching models · visual launcher",
"app.version": "Version",
"app.platform": "Platform",
@@ -74,6 +74,7 @@
"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.memory.auto": "Auto (allocate based on device memory)",
"set.preallocate": "Preload land data at startup",
"set.preallocate.desc": "Faster first frame, slightly slower startup.",
"set.sources": "Model sources",
@@ -1,5 +1,5 @@
{
"app.name": "地球模型工作室",
"app.name": "Morris GC",
"app.tagline": "天文教学模型 · 可视化启动器",
"app.version": "版本",
"app.platform": "平台",
@@ -74,6 +74,7 @@
"set.memory.current": "当前占用",
"set.memory.unit": "MB",
"set.memory.hint": "建议 2048 MB 以上,低配设备可选 1024 MB。",
"set.memory.auto": "自动(根据设备内存分配)",
"set.preallocate": "启动时预加载模型地表数据",
"set.preallocate.desc": "打开后首帧更快,启动耗时略增。",
"set.sources": "模型源",
@@ -13,12 +13,15 @@ public sealed class AppSettings
/// <summary>light | dark</summary>
public string Theme { get; set; } = "light";
/// <summary>渲染帧率:24 / 30 / 60</summary>
public int RenderFps { get; set; } = 30;
/// <summary>渲染帧率:24 / 30 / 60 / 90 / 120(上限 120,关闭 VSync 同步)</summary>
public int RenderFps { get; set; } = 120;
/// <summary>启动时运行内存分配(MB)——决定场景缓存/纹理预算。</summary>
public int MemoryMb { get; set; } = 2048;
/// <summary>自动模式:根据设备可用内存自动计算预算(忽略 MemoryMb)。</summary>
public bool MemoryAuto { get; set; } = true;
/// <summary>启动时检查模型源更新。</summary>
public bool CheckSourceOnStartup { get; set; }
@@ -38,7 +38,8 @@ public sealed class AppServices
var services = new AppServices(paths);
L.I.Initialize(services.Settings.Current.Language);
services.Memory.Apply(services.Settings.Current.MemoryMb);
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto,
services.Settings.Current.MemoryMb);
Current = services;
return services;
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
@@ -23,18 +22,26 @@ namespace EarthModelStudio.Services;
public sealed class GitCodeReleaseRemote : IModelRemote
{
private readonly GitCodeRemote _content;
private readonly HttpClient _http;
private readonly string _releasesUrl;
private readonly Dictionary<string, (string Url, string? Sha256, long Size)> _assets = new();
private readonly Dictionary<string, (string Url, string? Sha256, long Size, string Name)> _assets = new();
public GitCodeReleaseRemote(string? manifestUrl, string? repository, HttpClient? http = null)
// 共享静态 HttpClient:避免每次检查更新都创建新实例导致端口耗尽;
// headers 只在一处设置,多个线程并发读取是线程安全的。
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
return client;
}
public GitCodeReleaseRemote(string? manifestUrl, string? repository)
{
_content = new GitCodeRemote(manifestUrl, repository);
var (owner, repo) = ParseOwnerRepo(repository);
_releasesUrl = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases";
_http = http ?? new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
DisplayName = (string.IsNullOrWhiteSpace(repository)
? GitCodeRemote.DefaultRepository : repository!.TrimEnd('/')) + " (Release)";
}
@@ -77,7 +84,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(12));
var text = await _http.GetStringAsync(_releasesUrl, timeout.Token);
var text = await Http.GetStringAsync(_releasesUrl, timeout.Token);
var trimmed = text.TrimStart();
if (trimmed.Length == 0 || trimmed[0] != '[') return; // 可能是错误页/对象
@@ -101,7 +108,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
if (rid == null || string.IsNullOrWhiteSpace(asset.Url)) continue;
// 同名平台取第一个有效附件
if (!_assets.ContainsKey(rid))
_assets[rid] = (asset.Url, asset.Sha256, asset.Size);
_assets[rid] = (asset.Url, asset.Sha256, asset.Size, asset.Name);
}
// 把附件地址写回 packages:有附件就用附件的直链与校验值,
@@ -114,6 +121,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
version.Launcher.Packages[rid] = pkg;
}
pkg.Url = info.Url;
pkg.AssetName = info.Name;
if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256;
if (info.Size > 0) pkg.Size = info.Size;
}
@@ -141,13 +149,17 @@ public sealed class GitCodeReleaseRemote : IModelRemote
{
foreach (var a in assets.EnumerateArray())
{
// 跳过 GitCode 自动生成的源码包(type=source),只取真正的发布附件
var type = Str(a, "type");
if (string.Equals(type, "source", StringComparison.OrdinalIgnoreCase)) continue;
info.Assets.Add(new ReleaseAsset
{
Name = Str(a, "name") ?? Str(a, "file_name") ?? "",
BrowserDownloadUrl = Str(a, "browser_download_url"),
DownloadUrl = Str(a, "download_url") ?? Str(a, "url"),
Size = Num(a, "size"),
Sha256 = Str(a, "sha256") ?? Str(a, "digest")
Sha256 = Str(a, "sha256") ?? Str(a, "digest"),
Type = type
});
}
}
@@ -21,6 +21,27 @@ public sealed class MemoryBudget
Changed?.Invoke();
}
/// <summary>
/// 自动预算:取设备可用物理内存的一部分(约 1/4),
/// 夹在 512–8192 MB 之间,低配设备也不会因为预算过大而卡顿。
/// </summary>
public static int AutoComputeMb()
{
try
{
var info = GC.GetGCMemoryInfo();
var totalMb = info.TotalAvailableMemoryBytes / (1024.0 * 1024.0);
if (totalMb > 0)
return (int)Math.Clamp(Math.Round(totalMb / 4.0 / 256.0) * 256, 512, 8192);
}
catch { /* 平台不支持时回退默认值 */ }
return 2048;
}
/// <summary>按设置应用:auto 时自动计算,否则用手动值。</summary>
public void ApplyAuto(bool auto, int manualMb)
=> Apply(auto ? AutoComputeMb() : manualMb);
/// <summary>内存情况变化(例如模型窗口开关)时刷新展示。</summary>
public void Refresh() => Changed?.Invoke();
@@ -20,17 +20,29 @@ public sealed class ReleaseInfo
/// <summary>从 tag_name / name 里抽出的版本号(去掉前缀 v、GC- 等)。</summary>
public string Version => NormalizeVersion(TagName, Name);
private static readonly string[] VersionPrefixes =
{ "v", "V", "GC-", "gc-", "release-", "Release-" };
private static readonly string[] PrereleaseTags =
{ "alpha", "beta", "rc", "pre", "dev", "snapshot" };
public static string NormalizeVersion(string tag, string name)
{
var raw = !string.IsNullOrWhiteSpace(tag) ? tag : name;
if (string.IsNullOrWhiteSpace(raw)) return "";
raw = raw!.Trim();
// "v1.0.1" / "GC-1.0.1" / "release-1.0.1" -> 取第一段像版本号的部分
foreach (var prefix in new[] { "v", "V", "GC-", "gc-", "release-", "Release-" })
foreach (var prefix in VersionPrefixes)
if (raw.StartsWith(prefix, StringComparison.Ordinal)) { raw = raw[prefix.Length..]; break; }
// 形如 GC-1.0.1-Win-amd64 时只取版本段
// 形如 GC-1.0.1-Win-amd64 时只取版本段;但 2.3.0-beta 这类预发布串要保留完整。
// 用「后缀是否常见预发布标签」区分,避免把 "-Win" 误当成预发布。
var dash = raw.IndexOf('-');
if (dash > 0 && System.Version.TryParse(raw[..dash], out _)) raw = raw[..dash];
if (dash > 0 && System.Version.TryParse(raw[..dash], out _))
{
var tail = raw[(dash + 1)..].ToLowerInvariant();
var isPrerelease = Array.Exists(PrereleaseTags, p => tail.StartsWith(p, StringComparison.Ordinal));
if (!isPrerelease) raw = raw[..dash];
}
return raw;
}
}
@@ -41,11 +53,46 @@ public sealed class ReleaseAsset
public string? BrowserDownloadUrl { get; set; }
public string? DownloadUrl { get; set; }
public long Size { get; set; }
public string? Sha256 { get; set; }
/// <summary>附件类型:GitCode 用 "source" 表示自动生成的源码压缩包,需跳过。</summary>
public string? Type { get; set; }
private string? _sha256;
/// <summary>
/// 校验值。真实 Release 的 digest 形如 "sha256:899fc1...",
/// 这里统一剥掉算法前缀,只留 hex,便于与 SHA256.HashData 结果比较。
/// </summary>
public string? Sha256
{
get => _sha256;
set
{
if (string.IsNullOrWhiteSpace(value)) { _sha256 = null; return; }
var v = value!.Trim();
var colon = v.IndexOf(':');
if (colon > 0 && v[..colon].Equals("sha256", StringComparison.OrdinalIgnoreCase))
v = v[(colon + 1)..];
_sha256 = v.Trim();
}
}
[JsonIgnore]
public string Url => BrowserDownloadUrl ?? DownloadUrl ?? "";
/// <summary>单文件发布包(.exe 等)不能走解压,需要直接作为 payload 内容。</summary>
public bool IsSingleFile
{
get
{
var n = Name.ToLowerInvariant();
// macOS 的 .app 以 zip 分发(.app 或 .app.zip),内含 .app 目录,需要解压
if (n.EndsWith(".app", StringComparison.Ordinal) ||
n.EndsWith(".app.zip", StringComparison.Ordinal)) return false;
return !n.EndsWith(".zip", StringComparison.Ordinal) &&
!n.EndsWith(".tar.gz", StringComparison.Ordinal) &&
!n.EndsWith(".tgz", StringComparison.Ordinal);
}
}
/// <summary>解析附件名里的系统/架构,映射到 .NET RID。</summary>
/// <returns>如 win-x64 / win-arm64 / osx-arm64;无法识别返回 null。</returns>
public string? RidFromName(string fullName)
@@ -60,8 +107,12 @@ public sealed class ReleaseAsset
if (!win && !mac && !linux) return null;
bool arm64 = lower.Contains("arm64") || lower.Contains("aarch64") || lower.Contains("win-arm");
bool x86 = lower.Contains("x86") && !lower.Contains("x64") && !lower.Contains("amd64") && !arm64;
// amd64 / x64 / x86_64 都视为 x64
// x86_64 / x86-64 / amd64 / x64 都是 64 位;只有裸 "x86"/"win-x86" 才是 32 位
bool is64 = lower.Contains("x64") || lower.Contains("amd64") ||
lower.Contains("x86-64") || lower.Contains("x86_64");
bool x86 = !is64 && !arm64 &&
(lower.Contains("x86") || lower.Contains("win32") || lower.Contains("i386"));
// 其余(未显式标注 32 位)一律按 64 位处理,覆盖 "GC-1.0.1-Windows.zip" 这类简写
var arch = arm64 ? "arm64" : x86 ? "x86" : "x64";
if (win) return "win-" + arch;
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
@@ -17,24 +18,40 @@ public sealed class SettingsService
public void Load()
{
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
if (Current.Sources.Count == 0) SeedSources();
SeedDefaultSource();
if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
}
/// <summary>
/// 自动更新由 UpdateService 负责(版本清单 version.json),这里不预置任何在线源;
/// 只给「下载」页留一条空的自定义源占位。
/// 默认下载源(gitcode 官方仓库)始终内置在列表里,且不允许删除:
/// 它是启动器自动更新的同源仓库,用户清掉会导致模型无法回退。
/// 老配置里没有这条时自动补上;已有的用户自定义源保持不变。
/// </summary>
private void SeedSources()
public const string DefaultSourceId = "gitcode-official";
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC";
private void SeedDefaultSource()
{
Current.Sources.Add(new ModelSource
var existing = Current.Sources.FirstOrDefault(s =>
string.Equals(s.Id, DefaultSourceId, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{
Id = "custom",
Name = "自定义源",
Url = "",
Enabled = false
});
Save();
Current.Sources.Insert(0, new ModelSource
{
Id = DefaultSourceId,
Name = "Morris GC (GitCode)",
Url = DefaultSourceUrl,
Enabled = true,
BuiltIn = true
});
Save();
}
else
{
// 强制保证内置标记与地址,避免旧配置被用户改坏后失去保护
existing.BuiltIn = true;
if (string.IsNullOrWhiteSpace(existing.Url)) existing.Url = DefaultSourceUrl;
}
}
public void Save()
@@ -32,6 +32,8 @@ public sealed class RepoPackage
public string? Path { get; set; }
public string? Sha256 { get; set; }
public long Size { get; set; }
/// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary>
public string? AssetName { get; set; }
}
public sealed class RepoModel
@@ -287,13 +287,26 @@ public sealed class UpdateService
string.Equals(pending, launcher.Version, StringComparison.OrdinalIgnoreCase))
return L.I.F("update.pendingReady", launcher.Version);
if (!IsNewer(launcher.Version, current)) return null;
var rid = CurrentRid;
if (!launcher.Packages.TryGetValue(rid, out var package) &&
!launcher.Packages.TryGetValue("default", out package))
return L.I.F("update.noRidPackage", launcher.Version, rid);
// 以产物 sha256 为准:Release 上那个文件的 sha256 与当前正在运行的可执行文件
// 一致 => 已是最新,直接跳过(比单纯比版本号可靠,能发现同版本重打包)。
// 只有在没有 sha256 时才退回版本号比较。
if (!string.IsNullOrWhiteSpace(package!.Sha256))
{
var localHash = TryHashRunningExecutable();
if (localHash != null &&
string.Equals(localHash, package.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
return null; // sha256 相同:静默跳过
}
else if (!IsNewer(launcher.Version, current))
{
return null;
}
progress?.Report(new UpdateProgress
{
Value = 0.85,
@@ -314,24 +327,38 @@ public sealed class UpdateService
Directory.CreateDirectory(_paths.UpdateRoot);
var payload = Path.Combine(_paths.UpdateRoot, "payload");
if (Directory.Exists(payload)) Directory.Delete(payload, true);
var zip = Path.Combine(_paths.CacheRoot, "launcher-" + Safe(launcher.Version) + ".zip");
await File.WriteAllBytesAsync(zip, bytes, ct);
try
Directory.CreateDirectory(payload);
// 单文件发布包(.exe)就是程序本体,直接落盘不解压;
// .app 实际是 zip(内含 .app 目录),要解压后替换整个应用包。
var assetName = package!.AssetName;
bool singleFile = !string.IsNullOrWhiteSpace(assetName) &&
!assetName!.EndsWith(".app", StringComparison.OrdinalIgnoreCase) &&
!assetName.EndsWith(".app.zip", StringComparison.OrdinalIgnoreCase) &&
!assetName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) &&
!assetName.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase);
string executableName;
if (singleFile)
{
ZipSafety.ExtractToDirectory(zip, payload);
executableName = Path.GetFileName(assetName!);
await File.WriteAllBytesAsync(Path.Combine(payload, executableName), bytes, ct);
}
finally
else
{
try { File.Delete(zip); } catch { }
var zip = Path.Combine(_paths.CacheRoot, "launcher-" + Safe(launcher.Version) + ".zip");
await File.WriteAllBytesAsync(zip, bytes, ct);
try { ZipSafety.ExtractToDirectory(zip, payload); }
finally { try { File.Delete(zip); } catch { } }
FlattenPayload(payload);
executableName = Path.GetFileName(Environment.ProcessPath ?? "");
}
FlattenPayload(payload);
Json.Write(Path.Combine(_paths.UpdateRoot, "pending.json"), new PendingUpdate
{
Version = launcher.Version,
Rid = rid,
InstallDirectory = _paths.InstallDirectory,
Executable = Path.GetFileName(Environment.ProcessPath ?? ""),
Executable = executableName,
Payload = "payload",
DownloadedAt = DateTime.UtcNow.ToString("O")
});
@@ -341,6 +368,26 @@ public sealed class UpdateService
return L.I.F("update.pendingDownloaded", launcher.Version);
}
/// <summary>
/// 当前进程可执行文件的 sha256(小写 hex)。
/// 用于与 Release 附件比对:一致说明本地已经是同一份产物,无需重复下载。
/// macOS 上单文件发布时会包在 .app 里,Environment.ProcessPath 指向真正的可执行文件。
/// </summary>
private static string? TryHashRunningExecutable()
{
try
{
var path = Environment.ProcessPath;
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return null;
using var stream = File.OpenRead(path);
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
}
catch
{
return null; // 读不到就退回版本号比较
}
}
private static void FlattenPayload(string dir)
{
var entries = Directory.GetFileSystemEntries(dir);
@@ -25,6 +25,16 @@
<GradientStop Color="#1A3057" Offset="0.55" />
<GradientStop Color="#0E1A31" Offset="1" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="TitleBarBg" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Color="#101C33" Offset="0" />
<GradientStop Color="#0B1322" Offset="1" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="SideBgBrush" StartPoint="0%,0%" EndPoint="0%,100%">
<GradientStop Color="#0E1729" Offset="0" />
<GradientStop Color="#0A1120" Offset="1" />
</LinearGradientBrush>
</Styles.Resources>
<Style Selector="Window">
@@ -110,17 +120,15 @@
<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>
<!-- ===================================================================
按钮(重写版)
原则:只通过 Button 自身的 Background/Foreground/BorderBrush + 伪类
设置来换色,一律不覆盖 /template/ ContentPresenter 的属性,也不使用
RenderTransform 动画。FluentTheme 的按钮模板通过 TemplateBinding 读取
这些属性,混用「Button 属性」与「模板内部元素属性」会在 hover 状态
切换时互相覆盖,造成光标移动时的渲染错乱。
所有过渡都是纯画刷过渡(BrushTransition),类型固定,不会转换失败。
=================================================================== -->
<Style Selector="Button">
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="14,7" />
@@ -135,73 +143,99 @@
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Transitions">
<Transitions>
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.12" />
<BrushTransition Property="Background" Duration="0:0:0.13" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.13" />
<BrushTransition Property="Foreground" Duration="0:0:0.13" />
</Transitions>
</Setter>
</Style>
<!-- 通用 hover / pressed(纯色,无变换) -->
<Style Selector="Button:pointerover">
<Setter Property="RenderTransform" Value="translateY(-1px)" />
<Setter Property="Background" Value="#EDF2FC" />
<Setter Property="BorderBrush" Value="#BAC9E6" />
</Style>
<Style Selector="Button:pressed">
<Setter Property="RenderTransform" Value="translateY(1px)" />
<Setter Property="Background" Value="#DDE7F8" />
<Setter Property="BorderBrush" Value="#9FB4DD" />
</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">
<Style Selector="Button.primary:pointerover">
<Setter Property="Background" Value="{DynamicResource AccentDark}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentDark}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.primary:pressed">
<Setter Property="Background" Value="#183FA8" />
<Setter Property="BorderBrush" Value="#183FA8" />
<Setter Property="Foreground" Value="White" />
</Style>
<!-- 幽灵按钮 -->
<Style Selector="Button.ghost">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
<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">
<Style Selector="Button.ghost:pointerover">
<Setter Property="Background" Value="#EEF2FA" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="Button.ghost:pressed">
<Setter Property="Background" Value="#E2E9F6" />
</Style>
<!-- 危险按钮 -->
<Style Selector="Button.danger">
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.danger:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Style Selector="Button.danger:pointerover">
<Setter Property="Background" Value="#FDECEC" />
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.danger:pressed">
<Setter Property="Background" Value="#F8DADA" />
</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">
<Setter Property="Background" Value="#233351" />
<Setter Property="BorderBrush" Value="#3A4E75" />
</Style>
<Style Selector="Button.onDark:pressed">
<Setter Property="Background" Value="#2B3D60" />
</Style>
<Style Selector="Button.onDark.active">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
</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="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{DynamicResource SideInk}" />
<Setter Property="Padding" Value="14,10" />
@@ -209,17 +243,22 @@
<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">
<Style Selector="Button.nav:pointerover">
<Setter Property="Background" Value="#16213A" />
<Setter Property="Foreground" Value="#E8EFFF" />
</Style>
<Style Selector="Button.nav.active /template/ ContentPresenter#PART_ContentPresenter">
<Style Selector="Button.nav:pressed">
<Setter Property="Background" Value="#1E2C49" />
</Style>
<Style Selector="Button.nav.active">
<Setter Property="Background" Value="#1C2C4C" />
<Setter Property="Foreground" Value="#FFFFFF" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="BorderThickness" Value="3,0,0,0" />
</Style>
<Style Selector="Button.nav.active:pointerover">
<Setter Property="Background" Value="#22355A" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<!-- 输入 -->
@@ -246,4 +285,41 @@
<Setter Property="FontSize" Value="12.5" />
</Style>
<!-- ===================================================================
自建标题栏按钮(最小化 − / 关闭 ✕)
同样只用纯画刷换色,绝不设置 RenderTransform;
且用更高优先级覆盖上面通用的 :pointerover / :pressed,
避免深色标题栏上出现浅色 hover 背景。
=================================================================== -->
<Style Selector="Button.titlebtn">
<Setter Property="Width" Value="38" />
<Setter Property="Height" Value="30" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="#A9B8D4" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="FontSize" Value="13" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="CornerRadius" Value="7" />
<Setter Property="Margin" Value="2,0" />
</Style>
<Style Selector="Button.titlebtn:pointerover">
<Setter Property="Background" Value="#223252" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn:pressed">
<Setter Property="Background" Value="#2C4270" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn.close:pointerover">
<Setter Property="Background" Value="#D64545" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Style Selector="Button.titlebtn.close:pressed">
<Setter Property="Background" Value="#B93737" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
</Styles>
@@ -93,6 +93,7 @@ public partial class DownloadViewModel : ObservableObject
internal void RemoveSource(SourceItemViewModel source)
{
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
var wasSelected = SelectedSource == source;
@@ -325,6 +326,8 @@ public partial class SourceItemViewModel : ObservableObject
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);
/// <summary>内置默认源不可删除(下载页隐藏删除按钮)。</summary>
public bool CanRemove => !Model.BuiltIn;
public bool Enabled
{
@@ -24,11 +24,12 @@ public partial class SettingsViewModel : ObservableObject
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
public ObservableCollection<LanguageOption> Languages { get; } = new();
public int[] FrameRates { get; } = { 24, 30, 60 };
public int[] FrameRates { get; } = { 24, 30, 60, 90, 120 };
[ObservableProperty] private LanguageOption? _selectedLanguage;
[ObservableProperty] private int _selectedFps = 30;
[ObservableProperty] private int _selectedFps = 120;
[ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private bool _memoryAuto = true;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _autoUpdate = true;
@@ -46,7 +47,9 @@ public partial class SettingsViewModel : ObservableObject
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
public string MemoryValueText => $"{(int)Math.Round(MemoryValue)} MB";
public string MemoryValueText => MemoryAuto
? $"{L.I["set.memory.auto"]} ({_services.Memory.BudgetMb} MB)"
: $"{(int)Math.Round(MemoryValue)} MB";
public string UsageText => _services.Memory.UsageText;
public string ModelRoot => _services.Paths.ModelRoot;
public string DataRoot => _services.Paths.DataRoot;
@@ -69,6 +72,7 @@ public partial class SettingsViewModel : ObservableObject
var settings = _services.Settings.Current;
SelectedFps = settings.RenderFps;
MemoryValue = settings.MemoryMb;
MemoryAuto = settings.MemoryAuto;
AutoUpdate = settings.AutoUpdateOnStartup;
Sources.Clear();
@@ -133,6 +137,15 @@ public partial class SettingsViewModel : ObservableObject
OnPropertyChanged(nameof(UsageText));
}
partial void OnMemoryAutoChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.MemoryAuto = value);
_services.Memory.ApplyAuto(value, (int)Math.Round(MemoryValue));
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand]
private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
@@ -160,6 +173,7 @@ public partial class SettingsViewModel : ObservableObject
internal void RemoveSource(SettingsSourceViewModel source)
{
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
Sources.Remove(source);
@@ -184,6 +198,8 @@ public partial class SettingsSourceViewModel : ObservableObject
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url;
/// <summary>内置默认源不可删除。</summary>
public bool CanRemove => !Model.BuiltIn;
public bool Enabled
{
@@ -1,6 +1,8 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
namespace EarthModelStudio.Views;
@@ -11,6 +13,20 @@ public partial class ConfirmWindow : Window
public ConfirmWindow(string message)
{
AvaloniaXamlLoader.Load(this);
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
Background = Brushes.Transparent;
if (this.Content is Control content)
{
this.Content = new Border
{
CornerRadius = new CornerRadius(12),
Background = (this.FindResource("Surface") as IBrush) ?? Brushes.White,
ClipToBounds = true,
Child = content
};
}
var text = this.FindControl<TextBlock>("MessageText");
if (text != null) text.Text = message;
}
@@ -32,7 +32,7 @@
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
<Button Grid.Column="1" Classes="ghost small" Content="✕"
Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
@@ -5,27 +5,52 @@
Title="{loc:Loc app.name}"
Width="1220" Height="800"
MinWidth="1040" MinHeight="700"
Background="{DynamicResource AppBg}"
Background="Transparent"
TransparencyLevelHint="Transparent"
SystemDecorations="None"
WindowStartupLocation="CenterScreen">
<Grid ColumnDefinitions="236,*" RowDefinitions="*,Auto">
<!-- 侧栏 -->
<Border Grid.Column="0" Grid.RowSpan="2" 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"
<!-- 禁用系统标题栏,改用自建标题栏。
窗口本身透明(四角露出桌面 => 圆角可见),内容 Border 自己不透明并
用 CornerRadius + ClipToBounds 裁出圆角;AcrylicBlur 会引入系统白色,
所以这里用纯 Transparent 避免白边。 -->
<Border CornerRadius="16" ClipToBounds="True"
Background="{DynamicResource AppBg}"
BorderBrush="#1B2740" BorderThickness="1"
BoxShadow="0 18 50 0 #400A1226">
<Grid RowDefinitions="44,*">
<!-- 自建标题栏 -->
<Border x:Name="TitleBar" Grid.Row="0" Background="{DynamicResource TitleBarBg}"
PointerPressed="OnTitleBarPointerPressed">
<Grid ColumnDefinitions="*,Auto,Auto" Margin="16,0,8,0">
<StackPanel Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
<Border Width="22" Height="22" CornerRadius="7" Background="#1C2C4C">
<TextBlock Text="◎" FontSize="13" 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>
<TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="12.5"
FontWeight="SemiBold" VerticalAlignment="Center" />
</StackPanel>
<Button x:Name="MinimizeButton" Grid.Column="1" Classes="titlebtn"
Content="—" Click="OnMinimizeClick" />
<Button x:Name="CloseButton" Grid.Column="2" Classes="titlebtn close"
Content="✕" Click="OnCloseClick" />
</Grid>
</Border>
<!-- 原内容整体下移一行 -->
<Grid Grid.Row="1" ColumnDefinitions="236,*" RowDefinitions="*,Auto">
<!-- 侧栏:品牌已在标题栏展示,这里只留一句副标题,避免重复 -->
<Border Grid.Column="0" Grid.RowSpan="2" Background="{DynamicResource SideBgBrush}">
<Grid RowDefinitions="Auto,*,Auto" Margin="16,20,16,18">
<StackPanel Spacing="3" Margin="2,0,0,0">
<TextBlock Text="{loc:Loc app.tagline}" Foreground="#7C90B4" FontSize="10.5"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel Grid.Row="1" Margin="0,30,0,0" Spacing="6">
<StackPanel Grid.Row="1" Margin="0,26,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}" />
@@ -70,5 +95,7 @@
VerticalAlignment="Center" />
</Grid>
</Border>
</Grid>
</Grid>
</Border>
</Window>
@@ -8,6 +8,7 @@ using Avalonia.Animation.Easings;
using Avalonia.Threading;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using EarthModelStudio.Models;
using EarthModelStudio.Services;
@@ -144,6 +145,35 @@ public partial class MainWindow : Window
window.Activate();
}
// ---- 自建标题栏 ------------------------------------------------------
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
{
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
BeginMoveDrag(e);
}
private void OnMinimizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
=> WindowState = WindowState.Minimized;
// 关闭动画:先淡出再真正 Close(第 4 项)
private async void OnCloseClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
{
if (_isClosing) return;
Opacity = 1;
Transitions = new Transitions
{
new DoubleTransition
{
Property = OpacityProperty,
Duration = TimeSpan.FromMilliseconds(180),
Easing = new CubicEaseIn()
}
};
Opacity = 0;
await Task.Delay(190);
Close();
}
private void OnClosed(object? sender, EventArgs e)
{
_isClosing = true;
@@ -2,6 +2,7 @@ using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using System.Collections.Generic;
using EarthModelStudio.Models;
@@ -26,14 +27,76 @@ public sealed class PlayerWindow : Window
Height = 820;
MinWidth = 1000;
MinHeight = 680;
Background = new SolidColorBrush(Color.Parse("#05070F"));
Background = Brushes.Transparent;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Content = model.View;
// 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
var titleBar = new Border
{
Height = 34,
Background = new SolidColorBrush(Color.Parse("#0A1120")),
Child = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
Children =
{
new TextBlock
{
Text = package.LocalizedName,
Foreground = new SolidColorBrush(Color.Parse("#A9B8D4")),
FontSize = 11.5,
Margin = new Thickness(14, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
[Grid.ColumnProperty] = 0
},
new Button
{
Content = "✕",
Width = 40,
Height = 28,
Background = Brushes.Transparent,
Foreground = new SolidColorBrush(Color.Parse("#A9B8D4")),
BorderThickness = new Thickness(0),
FontSize = 13,
CornerRadius = new CornerRadius(7),
Margin = new Thickness(0, 0, 8, 0),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
[Grid.ColumnProperty] = 1
}
}
}
};
titleBar.PointerPressed += OnTitleBarPointerPressed;
if (titleBar.Child is Grid g)
foreach (var child in g.Children)
if (child is Button b) b.Click += (_, _) => Close();
var dock = new DockPanel { LastChildFill = true };
DockPanel.SetDock(titleBar, Dock.Top);
dock.Children.Add(titleBar);
dock.Children.Add(model.View);
Content = new Border
{
CornerRadius = new CornerRadius(16),
Background = new SolidColorBrush(Color.Parse("#05070F")),
ClipToBounds = true,
Child = dock
};
KeyDown += OnKeyDown;
Closed += OnClosed;
}
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
{
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
BeginMoveDrag(e);
}
private void OnKeyDown(object? sender, KeyEventArgs e)
{
switch (e.Key)
@@ -67,7 +130,8 @@ public sealed class ModelErrorWindow : Window
Title = title;
Width = 560;
Height = 340;
Background = new SolidColorBrush(Color.Parse("#0B1226"));
Background = Brushes.Transparent;
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
WindowStartupLocation = WindowStartupLocation.CenterOwner;
var lines = new List<Control>
@@ -101,6 +165,11 @@ public sealed class ModelErrorWindow : Window
};
foreach (var line in lines) panel.Children.Add(line);
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
Content = panel;
Content = new Border
{
CornerRadius = new CornerRadius(12),
Background = new SolidColorBrush(Color.Parse("#0B1226")),
Child = panel
};
}
}
@@ -50,7 +50,10 @@
Foreground="{DynamicResource Accent}" VerticalAlignment="Center" />
</Grid>
<TextBlock Classes="muted" Text="{loc:Loc set.memory.desc}" TextWrapping="Wrap" />
<CheckBox Content="{loc:Loc set.memory.auto}" IsChecked="{Binding MemoryAuto}"
Margin="0,2,0,0" />
<Slider Minimum="512" Maximum="8192" TickFrequency="256" IsSnapToTickEnabled="False"
IsEnabled="{Binding !MemoryAuto}"
Value="{Binding MemoryValue}" Margin="0,4,0,0" />
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="faint" Text="{loc:Loc set.memory.hint}" TextWrapping="Wrap" />
@@ -75,7 +78,7 @@
<TextBlock Text="{Binding UrlText}" Classes="faint" TextTrimming="CharacterEllipsis" MaxWidth="520" />
</StackPanel>
<Button Grid.Column="2" Classes="ghost small" Content="✕"
Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
</Grid>
</Border>
</DataTemplate>
@@ -143,14 +146,6 @@
<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}" />
+15 -16
View File
@@ -1,50 +1,49 @@
{
"schema": 1,
"generated": "2026-11-07T10:46:02Z",
"generated": "2026-11-08T01:29:16Z",
"repository": "https://gitcode.com/2509_92447106/GC",
"branch": "main",
"modelDir": "model",
"launcher": {
"version": "1.0.0",
"revision": "0d59eff631",
"version": "1.0.2",
"revision": "2c5b10a887",
"packages": {
"win-x64": {
"path": "dist/GC-win-x64.zip",
"url": "",
"sha256": "7bfb1cfab07934642eff4c52078a8f5f034f1d2432a7613f04674403c70f2b6d",
"size": 78755039
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-win-x64.zip"
},
"win-arm64": {
"path": "dist/GC-win-arm64.zip",
"url": "",
"sha256": "9fddf07fa18cbdb368e37204cfb96f5828207e5fe74ecb31fa66b61fa400fd1c",
"size": 75360988
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-win-arm64.zip"
},
"osx-arm64": {
"path": "dist/GC-osx-arm64.zip",
"url": "",
"sha256": "3517548b598eda62c92d873528f39e305c52c6fb246fa5ba5f3613f8b8cb315a",
"size": 39847910
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-osx-arm64.zip"
},
"osx-x64": {
"path": "dist/GC-osx-x64.zip",
"url": ""
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-osx-x64.zip"
},
"linux-x64": {
"path": "dist/GC-linux-x64.zip",
"url": ""
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.2/GC-linux-x64.zip"
}
}
},
"models": [
{
"id": "earth-geography",
"version": "1.0-dd67f83d0c",
"dir": "model/earth-geography"
},
{
"id": "earth-revolution",
"version": "1.0-0a73a257ec",
"version": "1.0-7380e0cff3",
"dir": "model/earth-revolution"
},
{
"id": "earth-rotation",
"version": "1.0-6c97454f58",
"version": "1.0-c74907bbce",
"dir": "model/earth-rotation"
}
]