using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using HarmonyLib; using Sandbox.Game.Entities.Blocks; using Sandbox.Game.EntityComponents; using VRageMath; namespace XFE.SeAgent.Plugin.Graphics { internal sealed partial class RayTracing { [StructLayout(LayoutKind.Sequential)] private struct Light { public Vector4 PositionRange,ColorIntensity,DirectionCone,Settings; } [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] private static extern int RtLights(IntPtr context,Light[] lights,uint count); private static readonly System.Reflection.FieldInfo LightingLogic=AccessTools.Field(typeof(MyLightingBlock),"m_lightingLogic"); private MyLightingBlock[] lightingBlocks=new MyLightingBlock[0]; // Game-thread scratch only; the selected array copied below is owned by // its immutable snapshot and never aliases this reusable collection. private readonly List lightCandidates=new List(); private Light[] CaptureLights(Vector3D origin) { var lights=lightCandidates;lights.Clear(); foreach(var block in lightingBlocks) { if(block.Closed || !block.IsWorking || !(LightingLogic?.GetValue(block) is MyLightingLogic logic)) continue; foreach(var light in logic.Lights) { var world=block.CubeGrid.WorldMatrix; var position=(Vector3)(Vector3D.Transform(light.Position,world)-origin); var direction=Vector3.TransformNormal(light.ReflectorDirection,world); direction=direction.LengthSquared()>1e-8f?Vector3.Normalize(direction):world.Forward; if(light.LightOn && light.Intensity>0 && light.Range>0) lights.Add(new Light { PositionRange=new Vector4(position+direction*light.PointLightOffset,light.Range), ColorIntensity=new Vector4(light.Color.ToVector3().ToLinearRGB(),light.Intensity),DirectionCone=new Vector4(0,0,0,-1),Settings=new Vector4(light.Falloff,0,0,0) }); if(light.ReflectorOn && light.ReflectorIntensity>0 && light.ReflectorRange>0) lights.Add(new Light { PositionRange=new Vector4(position,light.ReflectorRange),ColorIntensity=new Vector4(light.ReflectorColor.ToVector3().ToLinearRGB(),light.ReflectorIntensity), DirectionCone=new Vector4(direction,light.ReflectorConeMaxAngleCos),Settings=new Vector4(light.ReflectorFalloff,0,0,0) }); } } // Bound local-light cost. Capture the most influential fixtures for // this camera; secondary hit shaders resample these by contribution. return lights.OrderByDescending(l=>l.ColorIntensity.W*l.PositionRange.W*l.PositionRange.W/(1+new Vector3(l.PositionRange).LengthSquared())).Take(64).ToArray(); } } }