XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.UI.Xaml.Media;
using Windows.Foundation;
using XFEEDToolBox.Core.Models;
using XFEEDToolBox.Core.Navigation;
using XFEEDToolBox.Core.Rendering;
using XFEEDToolBox.Core.Services;
using XFEEDToolBox.Views;

namespace XFEEDToolBox;

public partial class App
{
    private static async Task<object> RunLocalSystemMapProbeAsync(string directory)
    {
        Directory.CreateDirectory(directory);
        var args=Environment.GetCommandLineArgs();var recording=GetArgument(args,"--system-map-snapshot");
        var recorded=recording is not null;string? recordingHash=null,failure=null;
        var checks=new List<object>();var captures=new List<string>();var states=new List<object>();var failedChecks=0;var unconfirmedChecks=0;
        var size=MainWindow.AppWindow.Size;var search=ViewModel.CurrentSystemSearch;
        var selected=ViewModel.SelectedSystemLocation?.Record.Identity;
        bool[] ReadFilters()=>[ViewModel.ShowSystemStars,ViewModel.ShowSystemAsteroids,ViewModel.ShowSystemPlanets,ViewModel.ShowSystemLandablePlanets,ViewModel.ShowSystemSettlements,ViewModel.ShowSystemStations,ViewModel.ShowSystemCarriers,ViewModel.ShowSystemPoints,ViewModel.ShowSystemSignals,ViewModel.ShowSystemOther];
        void SetFilters(bool[] value)
        {
            ViewModel.ShowSystemStars=value[0];ViewModel.ShowSystemAsteroids=value[1];ViewModel.ShowSystemPlanets=value[2];ViewModel.ShowSystemLandablePlanets=value[3];
            ViewModel.ShowSystemSettlements=value[4];ViewModel.ShowSystemStations=value[5];ViewModel.ShowSystemCarriers=value[6];ViewModel.ShowSystemPoints=value[7];ViewModel.ShowSystemSignals=value[8];ViewModel.ShowSystemOther=value[9];
        }
        var filters=ReadFilters();
        void Check(string id,bool? passed,string evidence)
        {if(passed==false)failedChecks++;if(passed is null)unconfirmedChecks++;checks.Add(new{id,status=passed is null?"unconfirmed":passed.Value?"passed":"failed",evidence});}
        void Require(bool passed,string message){if(!passed)throw new InvalidOperationException(message);}
        CurrentSystemSnapshot? source=null;CurrentSystemPage? page=null;
        object? Bounds(FrameworkElement? element)
        {
            if(page is null||element is null||element.ActualWidth<=0||element.ActualHeight<=0)return null;
            try{var point=element.TransformToVisual(page).TransformPoint(new(0,0));return new{element.Name,x=point.X,y=point.Y,width=element.ActualWidth,height=element.ActualHeight,right=point.X+element.ActualWidth,bottom=point.Y+element.ActualHeight};}
            catch(ArgumentException){return null;}catch(InvalidOperationException){return null;}
        }
        bool Visible(FrameworkElement element)
        {
            DependencyObject? current=element;
            while(current is not null)
            {if(current is UIElement ui&&ui.Visibility!=Visibility.Visible)return false;if(ReferenceEquals(current,page))break;current=VisualTreeHelper.GetParent(current);}
            return element.ActualWidth>0&&element.ActualHeight>0;
        }
        bool Fits(FrameworkElement child,FrameworkElement container)
        {
            if(child.ActualWidth<=0||child.ActualHeight<=0)return false;
            var at=child.TransformToVisual(container).TransformPoint(new(0,0));
            return at.X>=-1&&at.Y>=-1&&at.X+child.ActualWidth<=container.ActualWidth+1&&at.Y+child.ActualHeight<=container.ActualHeight+1;
        }
        static bool Overlaps(FrameworkElement first,FrameworkElement second,FrameworkElement relativeTo)
        {
            var a=first.TransformToVisual(relativeTo).TransformPoint(new(0,0));var b=second.TransformToVisual(relativeTo).TransformPoint(new(0,0));
            return a.X<b.X+second.ActualWidth-1&&a.X+first.ActualWidth>b.X+1&&a.Y<b.Y+second.ActualHeight-1&&a.Y+first.ActualHeight>b.Y+1;
        }
        void RecordedLabel()
        {
            if(!recorded||source is null)return;
            ViewModel.CurrentSystemStatus=$"录制目录核验 · {source.ObservedAt.ToLocalTime():yyyy-MM-dd HH:mm:ss zzz} · {ViewModel.CurrentSystemLocations.Count}/{source.Locations.Count} 个地点";
            ViewModel.SystemControlAvailability="录制目录核验 · 未连接游戏驾驶接口。";
            ViewModel.SystemFlightStatus="录制目录核验 · 仅验证浏览交互,不启动驾驶。";
        }
        static bool ProjectionChanged(LocalSystemProjection[] before,LocalSystemProjection[] after)
        {
            var old=before.ToDictionary(point=>point.Node.Location.Identity);
            return after.Any(point=>old.TryGetValue(point.Node.Location.Identity,out var previous)&&
                (Math.Abs(point.X-previous.X)>.1||Math.Abs(point.Y-previous.Y)>.1||Math.Abs(point.Depth-previous.Depth)>.001));
        }
        async Task<(string? GpuHash,LocalSystemProjection[] Projections,LocalSystemCamera Camera)> Capture(string name)
        {
            Require(page is not null,"The system page is not available.");RecordedLabel();page!.UpdateLayout();await Task.Delay(100);
            var map=page.MapForProbe;map.RenderNowForProbe();
            var snapshot=ViewModel.CurrentSystemSceneSnapshot??throw new InvalidOperationException("The current system snapshot disappeared.");
            var rows=ViewModel.CurrentSystemLocations.Select(row=>row.Record).ToArray();
            var projections=map.ProjectedLocations.ToArray();var camera=map.CameraState;
            var actual=snapshot.Locations.GroupBy(row=>row.Identity).ToDictionary(group=>group.Key,group=>group.First());
            var expected=new LocalSystemScene(snapshot,null,map.ViewOrientationForProbe).Nodes.ToDictionary(node=>node.Location.Identity);
            var fromSource=rows.All(row=>actual.TryGetValue(row.Identity,out var known)&&known==row)
                &&projections.All(point=>actual.TryGetValue(point.Node.Location.Identity,out var known)&&known==point.Node.Location
                    &&expected.TryGetValue(point.Node.Location.Identity,out var node)&&(point.Node.Position-node.Position).Length<1e-9);
            string? gpuHash=null;object? gpu=null;IDisposable? frozen=null;
            try
            {
                var frame=map.CapturePixelsForProbe();gpuHash=Convert.ToHexString(SHA256.HashData(frame.Pixels));
                gpu=new{frame.Width,frame.Height,sha256=gpuHash,bytes=frame.Pixels.Length,source="actual-D3D11-readback"};
                frozen=await map.FreezeForXamlProbeAsync();page.UpdateLayout();await Task.Delay(60);
                var path=Path.Combine(directory,name+".png");await CapturePageAsync(page,path);captures.Add(path);
            }
            catch(Exception error)
            {
                Check("gpu-"+name,false,error.ToString());
                var path=Path.Combine(directory,name+"-fallback.png");await CapturePageAsync(page,path);captures.Add(path);
            }
            finally{frozen?.Dispose();}
            FrameworkElement Find(string id)=>(FrameworkElement)(page.FindName(id)??throw new InvalidOperationException("Missing system page element: "+id));
            var list=Find("LocationsList");var card=Find("DestinationCard");var scene=Find("SceneLayout");
            var viewport=Find("ViewportHost");var actions=Find("DestinationActions");
            var detail=((card as Border)?.Child as Grid)?.Children.OfType<FrameworkElement>().FirstOrDefault(element=>element!=actions);
            var toolbar=Descendants(viewport).OfType<StackPanel>().FirstOrDefault(panel=>panel.Children.OfType<Button>().Count()==4);
            var badge=page.FindName("SceneStatusBadge") as FrameworkElement;
            var cardVisible=Visible(card);
            var detailsFit=!cardVisible||detail is not null&&Fits(detail,card)&&Fits(actions,card)&&!Overlaps(detail,actions,card)
                &&Descendants(detail).OfType<TextBlock>().Where(Visible).All(text=>Fits(text,detail));
            var hudFit=toolbar is not null&&Fits(toolbar,viewport)&&(badge is null||badge.Visibility!=Visibility.Visible||!Overlaps(badge,toolbar,viewport));
            var horizontal=Descendants(list).OfType<ScrollViewer>().Any(scroll=>scroll.ScrollableWidth>1);
            var cardFits=(!cardVisible||Fits(card,scene))&&Fits(scene,page);
            var listScroll=Descendants(list).OfType<ScrollViewer>().FirstOrDefault();
            var realizedRows=Descendants(list).OfType<ListViewItem>().Where(Visible).ToArray();
            var rowHeight=realizedRows.Select(row=>row.ActualHeight).DefaultIfEmpty(0).Min();
            var listViewportHeight=listScroll?.ViewportHeight??list.ActualHeight;
            var completeRows=realizedRows.Count(row=>Fits(row,(FrameworkElement?)listScroll??list));
            var neededRows=Math.Min(2,rows.Length);
            var catalogueUsable=neededRows==0||rowHeight>0&&listViewportHeight>=neededRows*rowHeight-1&&completeRows>=neededRows;
            var allSymbols=expected.Count>0&&projections.Length==expected.Count&&projections.All(point=>point.X-point.Radius>=-1&&point.Y-point.Radius>=-1
                &&point.X+point.Radius<=map.ProjectionWidth+1&&point.Y+point.Radius<=map.ActualHeight+1);
            states.Add(new{name,mode=recorded?"recorded-catalogue":"live-current-system",snapshot.SystemAddress,snapshot.SystemName,snapshot.EntityId,snapshot.Sequence,snapshot.ObservedAt,
                rows,projections=projections.Select(point=>new{point.Node.Location.Identity,point.Node.Location.Key,actualPosition=point.Node.Location.Position,
                    displayPosition=point.Node.Position,point.X,point.Y,point.Depth,point.Radius,point.Selected}).ToArray(),positionsFromSnapshot=fromSource,
                snapshot.PlayerPosition,snapshot.PlayerForward,camera,gpu,map.FrameCount,map.GraphicsError,
                pageWidth=page.ActualWidth,pageHeight=page.ActualHeight,windowWidth=MainWindow.AppWindow.Size.Width,windowHeight=MainWindow.AppWindow.Size.Height,
                markers=map.MarkerLocations.Select(point=>point.Node.Location.Identity),icons=map.IconsForProbe,
                selected=ViewModel.SelectedSystemLocation?.Record,ViewModel.SelectedSystemTitle,ViewModel.SelectedSystemKind,ViewModel.SelectedSystemDistance,ViewModel.SelectedSystemPositionStatus,
                ViewModel.CurrentSystemStatus,ViewModel.SystemControlAvailability,ViewModel.SystemFlightStatus,
                startEnabled=ViewModel.StartSystemFlightCommand.CanExecute(null),ViewModel.SystemFlightActive,
                search=ViewModel.CurrentSystemSearch,filters=ReadFilters(),list=Bounds(list),map=Bounds(map),viewport=Bounds(viewport),card=Bounds(card),goButton=Bounds(Find("GoButton")),
                cardVisible,details=Bounds(detail),actions=Bounds(actions),detailTexts=(detail is null?Enumerable.Empty<TextBlock>():Descendants(detail).OfType<TextBlock>()).Where(Visible).Select(text=>new{text.Text,bounds=Bounds(text)}).ToArray(),toolbar=Bounds(toolbar),sceneBadge=Bounds(badge),sceneBadgeVisible=badge?.Visibility==Visibility.Visible,
                listViewportHeight,rowHeight,fullyVisibleRows=completeRows,requiredVisibleRows=neededRows,catalogueUsable,
                allSymbolsWithinProjectionViewport=allSymbols,positionedCount=expected.Count,projectedCount=projections.Length,projectionWidth=map.ProjectionWidth,
                listScrollableHeight=Descendants(list).OfType<ScrollViewer>().Select(scroll=>scroll.ScrollableHeight).DefaultIfEmpty(0).Max(),horizontalOverflow=horizontal,cardFitsSceneAndPage=cardFits,detailsAndActionsFit=detailsFit,sceneHudFits=hudFit});
            Check("source-"+name,fromSource,"Every visible row and projected raw position is in this immutable real snapshot; display positions equal the production distance transform.");
            Check("layout-"+name,!horizontal&&cardFits,$"List horizontal overflow={horizontal}; destination card/scene fit={cardFits}; page {page.ActualWidth:F1} × {page.ActualHeight:F1} DIP.");
            Check("details-"+name,detailsFit,"Detail text containers fit inside their column and the destination card; the action column does not overlap the detail column.");
            Check("catalogue-viewport-"+name,catalogueUsable,$"Actual catalogue viewport {listViewportHeight:F1} DIP; row height {rowHeight:F1}; fully visible rows {completeRows}, required {neededRows}. A clipped selected-row stripe cannot count as a usable catalogue.");
            Check("hud-"+name,hudFit,"The actual map toolbar fits the viewport and does not intersect a visible scene-status badge.");
            Check("full-scene-"+name,Math.Abs(map.ActualWidth-page.ActualWidth)<1&&Math.Abs(map.ActualHeight-page.ActualHeight)<1&&Overlaps(Find("CataloguePanel"),map,page),"The 3D viewport fills the page and the catalogue overlays it instead of reserving a map column.");
            if(camera==map.OverviewCameraForProbe)Check("overview-symbols-"+name,expected.Count>0?allSymbols:null,"Overview must project every actual positioned node with its complete symbol radius inside the projection viewport, including narrow layouts.");
            return(gpuHash,projections,camera);
        }
        try
        {
            Require(!ViewModel.DemoMode,"System map acceptance must not use demonstration data.");
            if(recorded)
            {
                var dataArg=GetArgument(args,"--data-dir");
                var actual=Path.GetFullPath(Runtime.DataDirectory).TrimEnd(Path.DirectorySeparatorChar,Path.AltDirectorySeparatorChar);
                var production=Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"XFEstudio","XFEEDToolBox"));
                Require(args.Contains("--offline-preview")&&ViewModel.OfflinePreview&&dataArg is not null&&Path.IsPathFullyQualified(dataArg),"Recorded catalogue acceptance requires --offline-preview and an explicit absolute isolated --data-dir.");
                Require(!actual.Equals(production,StringComparison.OrdinalIgnoreCase)&&!actual.StartsWith(production+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase),"The recorded catalogue must not use production user data.");
                Require(Path.IsPathFullyQualified(recording!),"The recorded snapshot path must be absolute.");
                var bytes=await File.ReadAllBytesAsync(recording!);recordingHash=Convert.ToHexString(SHA256.HashData(bytes));
                source=JsonSerializer.Deserialize<CurrentSystemSnapshot>(bytes,ToolboxSettings.JsonOptions)??throw new InvalidDataException("The recorded catalogue is empty.");
                Require(source.SystemAddress>0&&source.ObservedAt!=default&&source.Locations.Count>0,"The recorded file has no usable actual system identity, observation time or locations.");
                ViewModel.ApplyCurrentSystemSnapshot(source);
            }
            AppShellPage.Current!.Navigate(typeof(CurrentSystemPage));await Task.Delay(250);
            page=(CurrentSystemPage)AppShellPage.Current.CurrentPage!;
            if(!recorded)
            {
                var requestedAt=DateTimeOffset.UtcNow;
                bool FreshRead()=>ViewModel.CurrentSystemSceneSnapshot is {} snapshot&&snapshot.ObservedAt>=requestedAt.AddSeconds(-2)
                    &&snapshot.ObservedAt<=DateTimeOffset.UtcNow.AddSeconds(1)
                    &&(Runtime.Player.Navigation.CurrentSystemAddress is not >0||Runtime.Player.Navigation.CurrentSystemAddress==snapshot.SystemAddress);
                ViewModel.ShowCurrentSystem();
                try
                {
                    await ViewModel.RefreshCurrentSystemCommand.ExecuteAsync(null);
                    var until=DateTimeOffset.UtcNow.AddSeconds(30);
                    while((!FreshRead()||ViewModel.CurrentSystemReading)&&DateTimeOffset.UtcNow<until)await Task.Delay(100);
                    source=ViewModel.CurrentSystemSceneSnapshot;
                }
                finally{ViewModel.HideCurrentSystem();}
                Require(FreshRead(),"No fresh catalogue of the actual current system was read; no recorded, stale or synthetic catalogue was substituted.");
            }
            SetFilters(Enumerable.Repeat(true,10).ToArray());ViewModel.CurrentSystemSearch="";ViewModel.SelectedSystemLocation=null;
            page.MapForProbe.ResetCamera();
            var overview=await Capture("system-map-overview");
            if(GetArgument(args,"--system-map-updates") is {} updatesDirectory)
            {
                var firstStars=overview.Projections.Where(point=>point.Node.Location.Category==SystemLocationCategory.Star).ToDictionary(point=>point.Node.Location.WorldAddress);
                foreach(var update in Directory.GetFiles(updatesDirectory,"system-*.json").Order(StringComparer.Ordinal))
                {
                    var next=JsonSerializer.Deserialize<CurrentSystemSnapshot>(await File.ReadAllTextAsync(update),ToolboxSettings.JsonOptions)!;
                    if(next.SystemAddress!=source!.SystemAddress||next.ObservedAt<=source.ObservedAt)continue;
                    source=next;ViewModel.ApplyCurrentSystemSnapshot(next);await Task.Delay(80);
                }
                var refreshed=await Capture("system-map-reference-refreshed");
                var drift=refreshed.Projections.Where(point=>point.Node.Location.Category==SystemLocationCategory.Star&&firstStars.ContainsKey(point.Node.Location.WorldAddress))
                    .Select(point=>Math.Sqrt(Math.Pow(point.X-firstStars[point.Node.Location.WorldAddress].X,2)+Math.Pow(point.Y-firstStars[point.Node.Location.WorldAddress].Y,2))).DefaultIfEmpty(double.NaN).Max();
                Check("reference-stable",drift<1&&refreshed.Camera==overview.Camera,$"Successive actual native snapshots preserve camera and stellar screen positions (maximum {drift:F6} DIP); only verified reference rotation is removed.");
            }
            Check("graphics-ready",overview.GpuHash is not null&&page.MapForProbe.GraphicsError.Length==0&&page.MapForProbe.FrameCount>0,"The off-screen GPU texture was drawn and read back; this does not prove native window presentation. Use the separate ordinary-composition capture for that check.");
            Check("ship-position",source!.PlayerPosition is {Finite:true}?true:null,"A main-ship marker can only be confirmed when this real snapshot includes finite PlayerPosition; no missing pose is replaced with zero.");
            var list=(ListView)page.FindName("LocationsList");
            var candidate=ViewModel.CurrentSystemLocations.FirstOrDefault(row=>row.Record.Position is {Finite:true}&&row.Record.Category is SystemLocationCategory.Station or SystemLocationCategory.Planet or SystemLocationCategory.LandablePlanet)
                ??ViewModel.CurrentSystemLocations.FirstOrDefault(row=>row.Record.Position is {Finite:true});
            if(candidate is not null)
            {
                list.SelectedItem=candidate;list.ScrollIntoView(candidate);await Task.Delay(100);
                var fromList=await Capture("system-map-list-selected");
                Check("list-selects-map",ViewModel.SelectedSystemLocation?.Record.Identity==candidate.Record.Identity&&fromList.Projections.Any(point=>point.Selected&&point.Node.Location.Identity==candidate.Record.Identity),"Actual ListView selection updates the same VM identity and selected scene node.");
            }
            else Check("list-selects-map",null,"No actual positioned row exists to select.");
            page.MapForProbe.ResetCamera();page.MapForProbe.RenderNowForProbe();
            var hit=page.MapForProbe.InteractiveLocations.Where(point=>point.X>18&&point.X<page.MapForProbe.ProjectionWidth-18&&point.Y>80&&point.Y<page.MapForProbe.ActualHeight-45)
                .OrderBy(point=>point.Node.Location.Identity==ViewModel.SelectedSystemLocation?.Record.Identity).FirstOrDefault();
            if(hit is not null)
            {
                var expected=LocalSystemScene.HitTest(page.MapForProbe.InteractiveLocations,hit.X,hit.Y).First();
                page.MapForProbe.SelectAtForProbe(new Point(hit.X,hit.Y));await Task.Delay(100);
                Check("map-selects-list",ViewModel.SelectedSystemLocation?.Record.Identity==expected.Node.Location.Identity&&(list.SelectedItem as Core.Presentation.SystemLocationLiveRow)?.Record.Identity==expected.Node.Location.Identity,"Uses production hit testing and the production map/list selection event; no Flyout or OS input is sent.");
            }
            else Check("map-selects-list",null,"No actual projected marker lies within the unobstructed hit-test region.");
            var before=await Capture("system-map-map-selected");
            page.MapForProbe.RotateForProbe(85,38);var rotated=await Capture("system-map-rotated");
            Check("camera-rotate",before.Camera!=rotated.Camera&&ProjectionChanged(before.Projections,rotated.Projections)&&before.GpuHash is not null&&rotated.GpuHash is not null&&before.GpuHash!=rotated.GpuHash,"Production camera rotation changes perspective projections and actual GPU texture pixels.");
            page.MapForProbe.PanForProbe(25,-18);var panned=await Capture("system-map-panned");
            Check("camera-pan",rotated.Camera!=panned.Camera&&ProjectionChanged(rotated.Projections,panned.Projections)&&rotated.GpuHash is not null&&panned.GpuHash is not null&&rotated.GpuHash!=panned.GpuHash,"Production pan changes camera target, projected positions and actual GPU pixels.");
            page.MapForProbe.Zoom(1.5);var zoomed=await Capture("system-map-zoomed");
            Check("camera-zoom",panned.Camera.Distance!=zoomed.Camera.Distance&&ProjectionChanged(panned.Projections,zoomed.Projections)&&panned.GpuHash is not null&&zoomed.GpuHash is not null&&panned.GpuHash!=zoomed.GpuHash,"Production zoom changes distance, projections and actual GPU pixels.");
            page.MapForProbe.FocusSelection();var focused=await Capture("system-map-focused");
            Check("camera-focus",ViewModel.SelectedSystemLocation?.Record.Position is {Finite:true}?focused.Camera.Distance==2.2:null,"Focus uses the selected real positioned node; it never supplies a game flight command.");
            page.MapForProbe.ResetCamera();var reset=await Capture("system-map-reset");
            Check("camera-overview",reset.Camera==page.MapForProbe.OverviewCameraForProbe,"Overview restores the production viewport-fitted camera preset.");
            SetFilters(Enumerable.Repeat(false,10).ToArray());await Capture("system-map-default-filter");
            Check("empty-types-show-all",ViewModel.CurrentSystemLocations.Count==source.Locations.Count&&page.MapForProbe.ProjectedLocations.Count==reset.Projections.Length,"No selected type is the default and shows every location, model and orbit, exactly like selecting all types.");
            ViewModel.ShowSystemStations=true;await Capture("system-map-one-type");
            Check("one-type-shortcut",ViewModel.CurrentSystemLocations.All(row=>row.Record.Category==SystemLocationCategory.Station)&&page.MapForProbe.MarkerLocations.All(point=>point.Node.Location.Category==SystemLocationCategory.Station)
                &&page.MapForProbe.ProjectedLocations.Count==reset.Projections.Length,"One checked type filters directly while every physical model stays in the scene.");
            SetFilters(Enumerable.Repeat(true,10).ToArray());
            ViewModel.ShowSystemCarriers=false;await Capture("system-map-type-filtered");
            Check("type-filter",ViewModel.CurrentSystemLocations.All(row=>(row.Record.Category&SystemLocationCategory.Carrier)==0)&&page.MapForProbe.MarkerLocations.All(point=>(point.Node.Location.Category&SystemLocationCategory.Carrier)==0)
                &&page.MapForProbe.ProjectedLocations.Count==reset.Projections.Length,"Category filtering removes matching icons and labels; model geometry and orbit coverage stay in the full scene.");
            ViewModel.ShowSystemCarriers=true;
            if(candidate is not null)
            {
                ViewModel.CurrentSystemSearch=candidate.Record.Name;await Capture("system-map-search-filtered");
                var current=ViewModel.CurrentSystemSceneSnapshot!;var expected=new SystemLocationFilter(SystemLocationCategory.All,candidate.Record.Name).Apply(current).Select(row=>row.Identity).Order().ToArray();
                Check("search-filter",ViewModel.CurrentSystemLocations.Select(row=>row.Record.Identity).Order().SequenceEqual(expected)&&page.MapForProbe.MarkerLocations.All(point=>expected.Contains(point.Node.Location.Identity))
                    &&page.MapForProbe.ProjectedLocations.Count==reset.Projections.Length,"Search filters list rows, icons and labels while retaining all physical 3D model positions and orbit lines.");
            }
            ViewModel.CurrentSystemSearch="";
            foreach(var star in ViewModel.CurrentSystemLocations.Where(row=>row.Record.Category==SystemLocationCategory.Star).Take(3).ToArray())
            {
                list.SelectedItem=star;page.MapForProbe.FocusSelection();page.MapForProbe.Zoom(2);await Task.Delay(100);
                await Capture("system-map-star-"+star.Record.NativeStarType);page.MapForProbe.ResetCamera();
            }
            var unknown=ViewModel.CurrentSystemLocations.FirstOrDefault(row=>row.Record.Position is not {Finite:true});
            if(unknown is not null)
            {
                list.SelectedItem=unknown;list.ScrollIntoView(unknown);await Capture("system-map-unknown-position");
                Check("unknown-position",!ViewModel.StartSystemFlightCommand.CanExecute(null)&&!page.MapForProbe.ProjectedLocations.Any(point=>point.Node.Location.Identity==unknown.Record.Identity)&&ViewModel.SelectedSystemPositionStatus.Contains("坐标待确认",StringComparison.Ordinal),"An actual unknown-position row stays selectable in the list, gets no invented scene point and cannot start flight.");
            }
            else Check("unknown-position",null,"This actual catalogue contains no unknown-position row; none was manufactured.");
            if(candidate is not null)list.SelectedItem=candidate;
            page.MapForProbe.ResetCamera();
            foreach(var (width,height,name) in new[]{(1510,980,"system-map-default-1510x980"),(1360,1040,"system-map-narrow-1360"),(1280,1040,"system-map-narrow-1280")})
            {MainWindow.AppWindow.Resize(new(width,height));await Task.Delay(250);page.UpdateLayout();await Capture(name);}
            Check("selection-does-not-start-flight",!ViewModel.SystemFlightActive,"Only list selection, camera and filters were invoked. Start/Stop/Go were never executed.");
            Check("control-execution",null,"Read-only UI acceptance records real CanExecute state but does not execute driving or test a live start/stop.");
            Check("telemetry-recovery",null,"No source fault, game restart or missing telemetry was manufactured; actual recovery needs separate runtime evidence.");
        }
        catch(Exception error){failure=error.ToString();}
        finally
        {
            MainWindow.AppWindow.Resize(size);ViewModel.CurrentSystemSearch=search;SetFilters(filters);
            ViewModel.SelectedSystemLocation=ViewModel.CurrentSystemLocations.FirstOrDefault(row=>row.Record.Identity==selected);page?.MapForProbe.ResetCamera();RecordedLabel();
            await File.WriteAllTextAsync(Path.Combine(directory,"system-map-evidence.json"),JsonSerializer.Serialize(new{at=DateTimeOffset.UtcNow,mode=recorded?"recorded-catalogue":"live-current-system",recording,recordingHash,
                snapshot=source,Runtime.DataDirectory,ViewModel.OfflinePreview,checks,captures,states,failure,failedChecks,unconfirmedChecks,structurePassed=failure is null&&failedChecks==0,
                startEnabled=ViewModel.StartSystemFlightCommand.CanExecute(null),ViewModel.SystemFlightActive,gameFlightCommandsInvoked=false,gameRestartInvoked=false,
                pluginPreparationAllowed=args.Contains("--prepare-system-map-interfaces"),pluginActionsInvoked=args.Contains("--prepare-system-map-interfaces"),osInputsSent=0,
                syntheticLocationsOrCoordinates=false,visualReview="GPU capture and assertions do not replace inspection of original pixels, details, OCR and the reference design."},ToolboxSettings.JsonOptions));
        }
        return new{failure,checks,captures,failedChecks,unconfirmedChecks,structurePassed=failure is null&&failedChecks==0,mode=recorded?"recorded-catalogue":"live-current-system",gameFlightCommandsInvoked=false,gameRestartInvoked=false};
    }
}