using System;
using System.Collections.Generic;
using System.Linq;
namespace ColdMint.scripts.utils;
///
/// Light layer utils
/// 光照层工具
///
public static class LightMaskUtils
{
private static readonly int[] PowInts =
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288];
///
/// Pass in a number and return the largest subscript that matches it.
/// 传入一个数字,返回与其匹配的最大下标
///
///
///
///
private static int GetMaxPow(int number, int startIndex)
{
for (var i = startIndex - 1; i >= 0; i--)
{
var pow = PowInts[i];
if (number >= pow)
{
return i;
}
}
return -1;
}
///
/// ParseMaskValue
/// 解析Mask的值
///
///
///maskValue
///值
///
///
///This callback returns true when the value is parsed, stopping the parsing immediately.
///当解析到值时,此回调返回true,立即停止解析。
///
///
///The position of the element corresponding to its value, For example, passing in 10, returning [1,3]
///与其值对应的元素位置,例如传入10,返回[1,3]
///
public static int[] ParseMaskValue(int maskValue, Func? afterParsingTheValue = null)
{
var result = new List();
var startIndex = PowInts.Length;
var indexInPowIntArray = GetMaxPow(maskValue, startIndex);
while (indexInPowIntArray > -1)
{
result.Insert(0, indexInPowIntArray);
if (afterParsingTheValue != null)
{
if (afterParsingTheValue.Invoke(indexInPowIntArray))
{
//If it needs to be stopped, then the result is returned directly.
//如果需要停止,那么直接返回结果。
return result.ToArray();
}
}
maskValue -= PowInts[indexInPowIntArray];
startIndex = indexInPowIntArray;
indexInPowIntArray = GetMaxPow(maskValue, startIndex);
}
return result.ToArray();
}
///
/// Is there a location within the mask value?
/// mask值内是否包含某个位置?
///
///
///
///
public static bool ContainsMaskValue(int maskValue, int index)
{
var result = false;
ParseMaskValue(maskValue, i =>
{
result = i == index;
return result;
});
return result;
}
///
/// Add a location to MaskValue
/// 为MaskValue添加某个位置
///
///
///
///
public static int AddIndexToMaskValue(int maskValue, int index)
{
if (ContainsMaskValue(maskValue,index))
{
return maskValue;
}
return maskValue + PowInts[index];
}
///
/// Converting an array to its corresponding value
/// 将数组转化为与其对应的值
///
///
///
public static int ArrayToMaskValue(int[] array)
{
return array.Sum(index => PowInts[index]);
}
}