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

XFE.SpaceEngineers.AgentBridge

【SpaceEngineer】AI调试插件

公开
关注 0 Fork 0 Star 0
UTF-8
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using HarmonyLib;
using ParallelTasks;
using VRage.Render.Scene.Components;

namespace XFE.SeAgent.Plugin.Performance
{
    internal static class ActorBatching
    {
        internal static int ChunkSize = 32;
        internal static int Workers = 0;
        [ThreadStatic] private static Batch spare;
        public static long Dispatches, ItemsProcessed;
        internal static volatile ActorMetrics Metrics;
        internal static volatile CacheCoreAffinity Affinity;
        private sealed class Batch
        {
            public readonly List<MyActorComponent> Items = new List<MyActorComponent>();
            public Action<MyActorComponent> Action;
            public ActorMetrics Metrics;
            public int Size;
            public int NextChunk, ChunkCount;
            public readonly Action<int> Run;
            public readonly Action<int> RunLane;
            public Batch() { Run = RunChunk; RunLane = DrainChunks; }
            private void DrainChunks(int lane)
            {
                int chunk;
                while ((chunk = Interlocked.Increment(ref NextChunk)) < ChunkCount) RunChunk(chunk);
            }
            private void RunChunk(int chunk)
            {
                Affinity?.MarkRenderThread();
                int start = chunk * Size, end = Math.Min(start + Size, Items.Count);
                if (Metrics == null) { for (int i = start; i < end; i++) Action(Items[i]); }
                else { for (int i = start; i < end; i++) Metrics.Measure(Items[i], Action); }
            }
        }

        // This replaces only the engine's explicitly parallel-safe actor component loop.
        // It retains the same priority, joins before serial updates, and uses the existing
        // worker pool. World mutation, actor hierarchy and serial callbacks stay untouched.
        public static void Run(IEnumerable<MyActorComponent> collection, Action<MyActorComponent> action,
            WorkPriority priority, WorkOptions? options, bool blocking)
        {
            // Preserve any future engine version's explicit worker cap/nonblocking path.
            if (!blocking || !options.HasValue || options.Value.MaximumThreads != int.MaxValue)
            {
                Parallel.ForEach(collection, action, priority, options, blocking); return;
            }
            var batch = spare ?? new Batch(); spare = null;
            try
            {
                // Framework List.AddRange(ICollection) creates a temporary array
                // even with sufficient capacity. Fill the reused snapshot directly.
                foreach (var item in collection) batch.Items.Add(item);
                batch.Action = action; batch.Metrics = Metrics;
                batch.Size = ChunkSize;
                int chunks = (batch.Items.Count + batch.Size - 1) / batch.Size;
                Interlocked.Increment(ref Dispatches); Interlocked.Add(ref ItemsProcessed, batch.Items.Count);
                int workers = Workers; // Configure may change the cap on the game thread.
                if (workers > 0)
                {
                    // This engine's Parallel.For overwrites MaximumThreads with
                    // iteration count. Limit lanes explicitly; each drains chunks.
                    batch.NextChunk = -1; batch.ChunkCount = chunks;
                    Parallel.For(0, Math.Min(chunks, workers), batch.RunLane, 1, priority, options, blocking);
                }
                else Parallel.For(0, chunks, batch.Run, 1, priority, options, blocking);
            }
            finally
            {
                batch.Action = null; batch.Metrics = null; batch.Items.Clear(); spare = batch;
            }
        }

        public static IEnumerable<CodeInstruction> ReplaceLoop(IEnumerable<CodeInstruction> instructions)
        {
            var result = new List<CodeInstruction>(); int matches = 0;
            foreach (var instruction in instructions)
            {
                if (instruction.opcode == OpCodes.Call && instruction.operand is MethodInfo method
                    && method.DeclaringType == typeof(Parallel) && method.Name == "ForEach" && method.IsGenericMethod
                    && method.GetGenericArguments()[0] == typeof(MyActorComponent) && method.GetParameters().Length == 5)
                {
                    instruction.operand = AccessTools.Method(typeof(ActorBatching), nameof(Run)); matches++;
                }
                result.Add(instruction);
            }
            if (matches != 1) throw new InvalidOperationException("Unsupported actor updater: expected one parallel component loop.");
            return result;
        }
    }
}