diff --git a/model/contour-map/contour-map.json b/model/contour-map/contour-map.json index 01d2950..999c526 100644 --- a/model/contour-map/contour-map.json +++ b/model/contour-map/contour-map.json @@ -5,8 +5,8 @@ "en": "Contour Map" }, "descriptionI18n": { - "zh-CN": "立体地形与平面等高线联动,判读山峰、山脊、山谷、鞍部、陡崖五种部位。", - "en": "Link 3D relief with contour lines; identify peaks, ridges, valleys, saddles and cliffs." + "zh-CN": "可旋转 3D 地形 + 等高切割/交线/投影/判坡四步动画,判读山峰、山脊、山谷、鞍部、陡崖五大典型地貌。", + "en": "Rotatable 3D terrain with a four-step animation of contour cutting, lines, projection and slope; identify five classic landforms." }, "author": "Morris GC", "tags": [ @@ -17,7 +17,7 @@ ], "assembly": "ContourMapModel.dll", "type": "GC.ContourMap.ContourMapFactory", - "version": "1.1", + "version": "1.2", "chrome": { "titleBar": "#0C1828", "titleBorder": "#1B2740", diff --git a/model/contour-map/contour-map.model/ContourMapModel.dll b/model/contour-map/contour-map.model/ContourMapModel.dll index cbdfd9e..16b4d92 100644 Binary files a/model/contour-map/contour-map.model/ContourMapModel.dll and b/model/contour-map/contour-map.model/ContourMapModel.dll differ diff --git a/model/contour-map/contour-map.model/help.json b/model/contour-map/contour-map.model/help.json index a65ec7d..4d5e963 100644 --- a/model/contour-map/contour-map.model/help.json +++ b/model/contour-map/contour-map.model/help.json @@ -1,130 +1,116 @@ { "zh-CN": { - "title": "如何使用 · 等高线地形图", + "title": "如何使用 · 等高线地形与五大典型地貌", "sections": [ { "h": "开始使用(跟着做)", "lines": [ - "第 1 步:顶部选一种地形(山地 / 盆地 / 丘陵 / 高原 / 平原),画面会换成对应的等高线图。", - "第 2 步:把鼠标移到图上任意位置,底部会显示该点的海拔、相对高度和地形部位。", - "第 3 步:观察左边的立体地形与右边的等高线图,找出同一个山峰,看它在两张图上分别长什么样。", - "第 4 步:点右下角「取消上色」,只留等高线;再点一次恢复分层设色,对比哪种更便于判读。", - "第 5 步:对着右侧的判读要点,依次在图上找出一个山峰、一条山脊、一条山谷、一处鞍部和一处陡崖。" + "第 1 步:点右下角「开始实验」,在立体地形里观察水平切面下降、交线形成、垂直投影与疏密判坡四步动画。", + "第 2 步:在立体地形上按住鼠标拖动可旋转视角,滚轮缩放;这是可交互的 3D 地形。", + "第 3 步:点画布上方「五大典型地貌」标签(山峰/山脊/山谷/鞍部/陡崖),画面换成对应的专门地形并叠加完整等高线,观察各自的等高线特征。", + "第 4 步:点底部「俯视图 / 立体图」在等高线地图与 3D 地形间切换;鼠标悬停任意位置,底部显示该点海拔与地形部位。", + "第 5 步:点「上色 / 取消上色」对比分层设色与纯等高线;点「全屏」进入全屏演示。" ] }, { - "h": "等高线是什么", + "h": "键盘快捷键", "lines": [ - "在地图上,把海拔相同的点用线连起来,这条线就叫等高线。", - "相邻两条等高线之间的高差叫等高距:本图山地、高原、盆地用 100 米,丘陵用 10 米,平原用 5 米。", - "等高线的闭合圈,数值由中心向四周递减的是山峰;四周高中间低的是盆地。", - "等高线向海拔低处凸出的是山脊(分水线);向海拔高处凸出的是山谷(集水线)。", - "两个山峰之间低下去的地方叫鞍部;等高线重叠或挤成一团的地方是陡崖。", - "等高线越密,坡度越陡;越疏,坡度越缓。", - "每 5 条等高线加粗一条叫计曲线,上面标着海拔,方便读数。" + "空格:播放 / 暂停实验。", + "数字 1 – 5:依次切换到山峰、山脊、山谷、鞍部、陡崖。" ] }, { - "h": "海拔与相对高度", + "h": "四步实验流程", "lines": [ - "海拔:地面某一点高出海平面的垂直距离。", - "相对高度:两个地点海拔的差值,也就是图上两点的落差。", - "底部读数里的「相对高度」是本图最低点到该点的高差。" + "等高切割:一个水平面从山顶向下移动,与山体在同一海拔相交。", + "形成交线:每个水平切面留下一条闭合交线,多层交线共同描述山体起伏。", + "投影成图:各高度的交线沿垂线投影到同一平面,累积成完整等高线图。", + "疏密判坡:坡度着色叠加等高线,陡处线密、缓处线疏。" ] }, { - "h": "五种地体的等高线特征", + "h": "五大典型地貌的判读", "lines": [ - "山地:海拔高、起伏大,等高线密集且数值跨度大。", - "盆地:四周高、中间低,等高线由外向内数值递减,常有河流发育。", - "丘陵:海拔不高、坡度和缓,等高线稀疏弯曲。", - "高原:海拔高而顶面平坦,等高线中部稀疏、边缘密集。", - "平原:海拔低、地面平坦,等高线很少甚至没有。" + "山峰:等高线闭合,数值由中心向四周递减(若向内降低则为洼地)。", + "山脊:等高线向海拔低处凸出(凸低为脊),脊线是分水线。", + "山谷:等高线向海拔高处凸出(凸高为谷),谷线是集水线,常发育河流。", + "鞍部:两座山峰之间相对低洼,俯视轮廓呈马鞍状收腰。", + "陡崖:等高线密集甚至重合,近乎垂直;n 条线重合时 (n−1)d ≤ ΔH < (n+1)d。" ] }, { - "h": "地图上的教科书符号", + "h": "等高线基础", "lines": [ - "分层设色:按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白),同一档内颜色完全相同。", - "山峰用 ▲ 加高程数字标注。", - "河流用蓝色线表示,沿谷底(等高线凸向高处的一侧)流。", - "陡崖用红色锯齿线表示。", - "指北针在图幅右上角,比例尺在左下角,分层设色图例在右下角。", - "地形剖面图在图幅底部:沿南北中线剖开地面,标出各点海拔,看清起伏。" + "同一条等高线上各点海拔相等;相邻等高线之间的高差叫等高距(本图 100 米)。", + "等高线越密坡越陡,越疏坡越缓。", + "每 5 条加粗一条叫计曲线,标注海拔便于读数。", + "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。" ] }, { - "h": "容易出错的地方", + "h": "地图符号", "lines": [ - "把「等高线密集 = 陡」记反:密集是陡,稀疏是缓。", - "把山脊和山谷看反:看凸出的方向 —— 凸向低处是山脊,凸向高处是山谷。", - "忽视等高距:等高距变了,同样的等高线密度代表的坡度就不同。", - "把计曲线当成普通等高线:计曲线加粗并标了数值,读高程要看它。" + "分层设色按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白)。", + "山峰用 ▲ 加高程数字标注;河流用蓝色线沿谷底绘制;陡崖用红色锯齿线表示。", + "指北针在图幅右上,比例尺在左下,分层设色图例在右下,地形剖面图在底部。" ] } ] }, "en": { - "title": "How to use · Contour Map", + "title": "How to use · Contour Lines & Five Landforms", "sections": [ { "h": "Getting started (follow along)", "lines": [ - "Step 1: pick a terrain type at the top (mountains / basin / hills / plateau / plain) — the map switches to its contour map.", - "Step 2: move the pointer anywhere on the map; the footer shows elevation, relative height and the terrain feature.", - "Step 3: compare the 3D block on the left with the contour map on the right — find the same peak in both.", - "Step 4: click “No colour” at the bottom right to keep only the contour lines; click again to restore the colour fill.", - "Step 5: using the panel on the right, find one peak, one ridge, one valley, one saddle and one cliff." + "Step 1: press Start to watch the four-step animation — contour cutting, line formation, vertical projection and slope reading.", + "Step 2: drag with the mouse to rotate the 3D terrain, scroll to zoom; it is fully interactive.", + "Step 3: click a landform tab above the canvas (peak / ridge / valley / saddle / cliff) to load its dedicated terrain with its full contour pattern.", + "Step 4: toggle Top view / 3D view at the bottom; hover anywhere to read elevation and terrain feature.", + "Step 5: use Colour / No colour to compare hypsometric tint with pure contour lines; use Fullscreen for presentation." ] }, { - "h": "What contour lines are", + "h": "Keyboard shortcuts", "lines": [ - "Connect points of equal elevation on a map and you get a contour line.", - "The height gap between neighbouring contours is the contour interval: 100 m for mountains, plateau and basin; 10 m for hills; 5 m for plain.", - "A closed loop whose values decrease outward is a peak; high ground around a low centre is a basin.", - "Contours bulging toward lower ground form a ridge (watershed); bulging toward higher ground form a valley (drainage).", - "The low ground between two peaks is a saddle; overlapping or tightly crowded contours mark a cliff.", - "The closer the contours, the steeper the slope; the wider apart, the gentler.", - "Every 5th contour is bolded as an index contour and labelled with its elevation." + "Space: play / pause the experiment.", + "Numbers 1 – 5: switch to peak, ridge, valley, saddle, cliff." ] }, { - "h": "Elevation and relative height", + "h": "The four experiment steps", "lines": [ - "Elevation is the vertical height of a point above sea level.", - "Relative height is the difference between two elevations — the drop between two points on the map.", - "The relative height in the footer is measured from the lowest point of this map." + "Contour cutting: a horizontal plane descends from the summit and intersects the mountain at one elevation.", + "Forming lines: each slice leaves a closed intersection line; stacked lines describe the relief.", + "Projection: intersection lines are projected vertically onto one plane, building the contour map.", + "Slope density: slope shading over contours — dense lines mean steep, sparse lines mean gentle." ] }, { - "h": "Contour patterns of the five terrains", + "h": "Reading the five landforms", "lines": [ - "Mountains: high elevation, large relief, dense contours over a wide value range.", - "Basin: high rim, low centre; values decrease inward, often with a river.", - "Hills: low elevation, gentle slopes, sparse winding contours.", - "Plateau: high but flat on top — contours sparse in the middle and crowded at the edges.", - "Plain: low and flat — few or no contour lines at all." + "Peak: closed contours, values decrease outward (if they decrease inward it is a depression).", + "Ridge: contours bulge toward lower ground; a watershed line.", + "Valley: contours bulge toward higher ground; a drainage line, often a stream.", + "Saddle: low ground between two peaks, pinched like a saddle in plan view.", + "Cliff: contours crowd or overlap, nearly vertical; n overlapping lines: (n−1)d ≤ ΔH < (n+1)d." ] }, { - "h": "Textbook map symbols", + "h": "Contour basics", "lines": [ - "Hypsometric tint: fixed colour bands by elevation (dark green → light green → green → pale yellow → yellow → light brown → brown → white); each band is a flat colour.", - "Peaks are marked with a ▲ and their elevation.", - "Rivers are drawn in blue along the valley floor (where contours bulge uphill).", - "Cliffs are marked with a red saw-tooth line.", - "A north arrow sits top-right, a scale bar bottom-left, and the tint legend bottom-right.", - "The terrain profile along the bottom cuts the ground open and labels elevations, showing the relief at a glance." + "All points on one contour share the same elevation; the gap between neighbours is the contour interval (100 m here).", + "Closer contours mean steeper slopes; wider spacing means gentler slopes.", + "Every 5th contour is bolded as an index contour and labelled with elevation.", + "Elevation is height above sea level; relative height is the difference between two elevations." ] }, { - "h": "Common mistakes", + "h": "Map symbols", "lines": [ - "Reversing dense and sparse: dense means steep, sparse means gentle.", - "Mixing up ridge and valley — look which way the bulge points: toward lower ground is a ridge, toward higher ground is a valley.", - "Ignoring the contour interval: change it and the same spacing means a different slope.", - "Treating index contours as ordinary ones — they are bold and labelled, so read elevations off them." + "Hypsometric tint uses fixed colour bands (dark green → light green → green → pale yellow → yellow → light brown → brown → white).", + "Peaks are marked with ▲ plus elevation; rivers are blue lines along valleys; cliffs use a red saw-tooth line.", + "North arrow top-right, scale bar bottom-left, tint legend bottom-right, terrain profile along the bottom." ] } ] diff --git a/model/contour-map/contour-map.model/i18n/en.json b/model/contour-map/contour-map.model/i18n/en.json index 1b403ad..c0ed82b 100644 --- a/model/contour-map/contour-map.model/i18n/en.json +++ b/model/contour-map/contour-map.model/i18n/en.json @@ -1,4 +1,4 @@ { - "app.title": "Contour Map", - "app.subtitle": "Grade 7 · Reading terrain maps: from 3D relief to contour lines" + "app.title": "Contour Lines · Five Classic Landforms", + "app.subtitle": "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs" } diff --git a/model/contour-map/contour-map.model/i18n/zh-CN.json b/model/contour-map/contour-map.model/i18n/zh-CN.json index d3c5625..8f9bcb7 100644 --- a/model/contour-map/contour-map.model/i18n/zh-CN.json +++ b/model/contour-map/contour-map.model/i18n/zh-CN.json @@ -1,4 +1,4 @@ { - "app.title": "等高线地形图", - "app.subtitle": "七年级上册 · 地形图的判读:从立体地形到平面等高线" + "app.title": "等高线地形 · 五大典型地貌判读", + "app.subtitle": "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖" } diff --git a/model/contour-map/contour-map.model/preview.png b/model/contour-map/contour-map.model/preview.png index 9303b4c..669d090 100644 Binary files a/model/contour-map/contour-map.model/preview.png and b/model/contour-map/contour-map.model/preview.png differ diff --git a/model/contour-map/src/ContourMapRuntime.cs b/model/contour-map/src/ContourMapRuntime.cs index 5e3f620..ba2cef9 100644 --- a/model/contour-map/src/ContourMapRuntime.cs +++ b/model/contour-map/src/ContourMapRuntime.cs @@ -24,6 +24,7 @@ public sealed class ContourMapRuntime : IModelRuntime { private TerrainField? _field; private Dictionary? _texts; + private ContourPage? _page; public void Prepare(IModelContext context) { @@ -41,22 +42,55 @@ public sealed class ContourMapRuntime : IModelRuntime public Control CreateView(IModelContext context) { _texts ??= LoadTexts(context.DataDirectory, context.Language); - // 五种地体都在界面里现场生成(切换很快,不必预先生成全部) - return new ContourPage(_texts).Build(); + // 实验地形 + 五大地貌都在界面里现场生成(切换很快,不必预先生成全部) + _page = new ContourPage(_texts); + return _page.Build(); } public void Dispose() { + _page?.Dispose(); + _page = null; _field = null; _texts = null; System.GC.SuppressFinalize(this); } + /// + /// 文案 = 内置默认(保证任何语言都有词)+ dataDir/i18n/<lang>.json 覆盖。 + /// 语言包缺失或某条没翻译时自动退回内置默认,不会露出裸 key。 + /// private static Dictionary LoadTexts(string dataDir, string language) { - var map = new Dictionary(DefaultTexts.Zh); var isEn = language.StartsWith("en", StringComparison.OrdinalIgnoreCase); + var map = new Dictionary(DefaultTexts.Zh); if (isEn) foreach (var kv in DefaultTexts.En) map[kv.Key] = kv.Value; + + var candidates = new List(); + if (!string.IsNullOrWhiteSpace(language)) candidates.Add(language); + candidates.Add(isEn ? "en" : "zh-CN"); + + foreach (var lang in candidates) + { + var path = System.IO.Path.Combine(dataDir, "i18n", lang + ".json"); + if (!System.IO.File.Exists(path)) continue; + try + { + using var doc = System.Text.Json.JsonDocument.Parse(System.IO.File.ReadAllText(path)); + if (doc.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) continue; + foreach (var p in doc.RootElement.EnumerateObject()) + { + if (p.Value.ValueKind != System.Text.Json.JsonValueKind.String) continue; + var v = p.Value.GetString(); + if (!string.IsNullOrWhiteSpace(v)) map[p.Name] = v!; + } + break; + } + catch + { + // 语言包损坏不影响开课,继续用内置默认 + } + } return map; } } diff --git a/model/contour-map/src/ContourPage.cs b/model/contour-map/src/ContourPage.cs index d11ac42..0a921a7 100644 --- a/model/contour-map/src/ContourPage.cs +++ b/model/contour-map/src/ContourPage.cs @@ -2,16 +2,22 @@ using System; using System.Collections.Generic; using Avalonia; using Avalonia.Controls; +using Avalonia.Input; using Avalonia.Layout; using Avalonia.Media; namespace GC.ContourMap; -/// 等高线模型的界面:顶部标题、中间双图联动、右侧判读要点、底部实时读数。 +/// +/// 等高线模型界面(完整复刻 HTML 课件功能): +/// 顶部标题 + 全屏;左侧可交互 3D 画布;右侧实验流程/五大地貌/判读要点观察面板; +/// 底部播放控制、俯视切换、上色开关、实时读数;支持键盘 1-5 / 空格快捷键。 +/// public sealed class ContourPage { private static readonly Color CAppBg = Color.Parse("#0B1524"); private static readonly Color CPanel = Color.Parse("#101E31"); + private static readonly Color CPanel2 = Color.Parse("#16263C"); private static readonly Color CLine = Color.Parse("#1E3350"); private static readonly Color CInk = Color.Parse("#EAF2FF"); private static readonly Color CInkDim = Color.Parse("#93A8C6"); @@ -20,37 +26,61 @@ public sealed class ContourPage private static readonly Color CWarn = Color.Parse("#FFB454"); private static readonly Color CGood = Color.Parse("#5FD69B"); - private TerrainField _field; private readonly Dictionary _texts; - private readonly Dictionary _cache = new(); - private Border? _colorBtn; - private TextBlock? _colorBtnText; - private TerrainKind _kind = TerrainKind.Mountain; + private readonly Dictionary _landformCache = new(); + private TerrainField _experimentField; + private ContourView? _view; private TextBlock? _readout; private TextBlock? _featureText; + private TextBlock? _hintText; + private TextBlock? _playLabel; + private TextBlock? _observeHeading; + private TextBlock? _observeSummary; + private StackPanel? _featureList; + private TextBlock? _viewToggleLabel; + + private readonly List _flowButtons = new(); + private readonly List _landformButtons = new(); + private Border? _playBtn; + private Border? _backBtn; + private Border? _colorBtn; + private TextBlock? _colorBtnText; + private ProgressBar? _progress; + + private int _step = 0; + private LandformKind? _selectedLandform; + private bool _disposed; + private TopLevel? _topLevel; + + private static readonly LandformKind[] LandformOrder = + { LandformKind.Peak, LandformKind.Ridge, LandformKind.Valley, LandformKind.Saddle, LandformKind.Cliff }; public ContourPage(Dictionary texts) { _texts = texts; - _field = GetField(TerrainKind.Mountain); - } - - /// 取(并缓存)某类地体的高度场,切换时不重复计算。 - private TerrainField GetField(TerrainKind kind) - { - if (!_cache.TryGetValue(kind, out var f)) - { - f = new TerrainField(kind, 192); - _cache[kind] = f; - } - return f; + _experimentField = new TerrainField(TerrainKind.Mountain, 192); } private string T(string key) => _texts.TryGetValue(key, out var v) ? v : key; - + private string T(string key, params object[] args) + { + var s = T(key); + try { return string.Format(System.Globalization.CultureInfo.InvariantCulture, s, args); } + catch { return s; } + } private static SolidColorBrush B(Color c) => new(c); + private TerrainField GetLandformField(LandformKind kind) + { + if (!_landformCache.TryGetValue(kind, out var f)) + { + f = new TerrainField(kind, 192); + _landformCache[kind] = f; + } + return f; + } + public Control Build() { var root = new Grid { Background = B(CAppBg) }; @@ -60,12 +90,18 @@ public sealed class ContourPage root.Children.Add(BuildHeader()); - var body = new Grid { Margin = new Thickness(14, 8, 14, 6) }; + var body = new Grid { Margin = new Thickness(12, 8, 12, 6) }; body.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star)); - body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(288))); + body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(344))); + body.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); + body.RowDefinitions.Add(new RowDefinition(GridLength.Star)); - _view = new ContourView(_field, T); + _view = new ContourView(_experimentField, T); _view.HoverChanged += OnHover; + _view.StepChanged += OnStepChanged; + _view.ProgressChanged += OnProgressChanged; + _view.PlaybackFinished += OnPlaybackFinished; + var canvasHolder = new Border { Background = B(Color.Parse("#08111E")), @@ -75,66 +111,103 @@ public sealed class ContourPage ClipToBounds = true, Child = _view }; - Grid.SetColumn(canvasHolder, 0); + Grid.SetRow(canvasHolder, 1); body.Children.Add(canvasHolder); + // ── 五大典型地貌标签(横向,像课件的选项卡)── + var tabs = new WrapPanel + { + Orientation = Orientation.Horizontal, + Margin = new Thickness(0, 0, 0, 8) + }; + _backBtn = MakePillButton(T("btn.backExperiment"), CAccent); + _backBtn.IsVisible = false; + _backBtn.PointerPressed += (_, _) => BackToExperiment(); + tabs.Children.Add(_backBtn); + foreach (var kind in LandformOrder) + { + var btn = MakeLandformButton(kind); + _landformButtons.Add(btn); + tabs.Children.Add(btn); + } + body.Children.Add(tabs); + var side = BuildSidePanel(); Grid.SetColumn(side, 1); + Grid.SetRow(side, 0); + Grid.SetRowSpan(side, 2); body.Children.Add(side); + // 窄窗口(封面缩略图、小屏)隐藏右侧栏,画布优先;宽窗口才展示流程与观察面板 + void ApplyResponsive(double width) + { + var narrow = width < 980; + side.IsVisible = !narrow; + body.ColumnDefinitions[1].Width = narrow ? new GridLength(0) : new GridLength(344); + } + root.SizeChanged += (_, e) => ApplyResponsive(e.NewSize.Width); + Grid.SetRow(body, 1); root.Children.Add(body); - root.Children.Add(BuildFooter()); - Grid.SetRow(root.Children[^1], 2); + var footer = BuildFooter(); + Grid.SetRow(footer, 2); + root.Children.Add(footer); + + root.AttachedToVisualTree += (_, _) => + { + _topLevel = TopLevel.GetTopLevel(root); + }; + root.KeyDown += OnKeyDown; + root.Focusable = true; return root; } + /// 窗口关闭时释放视图计时器,避免持有控件。 + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _view?.DisposeView(); + } + private Control BuildHeader() { var title = new TextBlock { Text = T("app.title"), Foreground = B(CInk), - FontSize = 16, + FontSize = 18, FontWeight = FontWeight.SemiBold }; var sub = new TextBlock { Text = T("app.subtitle"), - Foreground = B(CInkFaint), - FontSize = 10.5 + Foreground = B(CInkDim), + FontSize = 11.5 }; var stack = new StackPanel { Spacing = 2 }; stack.Children.Add(title); stack.Children.Add(sub); - // 地体类型选择:教科书里的五种基本地形 - var kinds = new (TerrainKind Kind, string Key)[] + var fsLabel = new TextBlock { Text = T("btn.fullscreen"), Foreground = B(CInk), FontSize = 11.5 }; + var fsBtn = new Border { - (TerrainKind.Mountain, "kind.mountain"), - (TerrainKind.Basin, "kind.basin"), - (TerrainKind.Hill, "kind.hill"), - (TerrainKind.Plateau, "kind.plateau"), - (TerrainKind.Plain, "kind.plain"), + Background = B(CPanel2), + BorderBrush = B(CLine), + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(8), + Padding = new Thickness(12, 6), + Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), + Child = fsLabel }; + fsBtn.PointerPressed += (_, _) => ToggleFullscreen(fsLabel); - var tabs = new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 6, - Margin = new Thickness(0, 9, 0, 0) - }; - foreach (var (kind, key) in kinds) - { - var btn = MakeKindTab(kind, T(key)); - tabs.Children.Add(btn); - } - - var header = new StackPanel(); - header.Children.Add(stack); - header.Children.Add(tabs); + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; + grid.Children.Add(stack); + Grid.SetColumn(fsBtn, 1); + grid.Children.Add(fsBtn); return new Border { @@ -142,70 +215,49 @@ public sealed class ContourPage BorderBrush = B(CLine), BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(18, 11, 18, 12), - Child = header + Child = grid }; } - /// 地体类型按钮:选中高亮。 - private Button MakeKindTab(TerrainKind kind, string label) - { - var b = new Button - { - Content = label, - FontSize = 11.5, - Padding = new Thickness(13, 5), - CornerRadius = new CornerRadius(8), - BorderThickness = new Thickness(1), - Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), - Tag = kind - }; - - void Style() - { - var on = _kind == kind; - b.Background = B(on ? CAccent : Color.Parse("#16263C")); - b.BorderBrush = B(on ? CAccent : Color.Parse("#263A56")); - b.Foreground = B(on ? Colors.White : CInkDim); - } - Style(); - - b.Click += (_, _) => - { - _kind = kind; - _field = GetField(kind); - _view?.SetField(_field); - // 重新刷新所有 tab 的选中态 - if (b.Parent is StackPanel sp) - foreach (var c in sp.Children) - if (c is Button sib && sib.Tag is TerrainKind) - { - var on = (TerrainKind)sib.Tag == _kind; - sib.Background = B(on ? CAccent : Color.Parse("#16263C")); - sib.BorderBrush = B(on ? CAccent : Color.Parse("#263A56")); - sib.Foreground = B(on ? Colors.White : CInkDim); - } - }; - return b; - } - private Control BuildSidePanel() { - var panel = new StackPanel { Spacing = 10, Margin = new Thickness(12, 0, 0, 0) }; + var panel = new StackPanel { Spacing = 8, Margin = new Thickness(12, 0, 0, 0) }; - panel.Children.Add(Section(T("side.features"))); - - foreach (var (titleKey, descKey) in new[] - { - ("feature.peak", "feature.peakDesc"), - ("feature.ridge", "feature.ridgeDesc"), - ("feature.valley", "feature.valleyDesc"), - ("feature.saddle", "feature.saddleDesc"), - ("feature.cliff", "feature.cliffDesc") - }) + // ── 实验流程四步 ── + panel.Children.Add(Section(T("flow.title"))); + for (var i = 0; i < 4; i++) { - panel.Children.Add(FeatureRow(T(titleKey), T(descKey))); + var btn = MakeFlowButton(i); + _flowButtons.Add(btn); + panel.Children.Add(btn); } + panel.Children.Add(Divider()); + + // ── 观察面板 ── + _observeHeading = new TextBlock + { + Text = T("observe.title"), + Foreground = B(CWarn), + FontSize = 12.5, + FontWeight = FontWeight.SemiBold + }; + _observeSummary = new TextBlock + { + Text = T("observe.default"), + Foreground = B(CInkDim), + FontSize = 10.5, + TextWrapping = TextWrapping.Wrap, + LineHeight = 16 + }; + _featureList = new StackPanel { Spacing = 3 }; + RenderObservation(null); + + panel.Children.Add(_observeHeading); + panel.Children.Add(_observeSummary); + panel.Children.Add(_featureList); + + // ── 判读要点 ── panel.Children.Add(Section(T("side.rules"))); panel.Children.Add(Bullet(T("rule.interval"))); panel.Children.Add(Bullet(T("rule.dense"))); @@ -228,55 +280,221 @@ public sealed class ContourPage return scroll; } - private Control Section(string text) => new TextBlock + private Border MakeFlowButton(int index) { - Text = text, - Foreground = B(CInkDim), - FontSize = 11.5, - FontWeight = FontWeight.SemiBold, - Margin = new Thickness(0, 4, 0, 0) - }; - - private Control Bullet(string text) => new TextBlock - { - Text = "• " + text, - Foreground = B(CInkDim), - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - LineHeight = 17 - }; - - private Control FeatureRow(string name, string desc) - { - var title = new TextBlock + var name = new TextBlock { - Text = name, - Foreground = B(CWarn), - FontSize = 12, + Text = $"{index + 1}. {T("flow.step." + index)}", + Foreground = B(CInk), + FontSize = 12.5, FontWeight = FontWeight.SemiBold }; - var d = new TextBlock + var desc = new TextBlock { - Text = desc, + Text = T("flow.desc." + index), Foreground = B(CInkFaint), - FontSize = 10.5, + FontSize = 11, TextWrapping = TextWrapping.Wrap, - LineHeight = 16 + LineHeight = 15 }; var stack = new StackPanel { Spacing = 1 }; - stack.Children.Add(title); - stack.Children.Add(d); - return stack; + stack.Children.Add(name); + stack.Children.Add(desc); + var border = new Border + { + Background = B(CPanel2), + BorderBrush = B(CLine), + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(8), + Padding = new Thickness(9, 6), + Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), + Child = stack, + Tag = index + }; + border.PointerPressed += (_, _) => + { + BackToExperiment(); + _view?.SetStep((ExperimentStep)index); + UpdateFlowStyles(); + }; + return border; + } + + private Border MakeLandformButton(LandformKind kind) + { + var key = kind.ToString().ToLowerInvariant(); + var name = new TextBlock + { + Text = T("landform." + key), + Foreground = B(CInk), + FontSize = 12.5, + FontWeight = FontWeight.SemiBold + }; + var sub = new TextBlock + { + Text = T("landform." + key + ".sub"), + Foreground = B(CInkFaint), + FontSize = 10.5, + VerticalAlignment = VerticalAlignment.Center + }; + var stack = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 7 }; + stack.Children.Add(name); + stack.Children.Add(sub); + var border = new Border + { + Background = B(CPanel2), + BorderBrush = B(CLine), + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(18), + Padding = new Thickness(14, 7), + Margin = new Thickness(0, 0, 8, 4), + Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), + Child = stack, + Tag = kind + }; + border.PointerPressed += (_, _) => SelectLandform(kind); + return border; + } + + private void SelectLandform(LandformKind kind) + { + _selectedLandform = kind; + _view?.Pause(); + _view?.SetField(GetLandformField(kind)); + _view?.SetMode(ViewMode.Perspective); + _view?.ShowContourPattern(); // 地貌专题先看完整的等高线形态 + UpdateLandformStyles(); + UpdateViewToggleLabel(); + + var key = kind.ToString().ToLowerInvariant(); + if (_observeHeading != null) _observeHeading.Text = T("landform." + key) + " · " + T("landform." + key + ".sub"); + if (_observeSummary != null) _observeSummary.Text = T("landform." + key + ".summary"); + RenderFeatureList(key); + if (_backBtn != null) _backBtn.IsVisible = true; + if (_hintText != null) _hintText.Text = T("landform." + key + ".hint"); + SetPlayLabel(T("btn.replay")); + } + + private void BackToExperiment() + { + if (_selectedLandform == null) return; + _selectedLandform = null; + _view?.SetField(_experimentField); + _view?.SetMode(ViewMode.Perspective); + _view?.Reset(); + UpdateLandformStyles(); + UpdateViewToggleLabel(); + RenderObservation(null); + if (_backBtn != null) _backBtn.IsVisible = false; + if (_hintText != null) _hintText.Text = T("hint.play"); + SetPlayLabel(T("btn.play")); + } + + private void RenderObservation(LandformKind? kind) + { + if (_observeHeading == null || _observeSummary == null || _featureList == null) return; + if (kind == null) + { + _observeHeading.Text = T("observe.title"); + _observeSummary.Text = T("observe.default"); + _featureList.Children.Clear(); + _featureList.Children.Add(Bullet(T("observe.default.f1"))); + _featureList.Children.Add(Bullet(T("observe.default.f2"))); + } + else + { + var key = kind.Value.ToString().ToLowerInvariant(); + _observeHeading.Text = T("landform." + key) + " · " + T("landform." + key + ".sub"); + _observeSummary.Text = T("landform." + key + ".summary"); + RenderFeatureList(key); + } + } + + private void RenderFeatureList(string key) + { + if (_featureList == null) return; + _featureList.Children.Clear(); + for (var i = 1; i <= 3; i++) + { + var k = $"landform.{key}.f{i}"; + if (_texts.ContainsKey(k)) _featureList.Children.Add(Bullet(T(k))); + } } private Control BuildFooter() { - _readout = new TextBlock + // 播放 / 重置 + _playLabel = new TextBlock { Text = T("btn.play"), Foreground = B(Colors.White), FontSize = 11.5, FontWeight = FontWeight.SemiBold }; + _playBtn = new Border { - Text = T("footer.hint"), - Foreground = B(CInkDim), - FontSize = 11.5 + Background = B(CAccent), + CornerRadius = new CornerRadius(8), + Padding = new Thickness(14, 7), + Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), + Child = _playLabel }; + _playBtn.PointerPressed += (_, _) => TogglePlay(); + + var resetBtn = MakePillButton(T("btn.reset"), Color.Parse("#2A3B55")); + resetBtn.PointerPressed += (_, _) => + { + BackToExperiment(); + _view?.Reset(); + if (_progress != null) _progress.Value = 0; + if (_hintText != null) _hintText.Text = T("hint.play"); + SetPlayLabel(T("btn.play")); + }; + + // 俯视 / 立体切换 + _viewToggleLabel = new TextBlock { Text = T("btn.viewTop"), Foreground = B(CInk), FontSize = 11.5 }; + var viewBtn = new Border + { + Background = B(CPanel2), + BorderBrush = B(CLine), + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(8), + Padding = new Thickness(11, 6), + Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), + Child = _viewToggleLabel + }; + viewBtn.PointerPressed += (_, _) => + { + _view?.ToggleMode(); + UpdateViewToggleLabel(); + }; + + // 上色开关 + _colorBtnText = new TextBlock { Text = T("btn.colorOn"), Foreground = B(Colors.White), FontSize = 11.5 }; + _colorBtn = new Border + { + Background = B(CAccent), + CornerRadius = new CornerRadius(8), + Padding = new Thickness(11, 6), + Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), + Child = _colorBtnText + }; + _colorBtn.PointerPressed += (_, _) => ToggleColor(); + + var controls = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; + controls.Children.Add(_playBtn); + controls.Children.Add(resetBtn); + controls.Children.Add(viewBtn); + controls.Children.Add(_colorBtn); + + _progress = new ProgressBar + { + Minimum = 0, + Maximum = 100, + Value = 0, + Height = 4, + VerticalAlignment = VerticalAlignment.Center, + Foreground = B(CAccent), + Background = B(Color.Parse("#1E3350")) + }; + + _hintText = new TextBlock { Text = T("hint.play"), Foreground = B(CInkDim), FontSize = 11.5 }; + + _readout = new TextBlock { Text = T("footer.hint"), Foreground = B(CInk), FontSize = 11.5 }; _featureText = new TextBlock { Text = "", @@ -286,64 +504,115 @@ public sealed class ContourPage HorizontalAlignment = HorizontalAlignment.Right }; - // 右下角「上色」开关:点击一次去掉分层设色,只显示线稿,再点恢复 - _colorBtnText = new TextBlock - { - Text = T("btn.color"), - FontSize = 11.5, - Foreground = B(Colors.White) - }; - _colorBtn = new Border - { - Background = B(CAccent), - CornerRadius = new CornerRadius(8), - Padding = new Thickness(13, 6), - Margin = new Thickness(0, 0, 12, 0), - Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), - Child = _colorBtnText - }; - _colorBtn.PointerPressed += (_, _) => ToggleColor(); + var info = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; + info.Children.Add(_readout); + Grid.SetColumn(_featureText, 1); + info.Children.Add(_featureText); - var left = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; - left.Children.Add(_readout); - Grid.SetColumn(_colorBtn, 1); - left.Children.Add(_colorBtn); + var leftStack = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center }; + leftStack.Children.Add(_hintText); + leftStack.Children.Add(info); + + var progStack = new StackPanel { Spacing = 6, VerticalAlignment = VerticalAlignment.Center }; + progStack.Children.Add(leftStack); + progStack.Children.Add(_progress); var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; - row.Children.Add(left); - Grid.SetColumn(_featureText, 1); - row.Children.Add(_featureText); + row.Children.Add(progStack); + Grid.SetColumn(controls, 1); + row.Children.Add(controls); return new Border { Background = B(CPanel), BorderBrush = B(CLine), BorderThickness = new Thickness(0, 1, 0, 0), - Padding = new Thickness(18, 9), + Padding = new Thickness(16, 9), Child = row }; } - /// 切换分层设色。 + private void TogglePlay() + { + if (_view == null) return; + if (_selectedLandform != null) BackToExperiment(); + _view.TogglePlay(); + SetPlayLabel(_view.IsPlaying ? T("btn.pause") : T("btn.play")); + if (_hintText != null) + _hintText.Text = _view.IsPlaying ? T("hint.playing") : T("hint.paused"); + } + private void ToggleColor() { if (_view == null) return; _view.Colored = !_view.Colored; - if (_colorBtn != null) - _colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55")); - if (_colorBtnText != null) - _colorBtnText.Text = _view.Colored ? T("btn.colorOn") : T("btn.color"); + if (_colorBtn != null) _colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55")); + if (_colorBtnText != null) _colorBtnText.Text = _view.Colored ? T("btn.colorOn") : T("btn.color"); + } + + private void SetPlayLabel(string text) { if (_playLabel != null) _playLabel.Text = text; } + + private void UpdateViewToggleLabel() + { + if (_viewToggleLabel == null || _view == null) return; + _viewToggleLabel.Text = _view.Mode == ViewMode.Top ? T("btn.view3d") : T("btn.viewTop"); + } + + private void UpdateFlowStyles() + { + for (var i = 0; i < _flowButtons.Count; i++) + { + var b = _flowButtons[i]; + var active = i == _step && _selectedLandform == null; + var done = i < _step && _selectedLandform == null; + StylePill(b, active ? CAccent : done ? Color.Parse("#1C3A5E") : CPanel2, + active ? Colors.White : done ? CGood : CInkDim); + } + } + + private void UpdateLandformStyles() + { + for (var i = 0; i < _landformButtons.Count; i++) + { + var b = _landformButtons[i]; + var kind = LandformOrder[i]; + var active = _selectedLandform == kind; + StylePill(b, active ? CAccent : CPanel2, active ? Colors.White : CInkDim); + } + } + + private static void StylePill(Border b, Color bg, Color fg) + { + b.Background = B(bg); + if (b.Child is TextBlock tb) tb.Foreground = B(fg); + else if (b.Child is StackPanel sp) + foreach (var c in sp.Children) + if (c is TextBlock t) t.Foreground = B(fg); + } + + private void OnStepChanged(ExperimentStep step) + { + _step = (int)step; + UpdateFlowStyles(); + if (_selectedLandform == null && _observeSummary != null) + _observeSummary.Text = T("flow.desc." + _step); + } + + private void OnProgressChanged(ExperimentStep step, double value) + => _progress?.Value = value * 100; + + private void OnPlaybackFinished() + { + SetPlayLabel(T("btn.replay")); + if (_hintText != null) _hintText.Text = T("hint.done"); } private void OnHover(double u, double v, float height, TerrainFeature feature) { if (_readout == null || _featureText == null) return; - - var relative = height - _field.MinHeight; - _readout.Text = string.Format( - System.Globalization.CultureInfo.InvariantCulture, - T("footer.readout"), (int)height, (int)relative); - + var field = _view?.Field ?? _experimentField; + var relative = height - field.MinHeight; + _readout.Text = T("footer.readout", (int)height, (int)relative); _featureText.Text = FeatureName(feature); _featureText.Foreground = B(feature switch { @@ -366,4 +635,87 @@ public sealed class ContourPage TerrainFeature.Slope => T("feature.slope"), _ => "" }; + + private void OnKeyDown(object? sender, KeyEventArgs e) + { + // 空格:播放/暂停 + if (e.Key == Key.Space) + { + e.Handled = true; + TogglePlay(); + return; + } + // 1-5:切换五大地貌 + var idx = -1; + switch (e.Key) + { + case Key.D1: case Key.NumPad1: idx = 0; break; + case Key.D2: case Key.NumPad2: idx = 1; break; + case Key.D3: case Key.NumPad3: idx = 2; break; + case Key.D4: case Key.NumPad4: idx = 3; break; + case Key.D5: case Key.NumPad5: idx = 4; break; + } + if (idx >= 0 && idx < LandformOrder.Length) + { + e.Handled = true; + SelectLandform(LandformOrder[idx]); + } + } + + private void ToggleFullscreen(TextBlock label) + { + if (_topLevel is not Window window) return; + if (window.WindowState == WindowState.FullScreen) + { + window.WindowState = WindowState.Normal; + label.Text = T("btn.fullscreen"); + } + else + { + window.WindowState = WindowState.FullScreen; + label.Text = T("btn.exitFullscreen"); + } + } + + // ── 控件工厂 + + private static TextBlock Section(string text) => new() + { + Text = text, + Foreground = BConst(CInk), + FontSize = 12.5, + FontWeight = FontWeight.SemiBold, + Margin = new Thickness(0, 2, 0, 2) + }; + + private static Border Divider() => new() + { + Height = 1, + Background = BConst(CLine), + Margin = new Thickness(0, 4, 0, 2) + }; + + private static TextBlock Bullet(string text) => new() + { + Text = "• " + text, + Foreground = BConst(CInkDim), + FontSize = 11.5, + TextWrapping = TextWrapping.Wrap, + LineHeight = 17 + }; + + private Border MakePillButton(string label, Color bg) + { + var tb = new TextBlock { Text = label, Foreground = B(Colors.White), FontSize = 11.5, HorizontalAlignment = HorizontalAlignment.Center }; + return new Border + { + Background = B(bg), + CornerRadius = new CornerRadius(8), + Padding = new Thickness(11, 6), + Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand), + Child = tb + }; + } + + private static SolidColorBrush BConst(Color c) => new(c); } diff --git a/model/contour-map/src/ContourView.cs b/model/contour-map/src/ContourView.cs index 03601d7..23f0c04 100644 --- a/model/contour-map/src/ContourView.cs +++ b/model/contour-map/src/ContourView.cs @@ -4,91 +4,105 @@ using System.Globalization; using System.Linq; using Avalonia; using Avalonia.Controls; +using Avalonia.Input; using Avalonia.Media; +using Avalonia.Threading; namespace GC.ContourMap; +/// 观察视角:立体(可旋转)或俯视(等高线图)。 +public enum ViewMode +{ + Perspective, + Top +} + +/// 实验流程的四个步骤,对应 HTML 课件的四条流程线。 +public enum ExperimentStep +{ + Cutting = 0, // 等高切割:水平面下降与山体相交 + Lines = 1, // 形成交线:多层交线共同描述起伏 + Projection = 2, // 投影成图:交线垂直投影到同一平面 + Density = 3 // 疏密判坡:等高线疏密反映坡度陡缓 +} + /// -/// 等高线教学画布,左右两块: -/// · 左:三维地形块(斜视图),表现真实起伏 -/// · 右:等高线俯视图(分层设色 + 等高线 + 标注) +/// 等高线教学画布(可交互 3D 版)。 /// -/// 鼠标在任一侧移动,两侧同步显示该点的海拔与地形部位 —— 这正是课本 -/// 「把立体地形转成平面等高线图」的关键对应关系。 +/// · 立体视角:软件光栅化的三维地形,鼠标拖拽旋转、滚轮缩放; +/// 水平切面沿高度下降 → 交线形成 → 垂直投影 → 疏密判坡,四步动画完整复刻 HTML 课件。 +/// · 俯视视角:分层设色等高线图 + 山峰/河流/陡崖符号 + 剖面图 + 图例/比例尺/指北针。 +/// · 两视角鼠标悬停同步显示海拔与地形部位。 /// public sealed class ContourView : Control { - // ── 配色(与启动器深色舞台一致) + // ── 配色 private static readonly Color CInk = Color.Parse("#111A2E"); private static readonly Color CLine = Color.Parse("#DCE7F8"); private static readonly Color CContour = Color.Parse("#3B2A18"); private static readonly Color CContourIndex = Color.Parse("#1F1508"); private static readonly Color CAccent = Color.Parse("#2F6BFF"); - private static readonly Color CWarn = Color.Parse("#FF6B4A"); + private static readonly Color CCutting = Color.Parse("#1FD1E8"); + private static readonly Color CProjection = Color.Parse("#7C5CFF"); private static readonly Typeface Font = new("Noto Sans CJK SC, Microsoft YaHei, Arial"); public TerrainField Field { get; private set; } - /// 切换到另一块地形(重新提取等高线)。 - public void SetField(TerrainField field) - { - Field = field; - _levels = Field.ContourLevels(); - _contours.Clear(); - foreach (var lv in _levels) - _contours.Add((lv, Field.ExtractContour(lv))); - InvalidateVisual(); - } - - /// 等高线缓存:level -> 折线集合。 private readonly List<(float Level, List> Lines)> _contours = new(); private List _levels = new(); public Func T { get; set; } = k => k; - // ── 交互状态 + // ── 相机 + private double _yawDeg = 34.0; + private double _pitchDeg = 36.0; + private double _zoom = 1.0; + private double _camS = 1, _camCx = 0, _camCy = 0; // UpdateCamera 算出的屏幕变换 + private bool _dragging; + private Point _lastPointer; + + // ── 交互 / 显示状态 private double _hoverU = 0.5, _hoverV = 0.5; private bool _hasHover; private Point _pointerPosition; - private HoverRegion _hoverRegion; - - private enum HoverRegion - { - None, - Terrain, - ContourMap - } - private bool _showContours = true; private bool _showLabels = true; - private bool _showSlope = true; private bool _colored = true; - public bool ShowContours + // ── 实验动画状态 + private ExperimentStep _step = ExperimentStep.Cutting; + private double _anim = 0.0; // 当前步骤内进度 0..1 + private bool _playing; + private DispatcherTimer? _timer; + private bool _disposed; + + // 供悬停命中测试的投影四边形(屏幕坐标 + 对应 u/v) + private readonly List<(Point P0, Point P1, Point P2, Point P3, double U, double V)> _hitQuads = new(); + + // 面片着色画刷缓存:每帧 5000 个面如果都 new 一个 brush,光分配就吃掉大半帧时间 + private readonly Dictionary _brushCache = new(); + + private SolidColorBrush ShadeBrush(int r, int g, int b) { - get => _showContours; - set => SetFlag(ref _showContours, value); + r = Math.Clamp(r / 4 * 4, 0, 252); + g = Math.Clamp(g / 4 * 4, 0, 252); + b = Math.Clamp(b / 4 * 4, 0, 252); + var key = (r << 16) | (g << 8) | b; + if (_brushCache.TryGetValue(key, out var brush)) return brush; + brush = new SolidColorBrush(Color.FromRgb((byte)r, (byte)g, (byte)b)); + _brushCache[key] = brush; + return brush; } - public bool ShowLabels - { - get => _showLabels; - set => SetFlag(ref _showLabels, value); - } + public bool ShowContours { get => _showContours; set => SetFlag(ref _showContours, value); } + public bool ShowLabels { get => _showLabels; set => SetFlag(ref _showLabels, value); } + public bool Colored { get => _colored; set => SetFlag(ref _colored, value); } - public bool ShowSlope - { - get => _showSlope; - set => SetFlag(ref _showSlope, value); - } - - /// 是否分层设色(关闭后只看线稿,便于观察等高线本身)。 - public bool Colored - { - get => _colored; - set => SetFlag(ref _colored, value); - } + public ViewMode Mode { get; private set; } = ViewMode.Perspective; + public ExperimentStep Step => _step; + public bool IsPlaying => _playing; + public double AnimationProgress => _anim; private void SetFlag(ref bool slot, bool value) { @@ -97,25 +111,210 @@ public sealed class ContourView : Control InvalidateVisual(); } - /// 当前悬停点信息,供外部状态栏显示。 + /// 当前悬停点信息。 public event Action? HoverChanged; + /// 步骤切换(供界面同步流程条与文案)。 + public event Action? StepChanged; + /// 播放进度变化(0..1,供界面显示进度条)。 + public event Action? ProgressChanged; + /// 整套动画播放完成。 + public event Action? PlaybackFinished; public ContourView(TerrainField field, Func text) { Field = field; T = text; ClipToBounds = true; + RebuildContours(); + _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(28), DispatcherPriority.Render, OnTick); + } + + /// 释放计时器,避免其持有控件导致模型窗口无法卸载。 + public void DisposeView() + { + if (_disposed) return; + _disposed = true; + if (_timer != null) + { + _timer.Stop(); + _timer.Tick -= OnTick; + _timer = null; + } + } + + private void RebuildContours() + { _levels = Field.ContourLevels(); + _contours.Clear(); foreach (var lv in _levels) _contours.Add((lv, Field.ExtractContour(lv))); + } - PointerMoved += (_, e) => + /// 切换到另一块地形(重新提取等高线)。 + public void SetField(TerrainField field) + { + Field = field; + RebuildContours(); + InvalidateVisual(); + } + + public void SetMode(ViewMode mode) + { + if (Mode == mode) return; + Mode = mode; + InvalidateVisual(); + } + + public void ToggleMode() => SetMode(Mode == ViewMode.Top ? ViewMode.Perspective : ViewMode.Top); + + public void SetStep(ExperimentStep step) + { + _step = step; + _anim = 0; + StepChanged?.Invoke(_step); + ProgressChanged?.Invoke(_step, _anim); + InvalidateVisual(); + } + + /// 播放/暂停切换。默认从当前步骤继续。 + public void TogglePlay() + { + if (_playing) Pause(); + else Play(); + } + + public void Play() + { + if (_playing) return; + // 已经播到最后一帧时再按播放,从头开始,避免“点了没反应” + if (_step == ExperimentStep.Density && _anim >= 1.0) { - var p = e.GetPosition(this); - UpdateHover(p); - }; - PointerExited += (_, _) => ClearHover(); + _step = ExperimentStep.Cutting; + _anim = 0; + StepChanged?.Invoke(_step); + } + _playing = true; + _timer?.Start(); + InvalidateVisual(); + } + + public void Pause() + { + if (!_playing) return; + _playing = false; + _timer?.Stop(); + InvalidateVisual(); + } + + /// 从头播放整套流程。 + public void PlayFromStart() + { + _step = ExperimentStep.Cutting; + _anim = 0; + StepChanged?.Invoke(_step); + Play(); + } + + /// 直接展示完整等高线(地貌专题用):停在“形成交线”步骤的终点,不切平山体。 + public void ShowContourPattern() + { + _playing = false; + _timer?.Stop(); + _step = ExperimentStep.Lines; + _anim = 1.0; + StepChanged?.Invoke(_step); + ProgressChanged?.Invoke(_step, _anim); + InvalidateVisual(); + } + + public void Reset() + { + Pause(); + _step = ExperimentStep.Cutting; + _anim = 0; + StepChanged?.Invoke(_step); + ProgressChanged?.Invoke(_step, _anim); + InvalidateVisual(); + } + + private void OnTick(object? sender, EventArgs e) + { + if (!_playing || _disposed) return; + _anim += 0.0105; // 每步约 2.7 秒 + if (_anim >= 1.0) + { + _anim = 0; + var next = (int)_step + 1; + if (next > 3) + { + _playing = false; + _timer?.Stop(); + _anim = 1; + ProgressChanged?.Invoke(_step, _anim); + PlaybackFinished?.Invoke(); + InvalidateVisual(); + return; + } + _step = (ExperimentStep)next; + StepChanged?.Invoke(_step); + } + ProgressChanged?.Invoke(_step, _anim); + InvalidateVisual(); + } + + // ---------------------------------------------------------------- 交互 + protected override void OnPointerPressed(PointerPressedEventArgs e) + { + base.OnPointerPressed(e); + if (Mode != ViewMode.Perspective) return; + if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; + _lastPointer = e.GetPosition(this); + _dragging = true; + e.Pointer.Capture(this); + } + + protected override void OnPointerMoved(PointerEventArgs e) + { + base.OnPointerMoved(e); + var p = e.GetPosition(this); + + if (_dragging && Mode == ViewMode.Perspective) + { + var dx = p.X - _lastPointer.X; + var dy = p.Y - _lastPointer.Y; + _lastPointer = p; + _yawDeg += dx * 0.45; + _pitchDeg = Math.Clamp(_pitchDeg + dy * 0.35, 12, 88); + InvalidateVisual(); + return; + } + + UpdateHover(p); + } + + protected override void OnPointerReleased(PointerReleasedEventArgs e) + { + base.OnPointerReleased(e); + if (!_dragging) return; + _dragging = false; + e.Pointer.Capture(null); + } + + protected override void OnPointerWheelChanged(PointerWheelEventArgs e) + { + base.OnPointerWheelChanged(e); + _zoom = Math.Clamp(_zoom * (1 + e.Delta.Y * 0.12), 0.55, 2.4); + e.Handled = true; + InvalidateVisual(); + } + + protected override void OnPointerExited(PointerEventArgs e) + { + base.OnPointerExited(e); + if (!_hasHover) return; + _hasHover = false; + InvalidateVisual(); } private void UpdateHover(Point p) @@ -123,200 +322,577 @@ public sealed class ContourView : Control var size = Bounds.Size; if (size.Width < 40 || size.Height < 40) return; - var (left, right) = SplitRects(size); - var map = ContourMapRect(right); double u = -1, v = -1; - var region = HoverRegion.None; - - if (map.Contains(p)) + if (Mode == ViewMode.Top) { - u = (p.X - map.X) / map.Width; - v = (p.Y - map.Y) / map.Height; - region = HoverRegion.ContourMap; + var map = TopMapRect(size); + if (map.Contains(p)) + { + u = (p.X - map.X) / map.Width; + v = (p.Y - map.Y) / map.Height; + } } - else if (left.Contains(p)) + else { - // 左图是斜视图,做逆变换近似:把点击位置反投到 u/v - (u, v) = UnprojectIso(left, p); - region = HoverRegion.Terrain; + // 在已渲染的投影四边形中命中测试,旋转后依然准确 + for (var i = _hitQuads.Count - 1; i >= 0; i--) + { + var q = _hitQuads[i]; + if (InQuad(p, q.P0, q.P1, q.P2, q.P3)) + { + u = q.U; v = q.V; + break; + } + } } - if (region == HoverRegion.None || u < 0 || u > 1 || v < 0 || v > 1) + if (u < 0 || u > 1 || v < 0 || v > 1) { - ClearHover(); + if (_hasHover) { _hasHover = false; InvalidateVisual(); } return; } + _hoverU = u; _hoverV = v; _hasHover = true; _pointerPosition = p; - _hoverRegion = region; - var h = Field.SampleSmooth(u, v); var f = TerrainAnalyzer.Classify(Field, u, v); HoverChanged?.Invoke(u, v, h, f); InvalidateVisual(); } - private void ClearHover() - { - if (!_hasHover) return; - _hasHover = false; - _hoverRegion = HoverRegion.None; - InvalidateVisual(); - } + private static bool InQuad(Point p, Point a, Point b, Point c, Point d) + => InTri(p, a, b, c) || InTri(p, a, c, d); - private (Rect Left, Rect Right) SplitRects(Size size) + private static bool InTri(Point p, Point a, Point b, Point c) { - var pad = 16.0; - var half = (size.Width - pad * 3) / 2; - var h = size.Height - pad * 2; - return (new Rect(pad, pad, half, h), - new Rect(pad * 2 + half, pad, half, h)); - } - - private static Rect ContourMapRect(Rect panel) - { - var profileHeight = Math.Min(132, panel.Height * 0.30); - return profileHeight > 50 - ? new Rect(panel.X, panel.Y, panel.Width, panel.Height - profileHeight) - : panel; + double Sign(Point p1, Point p2, Point p3) + => (p1.X - p3.X) * (p2.Y - p3.Y) - (p2.X - p3.X) * (p1.Y - p3.Y); + var d1 = Sign(p, a, b); + var d2 = Sign(p, b, c); + var d3 = Sign(p, c, a); + var neg = d1 < 0 || d2 < 0 || d3 < 0; + var pos = d1 > 0 || d2 > 0 || d3 > 0; + return !(neg && pos); } // ---------------------------------------------------------------- 渲染 - public override void Render(DrawingContext dc) { var size = Bounds.Size; if (size.Width < 80 || size.Height < 80) return; - dc.FillRectangle(new SolidColorBrush(Color.Parse("#0B1524")), new Rect(size)); - var (left, right) = SplitRects(size); - DrawIsoTerrain(dc, left); - DrawContourMap(dc, right); + if (Mode == ViewMode.Top) RenderTop(dc, size); + else RenderPerspective(dc, size); } - // ---- 左侧:三维地形块 ---- - private void DrawIsoTerrain(DrawingContext dc, Rect r) + // ================================================================ 立体视角 + + /// 把归一化地形坐标投影到屏幕,并给出深度(越大越靠近观察者)。 + private (Point Screen, double Depth) Project(double u, double v, double h, Size size) { - // 斜投影:x 向右,y 向前(缩小),高度向上 - var cx = r.X + r.Width * 0.5; - var cy = r.Y + r.Height * 0.62; - var scaleX = r.Width * 0.62; - var scaleY = r.Height * 0.30; - var heightScale = r.Height * 0.00011; // 高度压缩系数 + var (x1, sy3, depth) = RotateProject(u, v, h); + return (new Point(_camCx + x1 * _camS, _camCy + sy3 * _camS), depth); + } - Point Project(double u, double v, double h) => new( - cx + (u - 0.5) * scaleX, - cy + (v - 0.5) * scaleY - h * heightScale); + /// 绕竖轴旋转 + 俯仰,得到未缩放的屏幕横坐标与纵坐标。 + private (double X, double Y, double Depth) RotateProject(double u, double v, double h) + { + var wx = (u - 0.5) * 2.0; + var wy = (v - 0.5) * 2.0; + var span = Math.Max(1f, Field.MaxHeight - Field.MinHeight); + var wz = (h - Field.MinHeight) / span * 1.15; // 垂直夸张,凸显起伏 - // 逐格绘制(远到近,保证遮挡顺序正确) - const int N = 54; - for (var j = 0; j < N; j++) + var yaw = _yawDeg * Math.PI / 180.0; + var pitch = _pitchDeg * Math.PI / 180.0; + var x1 = wx * Math.Cos(yaw) - wy * Math.Sin(yaw); + var y1 = wx * Math.Sin(yaw) + wy * Math.Cos(yaw); + var sy3 = y1 * Math.Sin(pitch) - wz * Math.Cos(pitch); + var depth = y1 * Math.Cos(pitch) + wz * Math.Sin(pitch); + return (x1, sy3, depth); + } + + /// + /// 自动取景:把地形包围盒(八个角点)投影后缩放到画布内并居中。 + /// 这样无论旋转到哪个角度、换哪种地形,山体都铺满画面而不是缩在一角。 + /// + private void UpdateCamera(Size size) + { + double minX = double.MaxValue, maxX = double.MinValue; + double minY = double.MaxValue, maxY = double.MinValue; + foreach (var h in new[] { (double)Field.MinHeight, Field.MaxHeight }) + foreach (var u in new[] { 0.0, 1.0 }) + foreach (var v in new[] { 0.0, 1.0 }) { - for (var i = 0; i < N; i++) + var (x, y, _) = RotateProject(u, v, h); + if (x < minX) minX = x; if (x > maxX) maxX = x; + if (y < minY) minY = y; if (y > maxY) maxY = y; + } + + var w = Math.Max(1e-6, maxX - minX); + var hgt = Math.Max(1e-6, maxY - minY); + var s = Math.Min(size.Width * 0.90 / w, size.Height * 0.90 / hgt) * _zoom; + _camS = s; + _camCx = size.Width / 2 - (minX + maxX) / 2 * s; + _camCy = size.Height / 2 - (minY + maxY) / 2 * s; + } + + private void RenderPerspective(DrawingContext dc, Size size) + { + _hitQuads.Clear(); + UpdateCamera(size); + + // 切割步骤:水平面以上的山体被削去(h' = min(h, 切面高度)), + // 看到的是真实截面,而不是一张悬在半空的半透明板。 + var cutLevel = CurrentCutLevel; + var cutting = _step == ExperimentStep.Cutting; + var ceiling = cutting ? cutLevel : float.MaxValue; + + // 先画底座与四周侧壁,山体才有“厚度”,边缘不会悬空 + DrawBasePlate(dc, size); + DrawSkirt(dc, size, ceiling); + + // 采样地形四边形,按深度从远到近绘制(画家算法) + const int N = 62; + var quads = new List<(Point P0, Point P1, Point P2, Point P3, double Depth, double H, double U, double V, + double GX, double GY)>(); + for (var j = 0; j < N; j++) + for (var i = 0; i < N; i++) + { + var u0 = (double)i / N; var u1 = (double)(i + 1) / N; + var v0 = (double)j / N; var v1 = (double)(j + 1) / N; + var h00 = Field.SampleSmooth(u0, v0); + var h10 = Field.SampleSmooth(u1, v0); + var h11 = Field.SampleSmooth(u1, v1); + var h01 = Field.SampleSmooth(u0, v1); + if (cutting) { - var u0 = (double)i / N; var u1 = (double)(i + 1) / N; - var v0 = (double)j / N; var v1 = (double)(j + 1) / N; + h00 = Math.Min(h00, cutLevel); h10 = Math.Min(h10, cutLevel); + h11 = Math.Min(h11, cutLevel); h01 = Math.Min(h01, cutLevel); + } + var p00 = Project(u0, v0, h00, size).Screen; + var p10 = Project(u1, v0, h10, size).Screen; + var p11 = Project(u1, v1, h11, size).Screen; + var p01 = Project(u0, v1, h01, size).Screen; + var d = (Project(u0, v0, h00, size).Depth + Project(u1, v0, h10, size).Depth + + Project(u1, v1, h11, size).Depth + Project(u0, v1, h01, size).Depth) / 4.0; + var hAvg = (h00 + h10 + h11 + h01) / 4f; + // 坡度方向(用于光照):h11 在东南角,所以 dx 向东、dy 向南 + var gx = ((h10 + h11) - (h00 + h01)) * 0.5; + var gy = ((h01 + h11) - (h00 + h10)) * 0.5; + quads.Add((p00, p10, p11, p01, d, hAvg, (u0 + u1) / 2, (v0 + v1) / 2, gx, gy)); + } + quads.Sort((a, b) => a.Depth.CompareTo(b.Depth)); - var h00 = Field.SampleSmooth(u0, v0); - var h10 = Field.SampleSmooth(u1, v0); - var h11 = Field.SampleSmooth(u1, v1); - var h01 = Field.SampleSmooth(u0, v1); - var hAvg = (h00 + h10 + h11 + h01) / 4f; + var span = Math.Max(1f, Field.MaxHeight - Field.MinHeight); + foreach (var q in quads) + { + var (cr, cg, cb) = Colored + ? TerrainAnalyzer.ColorForHeightSmooth((float)q.H) + : (0xF3, 0xF0, 0xE6); - var (cr, cg, cb) = TerrainAnalyzer.ColorForHeight(hAvg, Field.MinHeight, Field.MaxHeight); - // 简易光照:面向西北的坡面更亮 - var shade = 0.78 + 0.42 * ((h00 - h11) / Math.Max(1f, Field.MaxHeight - Field.MinHeight) * -1 + 0.5); - shade = Math.Clamp(shade, 0.55, 1.25); + // 法线光照(西北主光 + 天顶补光):坡面朝向决定明暗,山体才有立体感 + var nx = -q.GX / span * 2.2; + var ny = -q.GY / span * 2.2; + var nl = Math.Sqrt(nx * nx + ny * ny + 1.0); + var lit = (nx * -0.55 + ny * -0.42 + 0.72) / nl; + var shade = 0.80 + 0.26 * Math.Clamp(lit, 0, 1) + 0.08 * ((q.H - Field.MinHeight) / span - 0.5); + shade = Math.Clamp(shade, 0.60, 1.10); + var brush = ShadeBrush( + (int)Math.Clamp(cr * shade, 0, 255), + (int)Math.Clamp(cg * shade, 0, 255), + (int)Math.Clamp(cb * shade, 0, 255)); - var brush = new SolidColorBrush(Color.FromRgb( - (byte)Math.Clamp(cr * shade, 0, 255), - (byte)Math.Clamp(cg * shade, 0, 255), - (byte)Math.Clamp(cb * shade, 0, 255))); + FillQuad(dc, brush, q.P0, q.P1, q.P2, q.P3); + _hitQuads.Add((q.P0, q.P1, q.P2, q.P3, q.U, q.V)); + } - var p00 = Project(u0, v0, h00); - var p10 = Project(u1, v0, h10); - var p11 = Project(u1, v1, h11); - var p01 = Project(u0, v1, h01); + // 四步实验可视化(叠加在地形上) + switch (_step) + { + case ExperimentStep.Cutting: DrawCutting(dc, size); break; + case ExperimentStep.Lines: DrawStackedLines(dc, size); break; + case ExperimentStep.Projection: DrawProjection(dc, size); break; + case ExperimentStep.Density: DrawDensity3D(dc, size); break; + } + + // 山峰 / 河流符号(3D 投影) + DrawSymbols3D(dc, size); + + // 悬停标记 + if (_hasHover) + { + var h = Field.SampleSmooth(_hoverU, _hoverV); + var at = Project(_hoverU, _hoverV, h, size).Screen; + dc.DrawEllipse(new SolidColorBrush(Colors.White), new Pen(new SolidColorBrush(CAccent), 2), at, 5, 5); + var stem = new Point(at.X, at.Y + 26); + dc.DrawLine(new Pen(new SolidColorBrush(CAccent), 1.5), at, stem); + Text(dc, $"{(int)h} m", stem.X, stem.Y + 2, 11.5, Colors.White, true, TextAlignment.Center); + } + + DrawStepBadge(dc, size); + } + + private static void FillQuad(DrawingContext dc, IBrush brush, Point a, Point b, Point c, Point d) + { + var geo = new StreamGeometry(); + using (var g = geo.Open()) + { + g.BeginFigure(a, true); + g.LineTo(b); g.LineTo(c); g.LineTo(d); + g.EndFigure(true); + } + // 同色描边:相邻四边形之间不会露出背景色缝(否则整片山体像罩了一层网格) + dc.DrawGeometry(brush, new Pen(brush, 1.0), geo); + } + + /// 给地形四周补一圈裙边(垂直侧壁),避免山体边缘悬空、露出底座缝隙。 + private void DrawSkirt(DrawingContext dc, Size size, float ceiling) + { + float Top(double u, double v) => Math.Min(Field.SampleSmooth(u, v), ceiling); + var rock = new SolidColorBrush(Color.Parse("#5A6B4A")); + var dark = new SolidColorBrush(Color.Parse("#3C4A34")); + const int N = 24; + for (var i = 0; i < N; i++) + { + var t0 = (double)i / N; var t1 = (double)(i + 1) / N; + // 南、北两条边 + foreach (var v in new[] { 1.0, 0.0 }) + { + var top0 = Project(t0, v, Top(t0, v), size).Screen; + var top1 = Project(t1, v, Top(t1, v), size).Screen; + var bot0 = Project(t0, v, Field.MinHeight - 1, size).Screen; + var bot1 = Project(t1, v, Field.MinHeight - 1, size).Screen; + FillQuad(dc, v > 0.5 ? rock : dark, top0, top1, bot1, bot0); + } + // 东、西两条边 + foreach (var u in new[] { 0.0, 1.0 }) + { + var top0 = Project(u, t0, Top(u, t0), size).Screen; + var top1 = Project(u, t1, Top(u, t1), size).Screen; + var bot0 = Project(u, t0, Field.MinHeight - 1, size).Screen; + var bot1 = Project(u, t1, Field.MinHeight - 1, size).Screen; + FillQuad(dc, u < 0.5 ? rock : dark, top0, top1, bot1, bot0); + } + } + } + + private void DrawBasePlate(DrawingContext dc, Size size) + { + var corners = new[] { (0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0) } + .Select(c => Project(c.Item1, c.Item2, Field.MinHeight - 1, size).Screen).ToArray(); + FillQuad(dc, new SolidColorBrush(Color.Parse("#132238")), corners[0], corners[1], corners[2], corners[3]); + var pen = new Pen(new SolidColorBrush(Color.Parse("#2C4C73")), 1.2); + var geo = new StreamGeometry(); + using (var g = geo.Open()) + { + g.BeginFigure(corners[0], true); + g.LineTo(corners[1]); g.LineTo(corners[2]); g.LineTo(corners[3]); + g.EndFigure(true); + } + dc.DrawGeometry(null, pen, geo); + } + + // 起始就落在山顶下方一点,打开就能看到“削掉山顶”的截面,而不是一张贴在山尖的板 + private float CurrentCutLevel => (float)(Field.MaxHeight - (Field.MaxHeight - Field.MinHeight) * (0.06 + 0.94 * _anim)); + + /// 步骤1:水平切面从山顶下降,与山体相交处高亮出交线。 + private void DrawCutting(DrawingContext dc, Size size) + { + var lv = Math.Clamp(CurrentCutLevel, Field.MinHeight, Field.MaxHeight); + // 切面 + var corners = new[] { (0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0) } + .Select(c => Project(c.Item1, c.Item2, lv, size).Screen).ToArray(); + FillQuad(dc, new SolidColorBrush(Color.FromArgb(38, 31, 209, 232)), corners[0], corners[1], corners[2], corners[3]); + var planePen = new Pen(new SolidColorBrush(Color.FromArgb(150, 31, 209, 232)), 1.2); + var pg = new StreamGeometry(); + using (var g = pg.Open()) + { + g.BeginFigure(corners[0], true); + g.LineTo(corners[1]); g.LineTo(corners[2]); g.LineTo(corners[3]); + g.EndFigure(true); + } + dc.DrawGeometry(null, planePen, pg); + + // 切面与山体的交线:在该高度上精确求解(不能只用缓存里的整百高程) + DrawExactContour3D(dc, size, lv, new Pen(new SolidColorBrush(CCutting), 2.6)); + // 切面标注 + Text(dc, $"水平面 {lv:0} m", corners[0].X + 6, corners[0].Y - 4, 11, CCutting, true); + } + + /// 步骤2:多层水平切面各留下一条交线,像千层糕一样堆叠。 + private void DrawStackedLines(DrawingContext dc, Size size) + { + var interval = Math.Max(10f, Field.EffectiveInterval); + var top = (float)(Math.Floor(Field.MaxHeight / interval) * interval); + var levels = new List(); + for (var lv = top; lv > Field.MinHeight + interval * 0.5f && levels.Count < 14; lv -= interval) + levels.Add(lv); + + var reveal = Math.Max(1, (int)Math.Ceiling(_anim * levels.Count)); + for (var k = 0; k < Math.Min(levels.Count, reveal); k++) + { + var lv = levels[k]; + var alpha = (byte)(120 + 120 * (1 - (double)k / levels.Count)); + DrawExactContour3D(dc, size, lv, + new Pen(new SolidColorBrush(Color.FromArgb(alpha, (byte)31, (byte)209, (byte)232)), 2.0)); + } + + // 最新的一层加一块很淡的切面,强调“水平切割” + if (reveal > 0 && reveal <= levels.Count) + { + var lv = levels[reveal - 1]; + var corners = new[] { (0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0) } + .Select(c => Project(c.Item1, c.Item2, lv, size).Screen).ToArray(); + FillQuad(dc, new SolidColorBrush(Color.FromArgb(16, 31, 209, 232)), corners[0], corners[1], corners[2], corners[3]); + } + } + + /// 步骤3:各高度交线沿垂线落到同一平面,累积成等高线图。 + private void DrawProjection(DrawingContext dc, Size size) + { + var interval = Math.Max(10f, Field.EffectiveInterval); + var top = (float)(Math.Floor(Field.MaxHeight / interval) * interval); + var levels = new List(); + for (var lv = top; lv > Field.MinHeight + interval * 0.5f && levels.Count < 9; lv -= interval) + levels.Add(lv); + + var drop = Ease(Math.Clamp(_anim / 0.72, 0, 1)); // 0→1:交线整体垂降 + var beamPen = new Pen(new SolidColorBrush(Color.FromArgb(40, 124, 92, 255)), 1.0); + var livePen = new Pen(new SolidColorBrush(Color.FromArgb(240, 31, 209, 232)), 2.0); + + foreach (var lv in levels) + { + var y = lv - (lv - Field.MinHeight) * (float)drop; + var lines = Field.ExtractContour(lv); + foreach (var line in lines) + { + if (line.Count < 2) continue; + + // 投影轨迹:从原高度到当前位置的竖线,稀疏采样才不会糊成一片帘子 + if (drop > 0.02 && drop < 0.995) + { + var step = Math.Max(5, line.Count / 10); + for (var i = 0; i < line.Count; i += step) + { + var a = Project(line[i].U, line[i].V, lv, size).Screen; + var b = Project(line[i].U, line[i].V, y, size).Screen; + dc.DrawLine(beamPen, a, b); + } + } var geo = new StreamGeometry(); using (var g = geo.Open()) { - g.BeginFigure(p00, true); - g.LineTo(p10); - g.LineTo(p11); - g.LineTo(p01); - g.EndFigure(true); + g.BeginFigure(Project(line[0].U, line[0].V, y, size).Screen, false); + for (var i = 1; i < line.Count; i++) + g.LineTo(Project(line[i].U, line[i].V, y, size).Screen); + g.EndFigure(false); } - dc.DrawGeometry(brush, null, geo); + dc.DrawGeometry(null, livePen, geo); } } - // 悬停指示 - if (_hasHover) + // 底面(投影平面)轮廓 + var corners = new[] { (0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0) } + .Select(c => Project(c.Item1, c.Item2, Field.MinHeight, size).Screen).ToArray(); + var pg = new StreamGeometry(); + using (var g = pg.Open()) { - var h = Field.SampleSmooth(_hoverU, _hoverV); - var p = _hoverRegion == HoverRegion.Terrain - ? _pointerPosition - : Project(_hoverU, _hoverV, h); - dc.DrawEllipse(new SolidColorBrush(Colors.White), new Pen(new SolidColorBrush(CAccent), 2), - p, 5, 5); - var stem = new Point(p.X, p.Y + 30); - dc.DrawLine(new Pen(new SolidColorBrush(CAccent), 1.5), p, stem); - Text(dc, $"{(int)h} m", stem.X, stem.Y + 3, 11.5, Colors.White, true, TextAlignment.Center); + g.BeginFigure(corners[0], true); + g.LineTo(corners[1]); g.LineTo(corners[2]); g.LineTo(corners[3]); + g.EndFigure(true); } + dc.DrawGeometry(new SolidColorBrush(Color.FromArgb(20, 124, 92, 255)), + new Pen(new SolidColorBrush(Color.FromArgb(110, 124, 92, 255)), 1.2), pg); + + Text(dc, "垂直投影 → 同一平面", 16, 44, 12, CProjection, true); } - /// 斜视图反投影(近似):把屏幕点还原成 u/v。 - private (double U, double V) UnprojectIso(Rect r, Point p) + /// 步骤4:坡度着色——陡处等高线密、缓处疏,直接体现判坡规律。 + private void DrawDensity3D(DrawingContext dc, Size size) { - var cx = r.X + r.Width * 0.5; - var cy = r.Y + r.Height * 0.62; - var scaleX = r.Width * 0.62; - var scaleY = r.Height * 0.30; - var u = (p.X - cx) / scaleX + 0.5; - var v = (p.Y - cy) / scaleY + 0.5; - return (u, v); - } - - // ---- 右侧:等高线俯视图 ---- - private void DrawContourMap(DrawingContext dc, Rect r) - { - var panel = r; - var mapRect = ContourMapRect(panel); - var profileRect = new Rect(panel.X, mapRect.Bottom, panel.Width, panel.Bottom - mapRect.Bottom); - r = mapRect; - // 分层设色底图 - const int N = 96; + const int N = 56; for (var j = 0; j < N; j++) + for (var i = 0; i < N; i++) { - for (var i = 0; i < N; i++) + var u = (i + 0.5) / N; var v = (j + 0.5) / N; + var slope = TerrainAnalyzer.SlopeAt(Field, u, v); // 归一化 0..1 + var (r, g, b) = SlopeColor(slope); + var p0 = Project((double)i / N, (double)j / N, Field.SampleSmooth((double)i / N, (double)j / N), size).Screen; + var p1 = Project((double)(i + 1) / N, (double)j / N, Field.SampleSmooth((double)(i + 1) / N, (double)j / N), size).Screen; + var p2 = Project((double)(i + 1) / N, (double)(j + 1) / N, Field.SampleSmooth((double)(i + 1) / N, (double)(j + 1) / N), size).Screen; + var p3 = Project((double)i / N, (double)(j + 1) / N, Field.SampleSmooth((double)i / N, (double)(j + 1) / N), size).Screen; + FillQuad(dc, new SolidColorBrush(Color.FromArgb(200, r, g, b)), p0, p1, p2, p3); + } + // 等高线保持可见 + var contourPen = new Pen(new SolidColorBrush(Color.FromArgb(170, 26, 22, 16)), 1.0); + foreach (var (_, lines) in _contours) + foreach (var line in lines) { - var u = (i + 0.5) / N; var v = (j + 0.5) / N; - var h = Field.SampleSmooth(u, v); - var (cr, cg, cb) = TerrainAnalyzer.ColorForHeight(h, Field.MinHeight, Field.MaxHeight); - var brush = _colored - ? new SolidColorBrush(Color.FromRgb(cr, cg, cb)) - : new SolidColorBrush(Color.Parse("#F3F0E6")); - dc.FillRectangle(brush, new Rect( - r.X + r.Width * i / N, - r.Y + r.Height * j / N, - r.Width / N + 1, - r.Height / N + 1)); + if (line.Count < 2) continue; + var geo = new StreamGeometry(); + using (var g = geo.Open()) + { + g.BeginFigure(Project(line[0].U, line[0].V, + Field.SampleSmooth(line[0].U, line[0].V), size).Screen, false); + for (var i = 1; i < line.Count; i++) + g.LineTo(Project(line[i].U, line[i].V, + Field.SampleSmooth(line[i].U, line[i].V), size).Screen); + g.EndFigure(false); + } + dc.DrawGeometry(null, contourPen, geo); + } + DrawSlopeLegend(dc, size); + } + + /// 在指定高度画一条等高线(提 lift 到该高度,贴合切面)。 + private void DrawContourAtLevel3D(DrawingContext dc, Size size, float level, Pen pen) + { + foreach (var (lv, lines) in _contours) + { + if (Math.Abs(lv - level) > (Field.EffectiveInterval * 0.6f)) continue; + foreach (var line in lines) + { + if (line.Count < 2) continue; + var geo = new StreamGeometry(); + using (var g = geo.Open()) + { + var p0 = Project(line[0].U, line[0].V, lv, size).Screen; + g.BeginFigure(p0, false); + for (var i = 1; i < line.Count; i++) + g.LineTo(Project(line[i].U, line[i].V, lv, size).Screen); + g.EndFigure(false); + } + dc.DrawGeometry(null, pen, geo); } } + } - Point P(double u, double v) => new(r.X + u * r.Width, r.Y + v * r.Height); + /// + /// 在指定高度精确求交线并绘制。线贴着地表走(按该点实际高度投影), + /// 这样在斜面上不会因为“线在水平面上、山体在它前面”而看起来断成虚线。 + /// + private void DrawExactContour3D(DrawingContext dc, Size size, float level, Pen pen) + { + var lines = Field.ExtractContour(level); + var ceiling = _step == ExperimentStep.Cutting ? level : float.MaxValue; + float Hug(double u, double v) => Math.Min(Field.SampleSmooth(u, v), ceiling); + + foreach (var line in lines) + { + if (line.Count < 2) continue; + var geo = new StreamGeometry(); + using (var g = geo.Open()) + { + g.BeginFigure(Project(line[0].U, line[0].V, Hug(line[0].U, line[0].V), size).Screen, false); + for (var i = 1; i < line.Count; i++) + g.LineTo(Project(line[i].U, line[i].V, Hug(line[i].U, line[i].V), size).Screen); + g.EndFigure(false); + } + dc.DrawGeometry(null, pen, geo); + } + } + + private void DrawSymbols3D(DrawingContext dc, Size size) + { + // 切割步骤里山体已被削到切面高度,符号也要跟着压在切面上,不能悬空 + var cut = _step == ExperimentStep.Cutting ? CurrentCutLevel : float.MaxValue; + float Flat(float h) => Math.Min(h, cut); + + // 山峰 ▲ + 高程(山峰已被切掉时不再标注,免得山顶点飘在切面上) + foreach (var (u, v, h) in Field.Peaks.Take(3)) + { + if (h > cut + 5) continue; + var at = Project(u, v, Flat(h), size).Screen; + var tri = new StreamGeometry(); + using (var g = tri.Open()) + { + g.BeginFigure(new Point(at.X, at.Y - 7), true); + g.LineTo(new Point(at.X - 5.5, at.Y + 3)); + g.LineTo(new Point(at.X + 5.5, at.Y + 3)); + g.EndFigure(true); + } + dc.DrawGeometry(new SolidColorBrush(Color.Parse("#1B1308")), null, tri); + Text(dc, ((int)h).ToString(), at.X + 8, at.Y - 8, 10, Color.Parse("#1B1308"), true); + } + // 河流(沿谷底的蓝线) + if (Field.River.Count > 1) + { + var geo = new StreamGeometry(); + using (var g = geo.Open()) + { + var p0 = Project(Field.River[0].U, Field.River[0].V, Flat(Field.SampleSmooth(Field.River[0].U, Field.River[0].V)), size).Screen; + g.BeginFigure(p0, false); + for (var i = 1; i < Field.River.Count; i++) + g.LineTo(Project(Field.River[i].U, Field.River[i].V, Flat(Field.SampleSmooth(Field.River[i].U, Field.River[i].V)), size).Screen); + g.EndFigure(false); + } + var pen = new Pen(new SolidColorBrush(Color.Parse("#2F9BE0")), 2.4); + pen.LineJoin = PenLineJoin.Round; + dc.DrawGeometry(null, pen, geo); + } + } + + private void DrawStepBadge(DrawingContext dc, Size size) + { + var titles = new[] { "① 等高切割", "② 形成交线", "③ 投影成图", "④ 疏密判坡" }; + var text = titles[(int)_step]; + var ft = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, + new Typeface(Font.FontFamily, FontStyle.Normal, FontWeight.Bold), 14, + new SolidColorBrush(Colors.White)); + var x = 14; var y = 12; + dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(190, 8, 24, 46)), null, + new Rect(x - 8, y - 5, ft.Width + 16, ft.Height + 10)); + dc.DrawText(ft, new Point(x, y)); + } + + // ================================================================ 俯视视角 + + private static Rect TopMapRect(Size size) + { + var profile = Math.Min(120, size.Height * 0.26); + return new Rect(14, 14, size.Width - 28, Math.Max(40, size.Height - 28 - profile)); + } + + private void RenderTop(DrawingContext dc, Size size) + { + var panel = new Rect(14, 14, size.Width - 28, size.Height - 28); + var map = TopMapRect(size); + var profileRect = new Rect(panel.X, map.Bottom, panel.Width, panel.Bottom - map.Bottom); + + // 分层设色 / 坡度着色底图 + const int N = 92; + for (var j = 0; j < N; j++) + for (var i = 0; i < N; i++) + { + var u = (i + 0.5) / N; var v = (j + 0.5) / N; + Color col; + if (_step == ExperimentStep.Density) + { + var (r, g, b) = SlopeColor(TerrainAnalyzer.SlopeAt(Field, u, v)); + col = Color.FromRgb(r, g, b); + } + else + { + var h = Field.SampleSmooth(u, v); + var (r, g, b) = _colored ? TerrainAnalyzer.ColorForHeight(h, Field.MinHeight, Field.MaxHeight) : ((byte)0xF3, (byte)0xF0, (byte)0xE6); + col = Color.FromRgb(r, g, b); + } + dc.FillRectangle(new SolidColorBrush(col), new Rect( + map.X + map.Width * i / N, map.Y + map.Height * j / N, + map.Width / N + 1, map.Height / N + 1)); + } + + Point P(double u, double v) => new(map.X + u * map.Width, map.Y + v * map.Height); // 等高线 if (_showContours) { foreach (var (level, lines) in _contours) { - var isIndex = Math.Abs(level % 500) < 0.5; // 每 5 条一条计曲线 - var pen = new Pen(new SolidColorBrush(isIndex ? CContourIndex : CContour), - isIndex ? 2.0 : 1.0); - + var isIndex = Math.Abs(level % 500) < 0.5; + var pen = new Pen(new SolidColorBrush(isIndex ? CContourIndex : CContour), isIndex ? 2.0 : 1.0); foreach (var line in lines) { if (line.Count < 2) continue; @@ -324,8 +900,7 @@ public sealed class ContourView : Control using (var g = geo.Open()) { g.BeginFigure(P(line[0].U, line[0].V), false); - for (var i = 1; i < line.Count; i++) - g.LineTo(P(line[i].U, line[i].V)); + for (var i = 1; i < line.Count; i++) g.LineTo(P(line[i].U, line[i].V)); g.EndFigure(false); } dc.DrawGeometry(null, pen, geo); @@ -333,7 +908,7 @@ public sealed class ContourView : Control } } - // 等高线高程标注(计曲线) + // 高程标注(计曲线) if (_showLabels) { foreach (var (level, lines) in _contours) @@ -344,35 +919,30 @@ public sealed class ContourView : Control if (line.Count < 12) continue; var mid = line[line.Count / 2]; var at = P(mid.U, mid.V); - if (at.X < r.X + 16 || at.X > r.Right - 16) continue; + if (at.X < map.X + 16 || at.X > map.Right - 16) continue; Text(dc, $"{(int)level}", at.X, at.Y - 7, 9.5, CContourIndex, true, TextAlignment.Center); } } } - // ── 教科书地形符号 ── - - // 河流:蓝色线(沿谷底流) + // 河流 if (Field.River.Count > 1) { var geo = new StreamGeometry(); using (var g = geo.Open()) { g.BeginFigure(P(Field.River[0].U, Field.River[0].V), false); - for (var i = 1; i < Field.River.Count; i++) - g.LineTo(P(Field.River[i].U, Field.River[i].V)); + for (var i = 1; i < Field.River.Count; i++) g.LineTo(P(Field.River[i].U, Field.River[i].V)); g.EndFigure(false); } - var riverPen = new Pen(new SolidColorBrush(Color.Parse("#2F7FD0")), 2.2); - riverPen.LineJoin = PenLineJoin.Round; - riverPen.LineCap = PenLineCap.Round; - dc.DrawGeometry(null, riverPen, geo); + var pen = new Pen(new SolidColorBrush(Color.Parse("#2F7FD0")), 2.2) { LineJoin = PenLineJoin.Round, LineCap = PenLineCap.Round }; + dc.DrawGeometry(null, pen, geo); } - // 山峰:▲ + 高程数字(教科书标注法) - foreach (var (pu, pv, ph) in Field.Peaks.Take(4)) + // 山峰 + foreach (var (u, v, h) in Field.Peaks.Take(4)) { - var at = P(pu, pv); + var at = P(u, v); var tri = new StreamGeometry(); using (var g = tri.Open()) { @@ -382,13 +952,13 @@ public sealed class ContourView : Control g.EndFigure(true); } dc.DrawGeometry(new SolidColorBrush(Color.Parse("#3A2A18")), null, tri); - Text(dc, ((int)ph).ToString(), at.X + 8, at.Y - 8, 10, Color.Parse("#3A2A18"), true); + Text(dc, ((int)h).ToString(), at.X + 8, at.Y - 8, 10, Color.Parse("#3A2A18"), true); } - // 陡崖:锯齿符号(教科书用锯齿线表示陡崖) - foreach (var (cu, cv) in Field.Cliffs.Take(40)) + // 陡崖锯齿 + foreach (var (u, v) in Field.Cliffs.Take(40)) { - var at = P(cu, cv); + var at = P(u, v); var saw = new StreamGeometry(); using (var g = saw.Open()) { @@ -409,50 +979,33 @@ public sealed class ContourView : Control { var at = P(_hoverU, _hoverV); var pen = new Pen(new SolidColorBrush(CAccent), 1.6); - dc.DrawLine(pen, new Point(r.X, at.Y), new Point(r.Right, at.Y)); - dc.DrawLine(pen, new Point(at.X, r.Y), new Point(at.X, r.Bottom)); + dc.DrawLine(pen, new Point(map.X, at.Y), new Point(map.Right, at.Y)); + dc.DrawLine(pen, new Point(at.X, map.Y), new Point(at.X, map.Bottom)); dc.DrawEllipse(new SolidColorBrush(Colors.White), new Pen(new SolidColorBrush(CAccent), 2), at, 5, 5); } - DrawNorthArrow(dc, r); - DrawScaleBar(dc, r); - DrawLegend(dc, r); - if (profileRect.Height > 50) DrawProfile(dc, profileRect, mapRect); - - // 边框 - dc.DrawRectangle(null, new Pen(new SolidColorBrush(CLine), 1.2), r); + DrawNorthArrow(dc, map); + DrawScaleBar(dc, map); + if (_step == ExperimentStep.Density) DrawSlopeLegend(dc, size); else DrawLegend(dc, map); + if (profileRect.Height > 50) DrawProfile(dc, profileRect, map); + dc.DrawRectangle(null, new Pen(new SolidColorBrush(CLine), 1.2), map); + DrawStepBadge(dc, size); } - /// - /// 地形剖面图(教科书等高线图必配):沿图幅中部的一条南北剖面线, - /// 画出地面起伏并标注各点海拔。这是最能体现「等高线图 ↔ 立体地形」关系的图。 - /// private void DrawProfile(DrawingContext dc, Rect r, Rect mapRect) { if (r.Height < 50) return; - - // 背景 dc.FillRectangle(new SolidColorBrush(Color.FromArgb(235, 252, 250, 244)), r); dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 1.0), r); - - // 纵轴比例:0 → 最大高程 var maxH = Math.Max(1f, Field.MaxHeight); - var baseY = r.Bottom - 18; - var topY = r.Y + 16; - - // 水平网格(每 200 m 一条) + var baseY = r.Bottom - 18; var topY = r.Y + 16; for (var hh = 200f; hh < maxH; hh += 200) { var gy = baseY - (hh / maxH) * (baseY - topY); - dc.DrawLine(new Pen(new SolidColorBrush(Color.FromArgb(70, 42, 52, 70)), 0.8), - new Point(r.X, gy), new Point(r.Right, gy)); + dc.DrawLine(new Pen(new SolidColorBrush(Color.FromArgb(70, 42, 52, 70)), 0.8), new Point(r.X, gy), new Point(r.Right, gy)); Text(dc, $"{hh:0}", r.X + 2, gy - 8, 7.5, Color.Parse("#5A6B80")); } - // 基准线 - dc.DrawLine(new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 1.2), - new Point(r.X, baseY), new Point(r.Right, baseY)); - - // 剖面线:沿图幅中部(v = 0.5)自西向东 + dc.DrawLine(new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 1.2), new Point(r.X, baseY), new Point(r.Right, baseY)); const int N = 160; var geo = new StreamGeometry(); using (var g = geo.Open()) @@ -463,16 +1016,12 @@ public sealed class ContourView : Control var hv = Field.SampleSmooth(u, 0.5); var y = baseY - (hv / maxH) * (baseY - topY); var x = r.X + u * r.Width; - if (i == 0) g.BeginFigure(new Point(x, y), false); - else g.LineTo(new Point(x, y)); + if (i == 0) g.BeginFigure(new Point(x, y), false); else g.LineTo(new Point(x, y)); } g.EndFigure(false); } dc.DrawGeometry(null, new Pen(new SolidColorBrush(Color.Parse("#B03A2E")), 2.0), geo); - - // 剖面线上的几个关键点(与等高线图上的位置对应) - var marks = new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }; - foreach (var u in marks) + foreach (var u in new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }) { var hv = Field.SampleSmooth(u, 0.5); var y = baseY - (hv / maxH) * (baseY - topY); @@ -480,98 +1029,93 @@ public sealed class ContourView : Control dc.DrawEllipse(new SolidColorBrush(Color.Parse("#B03A2E")), null, new Point(x, y), 3, 3); Text(dc, $"{hv:0}", x, y - 13, 8, Color.Parse("#8B2E24"), true, TextAlignment.Center); } - - // 标注:剖面线在图上的位置 Text(dc, T("profile.title"), r.X + 6, r.Y + 3, 9, Color.Parse("#2A3446"), true); - dc.DrawLine(new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 1.2, dashStyle: DashStyle.Dash), - new Point(r.X + r.Width / 2, mapRect.Y), new Point(r.X + r.Width / 2, r.Y)); } - /// 指北针(教科书地图必备,位于图幅右上角)。 private void DrawNorthArrow(DrawingContext dc, Rect r) { - var x = r.Right - 26; - var y = r.Y + 20; + var x = r.Right - 26; var y = r.Y + 22; var tri = new StreamGeometry(); using (var g = tri.Open()) { g.BeginFigure(new Point(x, y - 12), true); - g.LineTo(new Point(x - 5, y + 6)); - g.LineTo(new Point(x, y + 2)); - g.EndFigure(true); + g.LineTo(new Point(x - 5, y + 6)); g.LineTo(new Point(x, y + 2)); g.EndFigure(true); } dc.DrawGeometry(new SolidColorBrush(Color.Parse("#2A3446")), null, tri); - var tri2 = new StreamGeometry(); - using (var g2 = tri2.Open()) - { - g2.BeginFigure(new Point(x, y - 12), true); - g2.LineTo(new Point(x + 5, y + 6)); - g2.LineTo(new Point(x, y + 2)); - g2.EndFigure(true); - } - dc.DrawGeometry(new SolidColorBrush(Color.Parse("#8FA0B8")), null, tri2); Text(dc, "N", x, y + 8, 9.5, Color.Parse("#2A3446"), true, TextAlignment.Center); } - /// 比例尺(教科书地图必备,左下角)。 private void DrawScaleBar(DrawingContext dc, Rect r) { - var x = r.X + 14; - var y = r.Bottom - 22; - var w = 90.0; - var h = 5.0; - - // 分黑白相间的格(教科书比例尺画法) + var x = r.X + 14; var y = r.Bottom - 22; var w = 90.0; var h = 5.0; for (var i = 0; i < 4; i++) { var seg = new Rect(x + i * w / 4, y, w / 4, h); - dc.FillRectangle(new SolidColorBrush(i % 2 == 0 - ? Color.Parse("#2A3446") : Color.Parse("#FFFFFF")), seg); + dc.FillRectangle(new SolidColorBrush(i % 2 == 0 ? Color.Parse("#2A3446") : Color.Parse("#FFFFFF")), seg); dc.DrawRectangle(new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 0.8), seg); } Text(dc, "0", x, y - 11, 8.5, Color.Parse("#2A3446"), align: TextAlignment.Center); Text(dc, "1 km", x + w, y - 11, 8.5, Color.Parse("#2A3446"), align: TextAlignment.Center); } - /// 分层设色图例(教科书右下角的色阶表)。 private void DrawLegend(DrawingContext dc, Rect r) { var bands = new (float From, float To)[] { - (0, 200), (200, 400), (400, 600), (600, 800), - (800, 1000), (1000, 1200), (1200, 1400), (1400, 1600), (1600, 2000) + (0,200),(200,400),(400,600),(600,800),(800,1000), + (1000,1200),(1200,1400),(1400,1600),(1600,2000) }; - - var w = 62.0; - var rowH = 11.0; - var h = bands.Length * rowH + 16; - var x = r.Right - w - 12; - var y = r.Bottom - h - 12; - - dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(210, 255, 255, 255)), null, - new Rect(x, y, w, h)); - dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 0.9), - new Rect(x, y, w, h)); - + var w = 62.0; var rowH = 11.0; var h = bands.Length * rowH + 16; + var x = r.Right - w - 12; var y = r.Bottom - h - 12; + dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(210, 255, 255, 255)), null, new Rect(x, y, w, h)); + dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 0.9), new Rect(x, y, w, h)); Text(dc, T("legend.title"), x + 5, y + 3, 8.5, Color.Parse("#2A3446"), true); - for (var i = 0; i < bands.Length; i++) { - var (from, to) = bands[i]; - var mid = (from + to) / 2; + var (from, to) = bands[i]; var mid = (from + to) / 2; var (cr, cg, cb) = TerrainAnalyzer.ColorForHeight(mid, 0, 2000); var cy = y + 14 + i * rowH; - dc.FillRectangle(new SolidColorBrush(Color.FromRgb(cr, cg, cb)), - new Rect(x + 5, cy, 14, rowH - 2)); - dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 0.6), - new Rect(x + 5, cy, 14, rowH - 2)); - - var label = to >= 2000 ? ">1600 m" : $"{from:0}–{to:0} m"; - Text(dc, label, x + 23, cy, 8, Color.Parse("#2A3446")); + dc.FillRectangle(new SolidColorBrush(Color.FromRgb(cr, cg, cb)), new Rect(x + 5, cy, 14, rowH - 2)); + dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#2A3446")), 0.6), new Rect(x + 5, cy, 14, rowH - 2)); + Text(dc, to >= 2000 ? ">1600 m" : $"{from:0}–{to:0} m", x + 23, cy, 8, Color.Parse("#2A3446")); } } - // ---------------------------------------------------------------- 文字 + private void DrawSlopeLegend(DrawingContext dc, Size size) + { + var x = size.Width - 168; var y = size.Height - 58; var w = 150; var h = 12; + for (var i = 0; i < w; i++) + { + var (r, g, b) = SlopeColor(i / (double)w); + dc.FillRectangle(new SolidColorBrush(Color.FromRgb(r, g, b)), new Rect(x + i, y, 1.5, h)); + } + dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color.Parse("#8FA0B8")), 0.8), new Rect(x, y, w, h)); + Text(dc, T("slope.gentle"), x, y - 14, 9.5, Color.Parse("#EAF2FF")); + Text(dc, T("slope.steep"), x + w, y - 14, 9.5, Color.Parse("#EAF2FF"), align: TextAlignment.Right); + } + + private static (byte R, byte G, byte B) SlopeColor(double t) + { + t = Math.Clamp(t, 0, 1); + // 绿(缓) → 黄 → 红(陡) + byte r, g; + const byte b = 70; + if (t < 0.5) + { + var k = t / 0.5; + r = (byte)(0x4E + (0xE8 - 0x4E) * k); + g = (byte)(0x9E + (0xE2 - 0x9E) * k); + } + else + { + var k = (t - 0.5) / 0.5; + r = (byte)(0xE8 + (0xC0 - 0xE8) * k); + g = (byte)(0xE2 + (0x39 - 0xE2) * k); + } + return (r, g, b); + } + + private static double Ease(double t) => t * t * (3 - 2 * t); private void Text(DrawingContext dc, string s, double x, double y, double size, Color color, bool bold = false, TextAlignment align = TextAlignment.Left) @@ -580,6 +1124,7 @@ public sealed class ContourView : Control new Typeface(Font.FontFamily, FontStyle.Normal, bold ? FontWeight.Bold : FontWeight.Normal), size, new SolidColorBrush(color)); ft.TextAlignment = align; - dc.DrawText(ft, new Point(align == TextAlignment.Center ? x - ft.Width / 2 : x, y)); + dc.DrawText(ft, new Point(align == TextAlignment.Center ? x - ft.Width / 2 : + align == TextAlignment.Right ? x - ft.Width : x, y)); } } diff --git a/model/contour-map/src/DefaultTexts.cs b/model/contour-map/src/DefaultTexts.cs index 1eeab4f..4a81325 100644 --- a/model/contour-map/src/DefaultTexts.cs +++ b/model/contour-map/src/DefaultTexts.cs @@ -2,24 +2,88 @@ using System.Collections.Generic; namespace GC.ContourMap; -/// 内置全量文案兜底:没有语言包也能完整显示。 +/// 内置全量文案兜底:没有语言包也能完整显示(复刻 HTML 课件全部文案)。 internal static class DefaultTexts { public static readonly Dictionary Zh = new() { - ["app.title"] = "等高线地形图", - ["app.subtitle"] = "七年级上册 · 地形图的判读:从立体地形到平面等高线", + // 标题 + ["app.title"] = "等高线地形 · 五大典型地貌判读", + ["app.subtitle"] = "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖", - ["kind.mountain"] = "山地", - ["kind.basin"] = "盆地", - ["kind.hill"] = "丘陵", - ["kind.plateau"] = "高原", - ["kind.plain"] = "平原", - ["legend.title"] = "分层设色", - ["profile.title"] = "地形剖面图", + // 实验流程四步 + ["flow.title"] = "实验流程", + ["flow.step.0"] = "等高切割", + ["flow.step.1"] = "形成交线", + ["flow.step.2"] = "投影成图", + ["flow.step.3"] = "疏密判坡", + ["flow.desc.0"] = "观察水平面与山体在同一海拔相交,形成连续闭合线。", + ["flow.desc.1"] = "每个水平切面都会留下同高交线,多层交线共同描述山体起伏。", + ["flow.desc.2"] = "把各高度交线垂直投影到同一平面,得到完整等高线地形图。", + ["flow.desc.3"] = "等高线越密,坡度越陡;等高线越疏,坡度越缓。", + + // 观察面板 + ["observe.title"] = "实验演示", + ["observe.default"] = "点击开始实验,在立体地形中观察等高切割与交线形成,再通过四步图解理解投影与判坡。", + ["observe.features"] = "判读要点", + ["observe.default.f1"] = "同一条等高线上海拔相等", + ["observe.default.f2"] = "相邻等高线高差保持一致", + + // 五大典型地貌 + ["side.landforms"] = "五大典型地貌", + ["landform.peak"] = "山峰", + ["landform.ridge"] = "山脊", + ["landform.valley"] = "山谷", + ["landform.saddle"] = "鞍部", + ["landform.cliff"] = "陡崖", + ["landform.peak.sub"] = "闭合等高线", + ["landform.ridge.sub"] = "凸低为脊", + ["landform.valley.sub"] = "凸高为谷", + ["landform.saddle.sub"] = "两峰之间", + ["landform.cliff.sub"] = "密集或重合", + + ["landform.peak.summary"] = "山峰四周较低、中心突起;等高线闭合成环,海拔数值由外向内逐渐升高。", + ["landform.ridge.summary"] = "等高线弯曲部分向海拔低处凸出,脊线常成为两侧水系的分水岭。", + ["landform.valley.summary"] = "等高线弯曲部分向海拔高处凸出,谷底低洼并容易汇水形成河流。", + ["landform.saddle.summary"] = "鞍部位于相邻两座山峰之间,是沿山脊方向相对低洼的过渡地带。", + ["landform.cliff.summary"] = "陡崖坡面近直立,不同高程的等高线会高度密集,局部可投影到同一位置而重合。", + + ["landform.peak.f1"] = "中心海拔高、四周海拔低", + ["landform.peak.f2"] = "闭合线越向内,数值越大", + ["landform.peak.f3"] = "若数值向内降低,则应判为洼地", + ["landform.ridge.f1"] = "等高线凸向低值方向", + ["landform.ridge.f2"] = "脊线由高处向低处延伸", + ["landform.ridge.f3"] = "雨水沿脊线两侧分流", + ["landform.valley.f1"] = "等高线凸向高值方向", + ["landform.valley.f2"] = "V 形尖端指向上游高处", + ["landform.valley.f3"] = "谷底常发育河流", + ["landform.saddle.f1"] = "两组闭合等高线相邻", + ["landform.saddle.f2"] = "中部线条收窄,形似马鞍", + ["landform.saddle.f3"] = "常是翻越山岭的低垭口", + ["landform.cliff.f1"] = "密集表示陡坡,重合才是陡崖特征", + ["landform.cliff.f2"] = "单位水平距离内高差很大", + ["landform.cliff.f3"] = "n 条线重合时:(n−1)d ≤ ΔH < (n+1)d", + + ["landform.peak.hint"] = "山峰:闭合曲线,数值向中心升高", + ["landform.ridge.hint"] = "山脊:等高线向低处凸出,凸低为脊", + ["landform.valley.hint"] = "山谷:等高线向高处凸出,凸高为谷", + ["landform.saddle.hint"] = "鞍部:两峰之间相对低洼,俯视轮廓呈收腰形", + ["landform.cliff.hint"] = "陡崖:等高线密集或重合,坡度极陡", + + // 按钮 + ["btn.play"] = "开始实验", + ["btn.pause"] = "暂停实验", + ["btn.replay"] = "重新实验", + ["btn.reset"] = "重置", + ["btn.view3d"] = "立体图", + ["btn.viewTop"] = "俯视图", ["btn.color"] = "上色", ["btn.colorOn"] = "取消上色", + ["btn.fullscreen"] = "全屏", + ["btn.exitFullscreen"] = "退出全屏", + ["btn.backExperiment"] = "返回实验", + // 侧栏判读要点(通用地形) ["side.features"] = "五种地形部位", ["feature.peak"] = "山峰", ["feature.peakDesc"] = "等高线闭合,数值由中心向四周递减。", @@ -33,30 +97,99 @@ internal static class DefaultTexts ["feature.cliffDesc"] = "等高线重叠或非常密集,近乎垂直。", ["feature.slope"] = "坡面", + // 判读规则 ["side.rules"] = "判读要点", ["rule.interval"] = "等高距:相邻两条等高线的高度差,本图 100 米。", ["rule.dense"] = "等高线越密坡越陡,越疏坡越缓。", ["rule.index"] = "每 5 条加粗一条计曲线,标注海拔便于读数。", ["rule.height"] = "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。", - ["footer.hint"] = "把鼠标移到任意一侧,可查看该点的海拔与地形部位", - ["footer.readout"] = "海拔 {0} m 相对高度 {1} m" + // 底部读数 / 图例 + ["footer.hint"] = "拖动立体地形旋转、滚轮缩放;鼠标悬停可查看该点海拔与地形部位", + ["footer.readout"] = "海拔 {0} m 相对高度 {1} m", + ["legend.title"] = "分层设色", + ["profile.title"] = "地形剖面图", + ["slope.gentle"] = "缓坡(线疏)", + ["slope.steep"] = "陡坡(线密)", + + ["hint.play"] = "点击“开始实验”,观察等高切割与交线形成", + ["hint.playing"] = "实验播放中", + ["hint.paused"] = "实验已暂停 · 点击继续恢复播放", + ["hint.done"] = "实验流程播放完成 · 可重新实验或选择典型地貌观察" }; public static readonly Dictionary En = new() { - ["app.title"] = "Contour Map", - ["app.subtitle"] = "Grade 7 · Reading terrain maps: from 3D relief to contour lines", + ["app.title"] = "Contour Lines · Five Classic Landforms", + ["app.subtitle"] = "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs", - ["kind.mountain"] = "Mountains", - ["kind.basin"] = "Basin", - ["kind.hill"] = "Hills", - ["kind.plateau"] = "Plateau", - ["kind.plain"] = "Plain", - ["legend.title"] = "Hypsometric tint", - ["profile.title"] = "Terrain profile", + ["flow.title"] = "Experiment flow", + ["flow.step.0"] = "Contour cutting", + ["flow.step.1"] = "Forming lines", + ["flow.step.2"] = "Projection", + ["flow.step.3"] = "Slope density", + ["flow.desc.0"] = "Watch a horizontal plane intersect the mountain at one elevation, forming closed lines.", + ["flow.desc.1"] = "Each horizontal slice leaves an equal-height line; stacked lines describe the relief.", + ["flow.desc.2"] = "Project every intersection line vertically onto one plane to build the contour map.", + ["flow.desc.3"] = "Contours closer together mean a steeper slope; wider apart mean a gentler one.", + + ["observe.title"] = "Experiment demo", + ["observe.default"] = "Press play to watch contour cutting and line formation, then use the four steps to learn projection and slope reading.", + ["observe.features"] = "Key points", + ["observe.default.f1"] = "All points on one contour share the same elevation", + ["observe.default.f2"] = "Neighbouring contours keep a constant height interval", + + ["side.landforms"] = "Five classic landforms", + ["landform.peak"] = "Peak", + ["landform.ridge"] = "Ridge", + ["landform.valley"] = "Valley", + ["landform.saddle"] = "Saddle", + ["landform.cliff"] = "Cliff", + ["landform.peak.sub"] = "Closed contours", + ["landform.ridge.sub"] = "Bulges toward low ground", + ["landform.valley.sub"] = "Bulges toward high ground", + ["landform.saddle.sub"] = "Between two peaks", + ["landform.cliff.sub"] = "Dense or overlapping", + + ["landform.peak.summary"] = "A peak rises in the centre with lower ground around it; contours close into rings and values increase inward.", + ["landform.ridge.summary"] = "Contours bulge toward lower ground; a ridge line often divides two drainage systems.", + ["landform.valley.summary"] = "Contours bulge toward higher ground; valleys are low and collect water into streams.", + ["landform.saddle.summary"] = "A saddle lies between two adjacent peaks, a relatively low pass along the ridge.", + ["landform.cliff.summary"] = "A cliff face is nearly vertical, so contours crowd tightly or even overlap.", + + ["landform.peak.f1"] = "High centre, low surroundings", + ["landform.peak.f2"] = "Closed lines grow in value inward", + ["landform.peak.f3"] = "If values drop inward, it is a depression", + ["landform.ridge.f1"] = "Contours bulge toward lower values", + ["landform.ridge.f2"] = "Ridge line runs from high to low", + ["landform.ridge.f3"] = "Rain drains to either side of the ridge", + ["landform.valley.f1"] = "Contours bulge toward higher values", + ["landform.valley.f2"] = "V tip points upstream to high ground", + ["landform.valley.f3"] = "Streams often form along the valley floor", + ["landform.saddle.f1"] = "Two neighbouring closed contour groups", + ["landform.saddle.f2"] = "Contours pinch in the middle like a saddle", + ["landform.saddle.f3"] = "Often a low mountain pass", + ["landform.cliff.f1"] = "Dense means steep; overlap means cliff", + ["landform.cliff.f2"] = "Large elevation change over a short distance", + ["landform.cliff.f3"] = "n overlapping lines: (n−1)d ≤ ΔH < (n+1)d", + + ["landform.peak.hint"] = "Peak: closed curves, values rise toward the centre", + ["landform.ridge.hint"] = "Ridge: contours bulge toward low ground", + ["landform.valley.hint"] = "Valley: contours bulge toward high ground", + ["landform.saddle.hint"] = "Saddle: low ground between two peaks", + ["landform.cliff.hint"] = "Cliff: contours dense or overlapping, very steep", + + ["btn.play"] = "Start experiment", + ["btn.pause"] = "Pause experiment", + ["btn.replay"] = "Replay experiment", + ["btn.reset"] = "Reset", + ["btn.view3d"] = "3D view", + ["btn.viewTop"] = "Top view", ["btn.color"] = "Colour", ["btn.colorOn"] = "No colour", + ["btn.fullscreen"] = "Fullscreen", + ["btn.exitFullscreen"] = "Exit fullscreen", + ["btn.backExperiment"] = "Back to experiment", ["side.features"] = "Five terrain features", ["feature.peak"] = "Peak", @@ -77,7 +210,16 @@ internal static class DefaultTexts ["rule.index"] = "Every 5th contour is bolded and labelled as an index contour.", ["rule.height"] = "Elevation above sea level; relative height is the difference of two elevations.", - ["footer.hint"] = "Move the pointer over either side to read elevation and terrain feature", - ["footer.readout"] = "Elevation {0} m Relative height {1} m" + ["footer.hint"] = "Drag the 3D terrain to rotate, scroll to zoom; hover to read elevation and terrain feature", + ["footer.readout"] = "Elevation {0} m Relative height {1} m", + ["legend.title"] = "Hypsometric tint", + ["profile.title"] = "Terrain profile", + ["slope.gentle"] = "Gentle (sparse lines)", + ["slope.steep"] = "Steep (dense lines)", + + ["hint.play"] = "Press start to watch contour cutting and line formation", + ["hint.playing"] = "Experiment playing", + ["hint.paused"] = "Experiment paused · press to resume", + ["hint.done"] = "Experiment finished · replay or choose a landform" }; } diff --git a/model/contour-map/src/TerrainAnalyzer.cs b/model/contour-map/src/TerrainAnalyzer.cs index 8abde38..a620daf 100644 --- a/model/contour-map/src/TerrainAnalyzer.cs +++ b/model/contour-map/src/TerrainAnalyzer.cs @@ -123,8 +123,6 @@ public static class TerrainAnalyzer public static (byte R, byte G, byte B) ColorForHeight(float h, float min, float max) { // 按绝对高程分档(教科书就是这么画的:看的是海拔,不是相对高度) - const float band = 200f; // 每 200 米一档 - if (h < 200) return (0x1E, 0x6B, 0x3A); // 深绿:< 200 m if (h < 400) return (0x4E, 0x9E, 0x4E); // 浅绿:200–400 if (h < 600) return (0xA8, 0xC6, 0x66); // 绿:400–600 @@ -136,6 +134,31 @@ public static class TerrainAnalyzer return (0xF5, 0xF5, 0xF0); // 白:> 1600(雪线以上) } + /// + /// 3D 立体视图用的连续设色:与俯视图同一套色阶,但在档位之间线性过渡。 + /// 立体视图的色块是按三角面着色的,直接用硬分档会在坡面上切出锯齿状阶梯, + /// 看起来像渲染错误;俯视图仍保留硬分档(那才是课本的分层设色)。 + /// + public static (byte R, byte G, byte B) ColorForHeightSmooth(float h) + { + // 每个档位的代表色(取档位中心),由低到高 + (byte R, byte G, byte B)[] stops = + { + (0x1E, 0x6B, 0x3A), (0x4E, 0x9E, 0x4E), (0xA8, 0xC6, 0x66), + (0xE8, 0xE2, 0x9A), (0xE0, 0xC0, 0x5A), (0xC8, 0x9A, 0x63), + (0xA8, 0x74, 0x4C), (0xC8, 0xA8, 0x8C), (0xF5, 0xF5, 0xF0) + }; + const float band = 200f; + var p = Math.Clamp(h / band - 0.5f, 0f, stops.Length - 1f); // 0 => 档心 100 m + var i = (int)Math.Floor(p); + var j = Math.Min(i + 1, stops.Length - 1); + var t = p - i; + t = t * t * (3 - 2 * t); // 平滑过渡 + return (Lerp(stops[i].R, stops[j].R, t), + Lerp(stops[i].G, stops[j].G, t), + Lerp(stops[i].B, stops[j].B, t)); + } + /// 该颜色属于哪一档(用于图例)。 public static string BandName(float h) => h switch { @@ -152,4 +175,20 @@ public static class TerrainAnalyzer private static byte Lerp(byte a, byte b, double k) => (byte)Math.Clamp(a + (b - a) * k, 0, 255); + + /// + /// 归一化坡度(0=平缓,1=陡峭),用于「疏密判坡」着色。 + /// 以有限差分求地面梯度,并按本模型的典型高差归一化。 + /// + public static double SlopeAt(TerrainField f, double u, double v) + { + const double h = 0.006; + var du = (f.SampleSmooth(u + h, v) - f.SampleSmooth(u - h, v)) / (2 * h); + var dv = (f.SampleSmooth(u, v + h) - f.SampleSmooth(u, v - h)) / (2 * h); + var grad = Math.Sqrt(du * du + dv * dv); // 米 / 归一化距离 + // 按本图实际起伏自适应归一化:跨度越大,同样的相对坡度对应更大的梯度。 + // 固定阈值会让所有山体都顶到 1(整片红),判坡就失效了。 + var span = Math.Max(60f, f.MaxHeight - f.MinHeight); + return Math.Clamp(grad / (span * 2.6), 0, 1); + } } diff --git a/model/contour-map/src/TerrainField.cs b/model/contour-map/src/TerrainField.cs index fb43e7a..879e4c4 100644 --- a/model/contour-map/src/TerrainField.cs +++ b/model/contour-map/src/TerrainField.cs @@ -13,6 +13,16 @@ public enum TerrainKind Plain // 平原:海拔低、地面平坦 } +/// 五大典型地貌部位(等高线判读的核心对象)。 +public enum LandformKind +{ + Peak, // 山峰:闭合等高线,数值向内升高 + Ridge, // 山脊:等高线凸向低处,凸低为脊 + Valley, // 山谷:等高线凸向高处,凸高为谷 + Saddle, // 鞍部:两峰之间相对低洼,俯视收腰 + Cliff // 陡崖:等高线密集甚至重合 +} + /// /// 地形高度场(等高线模型的数据核心)。 /// @@ -42,6 +52,9 @@ public sealed class TerrainField /// 这块地形属于哪种类型(决定界面标题与说明)。 public TerrainKind Kind { get; } + /// 若这块地形是某个典型地貌部位,则记录其种类;否则为 null。 + public LandformKind? Landform { get; } + public TerrainField(TerrainKind kind = TerrainKind.Mountain, int size = 192) { Size = size; @@ -50,6 +63,16 @@ public sealed class TerrainField Build(kind); } + /// 创建一个专门表现某种典型地貌部位的高度场。 + public TerrainField(LandformKind landform, int size = 192) + { + Size = size; + Kind = TerrainKind.Mountain; + Landform = landform; + Heights = new float[size, size]; + BuildLandform(landform); + } + /// 该类型对应的等高距:平原/丘陵用 20m,山地/高原/盆地用 100m。 public float EffectiveInterval => Kind switch { @@ -266,6 +289,157 @@ public sealed class TerrainField MinHeight = min; MaxHeight = max; } + // ───────────────────────── 五大典型地貌部位 ───────────────────────── + + private void BuildLandform(LandformKind landform) + { + switch (landform) + { + case LandformKind.Peak: BuildPeak(); break; + case LandformKind.Ridge: BuildRidge(); break; + case LandformKind.Valley: BuildValley(); break; + case LandformKind.Saddle: BuildSaddle(); break; + case LandformKind.Cliff: BuildCliff(); break; + } + BuildFeatures(); + } + + /// 山峰:单峰为主、层层闭合,四周逐级降低。配一处小侧峰便于读鞍部。 + private void BuildPeak() + { + var min = double.MaxValue; var max = double.MinValue; + for (var y = 0; y < Size; y++) + for (var x = 0; x < Size; x++) + { + var u = (double)x / (Size - 1); + var v = (double)y / (Size - 1); + var du = u - 0.5; var dv = (v - 0.5) / 0.94; + var r = Math.Sqrt(du * du + dv * dv); + // 主峰:宽阔的穹状山体(半径约占图幅 8 成),层层闭合的等高线才画得开 + var core = Math.Exp(-Math.Pow(r / 0.36, 1.85)); + var rim = 1 - SmoothStep(0.36, 0.50, r); // 山脚过渡到平地 + var h = 65 + 1230 * core * rim; + // 东南侧肩部,让等高线不是完美同心圆 + h += 120 * Math.Exp(-(Math.Pow(u - 0.72, 2) + Math.Pow(v - 0.66, 2)) / 0.016) * rim; + h += 22 * Math.Sin(u * 7.3 + 0.6) * Math.Cos(v * 6.1) * rim; + h = Math.Max(0, h); + Heights[y, x] = (float)h; + if (h < min) min = h; if (h > max) max = h; + } + MinHeight = (float)min; MaxHeight = (float)max; + Tags.Clear(); + Tags.Add((0.5, 0.5, 0.09, TerrainFeature.Peak)); + } + + /// 山脊:一条狭长高地,等高线沿脊线向低处凸出(凸低为脊)。 + private void BuildRidge() + { + var min = double.MaxValue; var max = double.MinValue; + for (var y = 0; y < Size; y++) + for (var x = 0; x < Size; x++) + { + var u = (double)x / (Size - 1); + var v = (double)y / (Size - 1); + // 脊线沿 u 方向(西高东低),东西向是长坡,南北向是宽缓的两翼 + var crestV = 0.5 + 0.10 * Math.Sin(u * 3.1); // 脊线轻微弯曲 + var across = v - crestV; + var crest = 1150 - 380 * u; // 脊线海拔由西向东降低 + var lateral = Math.Exp(-Math.Pow(Math.Abs(across) / 0.27, 1.55)); + var h = 85 + (crest - 85) * lateral; + // 两翼的次级起伏,避免像一堵直墙 + h += 60 * Math.Exp(-Math.Pow(Math.Abs(across) - 0.30, 2) / 0.010) * (0.4 + 0.6 * (1 - u)); + h += 24 * Math.Sin(u * 8.0) * Math.Cos(v * 5.6); + h = Math.Max(0, h); + Heights[y, x] = (float)h; + if (h < min) min = h; if (h > max) max = h; + } + MinHeight = (float)min; MaxHeight = (float)max; + Tags.Clear(); + Tags.Add((0.30, 0.50, 0.09, TerrainFeature.Ridge)); + Tags.Add((0.70, 0.50, 0.09, TerrainFeature.Ridge)); + } + + /// 山谷:两侧高地夹持的低槽,等高线形成 V 形指向上游(凸高为谷)。 + private void BuildValley() + { + var min = double.MaxValue; var max = double.MinValue; + for (var y = 0; y < Size; y++) + for (var x = 0; x < Size; x++) + { + var u = (double)x / (Size - 1); + var v = (double)y / (Size - 1); + // 谷轴沿 v 方向:两侧高、中间是 V 形谷底;北侧(v 小)为上游更高 + var side = Math.Pow(Math.Abs(u - 0.5) / 0.5, 1.5); // 0=谷心 1=图边 + var downhill = 1 - v; // 上游 1 → 下游 0 + var h = 90 + 760 * downhill + 585 * side * (0.30 + 0.70 * downhill); + // 谷底再切深一点,形成明显的集水线 + h -= 70 * Math.Exp(-Math.Pow(u - 0.5, 2) / 0.0022); + h += 18 * Math.Sin(u * 6.5) * Math.Cos(v * 7.2); + h = Math.Max(0, h); + Heights[y, x] = (float)h; + if (h < min) min = h; if (h > max) max = h; + } + MinHeight = (float)min; MaxHeight = (float)max; + Tags.Clear(); + Tags.Add((0.50, 0.40, 0.075, TerrainFeature.Valley)); + Tags.Add((0.50, 0.68, 0.075, TerrainFeature.Valley)); + } + + /// 鞍部:两座山峰之间相对低洼、俯视轮廓收腰的过渡地带。 + private void BuildSaddle() + { + var min = double.MaxValue; var max = double.MinValue; + for (var y = 0; y < Size; y++) + for (var x = 0; x < Size; x++) + { + var u = (double)x / (Size - 1); + var v = (double)y / (Size - 1); + // 两峰在 v≈0.5 的连线上,u=0.27 与 u=0.73;中间 u=0.5 为垭口 + var d1 = Math.Sqrt(Math.Pow((u - 0.27) / 0.30, 2) + Math.Pow((v - 0.52) / 0.28, 2)); + var d2 = Math.Sqrt(Math.Pow((u - 0.73) / 0.30, 2) + Math.Pow((v - 0.48) / 0.28, 2)); + var p1 = 1140 * Math.Exp(-Math.Pow(d1, 2.2)); + var p2 = 1060 * Math.Exp(-Math.Pow(d2, 2.2)); + // 南北两侧缓慢降低,把两峰连成一条东西向的山梁 + var bench = 330 * Math.Exp(-Math.Pow((v - 0.5) / 0.34, 2)); + var h = 65 + bench + Math.Max(p1, p2); + h += 20 * Math.Sin(u * 8.0) * Math.Cos(v * 7.0); + h = Math.Max(0, h); + Heights[y, x] = (float)h; + if (h < min) min = h; if (h > max) max = h; + } + MinHeight = (float)min; MaxHeight = (float)max; + Tags.Clear(); + Tags.Add((0.28, 0.50, 0.05, TerrainFeature.Peak)); + Tags.Add((0.72, 0.50, 0.05, TerrainFeature.Peak)); + Tags.Add((0.50, 0.50, 0.045, TerrainFeature.Saddle)); + } + + /// 陡崖:一侧近乎直立的高差带,等高线在崖壁处高度密集甚至重合。 + private void BuildCliff() + { + var min = double.MaxValue; var max = double.MinValue; + for (var y = 0; y < Size; y++) + for (var x = 0; x < Size; x++) + { + var u = (double)x / (Size - 1); + var v = (double)y / (Size - 1); + // 西侧低台地、东侧高台地,中间一条近乎直立的高差带形成陡崖 + // 崖线略呈波状(真实崖壁不是一条直线),过渡带留出 2~3 个采样格 + var edge = SmoothStep(0.50, 0.62, u + 0.045 * Math.Sin(v * 5.2) + 0.02 * Math.Sin(v * 11.0)); + var h = 210 + 940 * edge; + // 高台地北高南低、顶面起伏,低台地保持缓坡 + h += 170 * (1 - v) * edge; + h += 55 * Math.Sin(v * 5.4) * Math.Cos(u * 4.2) * (0.4 + 0.6 * edge); + h += 26 * Math.Sin(u * 9.0); // 顶面轻微起伏 + h = Math.Max(0, h); + Heights[y, x] = (float)h; + if (h < min) min = h; if (h > max) max = h; + } + MinHeight = (float)min; MaxHeight = (float)max; + Tags.Clear(); + Tags.Add((0.50, 0.50, 0.035, TerrainFeature.Cliff)); + } + private static double SmoothStep(double a, double b, double x) { var t = Math.Clamp((x - a) / (b - a), 0, 1); @@ -452,46 +626,77 @@ public sealed class TerrainField private static double Lerp(double a, double b, double t) => a + (b - a) * Math.Clamp(double.IsNaN(t) ? 0.5 : t, 0, 1); - /// 把零散线段按端点邻近关系串成折线。 + /// + /// 把零散线段按端点串成完整折线。 + /// 关键点:必须**两端都延伸**。只往尾部延伸时,起点落在曲线中段就会把一条等高线 + /// 切成许多短链,渲染出来是断续的虚线(学生看到的就是“虚线等高线”)。 + /// private static List> Chain( List<(double U1, double V1, double U2, double V2)> segments) { - const double Eps = 0.004; - var result = new List>(); + // 量化到 1e-4 的网格做端点索引:共享边上的交点由同一次插值算出, + // 端点值完全一致;网格远小于采样间距(1/192≈0.0052),不会误并。 + const double Q = 1e4; + static (long, long) Key(double u, double v) + => ((long)Math.Round(u * Q), (long)Math.Round(v * Q)); + + var index = new Dictionary<(long, long), List>(); + void Register(double u, double v, int seg) + { + var k = Key(u, v); + if (!index.TryGetValue(k, out var list)) index[k] = list = new List(); + list.Add(seg); + } + + for (var i = 0; i < segments.Count; i++) + { + Register(segments[i].U1, segments[i].V1, i); + Register(segments[i].U2, segments[i].V2, i); + } + var used = new bool[segments.Count]; + var result = new List>(); + + int NextAt(double u, double v) + { + if (!index.TryGetValue(Key(u, v), out var list)) return -1; + foreach (var j in list) if (!used[j]) return j; + return -1; + } for (var i = 0; i < segments.Count; i++) { if (used[i]) continue; used[i] = true; - var line = new List<(double, double)> + var line = new List<(double U, double V)> { (segments[i].U1, segments[i].V1), (segments[i].U2, segments[i].V2) }; - // 向两端延伸 - var grown = true; - while (grown) + // 向尾部延伸 + while (true) { - grown = false; - var (tailU, tailV) = line[^1]; - for (var j = 0; j < segments.Count; j++) - { - if (used[j]) continue; - var s = segments[j]; - if (Near(tailU, tailV, s.U1, s.V1, Eps)) - { - line.Add((s.U2, s.V2)); used[j] = true; grown = true; break; - } - if (Near(tailU, tailV, s.U2, s.V2, Eps)) - { - line.Add((s.U1, s.V1)); used[j] = true; grown = true; break; - } - } + var (tu, tv) = line[^1]; + var j = NextAt(tu, tv); + if (j < 0) break; + used[j] = true; + var s = segments[j]; + line.Add(Key(s.U1, s.V1) == Key(tu, tv) ? (s.U2, s.V2) : (s.U1, s.V1)); } - if (line.Count >= 4) result.Add(line); + // 向头部延伸 + while (true) + { + var (hu, hv) = line[0]; + var j = NextAt(hu, hv); + if (j < 0) break; + used[j] = true; + var s = segments[j]; + line.Insert(0, Key(s.U1, s.V1) == Key(hu, hv) ? (s.U2, s.V2) : (s.U1, s.V1)); + } + + if (line.Count >= 3) result.Add(line); } return result;