Esempio n. 1
0
    /*--------------------------------------------------------------------------*/
    public static byte[] generate_key_secret(byte[] my_private, byte[] another_public)
    {
        if (my_private == null || my_private.Length != DH_KEY_LENGTH) return null;
        if (another_public == null || another_public.Length != DH_KEY_LENGTH) return null;

        UInt128 private_k = new UInt128(my_private);
        UInt128 another_k = new UInt128(another_public);

        /* secret_key = other_key^prv_key mod P*/
        UInt128 secret_k = UInt128._powmodp(another_k, private_k);
        byte[] secret_key = new byte[DH_KEY_LENGTH];
        secret_k.to_bytes(secret_key);
        return secret_key;
    }
        public void UInt128_Equals_Equivalent_ReturnsTrue()
        {
            var baseValue = new UInt128() { High = 1, Low = 2 };

            var testValues = new object[] { 
                baseValue, 
                new UInt128() { High = 1, Low = 2 } 
            };

            foreach (var testValue in testValues)
            {
                Assert.True(
                    baseValue.Equals(testValue));
            }
        }
        public void UInt128_Equals_Inequivalent_ReturnsFalse()
        {
            var baseValue = new UInt128() { High = 1, Low = 2 };

            var testValues = new object[] {
                null, 
                "", 
                new UInt128() { Low = 2 }, 
                new UInt128 { High = 1 } 
            };

            
            foreach (var testValue in testValues)
            {
                Assert.False(
                    baseValue.Equals(testValue));
            }
        }
Esempio n. 4
0
    /*--------------------------------------------------------------------------*/
    public static void generate_key_pair(byte[] public_key, byte[] private_key)
    {
        if (public_key == null || public_key.Length != DH_KEY_LENGTH) return;
        if (private_key == null || private_key.Length != DH_KEY_LENGTH) return;

        Random rand = new Random();

        /* generate random private key */
        for (int i = 0; i < DH_KEY_LENGTH; i++)
        {
            private_key[i] = (byte)(rand.Next() & 0xFF);
        }

        /* pub_key = G^prv_key mod P*/
        UInt128 private_k = new UInt128(private_key);
        UInt128 public_k = UInt128._powmodp(G, private_k);

        public_k.to_bytes(public_key);
    }
Esempio n. 5
0
        /// <summary>
        /// Creates an address from an address string ("2001:0db8:0::22:1.2.3.4").
        /// </summary>
        public IpV6Address(string value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            string cannonizedValue = value;

            // Handle ...:1.2.3.4
            int lastColonIndex = cannonizedValue.LastIndexOf(':');
            if (lastColonIndex == -1)
                throw new ArgumentException("Invalid IPv6 address format " + value);

            string lastPart = value.Substring(lastColonIndex + 1, cannonizedValue.Length - lastColonIndex - 1);
            if (lastPart.IndexOf('.') != -1)
            {
                uint lastPartValue = new IpV4Address(lastPart).ToValue();
                cannonizedValue = cannonizedValue.Substring(0, lastColonIndex + 1) +
                                  (lastPartValue >> 16).ToString("x", CultureInfo.InvariantCulture) + ":" + (lastPartValue & 0x0000FFFF).ToString("x", CultureInfo.InvariantCulture);
            }

            // Handle ...::...
            int doubleColonIndex = cannonizedValue.IndexOf("::", StringComparison.Ordinal);
            if (doubleColonIndex != -1)
            {
                int numMissingColons = 7 - cannonizedValue.Count(':');
                if (numMissingColons < 0)
                    throw new ArgumentException("Invalid IPv6 address format " + value);
                cannonizedValue = cannonizedValue.Substring(0, doubleColonIndex + 2) +
                                  new string(':', numMissingColons) +
                                  cannonizedValue.Substring(doubleColonIndex + 2);
            }

            IEnumerable<ushort> values =
                cannonizedValue.Split(':').Select(part => string.IsNullOrEmpty(part) ? (ushort)0 : ushort.Parse(part, NumberStyles.HexNumber, CultureInfo.InvariantCulture));

            ulong mostSignificant = values.Take(4).Aggregate((ulong)0, (sum, element) => (sum << 16) + element);
            ulong leastSignificant = values.Skip(4).Take(4).Aggregate((ulong)0, (sum, element) => (sum << 16) + element);

            _value = new UInt128(mostSignificant, leastSignificant);
        }
Esempio n. 6
0
 public void SetUInt128(string key, UInt128 value)
 {
     this.SetBytes(key, this.Serializer.Serialize(value));
 }
Esempio n. 7
0
 public static UInt128 Square(UInt128 a)
 {
     return UInt128.Square(a);
 }
Esempio n. 8
0
		public static unsafe byte[] GetBytesSwapped(UInt128 value)
		{
			byte* ptrHigh=(byte*)&value.High;
			byte* ptrLow=(byte*)&value.Low;
			return new byte[16] {
				ptrHigh[7], ptrHigh[6], ptrHigh[5], ptrHigh[4], ptrHigh[3], ptrHigh[2], ptrHigh[1], ptrHigh[0],
				ptrLow[7], ptrLow[6], ptrLow[5], ptrLow[4], ptrLow[3], ptrLow[2], ptrLow[1], ptrLow[0] };
		}
Esempio n. 9
0
 public static void Shift(ref Int128 c, int d)
 {
     UInt128.ArithmeticShift(ref c.v, d);
 }
Esempio n. 10
0
		/// <summary>
		/// Creates an instance of a CRC algorithm with the behaviour according to the parameters.
		/// </summary>
		/// <param name="polynomial">The polynomial to use. Unreflected and filled in the least significant bits without the leading 1.</param>
		/// <returns>The created instance.</returns>
		public static ICRC<UInt128> Create(UInt128 polynomial)
		{
			return new UnreflectedUInt128(polynomial, UInt128.Zero, false, UInt128.Zero, 128);
		}
Esempio n. 11
0
		/// <summary>
		/// Combines the CRCs of two blocks to the CRC of the blocks concatenated.
		/// </summary>
		/// <param name="crc1">The CRC of the first block.</param>
		/// <param name="crc2">The CRC of the second block.</param>
		/// <param name="lengthOfCRC2">The length of the second block in bytes.</param>
		/// <param name="polynomial">The polynomial used to create the CRCs. Unreflected and filled in the least significant bits.</param>
		/// <returns>The combined CRC value.</returns>
		public static UInt128 Combine(UInt128 crc1, UInt128 crc2, int lengthOfCRC2, UInt128 polynomial)
		{
			return Combine(crc1, crc2, lengthOfCRC2, polynomial, UInt128.Zero, false, UInt128.Zero, 128);
		}
Esempio n. 12
0
 public PartitionKeyHash(UInt128 value)
 {
     this.Value = value;
 }
Esempio n. 13
0
            private static PartitionKeyHash Hash(ReadOnlySpan <byte> bytesForHashing)
            {
                UInt128 hash = Cosmos.MurmurHash3.Hash128(bytesForHashing, seed: 0);

                return(new PartitionKeyHash(hash));
            }
Esempio n. 14
0
    static void AddOngoingAchievement(List <Tuple <AchievementData, UInt128> > ongoingAchievements,
                                      Dictionary <ScString, List <AchievementData> > group, string groupKey, UInt128 gatheredValue)
    {
        var ongoingAchievementData = group[groupKey]
                                     .FirstOrDefault(x => x.conditionOldArg <= gatheredValue && gatheredValue < x.conditionNewArg);

        if (ongoingAchievementData != null)
        {
            ongoingAchievements.Add(new Tuple <AchievementData, UInt128>(ongoingAchievementData, gatheredValue));
        }
    }
Esempio n. 15
0
    static void AddCanBeRedeemedAchievement(List <Tuple <AchievementData, UInt128> > canBeRedeemedAchievements,
                                            Dictionary <ScString, List <AchievementData> > group, string groupKey, UInt128 gatheredValue,
                                            UInt128 redeemedValue)
    {
        var gatheredValueClamped = gatheredValue.ToClampedLong();
        //ConDebug.Log($"groupKey={groupKey}");
        var achievementGroup = group[groupKey];
        var gatheredIndex    = Data.AchievementData_ConditionNewArg_UpperBound(achievementGroup, gatheredValueClamped) - 1;

        var redeemedValueClamped = redeemedValue.ToClampedLong();
        var nextRedeemIndex      = Data.AchievementData_ConditionNewArg_UpperBound(achievementGroup, redeemedValueClamped);

        if (nextRedeemIndex <= gatheredIndex && nextRedeemIndex < achievementGroup.Count)
        {
            canBeRedeemedAchievements.Add(
                new Tuple <AchievementData, UInt128>(achievementGroup[nextRedeemIndex], gatheredValue));
        }
    }
Esempio n. 16
0
        public Horizon(Switch device)
        {
            ControlData = new Nacp();

            Device = device;

            State = new SystemStateMgr();

            ResourceLimit = new KResourceLimit(this);

            KernelInit.InitializeResourceLimit(ResourceLimit);

            MemoryRegions = KernelInit.GetMemoryRegions();

            LargeMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize * 2);
            SmallMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize);

            UserSlabHeapPages = new KSlabHeap(
                UserSlabHeapBase,
                UserSlabHeapItemSize,
                UserSlabHeapSize);

            CriticalSection = new KCriticalSection(this);

            Scheduler = new KScheduler(this);

            TimeManager = new KTimeManager();

            Synchronization = new KSynchronization(this);

            ContextIdManager = new KContextIdManager();

            _kipId     = InitialKipId;
            _processId = InitialProcessId;

            Scheduler.StartAutoPreemptionThread();

            KernelInitialized = true;

            ThreadCounter = new CountdownEvent(1);

            Processes = new SortedDictionary <long, KProcess>();

            AutoObjectNames = new ConcurrentDictionary <string, KAutoObject>();

            // Note: This is not really correct, but with HLE of services, the only memory
            // region used that is used is Application, so we can use the other ones for anything.
            KMemoryRegionManager region = MemoryRegions[(int)MemoryRegion.NvServices];

            ulong hidPa  = region.Address;
            ulong fontPa = region.Address + HidSize;
            ulong iirsPa = region.Address + HidSize + FontSize;
            ulong timePa = region.Address + HidSize + FontSize + IirsSize;

            HidBaseAddress = (long)(hidPa - DramMemoryMap.DramBase);

            KPageList hidPageList  = new KPageList();
            KPageList fontPageList = new KPageList();
            KPageList iirsPageList = new KPageList();
            KPageList timePageList = new KPageList();

            hidPageList.AddRange(hidPa, HidSize / KMemoryManager.PageSize);
            fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
            iirsPageList.AddRange(iirsPa, IirsSize / KMemoryManager.PageSize);
            timePageList.AddRange(timePa, TimeSize / KMemoryManager.PageSize);

            HidSharedMem  = new KSharedMemory(this, hidPageList, 0, 0, MemoryPermission.Read);
            FontSharedMem = new KSharedMemory(this, fontPageList, 0, 0, MemoryPermission.Read);
            IirsSharedMem = new KSharedMemory(this, iirsPageList, 0, 0, MemoryPermission.Read);

            KSharedMemory timeSharedMemory = new KSharedMemory(this, timePageList, 0, 0, MemoryPermission.Read);

            TimeServiceManager.Instance.Initialize(device, this, timeSharedMemory, (long)(timePa - DramMemoryMap.DramBase), TimeSize);

            AppletState = new AppletStateMgr(this);

            AppletState.SetFocus(true);

            Font = new SharedFontManager(device, (long)(fontPa - DramMemoryMap.DramBase));

            IUserInterface.InitializePort(this);

            VsyncEvent = new KEvent(this);

            LoadKeySet();

            ContentManager = new ContentManager(device);

            // TODO: use set:sys (and get external clock source id from settings)
            // TODO: use "time!standard_steady_clock_rtc_update_interval_minutes" and implement a worker thread to be accurate.
            UInt128 clockSourceId = new UInt128(Guid.NewGuid().ToByteArray());

            IRtcManager.GetExternalRtcValue(out ulong rtcValue);

            // We assume the rtc is system time.
            TimeSpanType systemTime = TimeSpanType.FromSeconds((long)rtcValue);

            // First init the standard steady clock
            TimeServiceManager.Instance.SetupStandardSteadyClock(null, clockSourceId, systemTime, TimeSpanType.Zero, TimeSpanType.Zero, false);
            TimeServiceManager.Instance.SetupStandardLocalSystemClock(null, new SystemClockContext(), systemTime.ToSeconds());

            if (NxSettings.Settings.TryGetValue("time!standard_network_clock_sufficient_accuracy_minutes", out object standardNetworkClockSufficientAccuracyMinutes))
            {
                TimeSpanType standardNetworkClockSufficientAccuracy = new TimeSpanType((int)standardNetworkClockSufficientAccuracyMinutes * 60000000000);

                TimeServiceManager.Instance.SetupStandardNetworkSystemClock(new SystemClockContext(), standardNetworkClockSufficientAccuracy);
            }

            TimeServiceManager.Instance.SetupStandardUserSystemClock(null, false, SteadyClockTimePoint.GetRandom());

            // FIXME: TimeZone shoud be init here but it's actually done in ContentManager

            TimeServiceManager.Instance.SetupEphemeralNetworkSystemClock();

            LocalFileSystem serverBaseFs = new LocalFileSystem(device.FileSystem.GetBasePath());

            DefaultFsServerObjects fsServerObjects = DefaultFsServerObjects.GetDefaultEmulatedCreators(serverBaseFs, KeySet);

            GameCard = fsServerObjects.GameCard;

            FileSystemServerConfig fsServerConfig = new FileSystemServerConfig
            {
                FsCreators     = fsServerObjects.FsCreators,
                DeviceOperator = fsServerObjects.DeviceOperator,
                ExternalKeySet = KeySet.ExternalKeySet
            };

            FsServer = new FileSystemServer(fsServerConfig);
        }
Esempio n. 17
0
 public IpV6Address(UInt128 value)
 {
     this._value = value;
 }
Esempio n. 18
0
File: int128.cs Progetto: sgf/SCTP
 public static void Subtract(ref Int128 a, ref Int128 b)
 {
     UInt128.Subtract(ref a.v, ref b.v);
 }
Esempio n. 19
0
		/// <summary>
		/// Multiplication of matrix with vector (MOD 2). This method doesn't check the
		/// input arguments for performance reasons, so please make sure they are correct.
		/// </summary>
		/// <param name="matrix">The matrix to multiply with.</param>
		/// <param name="vector">The vector to be multiplied with the matrix.</param>
		/// <returns>The resulting vector.</returns>
		static UInt128 MatrixMult(UInt128[] matrix, UInt128 vector)
		{
			int index=0;
			UInt128[] mat=matrix;
			UInt128 vec=vector;

			UInt128 ret=0;

			while(vec!=0)
			{
				if((vec.Low&1)!=0) ret^=mat[index];
				vec>>=1;
				index++;
			}

			return ret;
		}
Esempio n. 20
0
 public Int128(ulong value)
 {
     UInt128.Create(out v, value);
 }
Esempio n. 21
0
		/// <summary>
		/// Combines the CRCs of two blocks to the CRC of the blocks concatenated.
		/// </summary>
		/// <param name="crc1">The CRC of the first block.</param>
		/// <param name="crc2">The CRC of the second block.</param>
		/// <param name="lengthOfCRC2">The length of the second block in bytes.</param>
		/// <param name="polynomial">The polynomial used to create the CRCs. Unreflected and filled in the least significant bits.</param>
		/// <param name="init">The initial value of the register. Unreflected and filled in the least significant bits.</param>
		/// <param name="refOut">Set <b>true</b>, if register is to be reflected before XORing with <paramref name="xorOut"/> and output.</param>
		/// <param name="xorOut">Value to be XORed with the reflected or unreflected register depending on <paramref name="refOut"/> before output. Filled in the least significant bits.</param>
		/// <param name="width">The width of the polynomial in bits. Must be greater than 0 and less than 129. Default is 128.</param>
		/// <returns>The combined CRC value.</returns>
		public static UInt128 Combine(UInt128 crc1, UInt128 crc2, int lengthOfCRC2, UInt128 polynomial, UInt128 init, bool refOut, UInt128 xorOut, int width=128)
		{
			if(lengthOfCRC2<0) throw new ArgumentOutOfRangeException("lengthOfCRC2", "Must not be less than zero (0).");
			if(width<=0||width>128) throw new ArgumentOutOfRangeException("width", "Must be greater than 0 and less than 129.");

			// Nothing to combine
			if(lengthOfCRC2==0) return crc1;

			// Gets value (2^width)-1.
			UInt128 mask=UInt128.MaxValue>>(128-width);

			crc1&=mask;
			crc2&=mask;
			polynomial&=mask;
			init&=mask;
			xorOut&=mask;

			crc1^=xorOut; // Remove xorOut from CRC1

			UInt128 crc=refOut?BitOrder.Reflect(crc1, width):crc1; // If CRC is reflected against SIMPLE and thus against the polynomial

			crc^=init; // Remove CRC2's register initialization value by adding to CRC

			UInt128[] mat1=new UInt128[width], mat2=new UInt128[width]; // Create matrices (for inplace squaring operation)

			// Fill matrix with 1-bit-shift-operation (bit 0 of register becomes bit 1, bit 1 becomes bit 2 and so on, when multiplied with this matrix)
			UInt128 row=2;
			for(int n=0; n<width-1; n++, row<<=1) mat1[n]=row;
			mat1[width-1]=polynomial; // and the polynomial (will be multiplied(XORed) into the register if top-bit is 1, when multiplied with this matrix)

			// Square to create 2-bit-operation matrix
			MatrixSquare(mat2, mat1, width);

			// Square again to create 4-bit-operation matrix (the first MatrixSquare inside the loop below, creates the 8-bit-operation matrix needed for
			// our lengthOfCRC2 zero-byte-operations)
			MatrixSquare(mat1, mat2, width);

			int length=lengthOfCRC2;

			// 'Add' lengthOfCRC2 zero-bytes to crc1
			do
			{
				// Square to create the next power-of-two-operation matrix
				MatrixSquare(mat2, mat1, width);

				// 'Add' zero-bytes
				if((length&1)!=0) crc=MatrixMult(mat2, crc);
				length>>=1;

				// Already done?
				if(length==0) break;

				// Square to create the next power-of-two-operation matrix
				MatrixSquare(mat1, mat2, width);

				// 'Add' zero-bytes
				if((length&1)!=0) crc=MatrixMult(mat1, crc);
				length>>=1;
			} while(length!=0);

			if(refOut) crc=BitOrder.Reflect(crc, width); // If CRC was reflected against SIMPLE => undo

			// Return combined crc
			crc^=crc2; // CRC2 still contains xorOut
			return crc;
		}
Esempio n. 22
0
 public Int128(double value)
 {
     UInt128.Create(out v, value);
 }
Esempio n. 23
0
 private static void Write(byte[] buffer, int offset, UInt128 value)
 {
     unsafe
     {
         fixed (byte* ptr = &buffer[offset])
         {
             *((UInt128*)ptr) = value;
         }
     }
 }
Esempio n. 24
0
 public Int128(decimal value)
 {
     UInt128.Create(out v, value);
 }
Esempio n. 25
0
		public static unsafe UInt128[] ToUInt128Array(byte[] value, int index=0, int count=0)
		{
			if(value==null) throw new ArgumentNullException("value");

			if(index<0||index>value.Length)
				throw new ArgumentOutOfRangeException("index", "Must be non-negative and less than or equal to the length of value.");

			if(count<0) throw new ArgumentOutOfRangeException("count", "Must be non-negative.");
			if(index+count*16>value.Length) throw new ArgumentOutOfRangeException("count", "Must be less than or equal to the length of the byte array minus the offset argument divided by 16.");

			if(count==0) count=(value.Length-index)/16;

			UInt128[] ret=new UInt128[count];
			fixed(byte* ptr=&value[index])
				for(int i=0; i<count; i++) ret[i]=new UInt128(*((ulong*)ptr+2*i+1), *((ulong*)ptr+2*i));
			return ret;
		}
Esempio n. 26
0
 public Int128(BigInteger value)
 {
     UInt128.Create(out v, value);
 }
Esempio n. 27
0
 public static UInt128 ModularDifference(UInt128 a, UInt128 b, UInt128 modulus)
 {
     return UInt128.ModSub(a, b, modulus);
 }
Esempio n. 28
0
 public bool Equals(UInt128 other)
 {
     return(Hi == other.Hi && Lo == other.Lo);
 }
Esempio n. 29
0
        public void SumTest()
        {
            UInt128 value1 = 0;
            UInt128 value2 = 0;
            Assert.AreEqual<UInt128>(0, value1 + value2);

            value1 = 1;
            Assert.AreEqual<UInt128>(1, value1 + value2);
            
            value2 = 1;
            Assert.AreEqual<UInt128>(2, value1 + value2);

            value1 = 100;
            Assert.AreEqual<UInt128>(101, value1 + value2);

            value2 = 1000;
            Assert.AreEqual<UInt128>(1100, value1 + value2);

            value1 = ulong.MaxValue;
            value2 = 0;
            Assert.AreEqual(ulong.MaxValue, value1 + value2);

            value2 = 1;
            Assert.AreEqual(new UInt128(1,0), value1 + value2);

            value2 = 2;
            Assert.AreEqual(new UInt128(1, 1), value1 + value2);

            value2 = ulong.MaxValue;
            Assert.AreEqual(new UInt128(1, ulong.MaxValue - 1), value1 + value2);

            value1 = 2;
            value2 = new UInt128(1000, ulong.MaxValue);
            Assert.AreEqual(new UInt128(1001, 1), value1 + value2);

            value1 = new UInt128(100, ulong.MaxValue / 2 + 1);
            value2 = new UInt128(1000, ulong.MaxValue / 2 + 2);
            Assert.AreEqual(new UInt128(1101, 1), value1 + value2);

            value1 = new UInt128(ulong.MaxValue / 2, ulong.MaxValue / 2 + 1);
            value2 = new UInt128(ulong.MaxValue / 2, ulong.MaxValue / 2 + 2);
            Assert.AreEqual(new UInt128(ulong.MaxValue, 1), value1 + value2);

            value1 = new UInt128(ulong.MaxValue / 2 + 1, ulong.MaxValue / 2 + 1);
            value2 = new UInt128(ulong.MaxValue / 2, ulong.MaxValue / 2 + 2);
            Assert.AreEqual(new UInt128(0, 1), value1 + value2);
        }
Esempio n. 30
0
        private static ulong Hash(byte[] input)
        {
            var len       = (uint)input.Length;
            var numChunks = len / 128;

            // copy tail, pad with zeroes
            var tail     = new byte[128];
            var tailSize = len % 128;

            Buffer.BlockCopy(input, (int)(len - tailSize), tail, 0, (int)tailSize);

            UInt128 hash;

            hash = numChunks != 0
                ? Hash_chunk(input, 128, 0)
                : Hash_chunk(tail, tailSize, 0);

            hash += RoundMagic;

            var offset = 0;

            if (numChunks != 0)
            {
                while (--numChunks > 0)
                {
                    offset += 128;
                    hash    = Hash_muladd(hash, RoundMagic, Hash_chunk(input, 128, offset));
                }

                if (tailSize > 0)
                {
                    hash = Hash_muladd(hash, RoundMagic, Hash_chunk(tail, tailSize, 0));
                }
            }

            hash += new UInt128(tailSize * 8, 0);

            if (hash > new UInt128(0x7fffffffffffffff, 0xffffffffffffffff))
            {
                hash++;
            }

            hash = hash << 1 >> 1;

            var x = hash.Hi + (hash.Lo >> 32);

            x = ((x + (x >> 32) + 1) >> 32) + hash.Hi;
            var y = (x << 32) + hash.Lo;

            var a = x + FinalMagic0;

            if (a < x)
            {
                a += 0x101;
            }

            var b = y + FinalMagic1;

            if (b < y)
            {
                b += 0x101;
            }

            var h   = new UInt128(a) * b;
            var mul = new UInt128(0x101);

            h = (mul * h.Hi) + h.Lo;
            h = (mul * h.Hi) + h.Lo;

            if (h.Hi > 0)
            {
                h += mul;
            }
            if (h.Lo > 0xFFFFFFFFFFFFFEFE)
            {
                h += mul;
            }
            return(h.Lo);
        }
 private void IdGetter(ref UInt128 val) => val = new UInt128((ulong)Position, 0);
Esempio n. 32
0
 private void SetTotal(UInt128 total) => _data.Total = total;
Esempio n. 33
0
File: int128.cs Progetto: sgf/SCTP
 public static void Add(ref Int128 a, ref Int128 b)
 {
     UInt128.Add(ref a.v, ref b.v);
 }
Esempio n. 34
0
 private void SetStaged(UInt128 staged) => _data.Staged = staged;
Esempio n. 35
0
 public static void AssertValue(this XElement element, UInt128 expectedValue)
 {
     element.AssertValue(expectedValue.ToString("x32"));
 }
Esempio n. 36
0
            void TrainTransform()
            {
                lock (_lock)
                {
                    if (_reversedMapping != null)
                    {
                        return;
                    }

                    using (var ch = _host.Start("DBScan"))
                    {
                        var sw = Stopwatch.StartNew();
                        sw.Start();
                        var points = new List <IPointIdFloat>();

                        int index;
                        if (!_input.Schema.TryGetColumnIndex(_args.features, out index))
                        {
                            ch.Except("Unable to find column '{0}'", _args.features);
                        }

                        // Caching data.
                        ch.Info("Caching the data.");
                        using (var cursor = _input.GetRowCursor(i => i == index))
                        {
                            var     getter   = cursor.GetGetter <VBuffer <float> >(index);
                            var     getterId = cursor.GetIdGetter();
                            UInt128 id       = new UInt128();

                            VBuffer <float> tmp = new VBuffer <float>();

                            for (int i = 0; cursor.MoveNext(); ++i)
                            {
                                getter(ref tmp);
                                getterId(ref id);
                                if (id > long.MaxValue)
                                {
                                    ch.Except("An id is outside the range for long {0}", id);
                                }
                                points.Add(new PointIdFloat((long)id, tmp.DenseValues()));
                            }
                        }

                        // Mapping.
                        // int: index of a cluster
                        // long: index of a point
                        var mapping = new int[points.Count];
                        var mapprev = new Dictionary <long, int>();

                        float distance = _args.epsilon;
                        if (distance <= 0)
                        {
                            float mind, maxd;
                            distance = EstimateDistance(ch, points, out mind, out maxd);
                            ch.Info("epsilon (=Radius) was estimating on random couples of points: {0} in [{1}, {2}]", distance, mind, maxd);
                        }

                        DBScan dbscanAlgo = new DBScan(points, _args.seed);
                        // Clustering.
                        ch.Info("Clustering {0} points.", points.Count);

                        int          nPoints = points.Count;
                        int          cyclesBetweenLogging = Math.Min(1000, nPoints / 10);
                        int          currentIteration     = 0;
                        Action <int> progressLogger       = nClusters =>
                        {
                            if (++currentIteration % cyclesBetweenLogging == 0)
                            {
                                ch.Info("Processing  {0}/{1} - NbClusters={2}", currentIteration, nPoints, nClusters);
                            }
                        };

                        Dictionary <long, int> results = dbscanAlgo.Cluster(
                            distance,
                            _args.minPoints,
                            seed: _args.seed,
                            onShuffle: msg => ch.Info(msg),
                            onPointProcessing: progressLogger);

                        // Cleaning small clusters.
                        ch.Info("Removing clusters with less than {0} points.", _args.minPoints);
                        var finalCounts_ = results.GroupBy(c => c.Value, (key, g) => new { key = key, nb = g.Count() });
                        var finalCounts  = finalCounts_.ToDictionary(c => c.key, d => d.nb);
                        results = results.Select(c => new KeyValuePair <long, int>(c.Key, finalCounts[c.Value] < _args.minPoints ? -1 : c.Value))
                                  .ToDictionary(c => c.Key, c => c.Value);

                        _reversedMapping = new Dictionary <long, Tuple <int, float> >();

                        ch.Info("Compute scores.");
                        HashSet <int> clusterIds = new HashSet <int>();
                        for (int i = 0; i < results.Count; ++i)
                        {
                            IPointIdFloat p = points[i];

                            int cluster = results[p.id];
                            mapprev[p.id] = cluster;
                            if (cluster >= 0)  // -1 is noise
                            {
                                mapping[cluster] = cluster;
                            }
                            mapping[i] = cluster;
                            if (cluster != DBScan.NOISE)
                            {
                                clusterIds.Add(cluster);
                            }
                        }
                        foreach (var p in points)
                        {
                            if (mapprev[p.id] < 0)
                            {
                                continue;
                            }
                            _reversedMapping[p.id] = new Tuple <int, float>(mapprev[p.id],
                                                                            dbscanAlgo.Score(p, _args.epsilon, mapprev));
                        }

                        // Adding points with no clusters.
                        foreach (var p in points)
                        {
                            if (!_reversedMapping.ContainsKey(p.id))
                            {
                                _reversedMapping[p.id] = new Tuple <int, float>(-1, float.PositiveInfinity);
                            }
                        }

                        if (_reversedMapping.Count != points.Count)
                        {
                            throw ch.Except("Mismatch between the number of points. This means some ids are not unique {0} != {1}.", _reversedMapping.Count, points.Count);
                        }

                        ch.Info("Found {0} clusters.", mapprev.Select(c => c.Value).Where(c => c >= 0).Distinct().Count());
                        sw.Stop();
                        ch.Info("'DBScan' finished in {0}.", sw.Elapsed);
                    }
                }
            }
Esempio n. 37
0
		/// <summary>
		/// Squares a matrix (MOD 2). This method doesn't check the input arguments for
		/// performance reasons, so please make sure they are correct.
		/// </summary>
		/// <param name="result">The matrix for the result. Must be at least <paramref name="width"/> long.</param>
		/// <param name="matrix">The matrix to be squared. Must be at least <paramref name="width"/> long.</param>
		/// <param name="width">The width of the matrix. Default is 128.</param>
		static void MatrixSquare(UInt128[] result, UInt128[] matrix, int width=128)
		{
			UInt128[] res=result;
			UInt128[] mat=matrix;
			for(int n=0; n<width; n++) res[n]=MatrixMult(mat, mat[n]);
		}
 private static unsafe void Write(byte[] buffer, int offset, UInt128 value)
 {
     fixed(byte *numPtr = &buffer[offset])
     * (UInt128 *)numPtr = value;
 }
Esempio n. 39
0
		/// <summary>
		/// Combines the CRCs of two blocks to the CRC of the blocks concatenated.
		/// </summary>
		/// <param name="crc1">The CRC of the first block.</param>
		/// <param name="crc2">The CRC of the second block.</param>
		/// <param name="lengthOfCRC2">The length of the second block in bytes.</param>
		/// <param name="polynomial">The polynomial used to create the CRCs. Unreflected and filled in the least significant bits.</param>
		/// <param name="init">The initial value of the register. Unreflected and filled in the least significant bits.</param>
		/// <param name="refOut">Set <b>true</b>, if register is to be reflected before output.</param>
		/// <returns>The combined CRC value.</returns>
		public static UInt128 Combine(UInt128 crc1, UInt128 crc2, int lengthOfCRC2, UInt128 polynomial, UInt128 init, bool refOut=false)
		{
			return Combine(crc1, crc2, lengthOfCRC2, polynomial, init, refOut, UInt128.Zero, 128);
		}
Esempio n. 40
0
        public Horizon(Switch device, ContentManager contentManager)
        {
            KernelContext = new KernelContext(device, device.Memory);

            Device = device;

            State = new SystemStateMgr();

            PerformanceState = new PerformanceState();

            // Note: This is not really correct, but with HLE of services, the only memory
            // region used that is used is Application, so we can use the other ones for anything.
            KMemoryRegionManager region = KernelContext.MemoryRegions[(int)MemoryRegion.NvServices];

            ulong hidPa  = region.Address;
            ulong fontPa = region.Address + HidSize;
            ulong iirsPa = region.Address + HidSize + FontSize;
            ulong timePa = region.Address + HidSize + FontSize + IirsSize;

            HidBaseAddress = hidPa - DramMemoryMap.DramBase;

            KPageList hidPageList  = new KPageList();
            KPageList fontPageList = new KPageList();
            KPageList iirsPageList = new KPageList();
            KPageList timePageList = new KPageList();

            hidPageList.AddRange(hidPa, HidSize / KMemoryManager.PageSize);
            fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
            iirsPageList.AddRange(iirsPa, IirsSize / KMemoryManager.PageSize);
            timePageList.AddRange(timePa, TimeSize / KMemoryManager.PageSize);

            HidSharedMem  = new KSharedMemory(KernelContext, hidPageList, 0, 0, KMemoryPermission.Read);
            FontSharedMem = new KSharedMemory(KernelContext, fontPageList, 0, 0, KMemoryPermission.Read);
            IirsSharedMem = new KSharedMemory(KernelContext, iirsPageList, 0, 0, KMemoryPermission.Read);

            KSharedMemory timeSharedMemory = new KSharedMemory(KernelContext, timePageList, 0, 0, KMemoryPermission.Read);

            TimeServiceManager.Instance.Initialize(device, this, timeSharedMemory, timePa - DramMemoryMap.DramBase, TimeSize);

            AppletState = new AppletStateMgr(this);

            AppletState.SetFocus(true);

            Font = new SharedFontManager(device, fontPa - DramMemoryMap.DramBase);

            VsyncEvent = new KEvent(KernelContext);

            DisplayResolutionChangeEvent = new KEvent(KernelContext);

            ContentManager = contentManager;

            // TODO: use set:sys (and get external clock source id from settings)
            // TODO: use "time!standard_steady_clock_rtc_update_interval_minutes" and implement a worker thread to be accurate.
            UInt128 clockSourceId = new UInt128(Guid.NewGuid().ToByteArray());

            IRtcManager.GetExternalRtcValue(out ulong rtcValue);

            // We assume the rtc is system time.
            TimeSpanType systemTime = TimeSpanType.FromSeconds((long)rtcValue);

            // Configure and setup internal offset
            TimeSpanType internalOffset = TimeSpanType.FromSeconds(ConfigurationState.Instance.System.SystemTimeOffset);

            TimeSpanType systemTimeOffset = new TimeSpanType(systemTime.NanoSeconds + internalOffset.NanoSeconds);

            if (systemTime.IsDaylightSavingTime() && !systemTimeOffset.IsDaylightSavingTime())
            {
                internalOffset = internalOffset.AddSeconds(3600L);
            }
            else if (!systemTime.IsDaylightSavingTime() && systemTimeOffset.IsDaylightSavingTime())
            {
                internalOffset = internalOffset.AddSeconds(-3600L);
            }

            internalOffset = new TimeSpanType(-internalOffset.NanoSeconds);

            // First init the standard steady clock
            TimeServiceManager.Instance.SetupStandardSteadyClock(null, clockSourceId, systemTime, internalOffset, TimeSpanType.Zero, false);
            TimeServiceManager.Instance.SetupStandardLocalSystemClock(null, new SystemClockContext(), systemTime.ToSeconds());

            if (NxSettings.Settings.TryGetValue("time!standard_network_clock_sufficient_accuracy_minutes", out object standardNetworkClockSufficientAccuracyMinutes))
            {
                TimeSpanType standardNetworkClockSufficientAccuracy = new TimeSpanType((int)standardNetworkClockSufficientAccuracyMinutes * 60000000000);

                // The network system clock needs a valid system clock, as such we setup this system clock using the local system clock.
                TimeServiceManager.Instance.StandardLocalSystemClock.GetClockContext(null, out SystemClockContext localSytemClockContext);
                TimeServiceManager.Instance.SetupStandardNetworkSystemClock(localSytemClockContext, standardNetworkClockSufficientAccuracy);
            }

            TimeServiceManager.Instance.SetupStandardUserSystemClock(null, false, SteadyClockTimePoint.GetRandom());

            // FIXME: TimeZone shoud be init here but it's actually done in ContentManager

            TimeServiceManager.Instance.SetupEphemeralNetworkSystemClock();

            DatabaseImpl.Instance.InitializeDatabase(device);

            HostSyncpoint = new NvHostSyncpt(device);

            SurfaceFlinger = new SurfaceFlinger(device);

            ConfigurationState.Instance.System.EnableDockedMode.Event += OnDockedModeChange;

            InitLibHacHorizon();
            InitializeAudioRenderer();
        }
Esempio n. 41
0
		/// <summary>
		/// Creates an instance of a CRC algorithm with the behaviour according to the parameters.
		/// </summary>
		/// <param name="polynomial">The polynomial to use. Unreflected and filled in the least significant bits without the leading 1.</param>
		/// <param name="init">The initial value of the register. Unreflected and filled in the least significant bits.</param>
		/// <param name="refIn">Set <b>true</b>, if input bits are reflected. Least significant bits first.</param>
		/// <param name="refOut">Set <b>true</b>, if register is to be reflected before XORing with <paramref name="xorOut"/> and output.</param>
		/// <param name="xorOut">Value to be XORed with the reflected or unreflected register depending on <paramref name="refOut"/> before output. Filled in the least significant bits.</param>
		/// <param name="width">The width of the polynomial in bits. Must be greater than 0 and less than 129. Default is 128.</param>
		/// <returns>The created instance.</returns>
		public static ICRC<UInt128> Create(UInt128 polynomial, UInt128 init, bool refIn, bool refOut, UInt128 xorOut, int width = 128)
		{
			if (refIn) return new ReflectedUInt128(polynomial, init, refOut, xorOut, width);
			return new UnreflectedUInt128(polynomial, init, refOut, xorOut, width);
		}
Esempio n. 42
0
 /// <summary>
 /// Writes the given value to the buffer using the given endianity and increments the offset by the number of bytes written.
 /// </summary>
 /// <param name="buffer">The buffer to write the value to.</param>
 /// <param name="offset">The offset in the buffer to start writing.</param>
 /// <param name="value">The value to write.</param>
 /// <param name="endianity">The endianity to use when converting the value to bytes.</param>
 public static void Write(this byte[] buffer, ref int offset, UInt128 value, Endianity endianity)
 {
     buffer.Write(offset, value, endianity);
     offset += UInt128.SizeOf;
 }
Esempio n. 43
0
		/// <summary>
		/// Creates an instance of a CRC algorithm with the behaviour according to the parameters.
		/// </summary>
		/// <param name="polynomial">The polynomial to use. Unreflected and filled in the least significant bits without the leading 1.</param>
		/// <param name="init">The initial value of the register. Unreflected and filled in the least significant bits.</param>
		/// <param name="refIn">Set <b>true</b>, if input bits are reflected. Least significant bits first.</param>
		/// <param name="refOut">Set <b>true</b>, if register is to be reflected before output.</param>
		/// <returns>The created instance.</returns>
		public static ICRC<UInt128> Create(UInt128 polynomial, UInt128 init, bool refIn = false, bool refOut = false)
		{
			if (refIn) return new ReflectedUInt128(polynomial, init, refOut, UInt128.Zero, 128);
			return new UnreflectedUInt128(polynomial, init, refOut, UInt128.Zero, 128);
		}
Esempio n. 44
0
		public static unsafe byte[] GetBytesSwapped(UInt128[] value, int index=0, int count=0)
		{
			if(value==null) throw new ArgumentNullException("value");

			if(index<0||index>value.Length)
				throw new ArgumentOutOfRangeException("index", "Must be non-negative and less than or equal to the length of value.");

			if(count<0) throw new ArgumentOutOfRangeException("count", "Must be non-negative.");
			if(index+count>value.Length) throw new ArgumentOutOfRangeException("count", "Must be less than or equal to the length of value minus the index argument.");

			if(count==0) count=value.Length-index;

			byte[] ret=new byte[count*16];
			fixed(byte* pRet=ret)
			{
				byte* iRet=pRet;
				ulong buffer;
				byte* ptr=(byte*)&buffer;
				for(int i=0; i<count; i++)
				{
					buffer=value[index+i].High;
					*(iRet++)=ptr[7];
					*(iRet++)=ptr[6];
					*(iRet++)=ptr[5];
					*(iRet++)=ptr[4];
					*(iRet++)=ptr[3];
					*(iRet++)=ptr[2];
					*(iRet++)=ptr[1];
					*(iRet++)=ptr[0];

					buffer=value[index+i].Low;
					*(iRet++)=ptr[7];
					*(iRet++)=ptr[6];
					*(iRet++)=ptr[5];
					*(iRet++)=ptr[4];
					*(iRet++)=ptr[3];
					*(iRet++)=ptr[2];
					*(iRet++)=ptr[1];
					*(iRet++)=ptr[0];
				}
			}
			return ret;
		}
Esempio n. 45
0
 /// <summary>
 /// Writes the given value to the buffer using the given endianity.
 /// </summary>
 /// <param name="buffer">The buffer to write the value to.</param>
 /// <param name="offset">The offset in the buffer to start writing.</param>
 /// <param name="value">The value to write.</param>
 /// <param name="endianity">The endianity to use when converting the value to bytes.</param>
 public static void Write(this byte[] buffer, int offset, UInt128 value, Endianity endianity)
 {
     if (IsWrongEndianity(endianity))
         value = HostToNetworkOrder(value);
     Write(buffer, offset, value);
 }
Esempio n. 46
0
 public static void Shift(out Int128 c, ref Int128 a, int d)
 {
     UInt128.ArithmeticShift(out c.v, ref a.v, d);
 }
Esempio n. 47
0
        private static UInt128 HostToNetworkOrder(UInt128 value)
        {
            UInt128 result;

            unsafe
            {
                UInt128* resultPtr = &result;
                byte* resultBytePtr = (byte*)resultPtr;

                UInt128* valuePtr = &value;
                byte* valueBytePtr = (byte*)valuePtr;

                for (int i = 0; i != UInt128.SizeOf; ++i)
                    resultBytePtr[i] = valueBytePtr[UInt128.SizeOf - i - 1];
            }

            return result;
        }
Esempio n. 48
0
        public static UInt128 StartFight(UInt128 guid = default(UInt128))
        {
            MovementManager.StopMove();
            WoWUnit targetNpc = null;

            try
            {
                if (guid == 0)
                {
                    targetNpc =
                        new WoWUnit(
                            ObjectManager.ObjectManager.GetNearestWoWUnit(
                                ObjectManager.ObjectManager.GetHostileUnitAttackingPlayer()).GetBaseAddress);
                }
                else
                {
                    targetNpc =
                        new WoWUnit(ObjectManager.ObjectManager.GetObjectByGuid(guid).GetBaseAddress);
                }

                if (!targetNpc.Attackable)
                {
                    nManagerSetting.AddBlackList(targetNpc.Guid, 20000); // blacklist 20 sec
                }

                if (ObjectManager.ObjectManager.Me.IsMounted &&
                    (CombatClass.InAggroRange(targetNpc) || CombatClass.InRange(targetNpc)))
                {
                    MountTask.DismountMount();
                }

                InFight = true;

                if (!ObjectManager.ObjectManager.Me.IsCast)
                {
                    Interact.InteractWith(targetNpc.GetBaseAddress);
                }
                Thread.Sleep(100);
                if (ObjectManager.ObjectManager.Me.GetMove && !ObjectManager.ObjectManager.Me.IsCast)
                {
                    MovementManager.StopMoveTo();
                }

                Point positionStartTarget = targetNpc.Position;

                int timer = 0;
figthStart:
                // If pos start is very different
                if (targetNpc.Position.DistanceTo(positionStartTarget) > 50)
                {
                    return(0);
                }
                if (!targetNpc.Attackable)
                {
                    nManagerSetting.AddBlackList(targetNpc.Guid, 20000); // blacklist 20 sec
                    // Some become unattackable instead of being dead.
                    // Some will evade.
                }
                if (Usefuls.IsInBattleground && !Battleground.IsFinishBattleground())
                {
                    List <WoWUnit> tLUnit = ObjectManager.ObjectManager.GetHostileUnitAttackingPlayer();
                    if (tLUnit.Count > 0)
                    {
                        if (ObjectManager.ObjectManager.GetNearestWoWUnit(tLUnit).GetDistance < targetNpc.GetDistance &&
                            ObjectManager.ObjectManager.GetNearestWoWUnit(tLUnit).SummonedBy == 0)
                        {
                            return(0);
                        }
                    }
                }
                if ((ObjectManager.ObjectManager.Me.InCombat && !CombatClass.InRange(targetNpc)) || TraceLine.TraceLineGo(targetNpc.Position)) // If obstacle or not in range
                {
                    bool         resultSucces;
                    List <Point> points = PathFinder.FindPath(targetNpc.Position, out resultSucces);
                    if (!resultSucces && !Usefuls.IsFlying && MountTask.GetMountCapacity() >= MountCapacity.Fly)
                    {
                        MountTask.Mount(true, true);
                    }

                    // TODO: Code a FindTarget that includes CombatClass.GetRange here or we will often do wierd thing with casters.
                    MovementManager.Go(points);
                    timer = Others.Times + (int)(Math.DistanceListPoint(points) / 3 * 1000) + 15000;

                    while (!ObjectManager.ObjectManager.Me.IsDeadMe && !targetNpc.IsDead && targetNpc.Attackable && !targetNpc.IsLootable &&
                           targetNpc.Health > 0 && targetNpc.IsValid &&
                           MovementManager.InMovement && InFight && Usefuls.InGame &&
                           (TraceLine.TraceLineGo(targetNpc.Position) || !CombatClass.InAggroRange(targetNpc))
                           )
                    {
                        // Mob already in fight
                        if (targetNpc.Type != Enums.WoWObjectType.Player && !(targetNpc.IsTargetingMe || targetNpc.Target == 0 || ((WoWUnit)ObjectManager.ObjectManager.GetObjectByGuid(targetNpc.Target)).
                                                                              SummonedBy == ObjectManager.ObjectManager.Me.Guid || targetNpc.Target == ObjectManager.ObjectManager.Pet.Guid))
                        {
                            return(targetNpc.Guid);
                        }

                        // Timer
                        if (Others.Times > timer && TraceLine.TraceLineGo(targetNpc.Position))
                        {
                            return(targetNpc.Guid);
                        }

                        // Target Pos Verif
                        if (!targetNpc.Position.IsValid)
                        {
                            return(targetNpc.Guid);
                        }

                        // If pos start is very different
                        if (targetNpc.Position.DistanceTo(positionStartTarget) > 50)
                        {
                            return(0);
                        }

                        // Return if player/pet is attacked by another unit
                        if (ObjectManager.ObjectManager.GetNumberAttackPlayer() > 0 && !targetNpc.IsTargetingMe && !(targetNpc.Target == ObjectManager.ObjectManager.Pet.Guid && targetNpc.Target > 0))
                        {
                            return(0);
                        }
                        Thread.Sleep(50);
                    }
                }
                timer = Others.Times + (int)(ObjectManager.ObjectManager.Me.Position.DistanceTo(targetNpc.Position) / 3 * 1000) + 5000;
                if (MovementManager.InMovement)
                {
                    MovementManager.StopMove();
                }

                if (!ObjectManager.ObjectManager.Me.IsCast && ObjectManager.ObjectManager.Me.Target != targetNpc.Guid)
                {
                    Interact.InteractWith(targetNpc.GetBaseAddress);
                }

                InFight = true;
                Thread.Sleep(200);
                if (CombatClass.InAggroRange(targetNpc))
                {
                    if (ObjectManager.ObjectManager.Me.GetMove && !ObjectManager.ObjectManager.Me.IsCast)
                    {
                        MovementManager.StopMoveTo();
                    }
                    if (!ObjectManager.ObjectManager.Me.GetMove && ObjectManager.ObjectManager.Me.IsMounted)
                    {
                        MountTask.DismountMount();
                    }
                }

                // If target died after only 0.2sec of fight, let's find a new target.
                if (targetNpc.IsDead || !targetNpc.IsValid || targetNpc.Attackable)
                {
                    WoWUnit newTargetNpc = new WoWUnit(ObjectManager.ObjectManager.GetNearestWoWUnit(ObjectManager.ObjectManager.GetHostileUnitAttackingPlayer()).GetBaseAddress);
                    if (newTargetNpc.IsValid && !ObjectManager.ObjectManager.Me.IsCast && ObjectManager.ObjectManager.Me.Target != newTargetNpc.Guid)
                    {
                        targetNpc = newTargetNpc;
                        Interact.InteractWith(targetNpc.GetBaseAddress);
                        // Face the new target
                        MovementManager.Face(targetNpc);
                    }
                }

                while (!ObjectManager.ObjectManager.Me.IsDeadMe && !targetNpc.IsDead && targetNpc.Attackable && targetNpc.IsValid && InFight &&
                       targetNpc.IsValid && !ObjectManager.ObjectManager.Me.InTransport)
                {
                    // Return if player attacked and this target not attack player
                    if (targetNpc.Type != Enums.WoWObjectType.Player && !targetNpc.IsTargetingMe && !(targetNpc.Target == ObjectManager.ObjectManager.Pet.Guid && targetNpc.Target > 0) &&
                        ObjectManager.ObjectManager.GetNumberAttackPlayer() > 0)
                    {
                        return(0);
                    }

                    // Cancel fight if the mob was tapped by another player
                    if (targetNpc.IsTapped)
                    {
                        return(0);
                    }

                    // Target Pos Verif
                    if (!targetNpc.Position.IsValid)
                    {
                        InFight = false;
                        return(targetNpc.Guid);
                    }

                    // Target mob if not target
                    if (ObjectManager.ObjectManager.Me.Target != targetNpc.Guid && !targetNpc.IsDead && !ObjectManager.ObjectManager.Me.IsCast)
                    {
                        Interact.InteractWith(targetNpc.GetBaseAddress);
                    }

                    // Move to target if out of range
                    if (!ObjectManager.ObjectManager.Me.IsCast &&
                        ((!ObjectManager.ObjectManager.Me.InCombat && !CombatClass.InAggroRange(targetNpc)) ||
                         ((ObjectManager.ObjectManager.Me.InCombat && !CombatClass.InRange(targetNpc)))))
                    {
                        int rJump = Others.Random(1, 20);
                        MovementManager.MoveTo(targetNpc);
                        if (rJump == 5)
                        {
                            MovementsAction.Jump();
                        }
                    }
                    // Create path if the mob is out of sight or out of range
                    if ((!CombatClass.InRange(targetNpc) && !ObjectManager.ObjectManager.Me.IsCast) ||
                        TraceLine.TraceLineGo(targetNpc.Position))
                    {
                        goto figthStart;
                    }
                    // Stop move if in range
                    if (CombatClass.InRange(targetNpc) && ObjectManager.ObjectManager.Me.GetMove &&
                        !ObjectManager.ObjectManager.Me.IsCast)
                    {
                        MovementManager.StopMoveTo();
                    }
                    if (ObjectManager.ObjectManager.Me.IsMounted)
                    {
                        MountTask.DismountMount();
                        Interact.InteractWith(targetNpc.GetBaseAddress);
                    }

                    // Face player to mob
                    MovementManager.Face(targetNpc);

                    // If obstacle between us and the target after this timer expires then stop the fight and blacklist
                    if (Others.Times > timer && TraceLine.TraceLineGo(targetNpc.Position) &&
                        targetNpc.HealthPercent > 90)
                    {
                        InFight = false;
                        return(targetNpc.Guid);
                    }

                    Thread.Sleep(75 + Usefuls.Latency);

                    // If timer expires and still not in fight, then stop the fight and blacklist
                    if (Others.Times > timer && !ObjectManager.ObjectManager.Me.InCombat && !targetNpc.IsDead)
                    {
                        InFight = false;
                        return(targetNpc.Guid);
                    }
                }

                MovementManager.StopMoveTo();
                InFight = false;
            }
            catch (Exception exception)
            {
                Logging.WriteError("StartFight(UInt128 guid = 0, bool inBg = false): " + exception);
                InFight = false;
            }
            try
            {
                if (targetNpc != null)
                {
                    return(targetNpc.Guid);
                }
            }
            catch
            {
                return(0);
            }
            return(0);
        }
Esempio n. 49
0
		public static byte[] GetBytes(UInt128[] value, bool bigEndian, int index=0, int count=0)
		{
			return IsLittleEndian^bigEndian?GetBytes(value, index, count):GetBytesSwapped(value, index, count);
		}
Esempio n. 50
0
        public static UInt128 StartFightDamageDealer(UInt128 guid = default(UInt128))
        {
            WoWUnit targetNpc = null;

            try
            {
                if (ObjectManager.ObjectManager.Me.IsMounted)
                {
                    return(0);
                }
                if (guid == 0)
                {
                    targetNpc = new WoWUnit(ObjectManager.ObjectManager.GetNearestWoWUnit(ObjectManager.ObjectManager.GetHostileUnitAttackingPlayer()).GetBaseAddress);
                }
                else
                {
                    targetNpc = new WoWUnit(ObjectManager.ObjectManager.GetObjectByGuid(guid).GetBaseAddress);
                }

                if (!targetNpc.Attackable)
                {
                    nManagerSetting.AddBlackList(targetNpc.Guid, 20000); // blacklist 20 sec
                    return(0);
                }

                InFight = true;

                if (!ObjectManager.ObjectManager.Me.IsCast)
                {
                    if (CombatClass.InRange(targetNpc) && CombatClass.GetRange <= 5) // Initiate auto attack on melees + target.
                    {
                        Interact.InteractWith(targetNpc.GetBaseAddress);
                    }
                    ObjectManager.ObjectManager.Me.Target = targetNpc.Guid;
                }
                Thread.Sleep(100);
                Point positionStartTarget = targetNpc.Position;
figthStart:
                // If pos start is far, we will Loop to it anyway.
                if (targetNpc.Position.DistanceTo(positionStartTarget) > CombatClass.GetRange + 5f)
                {
                    return(0);
                }
                if (!targetNpc.Attackable)
                {
                    nManagerSetting.AddBlackList(targetNpc.Guid, 20000); // blacklist 20 sec
                    return(0);
                }
                if (Usefuls.IsInBattleground && !Battleground.IsFinishBattleground())
                {
                    List <WoWUnit> tLUnit = ObjectManager.ObjectManager.GetHostileUnitAttackingPlayer();
                    if (tLUnit.Count > 0)
                    {
                        if (ObjectManager.ObjectManager.GetNearestWoWUnit(tLUnit).GetDistance < targetNpc.GetDistance && ObjectManager.ObjectManager.GetNearestWoWUnit(tLUnit).SummonedBy == 0)
                        {
                            return(0);
                        }
                    }
                }
                Thread.Sleep(200);
                if (CombatClass.InRange(targetNpc) && CombatClass.GetRange > 5 && ObjectManager.ObjectManager.Me.GetMove && !ObjectManager.ObjectManager.Me.IsCast)
                {
                    Logging.Write("Your class recquires you to stop moving in order to cast spell, as this product is passive, we wont try to force stop.");
                }
                if ((ObjectManager.ObjectManager.Me.Target != targetNpc.Guid) && !targetNpc.IsDead && !ObjectManager.ObjectManager.Me.IsCast)
                {
                    ObjectManager.ObjectManager.Me.Target = targetNpc.Guid;
                    if (CombatClass.GetRange <= 5) // Initiate auto attack on melees + target.
                    {
                        Interact.InteractWith(targetNpc.GetBaseAddress);
                    }
                }

                // If target died after only 0.2sec of fight, let's find a new target.
                if (targetNpc.IsDead || !targetNpc.IsValid)
                {
                    targetNpc = new WoWUnit(ObjectManager.ObjectManager.GetNearestWoWUnit(ObjectManager.ObjectManager.GetHostileUnitAttackingPlayer()).GetBaseAddress);
                    if (!ObjectManager.ObjectManager.Me.IsCast && ObjectManager.ObjectManager.Me.Target != targetNpc.Guid)
                    {
                        Interact.InteractWith(targetNpc.GetBaseAddress);
                    }
                    if (nManagerSetting.CurrentSetting.ActivateAutoFacingDamageDealer)
                    {
                        MovementManager.Face(targetNpc, false);
                    }
                }

                while (!ObjectManager.ObjectManager.Me.IsDeadMe && !targetNpc.IsDead && targetNpc.IsValid && InFight && targetNpc.Attackable)
                {
                    // check for IsTransport if we are specifically inside a taxi, but allow fighting in ships etc.
                    // I guess transport Id become the creature Id in that case ? So check if transport id is actually a unit and not a gameobject or a continentid ?

                    // Target Pos Verif
                    if (!targetNpc.Position.IsValid)
                    {
                        return(targetNpc.Guid);
                    }

                    // Target mob if not target
                    if (ObjectManager.ObjectManager.Me.Target != targetNpc.Guid && !targetNpc.IsDead && !ObjectManager.ObjectManager.Me.IsCast)
                    {
                        // Player has switched the target.
                        if (ObjectManager.ObjectManager.Me.Target == 0)
                        {
                            return(0);                 // if player have no target anymore, don't do anything.
                        }
                        if (CombatClass.GetRange <= 5) // Initiate auto attack on melees.
                        {
                            Interact.InteractWith(ObjectManager.ObjectManager.Target.GetBaseAddress);
                        }

                        // Switch Target
                        targetNpc = new WoWUnit(ObjectManager.ObjectManager.Target.GetBaseAddress);
                        goto figthStart;
                    }

                    if (nManagerSetting.CurrentSetting.ActivateAutoFacingDamageDealer)
                    {
                        MovementManager.Face(targetNpc, false);
                    }
                    // If we are not facing anymore, it's because of player moves in 99% of the case, so wait for the next player move to apply the facing.
                    Thread.Sleep(50);
                }
            }
            catch (Exception exception)
            {
                Logging.WriteError("StartFightDamageDealer(UInt128 guid = 0, bool inBg = false): " + exception);
            }
            if (targetNpc != null)
            {
                return(targetNpc.Guid);
            }
            return(0);
        }
Esempio n. 51
0
		public static UInt128[] ToUInt128ArraySwapped(byte[] value, int index=0, int count=0)
		{
			if(value==null) throw new ArgumentNullException("value");

			if(index<0||index>value.Length)
				throw new ArgumentOutOfRangeException("index", "Must be non-negative and less than or equal to the length of value.");

			if(count<0) throw new ArgumentOutOfRangeException("count", "Must be non-negative.");
			if(index+count*16>value.Length) throw new ArgumentOutOfRangeException("count", "Must be less than or equal to the length of the byte array minus the offset argument divided by 16.");

			if(count==0) count=(value.Length-index)/16;

			UInt128[] ret=new UInt128[count];
			for(int i=0; i<count; i++, index+=16)
				ret[i]=new UInt128(ToUInt64Swapped(value, index), ToUInt64Swapped(value, index+8));

			return ret;
		}
 /// <summary>
 /// Gets the hash of a undefined JSON value.
 /// </summary>
 /// <param name="seed">The seed to use.</param>
 /// <returns>The hash of a undefined JSON value.</returns>
 private static UInt128 GetUndefinedHash(UInt128 seed)
 {
     return(seed);
 }
Esempio n. 53
0
		public static byte[] GetBytes(UInt128 value, bool bigEndian)
		{
			return IsLittleEndian^bigEndian?GetBytes(value):GetBytesSwapped(value);
		}
 /// <summary>
 /// Gets the hash of a null JSON value.
 /// </summary>
 /// <param name="seed">The seed to use.</param>
 /// <returns>The hash of a null JSON value given a seed.</returns>
 private static UInt128 GetNullHash(UInt128 seed)
 {
     return(DistinctHash.GetHash(DistinctHash.NullHashSeed, seed));
 }
Esempio n. 55
0
 public static UInt128 Power(UInt128 value, UInt128 exponent)
 {
     UInt128 result;
     UInt128.Pow(out result, ref value, (uint)exponent);
     return result;
 }
 /// <summary>
 /// Gets the hash of a boolean JSON value.
 /// </summary>
 /// <param name="boolean">The boolean to hash.</param>
 /// <param name="seed">The seed.</param>
 /// <returns>The hash of a boolean JSON value.</returns>
 private static UInt128 GetBooleanHash(bool boolean, UInt128 seed)
 {
     return(DistinctHash.GetHash(boolean ? DistinctHash.TrueHashSeed : DistinctHash.FalseHashSeed, seed));
 }
Esempio n. 57
0
 public static UInt128 Cube(UInt128 a)
 {
     return a * a * a;
 }
 /// <summary>
 /// Gets the hash given a value and a seed.
 /// </summary>
 /// <param name="value">The value to hash.</param>
 /// <param name="seed">The seed.</param>
 /// <returns>The hash.</returns>
 public static UInt128 GetHash(UInt128 value, UInt128 seed)
 {
     return(DistinctHash.GetHash(UInt128.ToByteArray(value), seed));
 }
Esempio n. 59
0
        public void Substract()
        {
            UInt128 value1 = 0;
            UInt128 value2 = 0;
            Assert.AreEqual<UInt128>(0, value1 - value2);

            value1 = 1;
            Assert.AreEqual<UInt128>(1, value1 - value2);

            value2 = 1;
            Assert.AreEqual<UInt128>(0, value1 - value2);

            value1 = 100;
            Assert.AreEqual<UInt128>(99, value1 - value2);

            value1 = new UInt128(1, 0);
            value2 = 0;
            Assert.AreEqual<UInt128>(value1, value1 - value2);

            value2 = 1;
            Assert.AreEqual<UInt128>(ulong.MaxValue, value1 - value2);

            value2 = 2;
            Assert.AreEqual<UInt128>(ulong.MaxValue - 1, value1 - value2);

            value1 = new UInt128(100, 1);
            Assert.AreEqual<UInt128>(new UInt128(99, ulong.MaxValue), value1 - value2);

            value1 = 1;
            Assert.AreEqual<UInt128>(UInt128.MaxValue, value1 - value2);
        }
Esempio n. 60
0
 /// <summary>
 /// Initializes a new instance of the OrderedDistinctMap class.
 /// </summary>
 /// <param name="lastHash">The previous hash from the previous continuation.</param>
 private OrderedDistinctMap(UInt128 lastHash)
 {
     this.lastHash = lastHash;
 }