Skip to content

Commit

Permalink
use of different octrees file prefix
Browse files Browse the repository at this point in the history
use of octrees saved indication file
  • Loading branch information
repkins committed Dec 27, 2022
1 parent 88daebc commit 5f7f7f6
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 117 deletions.
11 changes: 11 additions & 0 deletions TerraformingShared/SaveLoad/SaveLoadExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace TerraformingShared.SaveLoad
{
static class SaveLoadExtensions
{
public const string IndicationFileName = ".saved";
}
}
19 changes: 18 additions & 1 deletion TerraformingShared/SaveLoad/SaveLoadManagerPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Terraforming.WorldStreaming;
using TerraformingShared.SaveLoad;
using UnityEngine;

namespace Terraforming.SaveLoad.SaveLoadManagerPatches
{
[HarmonyPatch(typeof(SaveLoadManager))]
[HarmonyPatch("SaveToTemporaryStorageAsync")]
[HarmonyPatch(nameof(SaveLoadManager.SaveToTemporaryStorageAsync))]
[HarmonyPatch(new Type[] { typeof(IOut<SaveLoadManager.SaveResult>), typeof(Texture2D) })]
static class SaveToTemporaryStorageAsyncPatch
{
Expand All @@ -34,10 +36,25 @@ static IEnumerator PostfixAsync(SaveLoadManager saveLoadManager, IEnumerator ori
}
octreesStreamer.WriteBatchOctrees();

WriteOctreesIndicationFile();

LargeWorldStreamer.main.frozen = false;
saveLoadManager.isSaving = false;

yield break;
}

private static void WriteOctreesIndicationFile()
{
var saveFilePath = LargeWorldStreamer.main.tmpPathPrefix;
var compiledOctreesPath = Path.Combine(saveFilePath, BatchOctreesStreamerExtensions.CompiledOctreesDirName);
var indicationFilePath = Path.Combine(compiledOctreesPath, SaveLoadExtensions.IndicationFileName);

if (!File.Exists(indicationFilePath))
{
Directory.CreateDirectory(compiledOctreesPath);
File.WriteAllBytes(indicationFilePath, new byte[0]);
}
}
}
}
134 changes: 20 additions & 114 deletions TerraformingShared/SaveLoad/UserStoragePCPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,112 +16,6 @@ namespace TerraformingShared.SaveLoad
[HarmonyPatch(typeof(UserStoragePC))]
static class UserStoragePCPatches
{
[HarmonyPatch(nameof(UserStoragePC.UpgradeSaveData))]
[HarmonyTranspiler]
static IEnumerable<CodeInstruction> RemoveDeletingOctrees(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase originalMethod)
{
var codeMatcherCursor = new CodeMatcher(instructions);

Action<CodeMatcher, ILGenerator>[] patchers =
{
AssignEmptyArrayToOctreesLocal
};

try
{
foreach (var patcher in patchers)
{
patcher.Invoke(codeMatcherCursor, generator);
}
}
catch (Exception ex)
{
Logger.Error(ex.ToString());

codeMatcherCursor.ReportFailure(originalMethod, Logger.Error);

return instructions;
}

return codeMatcherCursor.InstructionEnumeration();
}

private static void AssignEmptyArrayToOctreesLocal(CodeMatcher codeCursor, ILGenerator generator)
{
List<Label> labels;

codeCursor.Start();
codeCursor.MatchForward(useEnd: false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldstr, "compiled-batch-*.optoctrees"),
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(Directory), nameof(Directory.GetFiles), new[] { typeof(string), typeof(string), typeof(SearchOption) }))
);
codeCursor.ThrowIfInvalid("Could not find call to Directory.GetFiles with octrees search pattern");

labels = codeCursor.Instruction.ExtractLabels();

codeCursor.RemoveInstructions(4)
.InsertAndAdvance(new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(UserStoragePCPatches), nameof(GetEmptyArray))).WithLabels(labels));
}

private static string[] GetEmptyArray()
{
return new string[] { };
}

[HarmonyPatch(nameof(UserStoragePC.UpgradeSaveDataAsync))]
[HarmonyTranspiler]
static IEnumerable<CodeInstruction> SkipOctrees(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase originalMethod)
{
var codeMatcherCursor = new CodeMatcher(instructions);

Action<CodeMatcher, ILGenerator>[] patchers =
{
RemoveOctreesPattern
};

try
{
foreach (var patcher in patchers)
{
patcher.Invoke(codeMatcherCursor, generator);
}
}
catch (Exception ex)
{
Logger.Error(ex.ToString());

codeMatcherCursor.ReportFailure(originalMethod, Logger.Error);

return instructions;
}

return codeMatcherCursor.InstructionEnumeration();
}

private static void RemoveOctreesPattern(CodeMatcher codeCursor, ILGenerator generator)
{
List<Label> labels;

codeCursor.Start();
codeCursor.MatchForward(useEnd: false,
new CodeMatch(OpCodes.Brtrue),
new CodeMatch(OpCodes.Ldloc_S),
new CodeMatch(OpCodes.Ldstr, "compiled-batch-*.optoctrees"),
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(Directory), nameof(Directory.EnumerateFiles), new[] { typeof(string), typeof(string), typeof(SearchOption) })),
new CodeMatch(OpCodes.Call)
)
.ThrowIfInvalid("Could not find condition with call to Directory.EnumerateFiles uses octrees search pattern");

labels = codeCursor.Instruction.ExtractLabels();

codeCursor.RemoveInstructions(6);

codeCursor.Instruction.WithLabels(labels);
}

[HarmonyPatch(nameof(UserStoragePC.UpgradeSaveDataAsync))]
[HarmonyPostfix]
static void EnsureCompiledOctreesBackFromBackup(UserStoragePC __instance, string backupPath, ref UserStorageUtils.UpgradeOperation __result)
Expand All @@ -133,17 +27,16 @@ private static UserStorageUtils.UpgradeOperation EnsureCompiledOctreesRestoredFr
{
if (!string.IsNullOrEmpty(backupPath) && Directory.Exists(backupPath))
{
string compiledOctreesDirName = BatchOctreesStreamerExtensions.CompiledOctreesDirName;

var saveContainersToRestore = new List<string>();
foreach (string saveSlotDir in Directory.GetDirectories(userStoragePC.savePath))
{
string saveFileName = Path.GetFileName(saveSlotDir);
string saveCompiledOctreesPath = Path.Combine(saveSlotDir, compiledOctreesDirName);
string backupSaveCompiledOctreesPath = Path.Combine(backupPath, saveFileName, compiledOctreesDirName);
string saveCompiledOctreesPath = Path.Combine(saveSlotDir, BatchOctreesStreamerExtensions.CompiledOctreesDirName);
string saveCompiledOctreesIndicationFilePath = Path.Combine(saveCompiledOctreesPath, SaveLoadExtensions.IndicationFileName);
string backupSaveCompiledOctreesPath = Path.Combine(backupPath, saveFileName, BatchOctreesStreamerExtensions.CompiledOctreesDirName);

// Restore save slot if exists in backup and is empty in target save location
if (Directory.Exists(backupSaveCompiledOctreesPath) && !Directory.EnumerateFiles(saveCompiledOctreesPath).Any())
// Restore save slot if exists in backup and there is no indication file in target octrees location
if (Directory.Exists(backupSaveCompiledOctreesPath) && !File.Exists(saveCompiledOctreesIndicationFilePath))
{
saveContainersToRestore.Add(saveSlotDir);
}
Expand Down Expand Up @@ -182,8 +75,21 @@ private static void RestoreCompiledOctreesFromBackup(object owner, object state)
{
try
{
string newSaveCompiledOctreesPath = Path.Combine(saveSlotPath, compiledOctreesDirName);
UWE.Utils.CopyDirectory(backupSaveCompiledOctreesPath, newSaveCompiledOctreesPath);
string saveCompiledOctreesPath = Path.Combine(saveSlotPath, compiledOctreesDirName);

Directory.CreateDirectory(saveCompiledOctreesPath);
foreach (var backupSaveCompiledOctreesFilePath in Directory.EnumerateFiles(backupSaveCompiledOctreesPath, "compiled-batch-*.optoctrees"))
{
var oldFileName = Path.GetFileName(backupSaveCompiledOctreesFilePath);
var newFileName = oldFileName.Replace("compiled-batch", BatchOctreesStreamerExtensions.CompiledOctreesFileNamePrefix);

var saveCompiledOctreesFilePath = Path.Combine(saveCompiledOctreesPath, newFileName);

File.Copy(backupSaveCompiledOctreesFilePath, saveCompiledOctreesFilePath, true);
}

string saveCompiledOctreesIndicationFilePath = Path.Combine(saveCompiledOctreesPath, SaveLoadExtensions.IndicationFileName);
File.WriteAllBytes(saveCompiledOctreesIndicationFilePath, new byte[0]);

Logger.Info(string.Format("Compiled octrees restored from backup for save {0}.", saveFileName));
}
Expand Down
1 change: 1 addition & 0 deletions TerraformingShared/TerraformingShared.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<Compile Include="$(MSBuildThisFileDirectory)MainPatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Messaging\ErrorMessageExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Messaging\ErrorMessagePatches.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SaveLoad\SaveLoadExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SaveLoad\SaveLoadManagerPatches.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SaveLoad\UserStoragePCPatches.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Tools\BuilderExtensions.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ namespace Terraforming.WorldStreaming
{
static class BatchOctreesStreamerExtensions
{
public static readonly string CompiledOctreesDirName = "CompiledOctreesCache";
public const string CompiledOctreesDirName = "CompiledOctreesCache";
public const string CompiledOctreesFileNamePrefix = "batch-compiled";

public static string GetTmpPath(this BatchOctreesStreamer batchOctreesStreamer, Int3 batchId)
{
Expand All @@ -21,7 +22,7 @@ public static string GetTmpPath(this BatchOctreesStreamer batchOctreesStreamer,
Directory.CreateDirectory(tmpPathPrefix);
}

var fileName = $"compiled-batch-{batchId.x}-{batchId.y}-{batchId.z}.optoctrees";
var fileName = $"{CompiledOctreesFileNamePrefix}-{batchId.x}-{batchId.y}-{batchId.z}.optoctrees";
var fullPath = Path.Combine(tmpPathPrefix, fileName);

return fullPath;
Expand Down

0 comments on commit 5f7f7f6

Please sign in to comment.