Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save babon/1166fb8e18d3fb67553e27e2d4111191 to your computer and use it in GitHub Desktop.
Save babon/1166fb8e18d3fb67553e27e2d4111191 to your computer and use it in GitHub Desktop.
void SavePartMM(int offset = 0, int partSize = fullWidth * fullHeight * fullDepth, int chunkSizeDiv = 1024)
{
//crashes if empty save file for some reason, too unreliable to use
var mmf = MemoryMappedFile.CreateFromFile(Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer ? "/Users/user/Downloads/test.bytes" : "C:\\test.bytes", FileMode.OpenOrCreate, "apoca_save");
int chunkSize = fullWidth * fullHeight * fullDepth / chunkSizeDiv; //2 4 8 16 32 64 128 256 512 [1024] 2048
//const int chunkSize = /*536_752_128*//*67_094_016*//*8_323_200*//*4_193_376*//*2_096_688*/520_200/*262_086*/;
saveLock = true;
var stopwatch = new Stopwatch(); stopwatch.Start();
int endPoint = offset + partSize;
var a = new NativeArray<uint>(chunkSize, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
AsyncGPUReadback.RequestIntoNativeArray(ref a, texture, chunkSize * 4, offset * 4, OnCompleteReadback);
stopwatch.Stop();
void OnCompleteReadback(AsyncGPUReadbackRequest request)
{
stopwatch.Start();
if (request.hasError) Debug.LogError("request.hasError");
if (!request.done) Debug.LogError("!request.done");
//var first = a.First();
//var last = a.Last();
//print(new{offset, first, last});
using (var accessor = mmf.CreateViewAccessor(offset * 4, chunkSize * 4, MemoryMappedFileAccess.Write))
{
unsafe
{
byte* pointer = null;
try
{
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
UnsafeUtility.MemCpy(destination: pointer, a.GetUnsafeReadOnlyPtr(), chunkSize * 4);
}
finally
{
if (pointer != null) accessor.SafeMemoryMappedViewHandle.ReleasePointer();
}
}
}
offset += chunkSize;
if (offset >= endPoint)
{
a.Dispose();
mmf.Dispose();
stopwatch.Stop(); print("saved " + (stopwatch.ElapsedTicks / 10000d));
saveLock = false;
}
else
{
AsyncGPUReadback.RequestIntoNativeArray(ref a, texture, chunkSize * 4, offset * 4, OnCompleteReadback);
}
stopwatch.Stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment