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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Sandbox.Definitions;
using Sandbox.Game.Entities;
using VRage.Voxels;
using VRage.Voxels.DualContouring;
using VRageMath;

namespace XFE.SeAgent.Plugin.Graphics
{
    internal sealed partial class RayTracing
    {
        private readonly Dictionary<string,Mesh> voxelCache=new Dictionary<string,Mesh>();
        private readonly HashSet<MyVoxelBase> watchedVoxels=new HashSet<MyVoxelBase>();
        // Bounded jobs: storage reads/meshing are independent and engine mesher
        // instances are thread-local. Definitions and scene publication stay on
        // the game thread, in deterministic cell order.
        private const int VoxelWorkers=4, VoxelRadius=320;
        private readonly SemaphoreSlim voxelWorker=new SemaphoreSlim(VoxelWorkers);
        private int voxelChunks,voxelTriangles,voxelRevision;

        private void ResetVoxels()
        {
            foreach(var voxel in watchedVoxels) voxel.RangeChanged-=VoxelChanged;
            watchedVoxels.Clear(); voxelCache.Clear(); voxelChunks=voxelTriangles=0;
        }
        private void VoxelChanged(MyVoxelBase voxel,Vector3I min,Vector3I max,MyStorageDataTypeFlags flags)
        {
            // This event may originate outside the game thread. Do not mutate a
            // cache here. The next game update invalidates the scene atomically.
            Interlocked.Increment(ref voxelRevision);
            Interlocked.Increment(ref sceneGeneration);
            snapshots.Clear(); Interlocked.Exchange(ref resetHistory,1);
        }
        private IEnumerable<Placement> CollectVoxels(Vector3D camera)
        {
            int lod=options.VoxelLod, scale=1<<lod, cell=32, meters=cell*scale;
            var sphere=new BoundingSphereD(camera,VoxelRadius);
            var roots=MyEntities.GetEntities().OfType<MyVoxelBase>().Select(v=>v.RootVoxel).Where(v=>v!=null && !v.Closed && v.PositionComp.WorldAABB.Intersects(sphere)).Distinct().ToArray();
            var live=new HashSet<string>(); voxelChunks=voxelTriangles=0;
            foreach(var root in roots)
            {
                if(watchedVoxels.Add(root)) root.RangeChanged+=VoxelChanged;
                var storage=root.Storage; if(storage==null) continue;
                var local=Vector3D.Transform(camera,root.PositionComp.WorldMatrixNormalizedInv)+root.SizeInMetresHalf+root.StorageMin;
                var size=storage.Size;
                var low=Vector3I.Max(Vector3I.Zero,Vector3I.Floor((local-new Vector3D(VoxelRadius))/meters));
                var high=Vector3I.Min((size-Vector3I.One)/meters,Vector3I.Floor((local+new Vector3D(VoxelRadius))/meters));
                var cells=new List<Vector3I>();
                for(int z=low.Z;z<=high.Z;z++) for(int y=low.Y;y<=high.Y;y++) for(int x=low.X;x<=high.X;x++) {
                    var c=new Vector3I(x,y,z);
                    var box=new BoundingBoxD(c*meters,(c+Vector3I.One)*meters);
                    if(box.Intersects(new BoundingSphereD(local,VoxelRadius))) cells.Add(c);
                }
                cells.Sort((a,b)=>Vector3D.DistanceSquared(((Vector3D)a+new Vector3D(.5))*meters,local).CompareTo(Vector3D.DistanceSquared(((Vector3D)b+new Vector3D(.5))*meters,local)));
                var offset=root.SizeInMetresHalf+root.StorageMin;
                var pending=new Dictionary<int,Task<MyIsoMesh>>();
                int scheduled=0, revision=Volatile.Read(ref sceneGeneration);
                for(int cellNumber=0;cellNumber<cells.Count;cellNumber++)
                {
                    // Maintain a short look-ahead window rather than scheduling
                    // thousands of tasks or awaiting a new worker for every cell.
                    while(scheduled<Math.Min(cells.Count,cellNumber+VoxelWorkers)) {
                        int index=scheduled++;var c=cells[index];
                        if(voxelCache.ContainsKey(root.EntityId+":"+lod+":"+c)) continue;
                        var min=c*cell-Vector3I.One;var max=(c+Vector3I.One)*cell+new Vector3I(2);
                        pending.Add(index,Task.Run(async()=> {
                            await voxelWorker.WaitAsync();
                            try {
                                if(Volatile.Read(ref sceneGeneration)!=revision) return null;
                                return ((IMyIsoMesher)MyDualContouringMesher.Static).Precalc(storage,lod,min,max,MyStorageDataTypeFlags.ContentAndMaterial,0);
                            }
                            finally { voxelWorker.Release(); }
                        }));
                    }
                    var cellIndex=cells[cellNumber];
                    string key=root.EntityId+":"+lod+":"+cellIndex;
                    live.Add(key);
                    if(!voxelCache.TryGetValue(key,out var mesh))
                    {
                        // Engine mesher is thread-local; storage pins and ReadRange
                        // are the same concurrency-safe route used by engine jobs.
                        // The worker receives only storage and value coordinates,
                        // never an entity, definition manager or render collection.
                        var task=pending[cellNumber];
                        while(!task.IsCompleted) yield return null;
                        var iso=task.GetAwaiter().GetResult();
                        pending.Remove(cellNumber);
                        if(Volatile.Read(ref sceneGeneration)!=revision) yield break;
                        if(iso!=null && iso.VerticesCount>0 && iso.TrianglesCount>0) {
                            var vertices=new float[iso.VerticesCount*8];
                            for(int i=0;i<iso.VerticesCount;i++) {
                                var p=iso.Positions[i]*iso.PositionScale+iso.PositionOffset-offset;
                                int j=i*8; vertices[j]=(float)p.X;vertices[j+1]=(float)p.Y;vertices[j+2]=(float)p.Z;
                                var def=MyDefinitionManager.Static.GetVoxelMaterialDefinition(iso.Materials[i]);
                                if(def?.RenderParams.TextureSets!=null && def.RenderParams.TextureSets.Length>0) {
                                    var tex=def.RenderParams.TextureSets[0];
                                    vertices[j+5]=MaterialPath(tex.ColorMetalXZnY); vertices[j+6]=MaterialPath(tex.ColorMetalY);
                                    vertices[j+7]=1f/Math.Max(1,def.RenderParams.StandardTilingSetup.InitialScale);
                                } else vertices[j+7]=.1f;
                            }
                            var indices=new List<uint>(iso.TrianglesCount*3);
                            for(int i=0;i<iso.TrianglesCount;i++) {
                                var t=iso.Triangles[i];
                                // Halo samples give matching borders. Own triangles
                                // by their minimum cell to avoid overlapping chunks.
                                var anchor=Vector3I.Min(iso.Cells[t.V0],Vector3I.Min(iso.Cells[t.V1],iso.Cells[t.V2]))+iso.CellStart;
                                if(anchor.X<cellIndex.X*cell || anchor.Y<cellIndex.Y*cell || anchor.Z<cellIndex.Z*cell ||
                                   anchor.X>=(cellIndex.X+1)*cell || anchor.Y>=(cellIndex.Y+1)*cell || anchor.Z>=(cellIndex.Z+1)*cell) continue;
                                indices.Add(t.V0);indices.Add(t.V1);indices.Add(t.V2);
                            }
                            if(indices.Count>0) {
                                mesh=new Mesh { Id=++nextMesh,Vertices=vertices,Indices=indices.ToArray(),Materials=Enumerable.Repeat(VoxelFlag,indices.Count/3).ToArray() };
                                meshesById.Add(mesh.Id,mesh);
                            }
                        }
                        voxelCache[key]=mesh;
                    }
                    if(mesh!=null) { voxelChunks++;voxelTriangles+=mesh.Indices.Length/3; yield return new Placement { Owner=root,Local=Matrix.Identity,Mesh=mesh.Id }; }
                    yield return null;
                }
            }
            foreach(var key in voxelCache.Keys.Where(k=>!live.Contains(k)).ToArray()) voxelCache.Remove(key);
            foreach(var voxel in watchedVoxels.Where(v=>!roots.Contains(v)).ToArray()) { voxel.RangeChanged-=VoxelChanged;watchedVoxels.Remove(voxel); }
        }
    }
}