using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper8.Skyscraper.Math
{
	static class FastMath
	{
		private const int LUT_BITS = 10; // 1024 entries
		private const int LUT_SIZE = 1 << LUT_BITS;
		private static readonly float[] log2Mantissa = new float[LUT_SIZE];

		static FastMath()
		{
			for (int i = 0; i < LUT_SIZE; i++)
			{
				float m = 1.0f + (float)i / LUT_SIZE;
				log2Mantissa[i] = MathF.Log2(m);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float FastLog2(float x)
		{
			int bits = Unsafe.As<float, int>(ref x);

			int exponent = ((bits >> 23) & 0xFF) - 127;

			// normalize mantissa
			int mantissa = bits & 0x7FFFFF;
			int idx = mantissa >> (23 - LUT_BITS);

			return exponent + log2Mantissa[idx];
		}
	}
}
