using System;
namespace XFE.SeAgent.Plugin.Graphics
{
/// One producer and one consumer. Published/leased buffers are immutable
/// until released; the third buffer lets the producer proceed without waiting
/// for GPU work. Only pointer exchange uses the lock.
internal sealed class SnapshotExchange where T : class, new()
{
private readonly object gate = new object();
private readonly T[] buffers = { new T(), new T(), new T() };
private T current, reading;
public T Current { get { lock(gate) return current; } }
public T AcquireWritable()
{
lock(gate) foreach(var value in buffers)
if(!ReferenceEquals(value,current) && !ReferenceEquals(value,reading)) return value;
throw new InvalidOperationException("Single-producer snapshot pool exhausted.");
}
public void Publish(T value) { lock(gate) current=value; }
public T AcquireRead()
{
lock(gate) {
if(reading!=null) throw new InvalidOperationException("A snapshot reader is already active.");
return reading=current;
}
}
public void ReleaseRead(T value)
{
lock(gate) if(ReferenceEquals(reading,value)) reading=null;
}
public void Clear()
{
lock(gate) {
current=null;
// An outstanding reader owns its old object until ReleaseRead.
// New worlds do not keep old arrays/models alive in unused slots.
for(int i=0;i