y
This commit is contained in:
commit
1ee49b8966
1125 files changed
+32542
No files matched your search
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<RootNamespace>NeoRF.EarthModels</RootNamespace>
|
||||
<AssemblyName>EarthModelPreview</AssemblyName>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 直接编译共享引擎源码:封面必须由模型自己的渲染器画 -->
|
||||
<Compile Include="../src/**/*.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Media.Imaging;
|
||||
using NeoRF.EarthModels;
|
||||
|
||||
namespace NeoRF.EarthModels.Preview;
|
||||
|
||||
/// <summary>
|
||||
/// 封面生成工具:用模型自己的渲染器给每个模型画一张封面 preview.png。
|
||||
/// 封面在模型包里,启动器只负责显示 —— 所以公转模型的封面一定就是公转场景。
|
||||
/// 用法:dotnet run --project model-src/tools/PreviewGen -- <仓库根>
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private const int Width = 768;
|
||||
private const int Height = 316;
|
||||
|
||||
[STAThread]
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
var root = args.Length > 0 ? args[0] : Directory.GetCurrentDirectory();
|
||||
var modelRoot = Path.Combine(root, "model");
|
||||
if (!Directory.Exists(modelRoot))
|
||||
{
|
||||
Console.Error.WriteLine($"找不到模型库: {modelRoot}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var bench = args.Contains("--bench");
|
||||
|
||||
AppBuilder.Configure<Application>()
|
||||
.UseSkia()
|
||||
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
|
||||
.SetupWithoutStarting();
|
||||
|
||||
foreach (var modelDir in Directory.GetDirectories(modelRoot))
|
||||
{
|
||||
var id = Path.GetFileName(modelDir);
|
||||
if (id.StartsWith(".")) continue;
|
||||
var dataDir = Path.Combine(modelDir, id + ".model");
|
||||
var sceneFile = Path.Combine(dataDir, "scene.json");
|
||||
if (!File.Exists(sceneFile)) continue;
|
||||
|
||||
var runtime = SceneRuntime.Load(dataDir, 2048);
|
||||
var texts = ModelStrings.Load(dataDir, "zh-CN");
|
||||
var revolution = string.Equals(runtime.Scene.DefaultView, "revolution", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var view = new CelestialView
|
||||
{
|
||||
Scene = runtime,
|
||||
Texts = texts,
|
||||
View = revolution ? SceneView.Revolution : SceneView.Rotation,
|
||||
IsPlaying = false,
|
||||
ShowHud = false,
|
||||
ShowLabels = false,
|
||||
ShowOrbit = true,
|
||||
ShowGraticule = true,
|
||||
Width = Width,
|
||||
Height = Height
|
||||
};
|
||||
view.Measure(new Size(Width, Height));
|
||||
view.Arrange(new Rect(0, 0, Width, Height));
|
||||
view.JumpToOrbit(revolution ? 45 : 0);
|
||||
view.JumpToSpin(20);
|
||||
|
||||
if (bench)
|
||||
{
|
||||
// 真实窗口尺寸下的帧耗时
|
||||
view.Width = 1240;
|
||||
view.Height = 820;
|
||||
view.Measure(new Size(1240, 820));
|
||||
view.Arrange(new Rect(0, 0, 1240, 820));
|
||||
// 模拟播放态(运动时降分辨率),分别测静止高清帧与运动帧
|
||||
var animField = typeof(NeoRF.EarthModels.CelestialView)
|
||||
.GetField("_animating", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
for (var frame = 0; frame < 20; frame++)
|
||||
{
|
||||
view.JumpToSpin(20 + frame * 3);
|
||||
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
|
||||
tmp.Render(view);
|
||||
}
|
||||
sw.Stop();
|
||||
var still = sw.Elapsed.TotalMilliseconds / 20;
|
||||
animField?.SetValue(view, true);
|
||||
sw.Restart();
|
||||
for (var frame = 0; frame < 20; frame++)
|
||||
{
|
||||
view.JumpToSpin(20 + frame * 3);
|
||||
using var tmp = new RenderTargetBitmap(new PixelSize(1240, 820), new Vector(96, 96));
|
||||
tmp.Render(view);
|
||||
}
|
||||
sw.Stop();
|
||||
Console.WriteLine($"{id}: 静止 {still:0.0} ms/frame · 播放 {sw.Elapsed.TotalMilliseconds / 20:0.0} ms/frame");
|
||||
continue;
|
||||
}
|
||||
|
||||
var outFile = Path.Combine(dataDir, "preview.png");
|
||||
using (var bitmap = new RenderTargetBitmap(new PixelSize(Width, Height), new Vector(96, 96)))
|
||||
{
|
||||
bitmap.Render(view);
|
||||
bitmap.Save(outFile);
|
||||
}
|
||||
Console.WriteLine($"preview -> {outFile}");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
// VersionStamp:构建时自动给模型打版本。
|
||||
// 用法:dotnet run --project model/_engine/VersionStamp -- <仓库根> <启动器版本>
|
||||
// 输出:更新 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");
|
||||
|
||||
if (!Directory.Exists(modelRoot))
|
||||
{
|
||||
Console.Error.WriteLine($"找不到模型库: {modelRoot}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var relaxed = new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
|
||||
static string Rel(string baseDir, string file) =>
|
||||
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
|
||||
|
||||
static bool Distributable(string file)
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
if (name.StartsWith('.')) return false;
|
||||
if (name.EndsWith(".user", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
var rel = file.Replace('\\', '/');
|
||||
return !rel.Contains("/bin/", StringComparison.OrdinalIgnoreCase) &&
|
||||
!rel.Contains("/obj/", StringComparison.OrdinalIgnoreCase) &&
|
||||
!rel.EndsWith(".installing", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
static string Fingerprint(IEnumerable<byte[]> chunks)
|
||||
{
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
foreach (var chunk in chunks) hash.AppendData(chunk);
|
||||
return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
|
||||
}
|
||||
|
||||
Console.WriteLine("==> 自动计算模型版本(按模型包内容指纹)");
|
||||
var models = new List<Dictionary<string, string>>();
|
||||
|
||||
foreach (var dir in Directory.GetDirectories(modelRoot)
|
||||
.OrderBy(p => Path.GetFileName(p), StringComparer.Ordinal))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
if (id.StartsWith('_')) continue; // _sdk / _engine 是共享源码,不是模型
|
||||
|
||||
var manifestPath = Path.Combine(dir, id + ".json");
|
||||
var dataDir = Path.Combine(dir, id + ".model");
|
||||
if (!File.Exists(manifestPath) || !Directory.Exists(dataDir)) continue;
|
||||
|
||||
var manifest = JsonNode.Parse(File.ReadAllText(manifestPath))?.AsObject();
|
||||
if (manifest == null) continue;
|
||||
|
||||
// 版本号由模型清单里手写的 version 决定(作者手动升到 1.0 / 1.1 …),
|
||||
// 不再用内容指纹覆盖:指纹形式(1.0-393cb2b7d4)对用户不可读、也没有语义。
|
||||
var declared = manifest["version"]?.GetValue<string>();
|
||||
var version = string.IsNullOrWhiteSpace(declared) ? "1.0" : declared!.Trim();
|
||||
|
||||
// 内容指纹保留在 build 字段,仅用于构建溯源,不参与版本比较
|
||||
manifest.Remove("build");
|
||||
var canonical = manifest.ToJsonString(new JsonSerializerOptions { WriteIndented = false });
|
||||
var chunks = new List<byte[]> { Encoding.UTF8.GetBytes(canonical) };
|
||||
foreach (var file in Directory.GetFiles(dataDir, "*", SearchOption.AllDirectories)
|
||||
.Where(Distributable)
|
||||
.OrderBy(f => Rel(dataDir, f), StringComparer.Ordinal))
|
||||
{
|
||||
chunks.Add(Encoding.UTF8.GetBytes("\n" + Rel(dataDir, file) + "\n"));
|
||||
chunks.Add(File.ReadAllBytes(file));
|
||||
}
|
||||
var fingerprint = Fingerprint(chunks)[..10];
|
||||
|
||||
manifest["version"] = version;
|
||||
manifest["build"] = fingerprint;
|
||||
manifest["updatedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
File.WriteAllText(manifestPath, manifest.ToJsonString(relaxed) + "\n");
|
||||
|
||||
models.Add(new Dictionary<string, string>
|
||||
{
|
||||
["id"] = id,
|
||||
["version"] = version,
|
||||
["build"] = fingerprint,
|
||||
["dir"] = "model/" + id
|
||||
});
|
||||
Console.WriteLine($" {id,-20} {version,-8} (build {fingerprint})");
|
||||
}
|
||||
|
||||
// 启动器源码指纹(只展示,不触发升级;升级看 launcher.version)
|
||||
var srcRoot = Path.Combine(root, "src");
|
||||
var srcChunks = new List<byte[]>();
|
||||
if (Directory.Exists(srcRoot))
|
||||
{
|
||||
foreach (var file in Directory.GetFiles(srcRoot, "*", SearchOption.AllDirectories)
|
||||
.Where(Distributable)
|
||||
.Where(f => f.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".axaml", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".props", StringComparison.OrdinalIgnoreCase))
|
||||
.OrderBy(f => Rel(srcRoot, f), StringComparer.Ordinal))
|
||||
{
|
||||
srcChunks.Add(Encoding.UTF8.GetBytes(Rel(srcRoot, file) + "\n"));
|
||||
srcChunks.Add(File.ReadAllBytes(file));
|
||||
}
|
||||
}
|
||||
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"] = $"{releaseBase}/GC-{rid}.zip"
|
||||
};
|
||||
// 已生成的启动器更新包:把校验值和体积写进清单,供下载端校验
|
||||
var zipPath = Path.Combine(root, "dist", $"GC-{rid}.zip");
|
||||
if (File.Exists(zipPath))
|
||||
{
|
||||
var bytes = File.ReadAllBytes(zipPath);
|
||||
entry["sha256"] = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
entry["size"] = bytes.LongLength;
|
||||
}
|
||||
packages[rid] = entry;
|
||||
}
|
||||
|
||||
var versionDoc = new Dictionary<string, object>
|
||||
{
|
||||
["schema"] = 1,
|
||||
["generated"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||
["repository"] = Repository,
|
||||
["branch"] = "main",
|
||||
["modelDir"] = "model",
|
||||
["launcher"] = new Dictionary<string, object>
|
||||
{
|
||||
["version"] = launcherVersion,
|
||||
["revision"] = launcherRevision,
|
||||
["packages"] = packages
|
||||
},
|
||||
["models"] = models
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(versionDoc, relaxed) + "\n";
|
||||
File.WriteAllText(Path.Combine(root, "version.json"), json);
|
||||
File.WriteAllText(Path.Combine(modelRoot, "version.json"), json);
|
||||
Console.WriteLine($"==> version.json 已生成(启动器 {launcherVersion},模型 {models.Count} 个)");
|
||||
return 0;
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AssemblyName>VersionStamp</AssemblyName>
|
||||
<RootNamespace>VersionStamp</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
Binary file not shown.
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"runtimeTarget": {
|
||||
"name": ".NETCoreApp,Version=v8.0",
|
||||
"signature": ""
|
||||
},
|
||||
"compilationOptions": {},
|
||||
"targets": {
|
||||
".NETCoreApp,Version=v8.0": {
|
||||
"VersionStamp/1.0.3": {
|
||||
"runtime": {
|
||||
"VersionStamp.dll": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"libraries": {
|
||||
"VersionStamp/1.0.3": {
|
||||
"type": "project",
|
||||
"serviceable": false,
|
||||
"sha512": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"runtimeOptions": {
|
||||
"tfm": "net8.0",
|
||||
"framework": {
|
||||
"name": "Microsoft.NETCore.App",
|
||||
"version": "8.0.0"
|
||||
},
|
||||
"configProperties": {
|
||||
"System.Reflection.Metadata.MetadataUpdater.IsSupported": false,
|
||||
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
// <autogenerated />
|
||||
using System;
|
||||
using System.Reflection;
|
||||
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
|
||||
@@ -0,0 +1,23 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
[assembly: System.Reflection.AssemblyCompanyAttribute("NeoRF")]
|
||||
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
|
||||
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.3.0")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.3")]
|
||||
[assembly: System.Reflection.AssemblyProductAttribute("Earth Model Studio")]
|
||||
[assembly: System.Reflection.AssemblyTitleAttribute("VersionStamp")]
|
||||
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.3.0")]
|
||||
[assembly: System.Resources.NeutralResourcesLanguageAttribute("zh-Hans")]
|
||||
|
||||
// Generated by the MSBuild WriteCodeFragment class.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
74f99e4d9cbf91b981ea8bb9ca826e7a8f5f09eeb43c6922e054b3d03a9b8acf
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
is_global = true
|
||||
build_property.TargetFramework = net8.0
|
||||
build_property.TargetFrameworkIdentifier = .NETCoreApp
|
||||
build_property.TargetFrameworkVersion = v8.0
|
||||
build_property.TargetPlatformMinVersion =
|
||||
build_property.UsingMicrosoftNETSdkWeb =
|
||||
build_property.ProjectTypeGuids =
|
||||
build_property.InvariantGlobalization =
|
||||
build_property.PlatformNeutralAssembly =
|
||||
build_property.EnforceExtendedAnalyzerRules =
|
||||
build_property.EntryPointFilePath =
|
||||
build_property._SupportedPlatformList = Linux,macOS,Windows
|
||||
build_property.RootNamespace = VersionStamp
|
||||
build_property.ProjectDir = /Users/morris/Downloads/GC#/model/_engine/VersionStamp/
|
||||
build_property.EnableComHosting =
|
||||
build_property.EnableGeneratedComInterfaceComImportInterop =
|
||||
build_property.EffectiveAnalysisLevelStyle = 8.0
|
||||
build_property.EnableCodeStyleSeverity =
|
||||
@@ -0,0 +1,8 @@
|
||||
// <auto-generated/>
|
||||
global using System;
|
||||
global using System.Collections.Generic;
|
||||
global using System.IO;
|
||||
global using System.Linq;
|
||||
global using System.Net.Http;
|
||||
global using System.Threading;
|
||||
global using System.Threading.Tasks;
|
||||
Binary file not shown.
+1
@@ -0,0 +1 @@
|
||||
85742ef80cf2152cf4a4430f83d458331bf993698b5083cd8b3b2fcfbf3691ce
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/bin/Release/net8.0/VersionStamp
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/bin/Release/net8.0/VersionStamp.deps.json
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/bin/Release/net8.0/VersionStamp.runtimeconfig.json
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/bin/Release/net8.0/VersionStamp.dll
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/bin/Release/net8.0/VersionStamp.pdb
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/VersionStamp.GeneratedMSBuildEditorConfig.editorconfig
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/VersionStamp.AssemblyInfoInputs.cache
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/VersionStamp.AssemblyInfo.cs
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/VersionStamp.csproj.CoreCompileInputs.cache
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/VersionStamp.dll
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/refint/VersionStamp.dll
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/VersionStamp.pdb
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/VersionStamp.genruntimeconfig.cache
|
||||
/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/Release/net8.0/ref/VersionStamp.dll
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
d0976149c15255acc8dcb9e033721a42927c784807f5fd87fba864a81ecce360
|
||||
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"format": 1,
|
||||
"restore": {
|
||||
"/Users/morris/Downloads/GC#/model/_engine/VersionStamp/VersionStamp.csproj": {}
|
||||
},
|
||||
"projects": {
|
||||
"/Users/morris/Downloads/GC#/model/_engine/VersionStamp/VersionStamp.csproj": {
|
||||
"version": "1.0.3",
|
||||
"restore": {
|
||||
"projectUniqueName": "/Users/morris/Downloads/GC#/model/_engine/VersionStamp/VersionStamp.csproj",
|
||||
"projectName": "VersionStamp",
|
||||
"projectPath": "/Users/morris/Downloads/GC#/model/_engine/VersionStamp/VersionStamp.csproj",
|
||||
"packagesPath": "/Users/morris/.nuget/packages/",
|
||||
"outputPath": "/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/",
|
||||
"projectStyle": "PackageReference",
|
||||
"configFilePaths": [
|
||||
"/Users/morris/.nuget/NuGet/NuGet.Config"
|
||||
],
|
||||
"originalTargetFrameworks": [
|
||||
"net8.0"
|
||||
],
|
||||
"sources": {
|
||||
"https://api.nuget.org/v3/index.json": {}
|
||||
},
|
||||
"frameworks": {
|
||||
"net8.0": {
|
||||
"framework": "net8.0",
|
||||
"targetAlias": "net8.0",
|
||||
"projectReferences": {}
|
||||
}
|
||||
},
|
||||
"warningProperties": {
|
||||
"warnAsError": [
|
||||
"NU1605"
|
||||
]
|
||||
},
|
||||
"restoreAuditProperties": {
|
||||
"enableAudit": "true",
|
||||
"auditLevel": "low",
|
||||
"auditMode": "direct"
|
||||
},
|
||||
"SdkAnalysisLevel": "10.0.400"
|
||||
},
|
||||
"frameworks": {
|
||||
"net8.0": {
|
||||
"framework": "net8.0",
|
||||
"targetAlias": "net8.0",
|
||||
"imports": [
|
||||
"net461",
|
||||
"net462",
|
||||
"net47",
|
||||
"net471",
|
||||
"net472",
|
||||
"net48",
|
||||
"net481"
|
||||
],
|
||||
"assetTargetFallback": true,
|
||||
"warn": true,
|
||||
"frameworkReferences": {
|
||||
"Microsoft.NETCore.App": {
|
||||
"privateAssets": "all"
|
||||
}
|
||||
},
|
||||
"runtimeIdentifierGraphPath": "/usr/local/share/dotnet/sdk/10.0.401/PortableRuntimeIdentifierGraph.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
|
||||
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
|
||||
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
|
||||
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">/Users/morris/.nuget/packages/</NuGetPackageRoot>
|
||||
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">/Users/morris/.nuget/packages/</NuGetPackageFolders>
|
||||
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
|
||||
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">7.0.0</NuGetToolVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<SourceRoot Include="/Users/morris/.nuget/packages/" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"version": 4,
|
||||
"targets": {
|
||||
"net8.0": {}
|
||||
},
|
||||
"libraries": {},
|
||||
"projectFileDependencyGroups": {
|
||||
"net8.0": []
|
||||
},
|
||||
"packageFolders": {
|
||||
"/Users/morris/.nuget/packages/": {}
|
||||
},
|
||||
"project": {
|
||||
"version": "1.0.3",
|
||||
"restore": {
|
||||
"projectUniqueName": "/Users/morris/Downloads/GC#/model/_engine/VersionStamp/VersionStamp.csproj",
|
||||
"projectName": "VersionStamp",
|
||||
"projectPath": "/Users/morris/Downloads/GC#/model/_engine/VersionStamp/VersionStamp.csproj",
|
||||
"packagesPath": "/Users/morris/.nuget/packages/",
|
||||
"outputPath": "/Users/morris/Downloads/GC#/model/_engine/VersionStamp/obj/",
|
||||
"projectStyle": "PackageReference",
|
||||
"configFilePaths": [
|
||||
"/Users/morris/.nuget/NuGet/NuGet.Config"
|
||||
],
|
||||
"originalTargetFrameworks": [
|
||||
"net8.0"
|
||||
],
|
||||
"sources": {
|
||||
"https://api.nuget.org/v3/index.json": {}
|
||||
},
|
||||
"frameworks": {
|
||||
"net8.0": {
|
||||
"framework": "net8.0",
|
||||
"targetAlias": "net8.0",
|
||||
"projectReferences": {}
|
||||
}
|
||||
},
|
||||
"warningProperties": {
|
||||
"warnAsError": [
|
||||
"NU1605"
|
||||
]
|
||||
},
|
||||
"restoreAuditProperties": {
|
||||
"enableAudit": "true",
|
||||
"auditLevel": "low",
|
||||
"auditMode": "direct"
|
||||
},
|
||||
"SdkAnalysisLevel": "10.0.400"
|
||||
},
|
||||
"frameworks": {
|
||||
"net8.0": {
|
||||
"framework": "net8.0",
|
||||
"targetAlias": "net8.0",
|
||||
"imports": [
|
||||
"net461",
|
||||
"net462",
|
||||
"net47",
|
||||
"net471",
|
||||
"net472",
|
||||
"net48",
|
||||
"net481"
|
||||
],
|
||||
"assetTargetFallback": true,
|
||||
"warn": true,
|
||||
"frameworkReferences": {
|
||||
"Microsoft.NETCore.App": {
|
||||
"privateAssets": "all"
|
||||
}
|
||||
},
|
||||
"runtimeIdentifierGraphPath": "/usr/local/share/dotnet/sdk/10.0.401/PortableRuntimeIdentifierGraph.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dgSpecHash": "tJZIToOhfvc=",
|
||||
"success": true,
|
||||
"projectFilePath": "/Users/morris/Downloads/GC#/model/_engine/VersionStamp/VersionStamp.csproj",
|
||||
"expectedPackageFiles": [],
|
||||
"logs": []
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,904 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Avalonia;
|
||||
using Avalonia.Animation;
|
||||
using Avalonia.Animation.Easings;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using EarthModelStudio.ModelSdk;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary>
|
||||
/// 模型自己的界面:画布 + 触控友好工具栏 + 课堂演示卡 + 节气定格与步进。
|
||||
/// 启动器只负责下载、开窗口和进度条,不参与任何模型渲染或教学交互。
|
||||
/// </summary>
|
||||
public sealed class EarthModelView : UserControl, IDisposable
|
||||
{
|
||||
private static readonly IBrush PanelBg = new SolidColorBrush(Color.Parse("#C40A1020"));
|
||||
private static readonly IBrush ControlBg = new SolidColorBrush(Color.Parse("#16233C"));
|
||||
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#2E6BE6"));
|
||||
private static readonly IBrush TitleBrush = new SolidColorBrush(Color.Parse("#F2F6FF"));
|
||||
private static readonly IBrush TextBrush = new SolidColorBrush(Color.Parse("#DCE7FA"));
|
||||
private static readonly IBrush MutedBrush = new SolidColorBrush(Color.Parse("#7E93B8"));
|
||||
private static readonly IBrush FaintBrush = new SolidColorBrush(Color.Parse("#61779C"));
|
||||
private static readonly IBrush BodyBrush = new SolidColorBrush(Color.Parse("#8CA0C4"));
|
||||
private static readonly IBrush WarmBrush = new SolidColorBrush(Color.Parse("#FFC46B"));
|
||||
|
||||
private static readonly TimeSpan HoverDuration = TimeSpan.FromMilliseconds(120);
|
||||
private static readonly TimeSpan PanelDuration = TimeSpan.FromMilliseconds(190);
|
||||
|
||||
private readonly IModelContext _context;
|
||||
private readonly ModelStrings _texts;
|
||||
private readonly SceneRuntime _runtime;
|
||||
private readonly List<string> _views;
|
||||
private readonly List<ModelButton> _viewButtons = new();
|
||||
private readonly CelestialView _canvas;
|
||||
private readonly CelestialView _closeup;
|
||||
private readonly DispatcherTimer _uiTimer;
|
||||
|
||||
private Border? _viewSwitch;
|
||||
private StackPanel? _seasonPanel;
|
||||
private Border? _lessons;
|
||||
private Border? _closeupHost;
|
||||
private TextBlock? _closeupLabel;
|
||||
private ModelButton? _playButton;
|
||||
private ModelButton? _overheadButton;
|
||||
private ModelButton? _closeupButton;
|
||||
private TextBlock? _zoomText;
|
||||
private TextBlock? _cardState;
|
||||
private TextBlock? _cardTitle;
|
||||
private TextBlock? _cardDate;
|
||||
private TextBlock? _cardDirect;
|
||||
private TextBlock? _cardNote;
|
||||
|
||||
private bool _playing = true;
|
||||
private bool _labels = true;
|
||||
private bool _orbit = true;
|
||||
private bool _grid = true;
|
||||
private bool _tilt;
|
||||
private bool _showLessons = true;
|
||||
private bool _showCloseup = true;
|
||||
private bool _overhead;
|
||||
private double _lastDeclination = double.NaN;
|
||||
|
||||
public EarthModelView(IModelContext context, SceneRuntime runtime)
|
||||
{
|
||||
_context = context;
|
||||
_runtime = runtime;
|
||||
_texts = ModelStrings.Load(context.DataDirectory, context.Language);
|
||||
_views = ResolveViews(runtime.Scene);
|
||||
// 自转模型主画布本身就是放大的地球,不需要再来一份特写
|
||||
_showCloseup = IsRevolution;
|
||||
|
||||
Background = new SolidColorBrush(Color.Parse("#05070F"));
|
||||
|
||||
_canvas = new CelestialView
|
||||
{
|
||||
Scene = runtime,
|
||||
Texts = _texts,
|
||||
ShowLabels = true,
|
||||
ShowOrbit = true,
|
||||
ShowGraticule = true,
|
||||
ShowKeyLatitudes = true,
|
||||
FrameRate = 120,
|
||||
View = IsRevolution ? SceneView.Revolution : SceneView.Rotation
|
||||
};
|
||||
_canvas.JumpToOrbit(StartAngle);
|
||||
_canvas.JumpToSpin(20);
|
||||
_canvas.ZoomChanged += zoom =>
|
||||
{
|
||||
if (_zoomText != null) _zoomText.Text = $"{zoom * 100:0}%";
|
||||
};
|
||||
|
||||
// 课堂特写:同一套渲染器,把当前直射纬度放大给全班看
|
||||
_closeup = new CelestialView
|
||||
{
|
||||
Scene = runtime,
|
||||
Texts = _texts,
|
||||
View = SceneView.Rotation,
|
||||
IsPlaying = false,
|
||||
ShowHud = false,
|
||||
ShowLabels = true,
|
||||
ShowGraticule = false,
|
||||
ShowKeyLatitudes = true,
|
||||
InsetMode = true,
|
||||
Width = 240,
|
||||
Height = 240
|
||||
};
|
||||
_closeup.JumpToSpin(20);
|
||||
|
||||
_uiTimer = new DispatcherTimer(TimeSpan.FromMilliseconds(140),
|
||||
DispatcherPriority.Render, (_, _) => RefreshTeaching());
|
||||
|
||||
var root = new Grid { RowDefinitions = new RowDefinitions("Auto,Auto,*,Auto") };
|
||||
|
||||
var top = BuildTopBar();
|
||||
root.Children.Add(top);
|
||||
|
||||
var options = BuildOptionsBar();
|
||||
Grid.SetRow(options, 1);
|
||||
root.Children.Add(options);
|
||||
|
||||
var stage = new Grid();
|
||||
stage.Children.Add(_canvas);
|
||||
stage.Children.Add(BuildZoomPad());
|
||||
_lessons = BuildClassroomCard();
|
||||
stage.Children.Add(_lessons);
|
||||
Grid.SetRow(stage, 2);
|
||||
root.Children.Add(stage);
|
||||
|
||||
var bottom = BuildBottomBar();
|
||||
Grid.SetRow(bottom, 3);
|
||||
root.Children.Add(bottom);
|
||||
|
||||
Content = root;
|
||||
ApplyVisibility();
|
||||
RefreshTeaching();
|
||||
|
||||
// 打开时整窗淡入,避免「啪」地出现
|
||||
Opacity = 0;
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = OpacityProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(260),
|
||||
Easing = new CubicEaseOut()
|
||||
}
|
||||
};
|
||||
AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
Opacity = 1;
|
||||
_uiTimer.Start();
|
||||
if (TopLevel.GetTopLevel(this) is Window window)
|
||||
{
|
||||
_hostWindow = window;
|
||||
window.KeyDown += OnKeyDown;
|
||||
}
|
||||
};
|
||||
DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
_uiTimer.Stop();
|
||||
if (_hostWindow != null)
|
||||
{
|
||||
_hostWindow.KeyDown -= OnKeyDown;
|
||||
_hostWindow = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private Window? _hostWindow;
|
||||
|
||||
/// <summary>
|
||||
/// 窗口关闭时释放计时器、解绑窗口事件并释放两块球面位图,
|
||||
/// 否则 DispatcherTimer / KeyDown 会持有控件,使 collectible ALC 无法卸载。
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_uiTimer.Stop();
|
||||
if (_hostWindow != null)
|
||||
{
|
||||
_hostWindow.KeyDown -= OnKeyDown;
|
||||
_hostWindow = null;
|
||||
}
|
||||
_canvas.Dispose();
|
||||
_closeup.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private string CurrentView { get; set; } = "rotation";
|
||||
private double StartAngle => IsRevolution ? 60 : 0;
|
||||
private bool IsRevolution => string.Equals(CurrentView, "revolution", StringComparison.OrdinalIgnoreCase);
|
||||
private bool HasViewSwitch => _views.Count > 1;
|
||||
private List<SeasonPoint> Seasons => _runtime.Scene.Orbit.Seasons;
|
||||
|
||||
private static string NormalizeView(string? view)
|
||||
=> string.Equals(view, "revolution", StringComparison.OrdinalIgnoreCase) ? "revolution" : "rotation";
|
||||
|
||||
private List<string> ResolveViews(SceneDefinition scene)
|
||||
{
|
||||
var list = new List<string>();
|
||||
foreach (var v in scene.Views)
|
||||
{
|
||||
var normalized = NormalizeView(v);
|
||||
if (!list.Contains(normalized)) list.Add(normalized);
|
||||
}
|
||||
if (list.Count == 0) list.Add(NormalizeView(scene.DefaultView));
|
||||
CurrentView = list[0];
|
||||
return list;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 顶部主工具栏
|
||||
private Control BuildTopBar()
|
||||
{
|
||||
// 关闭按钮统一放在窗口右上角的自建标题栏,这里不再重复放左上角
|
||||
var title = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center };
|
||||
title.Children.Add(new TextBlock
|
||||
{
|
||||
Text = _texts.Pick(_runtime.Scene.NameI18n, _texts["title"]),
|
||||
Foreground = TitleBrush,
|
||||
FontSize = 14,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
});
|
||||
title.Children.Add(new TextBlock
|
||||
{
|
||||
Text = _texts.Pick(_runtime.Scene.DescriptionI18n, ""),
|
||||
Foreground = MutedBrush,
|
||||
FontSize = 10.5,
|
||||
MaxWidth = 330,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
});
|
||||
|
||||
var switchPanel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };
|
||||
switchPanel.Children.Add(MakeViewButton("rotation", _texts["view.rotation"]));
|
||||
switchPanel.Children.Add(MakeViewButton("revolution", _texts["view.revolution"]));
|
||||
_viewSwitch = new Border
|
||||
{
|
||||
Background = ControlBg,
|
||||
CornerRadius = new CornerRadius(10),
|
||||
Padding = new Thickness(3),
|
||||
Margin = new Thickness(16, 0, 0, 0),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Child = switchPanel
|
||||
};
|
||||
|
||||
var actions = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Spacing = 8,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
_playButton = MakeButton(_texts["pause"], TogglePlay);
|
||||
_playButton.MinWidth = 74;
|
||||
actions.Children.Add(_playButton);
|
||||
actions.Children.Add(MakeButton(_texts["reset"], () =>
|
||||
{
|
||||
_canvas.ResetAnimation();
|
||||
_canvas.JumpToOrbit(StartAngle);
|
||||
RefreshTeaching();
|
||||
}));
|
||||
actions.Children.Add(MakeButton("◀", () => Step(-5), large: true));
|
||||
actions.Children.Add(MakeButton("▶", () => Step(5), large: true));
|
||||
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") };
|
||||
Grid.SetColumn(title, 0);
|
||||
title.Margin = new Thickness(14, 0, 0, 0);
|
||||
grid.Children.Add(title);
|
||||
Grid.SetColumn(_viewSwitch, 1);
|
||||
grid.Children.Add(_viewSwitch);
|
||||
Grid.SetColumn(actions, 3);
|
||||
grid.Children.Add(actions);
|
||||
|
||||
return new Border { Background = PanelBg, Padding = new Thickness(16, 9), Child = grid };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 显示选项行
|
||||
private Control BuildOptionsBar()
|
||||
{
|
||||
var row = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Spacing = 7,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
row.Children.Add(MakeToggle(_texts["labels"], _labels, on => { _labels = on; _canvas.ShowLabels = on; }));
|
||||
row.Children.Add(MakeToggle(_texts["orbit"], _orbit, on => { _orbit = on; _canvas.ShowOrbit = on; }));
|
||||
row.Children.Add(MakeToggle(_texts["grid"], _grid, on => { _grid = on; _canvas.ShowGraticule = on; }));
|
||||
row.Children.Add(MakeToggle(_texts["tilt"], _tilt, on => { _tilt = on; _canvas.ExaggerateTilt = on; }));
|
||||
_closeupButton = MakeToggle(_texts["closeup"], _showCloseup, on =>
|
||||
{
|
||||
_showCloseup = on;
|
||||
ApplyVisibility();
|
||||
});
|
||||
row.Children.Add(_closeupButton);
|
||||
_overheadButton = MakeToggle(_texts["overhead"], _overhead, on =>
|
||||
{
|
||||
_overhead = on;
|
||||
// 视角只由这个显式控件改变;拖动永远不会碰它
|
||||
_canvas.CameraElevation = on ? (IsRevolution ? 74 : 62) : double.NaN;
|
||||
});
|
||||
row.Children.Add(_overheadButton);
|
||||
|
||||
var shortcut = new TextBlock
|
||||
{
|
||||
Text = _texts["shortcutHint"],
|
||||
Foreground = FaintBrush,
|
||||
FontSize = 10.5,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(12, 0, 0, 0)
|
||||
};
|
||||
|
||||
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
|
||||
grid.Children.Add(row);
|
||||
Grid.SetColumn(shortcut, 1);
|
||||
grid.Children.Add(shortcut);
|
||||
return new Border
|
||||
{
|
||||
Background = new SolidColorBrush(Color.Parse("#A00A1020")),
|
||||
Padding = new Thickness(16, 7),
|
||||
Child = grid
|
||||
};
|
||||
}
|
||||
|
||||
private ModelButton MakeViewButton(string view, string label)
|
||||
{
|
||||
var button = MakeButton(label, () => SwitchView(view));
|
||||
button.SetBase(string.Equals(CurrentView, view, StringComparison.OrdinalIgnoreCase) ? Accent : ControlBg);
|
||||
button.Tag = view;
|
||||
button.IsVisible = _views.Contains(view);
|
||||
_viewButtons.Add(button);
|
||||
return button;
|
||||
}
|
||||
|
||||
private ModelButton MakeToggle(string label, bool initial, Action<bool> changed)
|
||||
{
|
||||
var state = initial;
|
||||
ModelButton? button = null;
|
||||
button = MakeButton(label, () =>
|
||||
{
|
||||
state = !state;
|
||||
changed(state);
|
||||
button?.SetBase(state ? Accent : ControlBg);
|
||||
});
|
||||
button.SetBase(initial ? Accent : ControlBg);
|
||||
return button;
|
||||
}
|
||||
|
||||
private void SwitchView(string view)
|
||||
{
|
||||
CurrentView = NormalizeView(view);
|
||||
_canvas.View = IsRevolution ? SceneView.Revolution : SceneView.Rotation;
|
||||
_canvas.JumpToOrbit(StartAngle);
|
||||
_canvas.CameraElevation = _overhead ? (IsRevolution ? 74 : 62) : double.NaN;
|
||||
foreach (var button in _viewButtons)
|
||||
button.SetBase(string.Equals(button.Tag as string, CurrentView, StringComparison.OrdinalIgnoreCase)
|
||||
? Accent
|
||||
: ControlBg);
|
||||
ApplyVisibility();
|
||||
RefreshTeaching();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 画布浮动缩放板(触控大按钮)
|
||||
private Control BuildZoomPad()
|
||||
{
|
||||
var plus = MakeButton("+", () => _canvas.ZoomBy(1.25), large: true);
|
||||
var minus = MakeButton("-", () => _canvas.ZoomBy(1 / 1.25), large: true);
|
||||
var reset = MakeButton("⟲", () => _canvas.ResetView(), large: true);
|
||||
foreach (var b in new[] { plus, minus, reset })
|
||||
{
|
||||
b.MinWidth = 62;
|
||||
b.MinHeight = 48;
|
||||
b.HorizontalAlignment = HorizontalAlignment.Stretch;
|
||||
}
|
||||
|
||||
_zoomText = new TextBlock
|
||||
{
|
||||
Text = "100%",
|
||||
Foreground = TextBrush,
|
||||
FontSize = 13,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
TextAlignment = TextAlignment.Center,
|
||||
Margin = new Thickness(0, 2, 0, 2)
|
||||
};
|
||||
|
||||
var stack = new StackPanel { Spacing = 6, Width = 62 };
|
||||
stack.Children.Add(new TextBlock
|
||||
{
|
||||
Text = _texts["zoom"],
|
||||
Foreground = MutedBrush,
|
||||
FontSize = 10.5,
|
||||
TextAlignment = TextAlignment.Center
|
||||
});
|
||||
stack.Children.Add(plus);
|
||||
stack.Children.Add(_zoomText);
|
||||
stack.Children.Add(minus);
|
||||
stack.Children.Add(reset);
|
||||
|
||||
return new Border
|
||||
{
|
||||
HorizontalAlignment = HorizontalAlignment.Left,
|
||||
VerticalAlignment = VerticalAlignment.Bottom,
|
||||
Margin = new Thickness(16, 0, 0, 16),
|
||||
Background = new SolidColorBrush(Color.Parse("#C00B1226")),
|
||||
BorderBrush = new SolidColorBrush(Color.Parse("#26374F")),
|
||||
BorderThickness = new Thickness(1),
|
||||
CornerRadius = new CornerRadius(14),
|
||||
Padding = new Thickness(10),
|
||||
Child = stack
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 底部
|
||||
private Control BuildBottomBar()
|
||||
{
|
||||
var speedLabel = new TextBlock
|
||||
{
|
||||
Text = _texts["speed"],
|
||||
Foreground = new SolidColorBrush(Color.Parse("#9DB0D0")),
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var slider = new Slider
|
||||
{
|
||||
Minimum = 0.25,
|
||||
Maximum = 4,
|
||||
Value = 1,
|
||||
Margin = new Thickness(12, 0, 0, 0),
|
||||
Width = 180,
|
||||
Height = 38
|
||||
};
|
||||
var speedText = new TextBlock
|
||||
{
|
||||
Text = "1×",
|
||||
Foreground = TextBrush,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Width = 46,
|
||||
Margin = new Thickness(6, 0, 0, 0)
|
||||
};
|
||||
slider.ValueChanged += (_, e) =>
|
||||
{
|
||||
_canvas.Speed = e.NewValue;
|
||||
speedText.Text = $"{e.NewValue:0.##}×";
|
||||
};
|
||||
|
||||
var hint = new TextBlock
|
||||
{
|
||||
Text = _texts["hint"],
|
||||
Foreground = FaintBrush,
|
||||
FontSize = 10.5,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(20, 0, 0, 0),
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
};
|
||||
|
||||
_seasonPanel = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Spacing = 7,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
_seasonPanel.Children.Add(new TextBlock
|
||||
{
|
||||
Text = _texts["seasons"],
|
||||
Foreground = MutedBrush,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(0, 0, 6, 0)
|
||||
});
|
||||
foreach (var season in Seasons) _seasonPanel.Children.Add(MakeSeasonButton(season));
|
||||
|
||||
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto") };
|
||||
grid.Children.Add(speedLabel);
|
||||
Grid.SetColumn(slider, 1);
|
||||
grid.Children.Add(slider);
|
||||
Grid.SetColumn(speedText, 2);
|
||||
grid.Children.Add(speedText);
|
||||
Grid.SetColumn(hint, 3);
|
||||
grid.Children.Add(hint);
|
||||
Grid.SetColumn(_seasonPanel, 4);
|
||||
grid.Children.Add(_seasonPanel);
|
||||
|
||||
return new Border { Background = PanelBg, Padding = new Thickness(16, 8), Child = grid };
|
||||
}
|
||||
|
||||
private ModelButton MakeSeasonButton(SeasonPoint season)
|
||||
{
|
||||
var captured = season;
|
||||
var button = MakeButton(_texts[season.Key], () => JumpToSeason(captured));
|
||||
button.MinHeight = 44;
|
||||
return button;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 课堂演示卡
|
||||
private Border BuildClassroomCard()
|
||||
{
|
||||
var header = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
header.Children.Add(new TextBlock
|
||||
{
|
||||
Text = _texts["classroom"],
|
||||
Foreground = TitleBrush,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
FontSize = 13,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
});
|
||||
var close = MakeButton("✕", () => SetLessonsVisible(false));
|
||||
close.SetBase(Brushes.Transparent);
|
||||
Grid.SetColumn(close, 1);
|
||||
header.Children.Add(close);
|
||||
|
||||
_cardState = new TextBlock
|
||||
{
|
||||
Text = _texts["running"],
|
||||
Foreground = MutedBrush,
|
||||
FontSize = 11,
|
||||
Margin = new Thickness(0, 6, 0, 0)
|
||||
};
|
||||
_cardTitle = new TextBlock
|
||||
{
|
||||
Foreground = TitleBrush,
|
||||
FontSize = 20,
|
||||
FontWeight = FontWeight.Bold
|
||||
};
|
||||
_cardDate = new TextBlock { Foreground = MutedBrush, FontSize = 12 };
|
||||
_cardDirect = new TextBlock
|
||||
{
|
||||
Foreground = WarmBrush,
|
||||
FontSize = 27,
|
||||
FontWeight = FontWeight.Bold
|
||||
};
|
||||
_cardNote = new TextBlock
|
||||
{
|
||||
Foreground = BodyBrush,
|
||||
FontSize = 12,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 18
|
||||
};
|
||||
|
||||
_closeupHost = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(10),
|
||||
BorderBrush = new SolidColorBrush(Color.Parse("#26374F")),
|
||||
BorderThickness = new Thickness(1),
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
Margin = new Thickness(0, 4, 0, 2),
|
||||
Child = _closeup
|
||||
};
|
||||
|
||||
var readouts = new StackPanel { Spacing = 2 };
|
||||
readouts.Children.Add(_cardState);
|
||||
readouts.Children.Add(_cardTitle);
|
||||
readouts.Children.Add(_cardDate);
|
||||
readouts.Children.Add(new TextBlock
|
||||
{
|
||||
Text = _texts["directPoint"],
|
||||
Foreground = MutedBrush,
|
||||
FontSize = 11,
|
||||
Margin = new Thickness(0, 8, 0, 0)
|
||||
});
|
||||
readouts.Children.Add(_cardDirect);
|
||||
readouts.Children.Add(_cardNote);
|
||||
_closeupLabel = new TextBlock
|
||||
{
|
||||
Text = _texts["closeup"],
|
||||
Foreground = MutedBrush,
|
||||
FontSize = 11,
|
||||
Margin = new Thickness(0, 6, 0, 0)
|
||||
};
|
||||
readouts.Children.Add(_closeupLabel);
|
||||
readouts.Children.Add(_closeupHost);
|
||||
|
||||
var list = new StackPanel { Spacing = 2 };
|
||||
foreach (var lesson in _runtime.Scene.Lessons)
|
||||
{
|
||||
var title = new TextBlock
|
||||
{
|
||||
Text = _texts.Pick(lesson.TitleI18n, ""),
|
||||
Foreground = new SolidColorBrush(Color.Parse("#CFE0FF")),
|
||||
FontSize = 12,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
TextWrapping = TextWrapping.Wrap
|
||||
};
|
||||
var body = new TextBlock
|
||||
{
|
||||
Text = _texts.Pick(lesson.BodyI18n, ""),
|
||||
Foreground = BodyBrush,
|
||||
FontSize = 11,
|
||||
TextWrapping = TextWrapping.Wrap
|
||||
};
|
||||
var stack = new StackPanel { Spacing = 3 };
|
||||
stack.Children.Add(title);
|
||||
stack.Children.Add(body);
|
||||
|
||||
var button = new Button
|
||||
{
|
||||
Content = stack,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
HorizontalAlignment = HorizontalAlignment.Stretch,
|
||||
HorizontalContentAlignment = HorizontalAlignment.Left,
|
||||
Padding = new Thickness(8, 9),
|
||||
Margin = new Thickness(0, 1),
|
||||
MinHeight = 44,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new BrushTransition { Property = BackgroundProperty, Duration = HoverDuration }
|
||||
}
|
||||
};
|
||||
var captured = lesson;
|
||||
button.Click += (_, _) => ApplyLesson(captured);
|
||||
button.PointerEntered += (_, _) => button.Background = new SolidColorBrush(Color.Parse("#1B2A47"));
|
||||
button.PointerExited += (_, _) => button.Background = Brushes.Transparent;
|
||||
list.Children.Add(button);
|
||||
}
|
||||
|
||||
var content = new StackPanel { Spacing = 8 };
|
||||
content.Children.Add(readouts);
|
||||
content.Children.Add(new TextBlock
|
||||
{
|
||||
Text = _texts["lessons"],
|
||||
Foreground = TitleBrush,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
FontSize = 12.5
|
||||
});
|
||||
content.Children.Add(list);
|
||||
|
||||
var bodyGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
|
||||
bodyGrid.Children.Add(header);
|
||||
var scroller = new ScrollViewer
|
||||
{
|
||||
Content = content,
|
||||
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
|
||||
Margin = new Thickness(0, 8, 0, 0)
|
||||
};
|
||||
Grid.SetRow(scroller, 1);
|
||||
bodyGrid.Children.Add(scroller);
|
||||
|
||||
var panel = new Border
|
||||
{
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
VerticalAlignment = VerticalAlignment.Stretch,
|
||||
Width = 296,
|
||||
Margin = new Thickness(0, 12, 16, 12),
|
||||
Background = new SolidColorBrush(Color.Parse("#D00B1226")),
|
||||
CornerRadius = new CornerRadius(14),
|
||||
Padding = new Thickness(13),
|
||||
BorderBrush = new SolidColorBrush(Color.Parse("#26374F")),
|
||||
BorderThickness = new Thickness(1),
|
||||
Child = bodyGrid,
|
||||
RenderTransform = new TranslateTransform(0, 0)
|
||||
};
|
||||
panel.Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition { Property = OpacityProperty, Duration = PanelDuration, Easing = new CubicEaseOut() },
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = TranslateTransform.XProperty,
|
||||
Duration = PanelDuration,
|
||||
Easing = new CubicEaseOut()
|
||||
}
|
||||
};
|
||||
return panel;
|
||||
}
|
||||
|
||||
private void SetLessonsVisible(bool visible)
|
||||
{
|
||||
_showLessons = visible;
|
||||
if (_lessons == null) return;
|
||||
|
||||
if (visible)
|
||||
{
|
||||
_lessons.IsVisible = true;
|
||||
_lessons.Opacity = 1;
|
||||
if (_lessons.RenderTransform is TranslateTransform transform) transform.X = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
_lessons.Opacity = 0;
|
||||
if (_lessons.RenderTransform is TranslateTransform hidden) hidden.X = 26;
|
||||
|
||||
var timer = new DispatcherTimer { Interval = PanelDuration };
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
if (!_showLessons && _lessons != null) _lessons.IsVisible = false;
|
||||
};
|
||||
timer.Start();
|
||||
}
|
||||
|
||||
/// <summary>课堂卡与地球特写跟随当前轨道位置刷新(播放时每 140ms 更新一次)。</summary>
|
||||
private void RefreshTeaching()
|
||||
{
|
||||
if (_cardTitle == null) return;
|
||||
var season = IsRevolution ? _canvas.NearestSeason(6) : null;
|
||||
var decl = _canvas.SubsolarLatitude;
|
||||
|
||||
_cardState!.Text = _playing ? _texts["running"] : _texts["frozen"];
|
||||
_cardState.Foreground = _playing ? MutedBrush : WarmBrush;
|
||||
_cardTitle.Text = season != null
|
||||
? _texts[season.Key]
|
||||
: (IsRevolution ? _texts["seasons"] : _texts.Pick(_runtime.Scene.NameI18n, _texts["title"]));
|
||||
_cardDate!.Text = IsRevolution ? _canvas.CurrentDate : _texts["dayNight"];
|
||||
_cardDirect!.Text = season?.DeclinationDeg.HasValue == true
|
||||
? FormatDeclination(season.DeclinationDeg.Value)
|
||||
: _canvas.DeclinationLabel;
|
||||
_cardNote!.Text = !IsRevolution
|
||||
? _texts["rotationTeach"]
|
||||
: season != null
|
||||
? _texts.Pick(season.TeachingI18n, _texts["orbitTeach"])
|
||||
: _texts["orbitTeach"];
|
||||
|
||||
// 特写的直射纬度用缓动逼近目标,而不是瞬间跳变:
|
||||
// 公转时拖动/改变轨道角,晨昏线会平滑地移过去(每次 timer 步进一帧)。
|
||||
if (_showCloseup)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
private string FormatDeclination(double d)
|
||||
=> Math.Abs(d) < 0.05
|
||||
? "0° " + _texts["lat.equator"]
|
||||
: $"{Math.Abs(d):0.0}°" + (d > 0 ? _texts["northShort"] : _texts["southShort"]);
|
||||
|
||||
private void ApplyLesson(Lesson lesson)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(lesson.View))
|
||||
{
|
||||
var view = NormalizeView(lesson.View);
|
||||
if (!string.Equals(view, CurrentView, StringComparison.OrdinalIgnoreCase)) SwitchView(view);
|
||||
}
|
||||
// 讲要点时自动定格,读数不再跳动,方便指读板书
|
||||
SetPlaying(false);
|
||||
if (lesson.AngleDeg.HasValue) _canvas.JumpToOrbit(lesson.AngleDeg.Value);
|
||||
RefreshTeaching();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 教学操作
|
||||
private void SetPlaying(bool play)
|
||||
{
|
||||
_playing = play;
|
||||
_canvas.IsPlaying = play;
|
||||
if (_playButton?.Content is TextBlock block)
|
||||
block.Text = play ? _texts["pause"] : _texts["play"];
|
||||
RefreshTeaching();
|
||||
}
|
||||
|
||||
private void TogglePlay() => SetPlaying(!_playing);
|
||||
|
||||
private void Step(double deltaDeg)
|
||||
{
|
||||
SetPlaying(false);
|
||||
if (IsRevolution) _canvas.StepOrbit(deltaDeg);
|
||||
else _canvas.StepSpin(deltaDeg);
|
||||
RefreshTeaching();
|
||||
}
|
||||
|
||||
private void JumpToSeason(SeasonPoint season)
|
||||
{
|
||||
if (!IsRevolution) SwitchView("revolution");
|
||||
SetPlaying(false);
|
||||
_canvas.JumpToOrbit(season.AngleDeg);
|
||||
RefreshTeaching();
|
||||
}
|
||||
|
||||
private void JumpToSeasonIndex(int index)
|
||||
{
|
||||
if (index < 0 || index >= Seasons.Count) return;
|
||||
JumpToSeason(Seasons[index]);
|
||||
}
|
||||
|
||||
private void ToggleFullScreen()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is Window window)
|
||||
window.WindowState = window.WindowState == WindowState.FullScreen
|
||||
? WindowState.Normal
|
||||
: WindowState.FullScreen;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_context.Log("全屏切换失败: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Space:
|
||||
TogglePlay();
|
||||
e.Handled = true;
|
||||
break;
|
||||
case Key.Left:
|
||||
Step(-5);
|
||||
e.Handled = true;
|
||||
break;
|
||||
case Key.Right:
|
||||
Step(5);
|
||||
e.Handled = true;
|
||||
break;
|
||||
case Key.D1: JumpToSeasonIndex(0); e.Handled = true; break;
|
||||
case Key.D2: JumpToSeasonIndex(1); e.Handled = true; break;
|
||||
case Key.D3: JumpToSeasonIndex(2); e.Handled = true; break;
|
||||
case Key.D4: JumpToSeasonIndex(3); e.Handled = true; break;
|
||||
case Key.F: ToggleFullScreen(); e.Handled = true; break;
|
||||
case Key.Add: _canvas.ZoomBy(1.25); e.Handled = true; break;
|
||||
case Key.Subtract: _canvas.ZoomBy(1 / 1.25); e.Handled = true; break;
|
||||
case Key.D0: _canvas.ResetView(); e.Handled = true; break;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具
|
||||
private ModelButton MakeButton(string text, Action onClick, bool large = false)
|
||||
{
|
||||
var button = new ModelButton
|
||||
{
|
||||
Content = new TextBlock { Text = text, FontSize = large ? 20 : 12.5 },
|
||||
Foreground = TextBrush,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = large ? new Thickness(10, 8) : new Thickness(13, 9),
|
||||
MinWidth = large ? 46 : 44,
|
||||
MinHeight = 40,
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
button.SetBase(ControlBg);
|
||||
button.Click += (_, _) => onClick();
|
||||
return button;
|
||||
}
|
||||
|
||||
private void ApplyVisibility()
|
||||
{
|
||||
if (_viewSwitch != null) _viewSwitch.IsVisible = HasViewSwitch;
|
||||
if (_lessons != null) _lessons.IsVisible = _showLessons;
|
||||
if (_seasonPanel != null) _seasonPanel.IsVisible = IsRevolution;
|
||||
if (_closeupHost != null) _closeupHost.IsVisible = _showCloseup;
|
||||
if (_closeupLabel != null) _closeupLabel.IsVisible = _showCloseup;
|
||||
}
|
||||
|
||||
/// <summary>带悬停过渡的按钮:本地基础色 + 悬停提亮。</summary>
|
||||
private sealed class ModelButton : Button
|
||||
{
|
||||
private IBrush _base = ControlBg;
|
||||
private IBrush _hover = ControlBg;
|
||||
|
||||
public ModelButton()
|
||||
{
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new BrushTransition { Property = BackgroundProperty, Duration = HoverDuration }
|
||||
};
|
||||
}
|
||||
|
||||
public void SetBase(IBrush brush)
|
||||
{
|
||||
_base = brush;
|
||||
_hover = Lighten(brush);
|
||||
Background = brush;
|
||||
}
|
||||
|
||||
protected override void OnPointerEntered(PointerEventArgs e)
|
||||
{
|
||||
base.OnPointerEntered(e);
|
||||
Background = _hover;
|
||||
}
|
||||
|
||||
protected override void OnPointerExited(PointerEventArgs e)
|
||||
{
|
||||
base.OnPointerExited(e);
|
||||
Background = _base;
|
||||
}
|
||||
|
||||
private static IBrush Lighten(IBrush brush)
|
||||
{
|
||||
if (brush is not SolidColorBrush solid) return brush;
|
||||
var c = solid.Color;
|
||||
return new SolidColorBrush(Color.FromArgb(c.A,
|
||||
(byte)Math.Min(255, c.R + 26),
|
||||
(byte)Math.Min(255, c.G + 26),
|
||||
(byte)Math.Min(255, c.B + 30)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using Avalonia.Controls;
|
||||
using EarthModelStudio.ModelSdk;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary>
|
||||
/// 地球模型共享运行时:读自己目录下的 scene.json / land.json / i18n,
|
||||
/// 然后把自带界面交给启动器。启动器完全不知道“地球”“节气”这些东西。
|
||||
/// </summary>
|
||||
public sealed class EarthModelRuntime : IModelRuntime
|
||||
{
|
||||
public const int SupportedApiVersion = 1;
|
||||
|
||||
private SceneRuntime? _scene;
|
||||
|
||||
/// <summary>后台准备:读场景、生成地表纹理(耗时都花在这里,进度条能实时走)。</summary>
|
||||
public void Prepare(IModelContext context)
|
||||
{
|
||||
context.ReportProgress(0.03, "读取场景数据");
|
||||
_scene = SceneRuntime.Load(context.DataDirectory, context.MemoryBudgetMb, context.ReportProgress);
|
||||
context.Log($"[{context.ModelId}] 场景已加载:{_scene.Scene.DefaultView}," +
|
||||
$"地表纹理 {(_scene.Texture == null ? "无" : _scene.Texture.Width + "×" + _scene.Texture.Height)}");
|
||||
}
|
||||
|
||||
/// <summary>UI 线程构建界面(很快)。</summary>
|
||||
public Control CreateView(IModelContext context)
|
||||
{
|
||||
context.ReportProgress(0.78, "构建界面");
|
||||
_scene ??= SceneRuntime.Load(context.DataDirectory, context.MemoryBudgetMb, context.ReportProgress);
|
||||
var view = new EarthModelView(context, _scene);
|
||||
context.ReportProgress(1.0, "准备就绪");
|
||||
return view;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放预烘焙纹理(约 3MB 托管数组)与场景引用。窗口关闭时由启动器调用,
|
||||
/// 避免 collectible ALC 里的类型被长生命周期引用拖住而无法卸载。
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_scene = null;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
@@ -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,159 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary><id>.model/land.json —— 简化的大陆轮廓(经纬度多边形)。</summary>
|
||||
public sealed class LandData
|
||||
{
|
||||
[JsonPropertyName("polygons")] public List<LandPolygon> Polygons { get; set; } = new();
|
||||
|
||||
public static LandData? Load(string path)
|
||||
{
|
||||
if (!File.Exists(path)) return null;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<LandData>(File.ReadAllText(path), ModelJson.Options);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"解析地表数据失败 {path}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class LandPolygon
|
||||
{
|
||||
[JsonPropertyName("name")] public string? Name { get; set; }
|
||||
/// <summary>[[lon, lat], ...]</summary>
|
||||
[JsonPropertyName("points")] public List<double[]> Points { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等经纬度栅格地表掩膜(0=海洋 255=陆地),双线性采样。
|
||||
/// 每个模型只生成一次,受内存预算约束。
|
||||
/// </summary>
|
||||
public sealed class LandMask
|
||||
{
|
||||
public int Width { get; init; }
|
||||
public int Height { get; init; }
|
||||
public byte[] Bits { get; init; } = Array.Empty<byte>();
|
||||
|
||||
public long ByteSize => Bits.LongLength;
|
||||
|
||||
public static LandMask Build(LandData data, int width = 1440, int height = 720)
|
||||
{
|
||||
var bits = new byte[width * height];
|
||||
foreach (var poly in data.Polygons)
|
||||
{
|
||||
if (poly.Points.Count < 3) continue;
|
||||
var pts = Unwrap(poly.Points);
|
||||
if (pts.Count < 3) continue;
|
||||
for (var shift = -1; shift <= 1; shift++)
|
||||
Rasterize(bits, width, height, pts, shift * 360.0);
|
||||
}
|
||||
return new LandMask { Width = width, Height = height, Bits = bits };
|
||||
}
|
||||
|
||||
private static List<(double Lon, double Lat)> Unwrap(List<double[]> points)
|
||||
{
|
||||
var result = new List<(double, double)>(points.Count);
|
||||
if (points.Count == 0 || points[0].Length < 2) return result;
|
||||
var prev = points[0][0];
|
||||
result.Add((prev, points[0][1]));
|
||||
for (var i = 1; i < points.Count; i++)
|
||||
{
|
||||
if (points[i].Length < 2) continue;
|
||||
var lon = points[i][0];
|
||||
while (lon - prev > 180) lon -= 360;
|
||||
while (prev - lon > 180) lon += 360;
|
||||
result.Add((lon, points[i][1]));
|
||||
prev = lon;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void Rasterize(byte[] bits, int w, int h, List<(double Lon, double Lat)> pts, double lonShift)
|
||||
{
|
||||
var n = pts.Count;
|
||||
var xs = new double[n];
|
||||
var ys = new double[n];
|
||||
double minY = double.MaxValue, maxY = double.MinValue;
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
xs[i] = (pts[i].Lon + lonShift + 180.0) / 360.0 * w;
|
||||
ys[i] = (90.0 - pts[i].Lat) / 180.0 * h;
|
||||
if (ys[i] < minY) minY = ys[i];
|
||||
if (ys[i] > maxY) maxY = ys[i];
|
||||
}
|
||||
|
||||
var y0 = Math.Max(0, (int)Math.Floor(minY));
|
||||
var y1 = Math.Min(h - 1, (int)Math.Ceiling(maxY));
|
||||
var crossings = new List<double>(16);
|
||||
|
||||
for (var y = y0; y <= y1; y++)
|
||||
{
|
||||
var sy = y + 0.5;
|
||||
crossings.Clear();
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var j = (i + 1) % n;
|
||||
double ya = ys[i], yb = ys[j];
|
||||
if (!((ya <= sy && yb > sy) || (yb <= sy && ya > sy))) continue;
|
||||
var t = (sy - ya) / (yb - ya);
|
||||
crossings.Add(xs[i] + t * (xs[j] - xs[i]));
|
||||
}
|
||||
if (crossings.Count < 2) continue;
|
||||
crossings.Sort();
|
||||
for (var k = 0; k + 1 < crossings.Count; k += 2)
|
||||
{
|
||||
var xa = (int)Math.Ceiling(crossings[k] - 0.5);
|
||||
var xb = (int)Math.Floor(crossings[k + 1] - 0.5);
|
||||
if (xb < xa) continue;
|
||||
if (xb - xa >= w - 1)
|
||||
{
|
||||
for (var x = 0; x < w; x++) bits[y * w + x] = 255;
|
||||
continue;
|
||||
}
|
||||
for (var x = xa; x <= xb; x++)
|
||||
{
|
||||
var mx = x % w;
|
||||
if (mx < 0) mx += w;
|
||||
bits[y * w + mx] = 255;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>返回 0..1 的陆地覆盖度。</summary>
|
||||
public double Sample(double lonDeg, double latDeg)
|
||||
{
|
||||
var u = (lonDeg + 180.0) / 360.0 * Width - 0.5;
|
||||
var v = (90.0 - latDeg) / 180.0 * Height - 0.5;
|
||||
var x0 = (int)Math.Floor(u);
|
||||
var y0 = (int)Math.Floor(v);
|
||||
var fx = u - x0;
|
||||
var fy = v - y0;
|
||||
double sum = 0;
|
||||
for (var dy = 0; dy < 2; dy++)
|
||||
{
|
||||
var y = y0 + dy;
|
||||
if (y < 0) y = 0;
|
||||
if (y >= Height) y = Height - 1;
|
||||
var wy = dy == 0 ? 1 - fy : fy;
|
||||
for (var dx = 0; dx < 2; dx++)
|
||||
{
|
||||
var x = x0 + dx;
|
||||
var mx = x % Width;
|
||||
if (mx < 0) mx += Width;
|
||||
var wx = dx == 0 ? 1 - fx : fx;
|
||||
sum += Bits[y * Width + mx] * wx * wy;
|
||||
}
|
||||
}
|
||||
return sum / 255.0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.IO;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary>模型自己的 JSON 读写(不依赖启动器)。</summary>
|
||||
public static class ModelJson
|
||||
{
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
AllowTrailingCommas = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip
|
||||
};
|
||||
|
||||
public static T? Read<T>(string path)
|
||||
{
|
||||
if (!File.Exists(path)) return default;
|
||||
return JsonSerializer.Deserialize<T>(File.ReadAllText(path), Options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary>
|
||||
/// 模型自己的一份文案。优先读模型数据目录里的 <c>i18n/<language>.json</c>,
|
||||
/// 缺失时回退到代码内的默认文案,保证模型在没有语言包时也能完整显示。
|
||||
/// 启动器不再持有任何模型相关文案。
|
||||
/// </summary>
|
||||
public sealed class ModelStrings
|
||||
{
|
||||
private readonly Dictionary<string, string> _texts;
|
||||
|
||||
public string Language { get; }
|
||||
|
||||
private ModelStrings(string language, Dictionary<string, string> texts)
|
||||
{
|
||||
Language = language;
|
||||
_texts = texts;
|
||||
}
|
||||
|
||||
public static ModelStrings Default { get; } = new("zh-CN", DefaultTexts.Zh);
|
||||
|
||||
public string this[string key]
|
||||
=> _texts.TryGetValue(key, out var value) ? value
|
||||
: DefaultTexts.Zh.TryGetValue(key, out var fallback) ? fallback
|
||||
: key;
|
||||
|
||||
public string F(string key, params object[] args)
|
||||
=> string.Format(CultureInfo.InvariantCulture, this[key], args);
|
||||
|
||||
public string Pick(Dictionary<string, string>? i18n, string fallback)
|
||||
{
|
||||
if (i18n == null) return fallback;
|
||||
if (i18n.TryGetValue(Language, out var exact) && !string.IsNullOrWhiteSpace(exact)) return exact;
|
||||
foreach (var pair in i18n)
|
||||
{
|
||||
if (Language.StartsWith(pair.Key, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(pair.Value))
|
||||
return pair.Value;
|
||||
}
|
||||
if (i18n.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
public static ModelStrings Load(string dataDirectory, string language)
|
||||
{
|
||||
var zh = new Dictionary<string, string>(DefaultTexts.Zh);
|
||||
var isEnglish = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
|
||||
var chosen = isEnglish ? new Dictionary<string, string>(DefaultTexts.En) : new Dictionary<string, string>(zh);
|
||||
|
||||
// 语言包可以覆盖任意键:i18n/<language>.json
|
||||
var dir = Path.Combine(dataDirectory, "i18n");
|
||||
Overlay(Path.Combine(dir, language + ".json"), chosen);
|
||||
if (!isEnglish) Overlay(Path.Combine(dir, "zh-CN.json"), chosen);
|
||||
|
||||
return new ModelStrings(isEnglish ? "en" : "zh-CN", chosen);
|
||||
}
|
||||
|
||||
private static void Overlay(string path, Dictionary<string, string> target)
|
||||
{
|
||||
if (!File.Exists(path)) return;
|
||||
try
|
||||
{
|
||||
var map = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(path), ModelJson.Options);
|
||||
if (map == null) return;
|
||||
foreach (var pair in map) target[pair.Key] = pair.Value;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取模型语言包失败 {path}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class DefaultTexts
|
||||
{
|
||||
public static readonly Dictionary<string, string> Zh = new()
|
||||
{
|
||||
["title"] = "地球模型",
|
||||
["view.rotation"] = "自转",
|
||||
["view.revolution"] = "公转",
|
||||
["play"] = "播放",
|
||||
["pause"] = "暂停",
|
||||
["speed"] = "速度",
|
||||
["reset"] = "重置",
|
||||
["labels"] = "标注",
|
||||
["orbit"] = "轨道",
|
||||
["grid"] = "经纬网",
|
||||
["tilt"] = "夸张倾角",
|
||||
["lessons"] = "教学要点",
|
||||
["seasons"] = "节气定位",
|
||||
["close"] = "关闭窗口",
|
||||
["hint"] = "双指捏合或滚轮缩放 · 拖动可转动地球",
|
||||
["shortcutHint"] = "空格 播放/暂停 · ←→ 步进 · 1–4 二分二至 · F 全屏",
|
||||
["classroom"] = "课堂演示",
|
||||
["directPoint"] = "太阳直射",
|
||||
["frozen"] = "已定格",
|
||||
["running"] = "播放中",
|
||||
["step"] = "步进",
|
||||
["closeup"] = "地球特写",
|
||||
["overhead"] = "俯视",
|
||||
["sideview"] = "侧视",
|
||||
["zoom"] = "缩放",
|
||||
["orbitTeach"] = "太阳直射点在南北回归线之间往返,形成四季更替。",
|
||||
["rotationTeach"] = "晨昏线把地球分成昼半球与夜半球;自转产生昼夜交替与地方时差。",
|
||||
["dayNight"] = "昼夜交替周期 24 小时",
|
||||
["lat.equator"] = "赤道",
|
||||
["lat.tropicN"] = "北回归线 23.5°N",
|
||||
["lat.tropicS"] = "南回归线 23.5°S",
|
||||
["lat.polarN"] = "北极圈 66.5°N",
|
||||
["lat.polarS"] = "南极圈 66.5°S",
|
||||
["loading"] = "正在准备场景…",
|
||||
["subsolar"] = "太阳直射点",
|
||||
["north"] = "北极",
|
||||
["south"] = "南极",
|
||||
["northShort"] = "N",
|
||||
["southShort"] = "S",
|
||||
["sun"] = "太阳",
|
||||
["earth"] = "地球",
|
||||
["spinInfo"] = "自转 {0}° · 周期 {1} 小时",
|
||||
["orbitInfo"] = "公转 {0}°",
|
||||
["declinationInfo"] = "太阳直射 {0}",
|
||||
["dateInfo"] = "日期 {0}",
|
||||
["season.springEquinox"] = "春分",
|
||||
["season.summerSolstice"] = "夏至",
|
||||
["season.autumnEquinox"] = "秋分",
|
||||
["season.winterSolstice"] = "冬至"
|
||||
};
|
||||
|
||||
public static readonly Dictionary<string, string> En = new()
|
||||
{
|
||||
["title"] = "Earth model",
|
||||
["view.rotation"] = "Rotation",
|
||||
["view.revolution"] = "Revolution",
|
||||
["play"] = "Play",
|
||||
["pause"] = "Pause",
|
||||
["speed"] = "Speed",
|
||||
["reset"] = "Reset",
|
||||
["labels"] = "Labels",
|
||||
["orbit"] = "Orbit",
|
||||
["grid"] = "Graticule",
|
||||
["tilt"] = "Exaggerate tilt",
|
||||
["lessons"] = "Teaching notes",
|
||||
["seasons"] = "Solstices & equinoxes",
|
||||
["close"] = "Close window",
|
||||
["hint"] = "Pinch or scroll to zoom · drag to turn the Earth",
|
||||
["shortcutHint"] = "Space play/pause · ←→ step · 1–4 solstices & equinoxes · F fullscreen",
|
||||
["classroom"] = "Classroom",
|
||||
["directPoint"] = "Subsolar",
|
||||
["frozen"] = "Frozen",
|
||||
["running"] = "Playing",
|
||||
["step"] = "Step",
|
||||
["closeup"] = "Earth close-up",
|
||||
["overhead"] = "Top view",
|
||||
["sideview"] = "Side view",
|
||||
["zoom"] = "Zoom",
|
||||
["orbitTeach"] = "The subsolar point travels between the tropics, producing the seasons.",
|
||||
["rotationTeach"] = "The terminator splits day and night; rotation drives the day–night cycle and local time.",
|
||||
["dayNight"] = "Day–night cycle: 24 h",
|
||||
["lat.equator"] = "Equator",
|
||||
["lat.tropicN"] = "Tropic of Cancer 23.5°N",
|
||||
["lat.tropicS"] = "Tropic of Capricorn 23.5°S",
|
||||
["lat.polarN"] = "Arctic Circle 66.5°N",
|
||||
["lat.polarS"] = "Antarctic Circle 66.5°S",
|
||||
["loading"] = "Preparing scene…",
|
||||
["subsolar"] = "Subsolar point",
|
||||
["north"] = "North pole",
|
||||
["south"] = "South pole",
|
||||
["northShort"] = "N",
|
||||
["southShort"] = "S",
|
||||
["sun"] = "Sun",
|
||||
["earth"] = "Earth",
|
||||
["spinInfo"] = "Rotation {0}° · period {1} h",
|
||||
["orbitInfo"] = "Orbit {0}°",
|
||||
["declinationInfo"] = "Subsolar {0}",
|
||||
["dateInfo"] = "Date {0}",
|
||||
["season.springEquinox"] = "Spring equinox",
|
||||
["season.summerSolstice"] = "Summer solstice",
|
||||
["season.autumnEquinox"] = "Autumn equinox",
|
||||
["season.winterSolstice"] = "Winter solstice"
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary><id>.model/scene.json —— 模型数据(可视化场景描述)。</summary>
|
||||
public sealed class SceneDefinition
|
||||
{
|
||||
public int SchemaVersion { get; set; } = 1;
|
||||
public string Type { get; set; } = "planet";
|
||||
/// <summary>rotation | revolution</summary>
|
||||
public string DefaultView { get; set; } = "rotation";
|
||||
/// <summary>模型支持的视图;为空表示只有 defaultView。</summary>
|
||||
public List<string> Views { get; set; } = new();
|
||||
public Dictionary<string, string>? NameI18n { get; set; }
|
||||
public Dictionary<string, string>? DescriptionI18n { get; set; }
|
||||
public StarDefinition Star { get; set; } = new();
|
||||
public PlanetDefinition Planet { get; set; } = new();
|
||||
public OrbitDefinition Orbit { get; set; } = new();
|
||||
public List<Lesson> Lessons { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class StarDefinition
|
||||
{
|
||||
public string Name { get; set; } = "Sun";
|
||||
public Dictionary<string, string>? NameI18n { get; set; }
|
||||
public string Color { get; set; } = "#FFC24B";
|
||||
/// <summary>相对行星半径的视觉倍率</summary>
|
||||
public double RadiusScale { get; set; } = 0.5;
|
||||
}
|
||||
|
||||
public sealed class PlanetDefinition
|
||||
{
|
||||
public string Name { get; set; } = "Earth";
|
||||
public Dictionary<string, string>? NameI18n { get; set; }
|
||||
/// <summary>黄赤交角:教材值 23.5°(23°26′),决定南北回归线纬度。</summary>
|
||||
public double AxialTiltDeg { get; set; } = 23.5;
|
||||
/// <summary>回归线纬度,默认与黄赤交角一致;极圈 = 90 − 回归线。</summary>
|
||||
public double TropicDeg { get; set; } = 23.5;
|
||||
public double RotationHours { get; set; } = 23.93;
|
||||
public double OrbitDays { get; set; } = 365.26;
|
||||
public string OceanColor { get; set; } = "#1B5FA8";
|
||||
public string LandColor { get; set; } = "#4F8C4C";
|
||||
public string? IceColor { get; set; } = "#E8EEF4";
|
||||
public string? LandFile { get; set; } = "land.json";
|
||||
public bool ShowGraticule { get; set; } = true;
|
||||
}
|
||||
|
||||
public sealed class OrbitDefinition
|
||||
{
|
||||
public double SemiMajorAxis { get; set; } = 4.0;
|
||||
public double Eccentricity { get; set; } = 0.0167;
|
||||
public bool Show { get; set; } = true;
|
||||
/// <summary>节气方位声明:springTopSummerLeft = 上春分 / 左夏至(引擎按此布局绘制轨道)。</summary>
|
||||
public string SeasonLayout { get; set; } = "springTopSummerLeft";
|
||||
public List<SeasonPoint> Seasons { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class SeasonPoint
|
||||
{
|
||||
/// <summary>0=春分 90=夏至 180=秋分 270=冬至</summary>
|
||||
public double AngleDeg { get; set; }
|
||||
public string Key { get; set; } = "";
|
||||
public string? Date { get; set; }
|
||||
/// <summary>该节气的太阳直射纬度:春分/秋分 0,夏至 +23.5,冬至 −23.5。</summary>
|
||||
public double? DeclinationDeg { get; set; }
|
||||
/// <summary>课堂现象说明(写在模型数据里,启动器不参与)。</summary>
|
||||
public Dictionary<string, string>? TeachingI18n { get; set; }
|
||||
}
|
||||
|
||||
public sealed class Lesson
|
||||
{
|
||||
public Dictionary<string, string>? TitleI18n { get; set; }
|
||||
public Dictionary<string, string>? BodyI18n { get; set; }
|
||||
public string? View { get; set; }
|
||||
public double? AngleDeg { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary>
|
||||
/// 模型自己的场景运行时:场景描述 + 预烘焙地表纹理 + 调色板。
|
||||
/// 数据来自模型数据目录,不依赖启动器。
|
||||
/// </summary>
|
||||
public sealed class SceneRuntime
|
||||
{
|
||||
public SceneDefinition Scene { get; init; } = new();
|
||||
public PlanetTexture? Texture { get; init; }
|
||||
public Color Ocean { get; init; } = Color.Parse("#1B5FA8");
|
||||
public Color Land { get; init; } = Color.Parse("#4F8C4C");
|
||||
public Color Ice { get; init; } = Color.Parse("#E6EDF4");
|
||||
public Color Star { get; init; } = Color.Parse("#FFC24B");
|
||||
|
||||
public long MemoryBytes => Texture?.ByteSize ?? 0;
|
||||
|
||||
public static SceneRuntime Load(string dataDirectory, int memoryBudgetMb,
|
||||
Action<double, string?>? progress = null)
|
||||
{
|
||||
progress?.Invoke(0.06, "读取场景数据");
|
||||
var scenePath = Path.Combine(dataDirectory, "scene.json");
|
||||
var scene = ModelJson.Read<SceneDefinition>(scenePath) ?? new SceneDefinition();
|
||||
|
||||
var ocean = Parse(scene.Planet.OceanColor, "#1B5FA8");
|
||||
var land = Parse(scene.Planet.LandColor, "#4F8C4C");
|
||||
var ice = Parse(scene.Planet.IceColor, "#E6EDF4");
|
||||
|
||||
LandData? landData = null;
|
||||
var landFile = scene.Planet.LandFile;
|
||||
if (!string.IsNullOrWhiteSpace(landFile))
|
||||
{
|
||||
var path = Path.IsPathRooted(landFile!) ? landFile! : Path.Combine(dataDirectory, landFile!);
|
||||
progress?.Invoke(0.12, "读取地表轮廓");
|
||||
landData = LandData.Load(path);
|
||||
}
|
||||
|
||||
// 内存预算决定纹理分辨率(1024 宽约 3 MB)
|
||||
var width = memoryBudgetMb >= 1024 ? PlanetTexture.DefaultWidth
|
||||
: memoryBudgetMb >= 512 ? 768
|
||||
: 512;
|
||||
|
||||
progress?.Invoke(0.16, "生成地表纹理");
|
||||
var texture = PlanetTexture.Build(landData, width, ocean, land, ice,
|
||||
t => progress?.Invoke(0.16 + t * 0.48, "生成地表纹理"));
|
||||
|
||||
progress?.Invoke(0.68, "场景就绪");
|
||||
return new SceneRuntime
|
||||
{
|
||||
Scene = scene,
|
||||
Texture = texture,
|
||||
Ocean = ocean,
|
||||
Land = land,
|
||||
Ice = ice,
|
||||
Star = Parse(scene.Star.Color, "#FFC24B")
|
||||
};
|
||||
}
|
||||
|
||||
private static Color Parse(string? value, string fallback)
|
||||
=> Color.TryParse(string.IsNullOrWhiteSpace(value) ? fallback : value, out var c) ? c : Color.Parse(fallback);
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary>
|
||||
/// 预烘焙的等经纬度地表贴图:反照率 + 高度 + 冰盖 + 云层 + 夜间灯光。
|
||||
/// 只在模型加载时算一次,之后每帧只做采样 —— 比逐像素跑噪声快一个数量级,
|
||||
/// 而且能画出「真实一点」的地表:海洋深度、沙漠/雨林/针叶林带、山脉阴影、极地冰盖。
|
||||
/// </summary>
|
||||
public sealed class PlanetTexture
|
||||
{
|
||||
public const int DefaultWidth = 1024;
|
||||
|
||||
public int Width { get; }
|
||||
public int Height { get; }
|
||||
|
||||
/// <summary>打包的反照率(0xRRGGBB),每像素一次双线性即可拿三通道。</summary>
|
||||
public uint[] Albedo { get; }
|
||||
/// <summary>地形高度(0=海平面,255=高山)</summary>
|
||||
public byte[] Elevation { get; }
|
||||
/// <summary>云量</summary>
|
||||
public byte[] Cloud { get; }
|
||||
/// <summary>夜间灯光</summary>
|
||||
public byte[] Lights { get; }
|
||||
/// <summary>预烘焙的地形坡度:东向 / 北向高度梯度(加载时算一次,每帧直接采样)。</summary>
|
||||
public float[] SlopeEast { get; }
|
||||
public float[] SlopeNorth { get; }
|
||||
|
||||
public long ByteSize => (long)(Albedo.Length * 4 + Elevation.Length + Cloud.Length + Lights.Length
|
||||
+ SlopeEast.Length * 4 + SlopeNorth.Length * 4);
|
||||
|
||||
private PlanetTexture(int width, int height)
|
||||
{
|
||||
Width = width;
|
||||
Height = height;
|
||||
var count = width * height;
|
||||
Albedo = new uint[count];
|
||||
Elevation = new byte[count];
|
||||
Cloud = new byte[count];
|
||||
Lights = new byte[count];
|
||||
SlopeEast = new float[count];
|
||||
SlopeNorth = new float[count];
|
||||
}
|
||||
|
||||
public static PlanetTexture Build(LandData? landData, int width, Color ocean, Color land, Color ice,
|
||||
Action<double>? progress = null)
|
||||
{
|
||||
width = Math.Clamp(width, 256, 2048);
|
||||
var height = width / 2;
|
||||
var texture = new PlanetTexture(width, height);
|
||||
|
||||
progress?.Invoke(0.08);
|
||||
var mask = landData == null ? null : LandMask.Build(landData, width, height);
|
||||
progress?.Invoke(0.28);
|
||||
|
||||
// 到海岸的距离:海里用来做深度,陆地上用来做大陆性(内陆更干)
|
||||
var landDistance = new float[width * height];
|
||||
var oceanDistance = new float[width * height];
|
||||
ComputeDistances(mask, width, height, landDistance, oceanDistance);
|
||||
progress?.Invoke(0.42);
|
||||
|
||||
Parallel.For(0, height, y =>
|
||||
{
|
||||
var lat = 90.0 - (y + 0.5) * 180.0 / height;
|
||||
var latAbs = MathF.Abs((float)lat);
|
||||
var rowBase = y * width;
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var lon = (x + 0.5) * 360.0 / width - 180.0;
|
||||
var index = rowBase + x;
|
||||
var isLand = mask == null || mask.Bits[index] > 127;
|
||||
|
||||
var elevation = Fbm(lon * 2.1, lat * 2.1, 4, 0x51A3);
|
||||
var moisture = Fbm(lon * 1.35 + 40, lat * 1.35 - 20, 3, 0x9E2B);
|
||||
var detail = Fbm(lon * 0.85, lat * 0.85, 3, 0x2C77);
|
||||
|
||||
if (isLand)
|
||||
{
|
||||
// 内陆更干,靠海更湿
|
||||
var inland = Math.Clamp(landDistance[index] / (width * 0.06f), 0f, 1f);
|
||||
var wet = Math.Clamp(moisture * 0.78f + (1f - inland) * 0.16f
|
||||
- MathF.Max(0f, latAbs - 45f) / 90f, 0f, 1f);
|
||||
|
||||
var (r, g, b) = LandPalette(latAbs, wet, inland, elevation, detail, land, ice);
|
||||
texture.Albedo[index] = Pack(r, g, b);
|
||||
texture.Elevation[index] = (byte)Math.Clamp(elevation * 235f + detail * 20f, 0, 255);
|
||||
|
||||
// 夜间灯光:沿海平原、中低纬,稀疏分布
|
||||
// 夜间灯光:低频的城市群辉光(高频点会在小尺寸球面上变成噪点)
|
||||
var cityGlow = Smooth(0.55f, 0.92f, Fbm(lon * 1.7, lat * 1.7, 3, 0x7A31));
|
||||
if (latAbs < 60 && inland < 0.55f && elevation < 0.75f)
|
||||
texture.Lights[index] = ToByte(cityGlow * 0.55f);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 海洋:按离岸距离做深浅
|
||||
var depth = Math.Clamp(oceanDistance[index] / (width * 0.09f), 0f, 1f);
|
||||
depth = (float)Math.Pow(depth, 0.65);
|
||||
var shallowR = Math.Min(1f, ocean.R / 255f + 0.16f);
|
||||
var shallowG = Math.Min(1f, ocean.G / 255f + 0.22f);
|
||||
var shallowB = Math.Min(1f, ocean.B / 255f + 0.16f);
|
||||
var deepR = ocean.R / 255f * 0.32f;
|
||||
var deepG = ocean.G / 255f * 0.40f;
|
||||
var deepB = ocean.B / 255f * 0.52f;
|
||||
var wave = (detail - 0.5f) * 0.035f;
|
||||
|
||||
texture.Albedo[index] = Pack(
|
||||
ToByte(shallowR + (deepR - shallowR) * depth + wave),
|
||||
ToByte(shallowG + (deepG - shallowG) * depth + wave),
|
||||
ToByte(shallowB + (deepB - shallowB) * depth + wave));
|
||||
texture.Elevation[index] = 0;
|
||||
}
|
||||
|
||||
// 极地冰盖:纬度 + 噪声边界,海洋也能结冰
|
||||
var iceEdge = 62f + (detail - 0.5f) * 9f;
|
||||
var iceAmt = Smooth(iceEdge - 7f, iceEdge + 6f, latAbs);
|
||||
if (iceAmt > 0.001f)
|
||||
{
|
||||
var iceR = ice.R / 255f;
|
||||
var iceG = ice.G / 255f;
|
||||
var iceB = ice.B / 255f;
|
||||
var packed = texture.Albedo[index];
|
||||
texture.Albedo[index] = Pack(
|
||||
ToByte(Lerp(((packed >> 16) & 0xFF) / 255f, iceR, iceAmt)),
|
||||
ToByte(Lerp(((packed >> 8) & 0xFF) / 255f, iceG, iceAmt)),
|
||||
ToByte(Lerp((packed & 0xFF) / 255f, iceB, iceAmt)));
|
||||
}
|
||||
|
||||
// 云:多个尺度的 fbm,赤道与中纬多云
|
||||
var cloudBase = Fbm(lon * 0.55, lat * 0.7, 3, 0x1144);
|
||||
var band = 0.5f + 0.5f * MathF.Cos(latAbs / 90f * MathF.PI * 3.1f);
|
||||
var cloud = Smooth(0.48f, 0.84f, cloudBase * 0.86f + band * 0.14f);
|
||||
texture.Cloud[index] = ToByte(cloud * 0.72f);
|
||||
}
|
||||
});
|
||||
|
||||
// 云层做一次模糊,避免小尺寸球面上采样出噪点
|
||||
Blur(texture.Cloud, width, height, 2);
|
||||
|
||||
// 预烘焙地形坡度:渲染时不必每像素再取 4 次高度
|
||||
BakeSlopes(texture, width, height);
|
||||
progress?.Invoke(0.62);
|
||||
return texture;
|
||||
}
|
||||
|
||||
private static (byte R, byte G, byte B) LandPalette(float latAbs, float wet, float inland, float elevation,
|
||||
float detail, Color landBase, Color ice)
|
||||
{
|
||||
// 基色随纬度:赤道雨林 -> 温带 -> 针叶林 -> 苔原
|
||||
float r, g, b;
|
||||
var tropical = (1f - Smooth(8f, 24f, latAbs));
|
||||
var temperate = Smooth(20f, 34f, latAbs) * (1f - Smooth(46f, 60f, latAbs));
|
||||
var boreal = Smooth(46f, 60f, latAbs) * (1f - Smooth(62f, 70f, latAbs));
|
||||
var tundra = Smooth(60f, 72f, latAbs);
|
||||
|
||||
r = 0.13f; g = 0.36f; b = 0.17f; // 温带草原绿
|
||||
r = Lerp(r, 0.10f, tropical); g = Lerp(g, 0.42f, tropical); b = Lerp(b, 0.19f, tropical);
|
||||
r = Lerp(r, 0.17f, boreal); g = Lerp(g, 0.28f, boreal); b = Lerp(b, 0.17f, boreal);
|
||||
r = Lerp(r, 0.34f, tundra); g = Lerp(g, 0.36f, tundra); b = Lerp(b, 0.31f, tundra);
|
||||
|
||||
// 湿润度:干 -> 沙漠/草原
|
||||
var dry = Math.Clamp(1f - wet * 0.95f, 0f, 1f);
|
||||
var desertBand = Math.Clamp(1f - MathF.Abs(latAbs - 24f) / 13f, 0f, 1f);
|
||||
var desert = Math.Clamp(dry * 0.72f + desertBand * 0.62f, 0f, 1f);
|
||||
r = Lerp(r, 0.72f, desert * 0.85f);
|
||||
g = Lerp(g, 0.60f, desert * 0.85f);
|
||||
b = Lerp(b, 0.38f, desert * 0.85f);
|
||||
|
||||
// 高原/山地:岩石和雪
|
||||
var rock = Smooth(0.62f, 0.86f, elevation);
|
||||
r = Lerp(r, 0.44f, rock * 0.7f);
|
||||
g = Lerp(g, 0.40f, rock * 0.7f);
|
||||
b = Lerp(b, 0.34f, rock * 0.7f);
|
||||
|
||||
var snow = Smooth(0.86f, 0.97f, elevation + (latAbs - 40f) / 220f);
|
||||
r = Lerp(r, ice.R / 255f, snow);
|
||||
g = Lerp(g, ice.G / 255f, snow);
|
||||
b = Lerp(b, ice.B / 255f, snow);
|
||||
|
||||
// 细节扰动,避免大面积纯色
|
||||
var grain = (detail - 0.5f) * 0.07f;
|
||||
var baseMix = 0.25f;
|
||||
return (
|
||||
ToByte(Math.Clamp(r + grain + (landBase.R / 255f - 0.3f) * baseMix * 0.2f, 0f, 1f)),
|
||||
ToByte(Math.Clamp(g + grain + (landBase.G / 255f - 0.45f) * baseMix * 0.2f, 0f, 1f)),
|
||||
ToByte(Math.Clamp(b + grain + (landBase.B / 255f - 0.3f) * baseMix * 0.2f, 0f, 1f)));
|
||||
}
|
||||
|
||||
/// <summary>可分离盒式模糊(原地),用于软化云层。</summary>
|
||||
private static void Blur(byte[] data, int width, int height, int radius)
|
||||
{
|
||||
var temp = new byte[data.Length];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var row = y * width;
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var sum = 0;
|
||||
var count = 0;
|
||||
for (var k = -radius; k <= radius; k++)
|
||||
{
|
||||
var sx = (x + k + width) % width;
|
||||
sum += data[row + sx];
|
||||
count++;
|
||||
}
|
||||
temp[row + x] = (byte)(sum / count);
|
||||
}
|
||||
}
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var sum = 0;
|
||||
var count = 0;
|
||||
for (var k = -radius; k <= radius; k++)
|
||||
{
|
||||
var sy = Math.Clamp(y + k, 0, height - 1);
|
||||
sum += temp[sy * width + x];
|
||||
count++;
|
||||
}
|
||||
data[y * width + x] = (byte)(sum / count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>由高度图算东西/南北梯度,供球面光照直接使用。</summary>
|
||||
private static void BakeSlopes(PlanetTexture t, int width, int height)
|
||||
{
|
||||
const float relief = 0.055f * 90f;
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var row = y * width;
|
||||
var up = Math.Max(0, y - 1) * width;
|
||||
var down = Math.Min(height - 1, y + 1) * width;
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var left = (x - 1 + width) % width;
|
||||
var right = (x + 1) % width;
|
||||
t.SlopeEast[row + x] = (t.Elevation[row + right] - t.Elevation[row + left]) / 255f * relief;
|
||||
t.SlopeNorth[row + x] = (t.Elevation[up + x] - t.Elevation[down + x]) / 255f * relief;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 距离场
|
||||
private static void ComputeDistances(LandMask? mask, int width, int height, float[] landDistance, float[] oceanDistance)
|
||||
{
|
||||
var count = width * height;
|
||||
const float big = 1e6f;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var isLand = mask != null && mask.Bits[i] > 127;
|
||||
landDistance[i] = isLand ? big : -big;
|
||||
oceanDistance[i] = isLand ? -big : big;
|
||||
}
|
||||
|
||||
// 两遍 chamfer:陆地到海洋的距离 / 海洋到陆地的距离
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var i = y * width + x;
|
||||
if (mask != null && mask.Bits[i] > 127)
|
||||
{
|
||||
var best = big;
|
||||
if (x > 0 && mask.Bits[i - 1] <= 127) best = 0.5f;
|
||||
if (x < width - 1 && mask.Bits[i + 1] <= 127) best = Math.Min(best, 0.5f);
|
||||
if (y > 0 && mask.Bits[i - width] <= 127) best = Math.Min(best, 0.5f);
|
||||
if (y < height - 1 && mask.Bits[i + width] <= 127) best = Math.Min(best, 0.5f);
|
||||
if (best < big) landDistance[i] = best;
|
||||
}
|
||||
if (mask != null && mask.Bits[i] <= 127)
|
||||
{
|
||||
var best = big;
|
||||
if (x > 0 && mask.Bits[i - 1] > 127) best = 0.5f;
|
||||
if (x < width - 1 && mask.Bits[i + 1] > 127) best = Math.Min(best, 0.5f);
|
||||
if (y > 0 && mask.Bits[i - width] > 127) best = Math.Min(best, 0.5f);
|
||||
if (y < height - 1 && mask.Bits[i + width] > 127) best = Math.Min(best, 0.5f);
|
||||
if (best < big) oceanDistance[i] = best;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 正向传递
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var i = y * width + x;
|
||||
Propagate(landDistance, i, width, height, x, y, -1, 0, 1.4142f);
|
||||
Propagate(oceanDistance, i, width, height, x, y, -1, 0, 1.4142f);
|
||||
if (x > 0)
|
||||
{
|
||||
landDistance[i] = Math.Min(landDistance[i], landDistance[i - 1] + 1f);
|
||||
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - 1] + 1f);
|
||||
}
|
||||
if (y > 0)
|
||||
{
|
||||
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width] + 1f);
|
||||
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width] + 1f);
|
||||
if (x > 0)
|
||||
{
|
||||
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width - 1] + 1.4142f);
|
||||
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width - 1] + 1.4142f);
|
||||
}
|
||||
if (x < width - 1)
|
||||
{
|
||||
landDistance[i] = Math.Min(landDistance[i], landDistance[i - width + 1] + 1.4142f);
|
||||
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i - width + 1] + 1.4142f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 反向传递
|
||||
for (var y = height - 1; y >= 0; y--)
|
||||
{
|
||||
for (var x = width - 1; x >= 0; x--)
|
||||
{
|
||||
var i = y * width + x;
|
||||
if (x < width - 1)
|
||||
{
|
||||
landDistance[i] = Math.Min(landDistance[i], landDistance[i + 1] + 1f);
|
||||
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + 1] + 1f);
|
||||
}
|
||||
if (y < height - 1)
|
||||
{
|
||||
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width] + 1f);
|
||||
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width] + 1f);
|
||||
if (x < width - 1)
|
||||
{
|
||||
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width + 1] + 1.4142f);
|
||||
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width + 1] + 1.4142f);
|
||||
}
|
||||
if (x > 0)
|
||||
{
|
||||
landDistance[i] = Math.Min(landDistance[i], landDistance[i + width - 1] + 1.4142f);
|
||||
oceanDistance[i] = Math.Min(oceanDistance[i], oceanDistance[i + width - 1] + 1.4142f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
landDistance[i] = MathF.Max(0f, landDistance[i]);
|
||||
oceanDistance[i] = MathF.Max(0f, oceanDistance[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Propagate(float[] map, int index, int width, int height, int x, int y, int dx, int dy, float w)
|
||||
{
|
||||
var nx = x + dx;
|
||||
var ny = y + dy;
|
||||
if (nx < 0 || nx >= width || ny < 0 || ny >= height) return;
|
||||
var other = ny * width + nx;
|
||||
map[index] = Math.Min(map[index], map[other] + w);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 噪声
|
||||
/// <summary>值噪声 + 分形叠加(确定性,跨平台一致)。</summary>
|
||||
public static float Fbm(double x, double y, int octaves, int seed)
|
||||
{
|
||||
var amplitude = 1.0;
|
||||
var frequency = 1.0;
|
||||
var sum = 0.0;
|
||||
var norm = 0.0;
|
||||
for (var i = 0; i < octaves; i++)
|
||||
{
|
||||
sum += amplitude * ValueNoise(x * frequency, y * frequency, seed + i * 101);
|
||||
norm += amplitude;
|
||||
amplitude *= 0.5;
|
||||
frequency *= 2.07;
|
||||
}
|
||||
return (float)(sum / norm);
|
||||
}
|
||||
|
||||
private static double ValueNoise(double x, double y, int seed)
|
||||
{
|
||||
var xi = (int)Math.Floor(x);
|
||||
var yi = (int)Math.Floor(y);
|
||||
var xf = x - xi;
|
||||
var yf = y - yi;
|
||||
var u = xf * xf * (3 - 2 * xf);
|
||||
var v = yf * yf * (3 - 2 * yf);
|
||||
var a = Hash(xi, yi, seed);
|
||||
var b = Hash(xi + 1, yi, seed);
|
||||
var c = Hash(xi, yi + 1, seed);
|
||||
var d = Hash(xi + 1, yi + 1, seed);
|
||||
return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v;
|
||||
}
|
||||
|
||||
private static double Hash(int x, int y, int seed)
|
||||
{
|
||||
var h = (uint)(x * 374761393 + y * 668265263 + seed * 1442695041);
|
||||
h = (h ^ (h >> 13)) * 1274126177u;
|
||||
h ^= h >> 16;
|
||||
return (h & 0xFFFFFF) / (double)0xFFFFFF;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 采样
|
||||
public void Sample(double lon, double lat, out float r, out float g, out float b,
|
||||
out float elevation, out float cloud, out float lights,
|
||||
out float slopeEast, out float slopeNorth)
|
||||
{
|
||||
var u = (lon + 180.0) / 360.0 * Width - 0.5;
|
||||
var v = (90.0 - lat) / 180.0 * Height - 0.5;
|
||||
|
||||
var x0 = (int)Math.Floor(u);
|
||||
var y0 = (int)Math.Floor(v);
|
||||
var fx = (float)(u - x0);
|
||||
var fy = (float)(v - y0);
|
||||
|
||||
var x1 = x0 + 1;
|
||||
var y1 = y0 + 1;
|
||||
if (x0 < 0) x0 += Width; if (x1 < 0) x1 += Width;
|
||||
if (x0 >= Width) x0 -= Width; if (x1 >= Width) x1 -= Width;
|
||||
y0 = Math.Clamp(y0, 0, Height - 1);
|
||||
y1 = Math.Clamp(y1, 0, Height - 1);
|
||||
|
||||
var i00 = y0 * Width + x0;
|
||||
var i10 = y0 * Width + x1;
|
||||
var i01 = y1 * Width + x0;
|
||||
var i11 = y1 * Width + x1;
|
||||
|
||||
float w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy), w01 = (1 - fx) * fy, w11 = fx * fy;
|
||||
|
||||
var p00 = Albedo[i00];
|
||||
var p10 = Albedo[i10];
|
||||
var p01 = Albedo[i01];
|
||||
var p11 = Albedo[i11];
|
||||
var rr = ((p00 >> 16) & 0xFF) * w00 + ((p10 >> 16) & 0xFF) * w10 + ((p01 >> 16) & 0xFF) * w01 + ((p11 >> 16) & 0xFF) * w11;
|
||||
var gg = ((p00 >> 8) & 0xFF) * w00 + ((p10 >> 8) & 0xFF) * w10 + ((p01 >> 8) & 0xFF) * w01 + ((p11 >> 8) & 0xFF) * w11;
|
||||
var bb = (p00 & 0xFF) * w00 + (p10 & 0xFF) * w10 + (p01 & 0xFF) * w01 + (p11 & 0xFF) * w11;
|
||||
r = rr / 255f;
|
||||
g = gg / 255f;
|
||||
b = bb / 255f;
|
||||
|
||||
elevation = (Elevation[i00] * w00 + Elevation[i10] * w10 + Elevation[i01] * w01 + Elevation[i11] * w11) / 255f;
|
||||
cloud = (Cloud[i00] * w00 + Cloud[i10] * w10 + Cloud[i01] * w01 + Cloud[i11] * w11) / 255f;
|
||||
lights = Lights[i00] / 255f;
|
||||
slopeEast = SlopeEast[i00] * w00 + SlopeEast[i10] * w10 + SlopeEast[i01] * w01 + SlopeEast[i11] * w11;
|
||||
slopeNorth = SlopeNorth[i00] * w00 + SlopeNorth[i10] * w10 + SlopeNorth[i01] * w01 + SlopeNorth[i11] * w11;
|
||||
}
|
||||
|
||||
/// <summary>只采样高度(法线扰动用)。</summary>
|
||||
public float SampleHeight(double lon, double lat)
|
||||
{
|
||||
var u = (lon + 180.0) / 360.0 * Width - 0.5;
|
||||
var v = (90.0 - lat) / 180.0 * Height - 0.5;
|
||||
var x = Math.Clamp((int)Math.Round(u), 0, Width - 1);
|
||||
var y = Math.Clamp((int)Math.Round(v), 0, Height - 1);
|
||||
return Elevation[y * Width + x] / 255f;
|
||||
}
|
||||
|
||||
public float SampleCloud(double lon, double lat)
|
||||
{
|
||||
var u = (lon + 180.0) / 360.0 * Width - 0.5;
|
||||
var v = (90.0 - lat) / 180.0 * Height - 0.5;
|
||||
var x = Math.Clamp((int)Math.Round(u), 0, Width - 1);
|
||||
var y = Math.Clamp((int)Math.Round(v), 0, Height - 1);
|
||||
return Cloud[y * Width + x] / 255f;
|
||||
}
|
||||
|
||||
public static byte ToByte(float v) => (byte)Math.Clamp((int)(v * 255f + 0.5f), 0, 255);
|
||||
private static uint Pack(byte r, byte g, byte b) => ((uint)r << 16) | ((uint)g << 8) | b;
|
||||
private static float Lerp(float a, float b, float t) => a + (b - a) * Math.Clamp(t, 0f, 1f);
|
||||
private static float Smooth(float edge0, float edge1, float x)
|
||||
{
|
||||
if (edge1 <= edge0) return x >= edge1 ? 1f : 0f;
|
||||
var t = Math.Clamp((x - edge0) / (edge1 - edge0), 0f, 1f);
|
||||
return t * t * (3f - 2f * t);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Media.Imaging;
|
||||
|
||||
namespace NeoRF.EarthModels;
|
||||
|
||||
/// <summary>
|
||||
/// 球体像素级渲染:正交投影 + 预烘焙地表纹理 + 地形光照 + 云层 + 夜灯 + 大气边缘光。
|
||||
/// 纯 CPU 光栅、按行并行,不依赖 GPU,三平台效果一致。
|
||||
/// </summary>
|
||||
public static unsafe class SphereRaster
|
||||
{
|
||||
/// <summary>把球体画进 WriteableBitmap(整张位图会被覆盖)。</summary>
|
||||
public static void Draw(WriteableBitmap bitmap, int size, Matrix4x4 cam, Matrix4x4 planet,
|
||||
Vector3 light, PlanetTexture texture, double cloudShift, bool showClouds)
|
||||
{
|
||||
using var framebuffer = bitmap.Lock();
|
||||
var stride = framebuffer.RowBytes / 4;
|
||||
Render((uint*)framebuffer.Address, stride, size, cam, planet, light, texture, cloudShift, showClouds);
|
||||
}
|
||||
|
||||
public static void Render(uint* dst, int stride, int size, Matrix4x4 cam, Matrix4x4 planet,
|
||||
Vector3 light, PlanetTexture texture, double cloudShift, bool showClouds)
|
||||
{
|
||||
var radius = size * 0.5f - 1.0f;
|
||||
var center = size * 0.5f;
|
||||
var inv = 1f / radius;
|
||||
|
||||
// 相机空间法线 -> 行星本地法线
|
||||
var combined = Matrix4x4.Multiply(planet, cam);
|
||||
var mt = Matrix4x4.Transpose(combined);
|
||||
float m11 = mt.M11, m12 = mt.M12, m13 = mt.M13;
|
||||
float m21 = mt.M21, m22 = mt.M22, m23 = mt.M23;
|
||||
float m31 = mt.M31, m32 = mt.M32, m33 = mt.M33;
|
||||
|
||||
var lx = light.X; var ly = light.Y; var lz = light.Z;
|
||||
|
||||
Parallel.For(0, size, y =>
|
||||
{
|
||||
var ny = (center - y - 0.5f) * inv;
|
||||
var row = dst + (long)y * stride;
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var nx = (x + 0.5f - center) * inv;
|
||||
var r2 = nx * nx + ny * ny;
|
||||
if (r2 >= 1f)
|
||||
{
|
||||
row[x] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
var nz = MathF.Sqrt(1f - r2);
|
||||
|
||||
// 本地法线(用于取经纬度)
|
||||
var ux = nx * m11 + ny * m21 + nz * m31;
|
||||
var uy = nx * m12 + ny * m22 + nz * m32;
|
||||
var uz = nx * m13 + ny * m23 + nz * m33;
|
||||
|
||||
var lat = MathF.Asin(Math.Clamp(uy, -1f, 1f)) * 57.2957795f;
|
||||
var lon = MathF.Atan2(ux, uz) * 57.2957795f;
|
||||
|
||||
var cloudLon = lon + cloudShift;
|
||||
if (cloudLon > 180) cloudLon -= 360;
|
||||
if (cloudLon < -180) cloudLon += 360;
|
||||
|
||||
texture.Sample(lon, lat, out var ar, out var ag, out var ab,
|
||||
out var elevation, out var cloud, out var lights,
|
||||
out var dEast, out var dNorth);
|
||||
|
||||
// ---- 地形法线:局部基向量可由球面法线直接推出,不必再算 6 次三角函数
|
||||
// 点 P=(cosLat·sinLon, sinLat, cosLat·cosLon) = (ux,uy,uz)
|
||||
// 东向 = (cosLon,0,-sinLon),北向 = (-sinLat·sinLon, cosLat, -sinLat·cosLon)
|
||||
var cosLat = MathF.Sqrt(MathF.Max(ux * ux + uz * uz, 1e-6f));
|
||||
var invCos = 1f / cosLat;
|
||||
var eastX = uz * invCos;
|
||||
var eastZ = -ux * invCos;
|
||||
var northX = -uy * ux * invCos;
|
||||
var northY = cosLat;
|
||||
var northZ = -uy * uz * invCos;
|
||||
|
||||
var nLocalX = ux + eastX * dEast + northX * dNorth;
|
||||
var nLocalY = uy + northY * dNorth;
|
||||
var nLocalZ = uz + eastZ * dEast + northZ * dNorth;
|
||||
var nLen = MathF.Sqrt(nLocalX * nLocalX + nLocalY * nLocalY + nLocalZ * nLocalZ);
|
||||
if (nLen > 0.0001f) { nLocalX /= nLen; nLocalY /= nLen; nLocalZ /= nLen; }
|
||||
|
||||
var nCamX = nLocalX * combined.M11 + nLocalY * combined.M21 + nLocalZ * combined.M31;
|
||||
var nCamY = nLocalX * combined.M12 + nLocalY * combined.M22 + nLocalZ * combined.M32;
|
||||
var nCamZ = nLocalX * combined.M13 + nLocalY * combined.M23 + nLocalZ * combined.M33;
|
||||
|
||||
var lam = nx * lx + ny * ly + nz * lz; // 几何光照(晨昏线)
|
||||
var bump = nCamX * lx + nCamY * ly + nCamZ * lz; // 地形光照
|
||||
var day = Smooth(-0.18f, 0.22f, lam);
|
||||
var terrainLight = 0.82f + 0.42f * MathF.Max(0f, bump - lam);
|
||||
|
||||
var shade = (0.055f + 0.945f * day) * terrainLight;
|
||||
|
||||
var br = ar * shade;
|
||||
var bg = ag * shade;
|
||||
var bb = ab * shade;
|
||||
|
||||
// 海面高光(高度为 0 视为水面)
|
||||
if (elevation < 0.02f)
|
||||
{
|
||||
var t2 = MathF.Max(0f, lam);
|
||||
var t4 = t2 * t2 * t2 * t2;
|
||||
var t8 = t4 * t4;
|
||||
var t16 = t8 * t8;
|
||||
var spec = t16 * t8 * t4 * t2 * t2 * 0.62f;
|
||||
br += spec * 0.95f;
|
||||
bg += spec * 0.98f;
|
||||
bb += spec;
|
||||
}
|
||||
|
||||
// 云层(随经度缓慢漂移)
|
||||
if (showClouds && cloud > 0.02f)
|
||||
{
|
||||
var cloudLight = 0.10f + 0.90f * day;
|
||||
var c = Math.Clamp(cloud * 0.92f, 0f, 1f);
|
||||
var cloudR = 0.98f * cloudLight;
|
||||
var cloudG = 0.985f * cloudLight;
|
||||
var cloudB = 1.0f * cloudLight;
|
||||
br += (cloudR - br) * c;
|
||||
bg += (cloudG - bg) * c;
|
||||
bb += (cloudB - bb) * c;
|
||||
}
|
||||
|
||||
// 夜间灯光
|
||||
if (lights > 0.01f)
|
||||
{
|
||||
var night = 1f - day;
|
||||
var glow = lights * night * 0.35f;
|
||||
br += glow * 0.95f;
|
||||
bg += glow * 0.72f;
|
||||
bb += glow * 0.38f;
|
||||
}
|
||||
|
||||
// 大气边缘散射
|
||||
var rim = 1f - nz;
|
||||
rim *= rim;
|
||||
var litRim = rim * MathF.Max(0f, lam) * 0.98f;
|
||||
br += 0.30f * litRim;
|
||||
bg += 0.55f * litRim;
|
||||
bb += 1.00f * litRim;
|
||||
|
||||
// 夜面极淡反照
|
||||
var nightSide = 1f - day;
|
||||
br += 0.008f * nightSide;
|
||||
bg += 0.013f * nightSide;
|
||||
bb += 0.028f * nightSide;
|
||||
|
||||
var coverage = 1f;
|
||||
var edge = (1f - MathF.Sqrt(r2)) * radius;
|
||||
if (edge < 1f) coverage = MathF.Max(0f, edge);
|
||||
|
||||
var a = (uint)(coverage * 255f);
|
||||
var r8 = (uint)(Math.Clamp(br, 0f, 1f) * 255f * coverage);
|
||||
var g8 = (uint)(Math.Clamp(bg, 0f, 1f) * 255f * coverage);
|
||||
var b8 = (uint)(Math.Clamp(bb, 0f, 1f) * 255f * coverage);
|
||||
row[x] = (a << 24) | (r8 << 16) | (g8 << 8) | b8;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static float Smooth(float edge0, float edge1, float x)
|
||||
{
|
||||
if (edge1 <= edge0) return x >= edge1 ? 1f : 0f;
|
||||
var t = Math.Clamp((x - edge0) / (edge1 - edge0), 0f, 1f);
|
||||
return t * t * (3f - 2f * t);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user