using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using HarmonyLib; using Newtonsoft.Json.Linq; using Sandbox.Game.Components; using Sandbox.Game.Entities; using Sandbox.Game.World; using VRage.Game.Entity; using VRage.Game.Models; using VRageMath; using VRageRender; using VRageRender.Messages; namespace XFE.SeAgent.Plugin.Graphics { internal sealed partial class RayTracing { [StructLayout(LayoutKind.Sequential)] private struct SurfaceMaterial { public Vector4 ColorEmission; public uint Texture,Flags,Reserved0,Reserved1; } private sealed class ScreenBinding { public long EntityId; public uint Slot,Texture,RenderId; public string Material,DefaultTexture; } private sealed class ScreenModel { public MyModel Model;public Mesh Mesh;public ScreenBinding[] Bindings; } private sealed class ScreenState { public string Texture;public Vector3 Color=Vector3.One;public float Emission=1;public bool Visible=true,HasTexture; } private readonly List screenBindings=new List(); // game thread private readonly Dictionary> screenModels=new Dictionary>(); // Renderer messages and consumption run on the renderer, not game workers. private readonly Dictionary> screenStates=new Dictionary>(); private readonly SurfaceMaterial[] surfaceUpload=new SurfaceMaterial[33]; private long lastScreenCopy; private MyCockpit interiorCockpit; private volatile JObject screenStatus=new JObject(); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] private static extern int RtSurfaceMaterials(IntPtr context,SurfaceMaterial[] materials,uint count); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] private static extern int RtDynamicMaterial(IntPtr context,uint id,IntPtr srv); private void InstallScreenCapture() { var process=AccessTools.DeclaredMethod(Renderer,"ProcessMessageInternal",new[]{typeof(MyRenderMessageBase),typeof(int)}); if(process==null)throw new NotSupportedException("Renderer material message hook unavailable."); harmony.Patch(process,postfix:new HarmonyMethod(typeof(RayTracing),nameof(AfterMaterialMessage))); } private static void AfterMaterialMessage(MyRenderMessageBase message) { active?.CaptureMaterialMessage(message); } private ScreenState ScreenStateFor(uint id,string name) { if(!screenStates.TryGetValue(id,out var row)) { if(screenStates.Count>=65536)return null; screenStates.Add(id,row=new Dictionary(StringComparer.Ordinal)); } if(!row.TryGetValue(name,out var state)) { if(row.Count>=128)return null; row.Add(name,state=new ScreenState()); } return state; } private void CaptureMaterialMessage(MyRenderMessageBase message) { if(message is MyRenderMessageUpdateModelProperties p) { var state=ScreenStateFor(p.ID,p.MaterialName.String);if(state==null)return; if(p.DiffuseColor.HasValue)state.Color=p.DiffuseColor.Value.ToVector3(); if(p.Emissivity.HasValue)state.Emission=MathHelper.Clamp(p.Emissivity.Value,0,32); if(p.FlagsChange.HasValue) { var flags=p.FlagsChange.Value; if((flags.Add&RenderFlags.Visible)!=0)state.Visible=true; if((flags.Remove&RenderFlags.Visible)!=0)state.Visible=false; } } else if(message is MyRenderMessageChangeMaterialTexture t && t.Changes!=null) { foreach(var change in t.Changes) { var state=ScreenStateFor(t.RenderObjectID,change.Key.String);if(state==null)continue; state.Texture=change.Value.ColorMetalFileName;state.HasTexture=true; } } else if(message.MessageType==MyRenderMessageEnum.RemoveRenderObject) { var id=Member(message,"ID");if(id is uint value)screenStates.Remove(value); } } private void CheckCockpitModel() { var cockpit=MySession.Static.CameraController as MyCockpit; if(cockpit!=null && !(cockpit.IsInFirstPersonView || cockpit.ForceFirstPersonCamera))cockpit=null; if(ReferenceEquals(cockpit,interiorCockpit))return; var previous=interiorCockpit;interiorCockpit=cockpit; // A view toggle changes one cockpit, not the surrounding fleet or // voxels. Clearing the whole scene made reflections wait for the // sliced collector to finish thousands of unrelated blocks again. RefreshCockpitPlacements(previous);RefreshCockpitPlacements(cockpit); RefreshPlacementMeshes();lastSnapshot=0; Interlocked.Exchange(ref resetHistory,1);Interlocked.Exchange(ref lastScreenCopy,0); } private void RefreshCockpitPlacements(MyCockpit cockpit) { if(cockpit==null)return; var block=cockpit.SlimBlock; placements.RemoveAll(p=>ReferenceEquals(p.Block,block)); buildingPlacements?.RemoveAll(p=>ReferenceEquals(p.Block,block)); if(cockpit.Closed || Vector3D.DistanceSquared(cockpit.WorldMatrix.Translation,MySector.MainCamera.Position)>250*250)return; var current=EntityModels(cockpit,block,0).ToArray(); placements.AddRange(current);buildingPlacements?.AddRange(current); } private MyModel DisplayedModel(MyEntity entity) { if(ReferenceEquals(entity,interiorCockpit) && !string.IsNullOrEmpty(interiorCockpit.BlockDefinition.InteriorModel)) return MyModels.GetModelOnlyData(interiorCockpit.BlockDefinition.InteriorModel); return entity.Model; } private void ResetScreenCapture() { screenBindings.Clear();screenModels.Clear(); } private uint RenderIdFor(MyEntity entity) { // Independently meshed voxels use the storage origin, not a render // clipmap-cell transform. They retain their captured static pose. if(entity is MyVoxelBase || entity.Render==null)return uint.MaxValue; object selected=Member(entity.Render,ReferenceEquals(entity,interiorCockpit)?"InteriorRenderId":"ExteriorRenderId"); if(selected is uint id && id!=uint.MaxValue)return id; foreach(uint candidate in entity.Render.RenderObjectIDs)if(candidate!=uint.MaxValue)return candidate; return uint.MaxValue; } private Mesh CopyScreenModel(MyEntity entity,MyModel model,Mesh original) { if(original==null || !(entity.Render is MyRenderComponentScreenAreas render))return original; if(Vector3D.DistanceSquared(entity.WorldMatrix.Translation,MySector.MainCamera.Position)>64*64)return original; uint renderId=RenderIdFor(entity); if(!screenModels.TryGetValue(entity,out var variants))screenModels.Add(entity,variants=new List()); var cached=variants.FirstOrDefault(v=>v.Model==model); if(cached!=null) { // Exterior/interior variants share stable screen slots, but their // renderer IDs may change. Never mutate a leased snapshot binding. foreach(var binding in cached.Bindings)screenBindings[(int)binding.Slot-1]=new ScreenBinding {EntityId=binding.EntityId,Slot=binding.Slot,Texture=binding.Texture,RenderId=renderId,Material=binding.Material,DefaultTexture=binding.DefaultTexture}; meshesById[cached.Mesh.Id]=cached.Mesh;return cached.Mesh; } var areas=AccessTools.Field(typeof(MyRenderComponentScreenAreas),"m_screenAreas")?.GetValue(render) as IEnumerable;if(areas==null)return original; var names=new Dictionary(StringComparer.Ordinal); foreach(var area in areas) {var name=Member(area,"Material") as string;if(!string.IsNullOrEmpty(name))names[name]=Member(area,"OffscreenTextureName") as string;} // Reserve the viewed cockpit's interior screens even when the first // collected variant is exterior. Nearby LCDs must not consume their // slots before the player first enters the cockpit view. if(ReferenceEquals(entity,MySession.Static.CameraController))foreach(var name in names) { if(screenBindings.Count>=32)break; if(screenBindings.Any(b=>b.EntityId==entity.EntityId && b.Material==name.Key))continue; uint slot=(uint)screenBindings.Count+1; screenBindings.Add(new ScreenBinding {EntityId=entity.EntityId,Slot=slot,Texture=991+slot,RenderId=renderId,Material=name.Key,DefaultTexture=name.Value}); } var materials=(uint[])original.Materials.Clone();bool changed=false;var bindings=new List(); foreach(var part in original.Parts??new MeshPart[0]) { if(!names.TryGetValue(part.Name??"",out var texture))continue; var existing=screenBindings.FirstOrDefault(b=>b.EntityId==entity.EntityId && b.Material==part.Name); if(existing==null && screenBindings.Count>=32)continue; uint slot=existing?.Slot??(uint)screenBindings.Count+1; var binding=new ScreenBinding {EntityId=entity.EntityId,Slot=slot,Texture=991+slot,RenderId=renderId,Material=part.Name,DefaultTexture=texture}; if(existing==null)screenBindings.Add(binding);else screenBindings[(int)slot-1]=binding; bindings.Add(binding); for(int i=part.Start;i