private void Update() { if (_grown) { return; } _timeSincePlanted += Time.deltaTime; var newSpriteIndex = Mathf.FloorToInt((_timeSincePlanted / _timeToGrow) * _growSprites.Length - 1); if (_currentSpriteIndex != newSpriteIndex) { _currentSpriteIndex = newSpriteIndex; _spriteRenderer.sprite = _growSprites[_currentSpriteIndex]; } if (_timeSincePlanted < _timeToGrow) { return; } // Debug.Log("Plant " + GetHashCode() + " grown"); _grown = true; _spriteRenderer.sprite = _growSprites[_growSprites.Length - 1]; TownController.Instance.PushNewOrder(OrderType.HarvestPlant, BitMath.RoundToInt((Vector2)transform.position)); }
/** * Get the water tile type at a tile. * @param t Water tile to query. * @return Water tile type at the tile. */ //inline public static WaterTileType GetWaterTileType(TileIndex t) { if (TileMap.IsTileType(t, TileType.MP_WATER) == false) { throw new ArgumentException(nameof(t), "Supplied tile must be of type MP_WATER"); } switch ((WaterTileTypeBitLayout)BitMath.GB(Map._m[t].m5, (byte)WaterTileTypeBitLayout.WBL_TYPE_BEGIN, (byte)WaterTileTypeBitLayout.WBL_TYPE_COUNT)) { case WaterTileTypeBitLayout.WBL_TYPE_NORMAL: return(BitMath.HasBit(Map._m[t].m5, (byte)WaterTileTypeBitLayout.WBL_COAST_FLAG) ? WaterTileType.WATER_TILE_COAST : WaterTileType.WATER_TILE_CLEAR); case WaterTileTypeBitLayout.WBL_TYPE_LOCK: return(WaterTileType.WATER_TILE_LOCK); case WaterTileTypeBitLayout.WBL_TYPE_DEPOT: return(WaterTileType.WATER_TILE_DEPOT); default: throw new NotReachedException(); } }
private void Update() { if (!IsProducing) { return; } _currentProductionTime += Time.deltaTime; if (_currentProductionTime < _productionTime) { return; } SpawnController.Instance.SpawnDroppedItem(_producedItem, Position + BitMath.RoundToInt(Vector2.down), _producedItemAmmount); _currentProductionTime = 0; RawMaterialStored -= MaterialAmmountNeeded; TriggerCallback(NotificationType.OnFactoryProgressChanged); if (RawMaterialStored < MaterialAmmountNeeded) { IsProducing = false; } }
public void CountLeadinZeros() { Random r = new Random(); Assert.AreEqual(32, BitMath.CountLeadingZeros(0u)); Assert.AreEqual(0, BitMath.CountLeadingZeros(uint.MaxValue)); for (int k = 0; k < 10; k++) { for (int x = 0; x < 32; x++) { Assert.AreEqual(31 - x, BitMath.CountLeadingZeros(1u << x | Next(r, 1u << x))); } } Assert.AreEqual(64, BitMath.CountLeadingZeros(0ul)); Assert.AreEqual(0, BitMath.CountLeadingZeros(ulong.MaxValue)); for (int k = 0; k < 10; k++) { for (int x = 0; x < 63; x++) { Assert.AreEqual(63 - x, BitMath.CountLeadingZeros(1ul << x | Next(r, 1ul << x))); } } }
private void CalcDirSize(string rootDirectory, IFileSystem fileSystem) { if (this.M_DirTableLen == 0) { this.M_DirTableLen = 0x18; } else { this.M_DirTableLen += 0x18 + BitMath.Align(Path.GetFileName(rootDirectory.TrimEnd('/')).Length * 2, 4); } var filePaths = fileSystem.GetFiles(rootDirectory, "*", true); foreach (var filePath in filePaths) { var filename = Path.GetFileName(filePath); this.M_FileTableLen += 0x20 + BitMath.Align(filename.Length * 2, 4); } var dirPaths = fileSystem.GetDirectories(rootDirectory, true); foreach (var dirPath in dirPaths) { CalcDirSize(dirPath, fileSystem); } this.FileNum += filePaths.Length; this.DirNum += dirPaths.Length; }
/// <summary> /// Creates a new CustomFileStream /// </summary> /// <param name="stream">The filestream to use as the base stream</param> /// <param name="ioSize">The size of a buffer pool entry</param> /// <param name="fileStructureBlockSize">The size of an individual block</param> /// <param name="fileName">The filename</param> /// <param name="isReadOnly">If the file is read only</param> /// <param name="isSharingEnabled">if the file is exclusively opened</param> private CustomFileStream(FileStream stream, int ioSize, int fileStructureBlockSize, string fileName, bool isReadOnly, bool isSharingEnabled) { if (ioSize < 4096) { throw new ArgumentOutOfRangeException("ioSize", "Cannot be less than 4096"); } if (fileStructureBlockSize > ioSize) { throw new ArgumentOutOfRangeException("fileStructureBlockSize", "Must not be greater than BufferPoolSize"); } if (!BitMath.IsPowerOfTwo(ioSize)) { throw new ArgumentException("Must be a power of 2", "ioSize"); } if (!BitMath.IsPowerOfTwo(fileStructureBlockSize)) { throw new ArgumentException("Must be a power of 2", "fileStructureBlockSize"); } m_ioSize = ioSize; m_fileName = fileName; m_isReadOnly = isReadOnly; m_isSharingEnabled = isSharingEnabled; m_fileStructureBlockSize = fileStructureBlockSize; m_bufferQueue = ResourceList.GetResourceQueue(ioSize); m_syncRoot = new object(); m_stream = stream; m_length.Value = m_stream.Length; }
public void BitMath_Should_Return_Is_Postive_Power_Of_2() { Boolean actual = BitMath.IsPositivePowerOf2(1); const Boolean expected = true; Assert.Equal(expected, actual); }
public async Task Initalize() { var headerSize = await CiaData.ReadInt32Async(0); CiaHeader = new CiaHeader(await CiaData.ReadArrayAsync(0, headerSize)); var certOffset = BitMath.Align(headerSize, 64); var ticketOffset = BitMath.Align(certOffset + CiaHeader.CertificateChainSize, 64); var tmdOffset = BitMath.Align(ticketOffset + CiaHeader.TicketSize, 64); var contentOffset = BitMath.Align(tmdOffset + CiaHeader.TmdFileSize, 64); var metaOffset = BitMath.Align(contentOffset + CiaHeader.ContentSize, 64); TmdMetadata = await TmdMetadata.Load(CiaData.GetReadOnlyDataReference(tmdOffset, CiaHeader.TmdFileSize)); Partitions = new NcchPartition[TmdMetadata.ContentChunkRecords.Length]; long partitionStart = contentOffset; for (var i = 0; i < TmdMetadata.ContentChunkRecords.Length; i++) { var chunkRecord = TmdMetadata.ContentChunkRecords[i]; var partitionLength = chunkRecord.ContentSize; int contentIndex = chunkRecord.ContentIndex; Partitions[i] = await NcchPartition.Load(CiaData.GetReadOnlyDataReference(partitionStart, partitionLength)); partitionStart += partitionLength; } IsDlcContainer = TmdMetadata.TitleId >> 32 == 0x0004008C; }
public void TrailingZeroBitsByteShouldMatchWider() { byte v = byte.MinValue; while (true) { Assert.AreEqual(BitMath.TrailingZeroBits(v), BitMath.TrailingZeroBits(unchecked ((sbyte)v)), "sbyte"); if (v == 0) { v++; continue; // the result for 0 is type dependant } Assert.AreEqual(BitMath.TrailingZeroBits(v), BitMath.TrailingZeroBits((ushort)v), "short"); Assert.AreEqual(BitMath.TrailingZeroBits(v), BitMath.TrailingZeroBits((short)v), "short"); Assert.AreEqual(BitMath.TrailingZeroBits(v), BitMath.TrailingZeroBits((uint)v), "uint"); Assert.AreEqual(BitMath.TrailingZeroBits(v), BitMath.TrailingZeroBits((int)v), "int"); Assert.AreEqual(BitMath.TrailingZeroBits(v), BitMath.TrailingZeroBits((ulong)v), "ulong"); Assert.AreEqual(BitMath.TrailingZeroBits(v), BitMath.TrailingZeroBits((long)v), "long"); Assert.AreEqual(BitMath.TrailingZeroBits(v), BitMath.TrailingZeroBits((UInt128)v), "UInt128"); if (v == byte.MaxValue) { break; } v++; } }
public static float ToIEEE754(ulong *value) { int exp = 127 + (value[1] == 0 ? 63 + BitMath.FLS64(value[1]) : BitMath.FLS64(*value) - 1); if (exp < 127) { return(0f); } uint raw = (uint)(exp << 23); int x = exp >> 6; // x / 64 int y = exp & 0x3F; // x % 64 if (y < 23) { raw |= (uint)value[x] & ((1u << y) - 1); if (--x >= 0) { raw |= (uint)(value[x] >> (41 + y)) & ((1u << (23 - y)) - 1); } } else { raw |= (uint)(value[x] >> (y - 23)) & 0x7F_FFFF; } return(*(float *)&raw); }
private void OnCursorClick() { var roundedPos = BitMath.RoundToInt(_inputModel.WorldCursorPos); transform.position = (Vector2)roundedPos; _buildModel.CurrentBuilding.Position = roundedPos; }
/** * Terminate road works on a tile. * @param t Tile to stop the road works on. * @pre HasRoadWorks(t) */ public static void TerminateRoadWorks(this TileIndex t) { Debug.Assert(HasRoadWorks(t)); SetRoadside(t, (Roadside)(GetRoadside(t) - Roadside.ROADSIDE_GRASS_ROAD_WORKS + Roadside.ROADSIDE_GRASS)); /* Stop the counter */ BitMath.SB(Map._me[t].m7, 0, 4, 0); }
private void AddFiles(List <RomfsFile> Entries) { string PrevDirPath = ""; for (int i = 0; i < Entries.Count; i++) { var fileName = Path.GetFileName(Entries[i].FullName); Romfs_FileEntry Entry = new Romfs_FileEntry(); string DirPath = Path.GetDirectoryName(Entries[i].FullName); int ParentIndex = GetRomfsDirEntry(DirPath); Entry.FullName = Entries[i].FullName; Entry.Offset = this.FileTableLen; Entry.ParentDirOffset = this.DirTable[ParentIndex].Offset; Entry.SiblingOffset = ROMFS_UNUSED_ENTRY; if (DirPath == PrevDirPath) { this.FileTable[i - 1].SiblingOffset = Entry.Offset; } if (this.DirTable[ParentIndex].FileOffset == ROMFS_UNUSED_ENTRY) { this.DirTable[ParentIndex].FileOffset = Entry.Offset; } Entry.HashKeyPointer = ROMFS_UNUSED_ENTRY; Entry.NameSize = fileName.Length * 2; Entry.Name = fileName; Entry.DataOffset = Entries[i].Offset; Entry.DataSize = Entries[i].Size; this.FileTable.Add(Entry); this.FileTableLen += 0x20 + BitMath.Align(fileName.Length * 2, 4); PrevDirPath = DirPath; } }
public void TestBitAndByteCalculations() { Assert.IsFalse(BitMath.IsPowerOf2(0)); Assert.IsTrue(BitMath.IsPowerOf2(1)); Assert.IsTrue(BitMath.IsPowerOf2(2)); Assert.IsFalse(BitMath.IsPowerOf2(3)); Assert.IsTrue(BitMath.IsPowerOf2(4)); Assert.IsFalse(BitMath.IsPowerOf2(5)); Assert.IsFalse(BitMath.IsPowerOf2(6)); Assert.AreEqual(0, BitMath.RequiredBytes(0)); for (int i = 1; i <= 8; ++i) { Assert.AreEqual(1, BitMath.RequiredBytes(i)); } Assert.AreEqual(2, BitMath.RequiredBytes(9)); Assert.AreEqual(2, BitMath.RequiredBytes(16)); Assert.AreEqual(3, BitMath.RequiredBytes(17)); Assert.AreEqual(0, BitMath.BitsInBytes(0)); Assert.AreEqual(8, BitMath.BitsInBytes(1)); Assert.AreEqual(16, BitMath.BitsInBytes(2)); Assert.AreEqual(24, BitMath.BitsInBytes(3)); Assert.AreEqual(0, BitMath.RoundToUpperByteBoundry(0)); Assert.AreEqual(8, BitMath.RoundToUpperByteBoundry(1)); Assert.AreEqual(8, BitMath.RoundToUpperByteBoundry(2)); Assert.AreEqual(16, BitMath.RoundToUpperByteBoundry(9)); Assert.AreEqual(16, BitMath.RoundToUpperByteBoundry(16)); Assert.AreEqual(24, BitMath.RoundToUpperByteBoundry(17)); }
/// <summary> /// Returns a cryptographically strong number that is less than the the supplied value /// </summary> /// <param name="maxValue">the max value to return exclusive</param> /// <returns></returns> /// <remarks> /// if 0 is provided, 0 is returned /// </remarks> private static ulong GetRandomNumberLessThan(ulong maxValue) { //A crypto number cannot be achieved via *, /, or % since these //operations have rounding and uneven redistribution properties. //Method: In order to get a crypto number <= maxValue //A random number must be generated. If the random number is in range, it //may be kept, otherwise a new number must be generated. //To increase the likelihood that the number is in range, //bit masking can be used on the higher order bits to //create a 75% likelihood (on average) that the number will be in range. //Exception cases where algorithm doesn't work if (maxValue == 0 || maxValue == 1) { return(0); } //Determine the number of random bits that I need int leadingZeroes = BitMath.CountLeadingZeros(maxValue); ulong value = UInt64; //By shifting the value by the number of leading zeros, I'll have //a number with the highest likelihood of being in range while (value >> leadingZeroes >= maxValue) { //If the number is outside of range, all bits must //be discarded and new ones generated. Not doing this //technically alters the crypto-random nature of the value being generated. value = UInt64; } return(value >> leadingZeroes); }
public DropItemType DestroyItem(Vector2Int pos, out int ammount) { DroppedItemController target = null; foreach (var item in _townModel.DroppedItems) { if (BitMath.RoundToInt((Vector2)item.transform.position) != pos) { continue; } target = item; break; } if (target == null) { throw new Exception("No item to destroy at " + pos); } var type = target.Type; ammount = target.Ammount; _townModel.DroppedItems.Remove(target); Destroy(target.gameObject); return(type); }
public static SignalType GetSignalType(this TileIndex t, Track track) { Debug.Assert(GetRailTileType(t) == RailTileType.RAIL_TILE_SIGNALS); byte pos = (byte)((track == Track.TRACK_LOWER || track == Track.TRACK_RIGHT) ? 4 : 0); return((SignalType)BitMath.GB(Map._m[t].m2, pos, 3)); }
private void AcceptsMovementState() { switch (_lastNotificationType) { case NotificationType.None: if (_hasToMove) { _hasToMove = Move(_lastClickPos); } break; case NotificationType.OnCursorClick: _lastClickPos = BitMath.RoundToInt(_inputModel.WorldCursorPos); _lastNotificationType = NotificationType.None; _hasToMove = true; break; case NotificationType.DragBegin: Move(_inputModel.WorldCursorPos); break; case NotificationType.DragEnd: _lastClickPos = BitMath.RoundToInt(_inputModel.WorldCursorPos); _lastNotificationType = NotificationType.None; _hasToMove = true; break; } }
static byte[] MFcrypt(byte[] P, byte[] S, int cost, int blockSize, int parallel, int?maxThreads) { int MFLen = blockSize * 128; if (maxThreads == null) { maxThreads = int.MaxValue; } if (!BitMath.IsPositivePowerOf2(cost)) { throw Exceptions.ArgumentOutOfRange("cost", "Cost must be a positive power of 2."); } Check.Range("blockSize", blockSize, 1, int.MaxValue / 128); Check.Range("parallel", parallel, 1, int.MaxValue / MFLen); Check.Range("maxThreads", (int)maxThreads, 1, int.MaxValue); byte[] B = Pbkdf2.ComputeDerivedKey(new HMACSHA256(P), S, 1, parallel * MFLen); uint[] B0 = new uint[B.Length / 4]; for (int i = 0; i < B0.Length; i++) { B0[i] = BitPacking.UInt32FromLEBytes(B, i * 4); } // code is easier with uint[] ThreadSMixCalls(B0, MFLen, cost, blockSize, parallel, (int)maxThreads); for (int i = 0; i < B0.Length; i++) { BitPacking.LEBytesFromUInt32(B0[i], B, i * 4); } Security.Clear(B0); return(B); }
/** * Get the tropic zone * @param tile the tile to get the zone of * @pre tile < MapSize() * @return the zone type */ /*inline*/ public static TropicZone GetTropicZone(TileIndex tile) { if (tile >= Map.MapSize()) { throw new ArgumentOutOfRangeException(nameof(tile), "Must be less than MapSize()"); } return((TropicZone)BitMath.GB(Map._m[tile].type, 0, 2)); }
/** * Get the tiletype of a given tile. * * @param tile The tile to get the TileType * @return The tiletype of the tile * @pre tile < MapSize() */ /*inline*/ public static TileType GetTileType(TileIndex tile) { if (tile >= Map.MapSize()) { throw new ArgumentOutOfRangeException(nameof(tile), $"Must be less than {Map.MapSize()}"); } return((TileType)BitMath.GB(Map._m[tile].type, 4, 4)); }
/** * Get the part of a ship depot. * @param t Water tile to query. * @return Part of the depot. * @pre IsShipDepotTile(t) */ /*inline*/ public static DepotPart GetShipDepotPart(TileIndex t) { if (IsShipDepotTile(t) == false) { throw new ArgumentException(nameof(t)); } return((DepotPart)BitMath.GB(Map._m[t].m5, (byte)WaterTileTypeBitLayout.WBL_DEPOT_PART, 1)); }
public void CreateBitMask() { for (int x = 0; x < 64; x++) { Assert.AreEqual((1ul << x) - 1, BitMath.CreateBitMask(x)); } Assert.AreEqual(ulong.MaxValue, BitMath.CreateBitMask(64)); }
public void BitMath_Should_Return_Count_Of_31() { //Integer as 32 digit binary number Int32 actual = BitMath.CountLeadingZeros(1); const Int32 expected = 31; Assert.Equal(expected, actual); }
/** * Set the water class at a tile. * @param t Water tile to change. * @param wc New water class. * @pre IsTileType(t, MP_WATER) || IsTileType(t, MP_STATION) || IsTileType(t, MP_INDUSTRY) || IsTileType(t, MP_OBJECT) */ //inline public static void SetWaterClass(TileIndex t, WaterClass wc) { if (HasTileWaterClass(t) == false) { throw new ArgumentException(nameof(t)); } BitMath.SB(ref Map._m[t].m1, 5, 2, (uint)wc); }
/// <summary> /// Creates a <see cref="LargeArray{T}"/> with the specified jagged array depth. /// </summary> /// <param name="jaggedArrayDepth">the number of elements per jagged array. Rounds up to the nearest power of 2.</param> public LargeArray(int jaggedArrayDepth) { m_size = (int)BitMath.RoundUpToNearestPowerOfTwo((uint)jaggedArrayDepth); m_mask = m_size - 1; m_bitShift = BitMath.CountBitsSet((uint)m_mask); m_array = new T[0][]; m_capacity = 0; }
/** * Get the axis of the ship depot. * @param t Water tile to query. * @return Axis of the depot. * @pre IsShipDepotTile(t) */ /*inline*/ public static Axis GetShipDepotAxis(TileIndex t) { if (IsShipDepotTile(t) == false) { throw new ArgumentException(nameof(t)); } return((Axis)BitMath.GB(Map._m[t].m5, (byte)WaterTileTypeBitLayout.WBL_DEPOT_AXIS, 1)); }
/** * Get the water class at a tile. * @param t Water tile to query. * @pre IsTileType(t, MP_WATER) || IsTileType(t, MP_STATION) || IsTileType(t, MP_INDUSTRY) || IsTileType(t, MP_OBJECT) * @return Water class at the tile. */ //inline public static WaterClass GetWaterClass(TileIndex t) { if (HasTileWaterClass(t) == false) { throw new ArgumentException(nameof(t)); } return((WaterClass)BitMath.GB(Map._m[t].m1, 5, 2)); }
public void BitMath_Shift_Left_Should_Return_3() { Byte data = 1; Byte actual = BitMath.ShiftLeft(data, 3); const Byte expected = 8; //Math.Pow(2, 3); Assert.Equal(expected, actual); }
public void BitMath_Should_Return_Count_Of_28() { //Integer as 32 digit binary number //15 = 1111 in binary, so 32 - 4 = 28 Int32 actual = BitMath.CountLeadingZeros(15); const Int32 expected = 28; Assert.Equal(expected, actual); }