Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FastBiomeQuery #151

Draft
wants to merge 4 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion GameData/KSPCommunityFixes/Settings.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ KSP_COMMUNITY_FIXES
// Avoids big spikes on the poles and incorrect biomes where the oles have disparate biomes.
MapSOCorrectWrapping = true
// The Mohole is a result of the bug the MapSOCorrectWrapping patch is fixing. If set to
// true, the patch won't apply to the stock Moho height/biome maps
// true, the patch won't apply to the stock Moho height map
MapSOCorrectWrappingIgnoreMoho = true

// Fix spread angle still being applied after decoupling symmetry-placed parachutes.
Expand Down
76 changes: 43 additions & 33 deletions KSPCommunityFixes/BugFixes/MapSOCorrectWrapping.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

namespace KSPCommunityFixes
Expand All @@ -26,8 +27,8 @@ protected override void ApplyPatches(List<PatchInfo> patches)
// see https://github.com/KSPModdingLibs/KSPCommunityFixes/issues/121
// The patched ConstructBilinearCoords() methods will have the side effect of removing the Mohole because Squad
// choose that "this is not a bug, it's a feature".
// To prevent it, we acquire references to the Moho MapSO instances (biome map and height map) and fall back
// to the original stock implementation if the method is called on those instances.
// To prevent it, we acquire references to the Moho MapSO heightmap instance and fall back to the original stock
// implementation if the method is called on those instances.
// Note that all stock bodies will actually get a significantly different terrain at the poles due to this patch,
// but due to how performance sensitive those method are, checking all stock MapSO instances (there are 40 of them)
// isn't really an option.
Expand All @@ -46,8 +47,9 @@ protected override void ApplyPatches(List<PatchInfo> patches)
}
}

private static MapSO moho_biomes;
private static MapSO moho_height;
private static readonly double lessThanOneDouble = StaticHelpers.BitDecrement(1.0);
private static readonly float lessThanOneFloat = StaticHelpers.BitDecrement(1f);

static void PSystemSetup_Awake_Postfix(PSystemSetup __instance)
{
Expand All @@ -58,15 +60,7 @@ static void PSystemSetup_Awake_Postfix(PSystemSetup __instance)

foreach (MapSO mapSo in so)
{
if (mapSo.MapName == "moho_biomes"
&& mapSo.Size == 6291456
&& mapSo._data[0] == 216
&& mapSo._data[1] == 178
&& mapSo._data[2] == 144)
{
moho_biomes = mapSo;
}
else if (mapSo.MapName == "moho_height"
if (mapSo.MapName == "moho_height"
&& mapSo.Size == 2097152
&& mapSo._data[1509101] == 146
&& mapSo._data[1709108] == 162
Expand All @@ -79,54 +73,70 @@ static void PSystemSetup_Awake_Postfix(PSystemSetup __instance)

static bool MapSO_ConstructBilinearCoords_Float(MapSO __instance, float x, float y)
{
if (ReferenceEquals(__instance, moho_biomes) || ReferenceEquals(__instance, moho_height))
return true;

// X wraps around as it is longitude.
x = Mathf.Abs(x - Mathf.Floor(x));

__instance.centerX = x * __instance._width;
__instance.minX = Mathf.FloorToInt(__instance.centerX);
__instance.maxX = Mathf.CeilToInt(__instance.centerX);
__instance.minX = (int)__instance.centerX;
__instance.maxX = __instance.minX + 1;
__instance.midX = __instance.centerX - __instance.minX;
if (__instance.maxX == __instance._width)
__instance.maxX = 0;

// Y clamps as it is latitude and the poles don't wrap to each other.
y = Mathf.Clamp(y, 0, 0.99999f);
if (y >= 1f)
y = lessThanOneFloat;
else if (y < 0f)
y = 0f;

__instance.centerY = y * __instance._height;
__instance.minY = Mathf.FloorToInt(__instance.centerY);
__instance.maxY = Mathf.CeilToInt(__instance.centerY);
__instance.minY = (int)__instance.centerY;
__instance.maxY = __instance.minY + 1;
__instance.midY = __instance.centerY - __instance.minY;
if (__instance.maxY >= __instance._height)
__instance.maxY = __instance._height - 1;

if (__instance.maxY == __instance._height)
{
if (ReferenceEquals(__instance, moho_height))
__instance.maxY = 0; // use incorrect wrapping for moho
else
__instance.maxY = __instance._height - 1;
}

return false;
}

static bool MapSO_ConstructBilinearCoords_Double(MapSO __instance, double x, double y)
{
if (ReferenceEquals(__instance, moho_biomes) || ReferenceEquals(__instance, moho_height))
return true;

// X wraps around as it is longitude.
x = Math.Abs(x - Math.Floor(x));

__instance.centerXD = x * __instance._width;
__instance.minX = (int)Math.Floor(__instance.centerXD);
__instance.maxX = (int)Math.Ceiling(__instance.centerXD);
__instance.minX = (int)__instance.centerXD;
__instance.maxX = __instance.minX + 1;
__instance.midX = (float)__instance.centerXD - __instance.minX;
if (__instance.maxX == __instance._width)
__instance.maxX = 0;

// Y clamps as it is latitude and the poles don't wrap to each other.
y = Math.Min(Math.Max(y, 0), 0.99999);
if (y >= 1.0)
y = lessThanOneDouble;
else if (y < 0.0)
y = 0.0;

__instance.centerYD = y * __instance._height;
__instance.minY = (int)Math.Floor(__instance.centerYD);
__instance.maxY = (int)Math.Ceiling(__instance.centerYD);
__instance.minY = (int)__instance.centerYD;
__instance.maxY = __instance.minY + 1;
__instance.midY = (float)__instance.centerYD - __instance.minY;
if (__instance.maxY >= __instance._height)
__instance.maxY = __instance._height - 1;
if (__instance.maxY == __instance._height)
{
if (ReferenceEquals(__instance, moho_height))
__instance.maxY = 0; // use incorrect wrapping for moho
else
__instance.maxY = __instance._height - 1;
}

return false;
}


}
}
1 change: 1 addition & 0 deletions KSPCommunityFixes/KSPCommunityFixes.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@
<Compile Include="Performance\DisableHiddenPortraits.cs" />
<Compile Include="Performance\DisableMapUpdateInFlight.cs" />
<Compile Include="Performance\DragCubeGeneration.cs" />
<Compile Include="Performance\FastBiomeQuery.cs" />
<Compile Include="Performance\FastLoader.cs" />
<Compile Include="Performance\LocalizerPerf.cs" />
<Compile Include="Performance\MemoryLeaks.cs" />
Expand Down
84 changes: 83 additions & 1 deletion KSPCommunityFixes/Library/StaticHelpers.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
namespace KSPCommunityFixes
using System.Runtime.CompilerServices;
using System;

namespace KSPCommunityFixes
{
static class StaticHelpers
{
Expand Down Expand Up @@ -38,5 +41,84 @@ public static string HumanReadableBytes(long bytes)
// Return formatted number with suffix
return readable.ToString("0.### ") + suffix;
}

/// <summary>
/// Returns the largest value that compares less than a specified value.
/// </summary>
/// <param name="x">The value to decrement.</param>
/// <returns>The largest value that compares less than x, or NegativeInfinity if x equals NegativeInfinity, or NaN if x equals NaN.</returns>
/// // https://github.com/dotnet/runtime/blob/af4efb1936b407ca5f4576e81484cf5687b79a26/src/libraries/System.Private.CoreLib/src/System/Math.cs#L210
public static double BitDecrement(double x)
{
long bits = BitConverter.DoubleToInt64Bits(x);

if (((bits >> 32) & 0x7FF00000) >= 0x7FF00000)
{
// NaN returns NaN
// -Infinity returns -Infinity
// +Infinity returns double.MaxValue
return (bits == 0x7FF00000_00000000) ? double.MaxValue : x;
}

if (bits == 0x00000000_00000000)
{
// +0.0 returns -double.Epsilon
return -double.Epsilon;
}

// Negative values need to be incremented
// Positive values need to be decremented

bits += ((bits < 0) ? +1 : -1);
return BitConverter.Int64BitsToDouble(bits);
}

// https://github.com/dotnet/runtime/blob/af4efb1936b407ca5f4576e81484cf5687b79a26/src/libraries/System.Private.CoreLib/src/System/MathF.cs#L52
public static float BitDecrement(float x)
{
int bits = SingleToInt32Bits(x);

if ((bits & 0x7F800000) >= 0x7F800000)
{
// NaN returns NaN
// -Infinity returns -Infinity
// +Infinity returns float.MaxValue
return (bits == 0x7F800000) ? float.MaxValue : x;
}

if (bits == 0x00000000)
{
// +0.0 returns -float.Epsilon
return -float.Epsilon;
}

// Negative values need to be incremented
// Positive values need to be decremented

bits += ((bits < 0) ? +1 : -1);
return Int32BitsToSingle(bits);
}

/// <summary>
/// Converts the specified single-precision floating point number to a 32-bit signed integer.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>A 32-bit signed integer whose bits are identical to <paramref name="value"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int SingleToInt32Bits(float value)
{
return *((int*)&value);
}

/// <summary>
/// Converts the specified 32-bit signed integer to a single-precision floating point number.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>A single-precision floating point number whose bits are identical to <paramref name="value"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe float Int32BitsToSingle(int value)
{
return *((float*)&value);
}
}
}
Loading
Loading