public void TestlPerfomanceWithBigAdsCount()
        {
            const int GenerationCount = 10000;
            //long totalRndProfit = 0;
            //long totalMaxProfit = 0;
            //long totalRealProfit = 0;
            //totalMaxProfit += _maxAbsProfit;
            //_maxAbsProfit = 0;

            //totalRealProfit += _realProfit;
            //_realProfit = 0;

            //totalRndProfit += _rndProfit;
            //_rndProfit = 0;

            ResetState();
            for (int a = 0; a < GenerationCount; a++)
            {
                List<Ad> ads = GenerateAds(200, 0, 0.3);
                TestPerfomance(ads);
                _rnd = new ThreadSafeRandom();
            }

            //double perc = (double)_failedCount / (_failedCount + _correctCount);
            //Console.WriteLine("Failed: {0}%.", perc * 100);
            // Console.WriteLine("Done in {0} ms.", stopwatch.ElapsedMilliseconds);
            Console.WriteLine("Max profit: {0}. Real profit: {1}. Rnd profit: {2}", _maxAbsProfit, _realProfit, _rndProfit);
            Console.WriteLine("Real profit is smaller then max on: {0}%. Rnd profit: {1}%", (-100d * (_maxAbsProfit - _realProfit) / _maxAbsProfit), (-100d * (_maxAbsProfit - _rndProfit) / _maxAbsProfit));
        }
Example #2
0
        //-------------------------------------------------------------------------
        public CellApp()
        {
            Instance = this;

            Cfg = new CellConfig();
            Rd = new ThreadSafeRandom();
            jsonCfg = new JsonConfig();
            // 注册BtFactory
            _regBtFactory(new BtFactoryBot());
            _regBtFactory(new BtFactoryPlayer());
        }
        public BeginTransactionRetryDecorator(ISqLiteTransactionWrapper decorated,
            ILogFactory log,
            ThreadSafeRandom threadSafeRandom)
        {
            Guard.NotNull(() => decorated, decorated);
            Guard.NotNull(() => log, log);
            Guard.NotNull(() => threadSafeRandom, threadSafeRandom);

            _decorated = decorated;
            _log = log.Create();
            _threadSafeRandom = threadSafeRandom;
        }
 /// <summary>
 /// Initializes the StrengthenMgr. 
 /// </summary>
 /// <returns></returns>
 public static bool Init()
 {
     try
     {
         m_lock = new System.Threading.ReaderWriterLock();
         _consortiaLevel = new Dictionary<int, ConsortiaLevelInfo>();
         rand = new ThreadSafeRandom();
         return Load(_consortiaLevel);
     }
     catch (Exception e)
     {
         if (log.IsErrorEnabled)
             log.Error("ConsortiaLevelMgr", e);
         return false;
     }
 }
Example #5
0
        /// <summary>
        /// Initializes the BallMgr. 
        /// </summary>
        /// <returns></returns>
        public static bool Init()
        {
            try
            {
                m_lock = new System.Threading.ReaderWriterLock();
                _fusions = new Dictionary<string, FusionInfo>();
                rand = new ThreadSafeRandom();
                return LoadFusion(_fusions);
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                    log.Error("FusionMgr", e);
                return false;
            }

        }
Example #6
0
		public static double Calculate(int iterations)
		{
			var random = new ThreadSafeRandom();
			var inCircle = ParallelEnumerable.Range(0, iterations)
				// doesn't make sense to use more threads than we have processors
				.WithDegreeOfParallelism(Environment.ProcessorCount)
				.Select(_ =>
				{
					double a, b;
					return Math.Sqrt((a = random.NextDouble()) * a + (b = random.NextDouble()) * b) <= 1;
				})
				.Aggregate<bool, int, int>(
					0, // Seed
					(agg, val) => val ? agg + 1 : agg, // Iterations
					(agg, subTotal) => agg + subTotal, // Aggregating subtotals
					result => result); // No projection of result needed

			return ((double)inCircle / iterations) * 4;
		}
Example #7
0
        /// <summary>
        /// Initializes the StrengthenMgr. 
        /// </summary>
        /// <returns></returns>
        public static bool Init()
        {
            try
            {
                m_lock = new System.Threading.ReaderWriterLock();
                _strengthens = new Dictionary<int, StrengthenInfo>();
                m_Refinery_Strengthens = new Dictionary<int, StrengthenInfo>();
                Strengthens_Goods = new Dictionary<int, StrengthenGoodsInfo>();
                rand = new ThreadSafeRandom();
                return LoadStrengthen(_strengthens, m_Refinery_Strengthens);
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                    log.Error("StrengthenMgr", e);
                return false;
            }

        }
		public static double Calculate(int iterations)
		{
			var counterLockObject = new object();
			int inCircle = 0;
			var random = new ThreadSafeRandom();

			Parallel.For(0, iterations,
				// doesn't make sense to use more threads than we have processors
				new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, 
				() => 0, (i, _, tLocal) =>
					{
#if LANG_EXPERIMENTAL
                        // Note C# 6 declarating expression here
                        return tLocal += Math.Sqrt((var a = random.NextDouble()) * a 
                            + (var b = random.NextDouble()) * b) <= 1 ? 1 : 0;
#else
						double a, b;
                        return tLocal += Math.Sqrt((a = random.NextDouble()) * a + (b = random.NextDouble()) * b) <= 1 ? 1 : 0;
#endif
                    },
				subTotal => Interlocked.Add(ref inCircle, subTotal));

			return ((double)inCircle / iterations) * 4;
		}
        private static int GetArmorLevelModifier(int tier, int armorType)
        {
            // Olthoi Armor base weenies already have the full amount of AL
            if (armorType > (int)LootTables.ArmorType.OlthoiKoujiaArmor)
            {
                return(0);
            }

            if (armorType > (int)LootTables.ArmorType.HaebreanArmor &&
                armorType < (int)LootTables.ArmorType.OlthoiAlduressaArmor)
            {
                switch (tier)
                {
                case 7:
                    return(ThreadSafeRandom.Next(0, 40));

                default:
                    return(ThreadSafeRandom.Next(160, 200));
                }
            }

            switch (tier)
            {
            case 1:
                if (armorType == (int)LootTables.ArmorType.StuddedLeatherArmor ||
                    armorType == (int)LootTables.ArmorType.Helms ||
                    armorType == (int)LootTables.ArmorType.Shields)
                {
                    return(ThreadSafeRandom.Next(0, 27));
                }
                else if (armorType == (int)LootTables.ArmorType.LeatherArmor ||
                         armorType == (int)LootTables.ArmorType.MiscClothing)
                {
                    return(ThreadSafeRandom.Next(0, 23));
                }
                else
                {
                    return(ThreadSafeRandom.Next(0, 40));
                }

            case 2:
                if (armorType == (int)LootTables.ArmorType.StuddedLeatherArmor ||
                    armorType == (int)LootTables.ArmorType.Helms ||
                    armorType == (int)LootTables.ArmorType.Shields)
                {
                    return(ThreadSafeRandom.Next(27, 54));
                }
                else if (armorType == (int)LootTables.ArmorType.LeatherArmor ||
                         armorType == (int)LootTables.ArmorType.MiscClothing)
                {
                    return(ThreadSafeRandom.Next(23, 46));
                }
                else
                {
                    return(ThreadSafeRandom.Next(40, 80));
                }

            case 3:
                if (armorType == (int)LootTables.ArmorType.StuddedLeatherArmor ||
                    armorType == (int)LootTables.ArmorType.Helms ||
                    armorType == (int)LootTables.ArmorType.Shields)
                {
                    return(ThreadSafeRandom.Next(54, 81));
                }
                else if (armorType == (int)LootTables.ArmorType.LeatherArmor ||
                         armorType == (int)LootTables.ArmorType.MiscClothing)
                {
                    return(ThreadSafeRandom.Next(46, 69));
                }
                else if (armorType == (int)LootTables.ArmorType.CovenantArmor)
                {
                    return(ThreadSafeRandom.Next(90, 130));
                }
                else
                {
                    return(ThreadSafeRandom.Next(80, 120));
                }

            case 4:
                if (armorType == (int)LootTables.ArmorType.StuddedLeatherArmor ||
                    armorType == (int)LootTables.ArmorType.Helms ||
                    armorType == (int)LootTables.ArmorType.Shields)
                {
                    return(ThreadSafeRandom.Next(81, 108));
                }
                else if (armorType == (int)LootTables.ArmorType.LeatherArmor ||
                         armorType == (int)LootTables.ArmorType.MiscClothing)
                {
                    return(ThreadSafeRandom.Next(69, 92));
                }
                else if (armorType == (int)LootTables.ArmorType.CovenantArmor)
                {
                    return(ThreadSafeRandom.Next(130, 170));
                }
                else
                {
                    return(ThreadSafeRandom.Next(120, 160));
                }

            case 5:
                if (armorType == (int)LootTables.ArmorType.StuddedLeatherArmor ||
                    armorType == (int)LootTables.ArmorType.Helms ||
                    armorType == (int)LootTables.ArmorType.Shields)
                {
                    return(ThreadSafeRandom.Next(108, 135));
                }
                else if (armorType == (int)LootTables.ArmorType.LeatherArmor ||
                         armorType == (int)LootTables.ArmorType.MiscClothing)
                {
                    return(ThreadSafeRandom.Next(92, 115));
                }
                else if (armorType == (int)LootTables.ArmorType.CovenantArmor)
                {
                    return(ThreadSafeRandom.Next(170, 210));
                }
                else
                {
                    return(ThreadSafeRandom.Next(160, 200));
                }

            case 6:
                if (armorType == (int)LootTables.ArmorType.StuddedLeatherArmor ||
                    armorType == (int)LootTables.ArmorType.Helms ||
                    armorType == (int)LootTables.ArmorType.Shields)
                {
                    return(ThreadSafeRandom.Next(135, 162));
                }
                else if (armorType == (int)LootTables.ArmorType.LeatherArmor ||
                         armorType == (int)LootTables.ArmorType.MiscClothing)
                {
                    return(ThreadSafeRandom.Next(115, 138));
                }
                else if (armorType == (int)LootTables.ArmorType.CovenantArmor)
                {
                    return(ThreadSafeRandom.Next(210, 250));
                }
                else
                {
                    return(ThreadSafeRandom.Next(200, 240));
                }

            case 7:
                if (armorType == (int)LootTables.ArmorType.StuddedLeatherArmor ||
                    armorType == (int)LootTables.ArmorType.Helms ||
                    armorType == (int)LootTables.ArmorType.Shields)
                {
                    return(ThreadSafeRandom.Next(162, 189));
                }
                else if (armorType == (int)LootTables.ArmorType.LeatherArmor ||
                         armorType == (int)LootTables.ArmorType.MiscClothing)
                {
                    return(ThreadSafeRandom.Next(138, 161));
                }
                else if (armorType == (int)LootTables.ArmorType.CovenantArmor)
                {
                    return(ThreadSafeRandom.Next(250, 290));
                }
                else
                {
                    return(ThreadSafeRandom.Next(240, 280));
                }

            case 8:
                if (armorType == (int)LootTables.ArmorType.StuddedLeatherArmor ||
                    armorType == (int)LootTables.ArmorType.Helms ||
                    armorType == (int)LootTables.ArmorType.Shields)
                {
                    return(ThreadSafeRandom.Next(189, 216));
                }
                else if (armorType == (int)LootTables.ArmorType.LeatherArmor ||
                         armorType == (int)LootTables.ArmorType.MiscClothing)
                {
                    return(ThreadSafeRandom.Next(161, 184));
                }
                else if (armorType == (int)LootTables.ArmorType.CovenantArmor)
                {
                    return(ThreadSafeRandom.Next(290, 330));
                }
                else
                {
                    return(ThreadSafeRandom.Next(280, 320));
                }

            default:
                return(0);
            }
        }
Example #10
0
        public static bool Init()
        {
            try
            {
                random = new ThreadSafeRandom();
                m_lock = new System.Threading.ReaderWriterLock();

                _maps = new Dictionary<int, MapPoint>();
                _mapInfos = new Dictionary<int, Map>();
                if (!LoadMap(_maps, _mapInfos))
                    return false;

                _serverMap = new Dictionary<int, List<int>>();
                if (!InitServerMap(_serverMap))
                    return false;
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                    log.Error("MapMgr", e);
                return false;
            }
            return true;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UniformOneGenerator"/> class.
 /// </summary>
 /// 
 /// <remarks>Initializes random numbers generator with zero seed.</remarks>
 /// 
 public UniformOneGenerator( )
 {
     rand = new ThreadSafeRandom( 0 );
 }
Example #12
0
        private static void RandomizeArtGallery()
        {
            var wideAssets = TFCBuilder.ListTextureAssets("Kasumi.ArtGallery.wide").Select(x => $"Kasumi.ArtGallery.wide.{x}").ToList();
            var tallAssets = TFCBuilder.ListTextureAssets("Kasumi.ArtGallery.tall").Select(x => $"Kasumi.ArtGallery.tall.{x}").ToList();

            wideAssets.Shuffle();
            tallAssets.Shuffle();

            var artyGallery = GetKasumiArtGallerySetup();

            foreach (var kagf in artyGallery)
            {
                var artGalleryF = MERFileSystem.GetPackageFile(kagf.PackageName);
                if (artGalleryF != null && File.Exists(artGalleryF))
                {
                    var artGalleryP = MEPackageHandler.OpenMEPackage(artGalleryF);

                    // Rename instances so they're memory unique so we have a few more paintings
                    if (kagf.RenameMemoryInstances)
                    {
                        if (kagf.TallTextureUIndexes != null)
                        {
                            foreach (var uindex in kagf.TallTextureUIndexes)
                            {
                                if (!artGalleryP.GetUExport(uindex).IsTexture())
                                {
                                    Debugger.Break();
                                }
                                artGalleryP.GetUExport(uindex).ObjectName = $"ME2R_T_KASUMIPAINTING{ThreadSafeRandom.Next(15000)}";
                            }
                        }

                        // Rename mats so they're also unique
                        if (kagf.WideTextureUIndexes != null)
                        {
                            foreach (var uindex in kagf.WideTextureUIndexes)
                            {
                                if (!artGalleryP.GetUExport(uindex).IsTexture())
                                {
                                    Debugger.Break();
                                }
                                artGalleryP.GetUExport(uindex).ObjectName = $"ME2R_W_KASUMIPAINTING{ThreadSafeRandom.Next(15000)}";
                            }
                        }

                        if (kagf.MaterialUIndexes != null)
                        {
                            foreach (var uindex in kagf.MaterialUIndexes)
                            {
                                var exp = artGalleryP.GetUExport(uindex);
                                if (!exp.ClassName.Contains("Material"))
                                {
                                    Debugger.Break();
                                }
                                artGalleryP.GetUExport(uindex).ObjectName = $"ME2R_PAINTMAT_KASUMI{ThreadSafeRandom.Next(15000)}";
                            }
                        }
                    }

                    InstallARArtTextures(kagf.WideTextureUIndexes, wideAssets, artGalleryP, "Wide");
                    InstallARArtTextures(kagf.TallTextureUIndexes, tallAssets, artGalleryP, "Tall");

                    MERFileSystem.SavePackage(artGalleryP);
                }
            }
        }
Example #13
0
        public uint CalculateManaUsage(Creature caster, Spell spell, WorldObject target = null)
        {
            var baseCost = spell.BaseMana;

            // for casting spells built into a casting implement, use the ItemManaCost
            var castItem = caster.GetEquippedWand();

            if (castItem != null && (castItem.SpellDID ?? 0) == spell.Id)
            {
                baseCost = (uint)(castItem.ItemManaCost ?? 0);
            }

            uint mana_conversion_skill = (uint)Math.Round(caster.GetCreatureSkill(Skill.ManaConversion).Current *GetWeaponManaConversionModifier(caster));

            uint difficulty = spell.PowerMod;   // modified power difficulty

            double baseManaPercent = 1.0;

            if (mana_conversion_skill > difficulty)
            {
                baseManaPercent = (double)difficulty / mana_conversion_skill;
            }

            uint preCost = 0;

            if ((spell.School == MagicSchool.ItemEnchantment) && (spell.MetaSpellType == SpellType.Enchantment) &&
                (spell.Category >= SpellCategory.ArmorValueRaising) && (spell.Category <= SpellCategory.AcidicResistanceLowering) && target is Player targetPlayer)
            {
                int numTargetItems = 1;
                if (targetPlayer != null)
                {
                    numTargetItems = targetPlayer.EquippedObjects.Values.Count(i => (i is Clothing || i.IsShield) && i.IsEnchantable);
                }

                preCost = (uint)Math.Round((baseCost + (spell.ManaMod * numTargetItems)) * baseManaPercent);
            }
            else if ((spell.Flags & SpellFlags.FellowshipSpell) != 0)
            {
                int numFellows = 1;
                var player     = this as Player;
                if (player != null && player.Fellowship != null)
                {
                    numFellows = player.Fellowship.FellowshipMembers.Count;
                }

                preCost = (uint)Math.Round((baseCost + (spell.ManaMod * numFellows)) * baseManaPercent);
            }
            else
            {
                preCost = (uint)Math.Round(baseCost * baseManaPercent);
            }

            if (preCost < 1)
            {
                preCost = 1;
            }

            uint manaUsed = ThreadSafeRandom.Next(1, preCost);

            return(manaUsed);
        }
Example #14
0
        private float DoCalculateDamage(Creature attacker, Creature defender, WorldObject damageSource)
        {
            var playerAttacker = attacker as Player;
            var playerDefender = defender as Player;

            Attacker = attacker;
            Defender = defender;

            CombatType = damageSource.ProjectileSource == null?attacker.GetCombatType() : CombatType.Missile;

            DamageSource = damageSource;

            Weapon = damageSource.ProjectileSource == null?attacker.GetEquippedWeapon() : damageSource.ProjectileLauncher;

            AttackType   = attacker.AttackType;
            AttackHeight = attacker.AttackHeight ?? AttackHeight.Medium;

            // check lifestone protection
            if (playerDefender != null && playerDefender.UnderLifestoneProtection)
            {
                LifestoneProtection = true;
                playerDefender.HandleLifestoneProtection();
                return(0.0f);
            }

            if (defender.Invincible)
            {
                return(0.0f);
            }

            // overpower
            if (attacker.Overpower != null)
            {
                Overpower = Creature.GetOverpower(attacker, defender);
            }

            // evasion chance
            if (!Overpower)
            {
                EvasionChance = GetEvadeChance(attacker, defender);
                if (EvasionChance > ThreadSafeRandom.Next(0.0f, 1.0f))
                {
                    Evaded = true;
                    return(0.0f);
                }
            }

            // get base damage
            if (playerAttacker != null)
            {
                GetBaseDamage(playerAttacker);
            }
            else
            {
                GetBaseDamage(attacker, AttackMotion ?? MotionCommand.Invalid);
            }

            if (DamageType == DamageType.Undef && !AllowDamageTypeUndef.Contains(damageSource.WeenieClassId))
            {
                log.Error($"DamageEvent.DoCalculateDamage({attacker?.Name} ({attacker?.Guid}), {defender?.Name} ({defender?.Guid}), {damageSource?.Name} ({damageSource?.Guid})) - DamageType == DamageType.Undef");
                GeneralFailure = true;
            }

            if (GeneralFailure)
            {
                return(0.0f);
            }

            // get damage modifiers
            PowerMod     = attacker.GetPowerMod(Weapon);
            AttributeMod = attacker.GetAttributeMod(Weapon);
            SlayerMod    = WorldObject.GetWeaponCreatureSlayerModifier(attacker, defender);

            // ratings
            DamageRatingBaseMod = Creature.GetPositiveRatingMod(attacker.GetDamageRating());
            RecklessnessMod     = Creature.GetRecklessnessMod(attacker, defender);
            SneakAttackMod      = attacker.GetSneakAttackMod(defender);
            HeritageMod         = attacker.GetHeritageBonus(Weapon) ? 1.05f : 1.0f;

            DamageRatingMod = Creature.AdditiveCombine(DamageRatingBaseMod, RecklessnessMod, SneakAttackMod, HeritageMod);

            // damage before mitigation
            DamageBeforeMitigation = BaseDamage * AttributeMod * PowerMod * SlayerMod * DamageRatingMod;

            // critical hit?
            var attackSkill = attacker.GetCreatureSkill(attacker.GetCurrentWeaponSkill());

            CriticalChance = WorldObject.GetWeaponCriticalChance(attacker, attackSkill, defender);
            if (CriticalChance > ThreadSafeRandom.Next(0.0f, 1.0f))
            {
                if (playerDefender != null && playerDefender.AugmentationCriticalDefense > 0)
                {
                    var criticalDefenseMod    = playerAttacker != null ? 0.05f : 0.25f;
                    var criticalDefenseChance = playerDefender.AugmentationCriticalDefense * criticalDefenseMod;

                    if (criticalDefenseChance > ThreadSafeRandom.Next(0.0f, 1.0f))
                    {
                        CriticalDefended = true;
                    }
                }

                if (!CriticalDefended)
                {
                    IsCritical = true;

                    CriticalDamageMod = 1.0f + WorldObject.GetWeaponCritDamageMod(attacker, attackSkill, defender);

                    // recklessness excluded from crits
                    RecklessnessMod        = 1.0f;
                    DamageRatingMod        = Creature.AdditiveCombine(DamageRatingBaseMod, SneakAttackMod, HeritageMod);
                    DamageBeforeMitigation = BaseDamageMod.MaxDamage * AttributeMod * PowerMod * SlayerMod * DamageRatingMod * CriticalDamageMod;
                }
            }

            // armor rending and cleaving
            var armorRendingMod = 1.0f;

            if (Weapon != null && Weapon.HasImbuedEffect(ImbuedEffectType.ArmorRending))
            {
                armorRendingMod = WorldObject.GetArmorRendingMod(attackSkill);
            }

            var armorCleavingMod = attacker.GetArmorCleavingMod(Weapon);

            var ignoreArmorMod = Math.Min(armorRendingMod, armorCleavingMod);

            // get body part / armor pieces / armor modifier
            if (playerDefender != null)
            {
                // select random body part @ current attack height
                GetBodyPart(AttackHeight);

                // get player armor pieces
                Armor = attacker.GetArmorLayers(playerDefender, BodyPart);

                // get armor modifiers
                ArmorMod = attacker.GetArmorMod(DamageType, Armor, Weapon, ignoreArmorMod);
            }
            else
            {
                // determine height quadrant
                Quadrant = GetQuadrant(Defender, Attacker, AttackHeight, DamageSource);

                // select random body part @ current attack height
                GetBodyPart(Defender, Quadrant);
                if (Evaded)
                {
                    return(0.0f);
                }

                Armor = CreaturePart.GetArmorLayers(PropertiesBodyPart.Key);

                // get target armor
                ArmorMod = CreaturePart.GetArmorMod(DamageType, Armor, Attacker, Weapon, ignoreArmorMod);
            }

            if (Weapon != null && Weapon.HasImbuedEffect(ImbuedEffectType.IgnoreAllArmor))
            {
                ArmorMod = 1.0f;
            }

            // get resistance modifiers
            WeaponResistanceMod = WorldObject.GetWeaponResistanceModifier(attacker, attackSkill, DamageType);

            if (playerDefender != null)
            {
                ResistanceMod = playerDefender.GetResistanceMod(DamageType, Attacker, Weapon, WeaponResistanceMod);
            }
            else
            {
                var resistanceType = Creature.GetResistanceType(DamageType);
                ResistanceMod = (float)Math.Max(0.0f, defender.GetResistanceMod(resistanceType, Attacker, Weapon, WeaponResistanceMod));
            }

            // damage resistance rating
            DamageResistanceRatingMod = Creature.GetNegativeRatingMod(defender.GetDamageResistRating(CombatType));

            // get shield modifier
            ShieldMod = defender.GetShieldMod(attacker, DamageType, Weapon);

            // calculate final output damage
            Damage          = DamageBeforeMitigation * ArmorMod * ShieldMod * ResistanceMod * DamageResistanceRatingMod;
            DamageMitigated = DamageBeforeMitigation - Damage;

            return(Damage);
        }
Example #15
0
        public Spectrum Li(Ray r, Scene s)
        {
            /* BASIC Implement
            repeat
                r <- random ray from camera
                L <- 0, β <- 1, nbounces <- 0
                repeat
                   isect <- intersect r with scene
                   if isect == null // no hit
                      break
                   wo <- -r
                   if isect == light // light hit
                      L<- β*Le(wo) // add light emitted
                      break
                   wi <- random ray from isect
                   (f,pr) <- bsdf(isect,wi,wo)
                   β <- β*f*|cosθ|/pr
                   r <- wi
                   nbounces <- nbounces+1
                AddSampleToImage(L,r)
            */


            /* Russian Roulette Implement

            (f,pr) <- bsdf(isect,wi,wo)
            β <- β*f*|cosθ|/pr
            r <- wi
            if nbounces>3
            q <- 1 - max(β)
            if random() < q
            break
            β <- β/(1-q)

             */
            var L = Spectrum.ZeroSpectrum;
            var beta = Spectrum.Create((double)1);
            int nbounces = 0;
            double q;

            while(nbounces < 20) {
                (double? mint, SurfaceInteraction si) = s.Intersect(r);

                // If nothing hit end
                if (si == null) {
                    break;
                }

                // If Light hit include it and finish
                if (si.Obj is Light) {
                    if (nbounces == 0)
                    {
                        L = beta * si.Le(si.Wo);
                        //Console.WriteLine(beta.c);
                        //Console.WriteLine(L.c);
                    }
                    break;
                }

                // Sample light from SurfaceInteraction
                // TODO
                Spectrum Ld = Light.UniformSampleOneLight(si, s);

                L = L.AddTo(beta * Ld);
                
                // Make new reflected Ray
                //Ray wi = si.SpawnRay(UniformSampleSphere());
                
                // Get BSDF of hit object
                (Spectrum f, Vector3 wi, double pr, bool p) = (si.Obj as Shape).BSDF.Sample_f(si.Wo, si);

                // Update beta
                beta = beta * f * Utils.AbsCosTheta(wi) / pr;
                // Set reflected Ray as original Ray
                r = new Ray(si.Point, wi);

                if (nbounces > 3) {
                    q = 1 - beta.Max();
                    if (ThreadSafeRandom.NextDouble() < q) {
                        break;
                    }
                    beta /= (1 - q);
                }

                nbounces += 1;
            }
            Console.WriteLine(L.c);
            return L;
        }
        private async Task PutFileAcrossDrivesAsync(
            FileRealizationMode allowedFileRealizationMode,
            bool contentAlreadyCached,
            bool contentShouldBeCached,
            Func <PutResult, bool> checkResult)
        {
            // This only works when we have multiple drives.
            if (FileSystem is not MemoryFileSystem)
            {
                return;
            }

            using (var testDirectory = new DisposableDirectory(FileSystem))
            {
                var context = new Context(Logger);

                try
                {
                    using (var store = Create(testDirectory.Path, Clock))
                    {
                        await store.StartupAsync(context).ShouldBeSuccess();

                        byte[]      bytes       = ThreadSafeRandom.GetBytes(ValueSize);
                        ContentHash contentHash = bytes.CalculateHash(ContentHashType);

                        // Verify content doesn't exist yet in store
                        Assert.False(await store.ContainsAsync(context, contentHash, null));

                        var pathToContentDifferentVolume = new AbsolutePath(PathGeneratorUtilities.GetAbsolutePath("D", "foo.txt"));

                        try
                        {
                            FileSystem.WriteAllBytes(pathToContentDifferentVolume, bytes);
                            if (contentAlreadyCached)
                            {
                                await store.PutFileAsync(
                                    context, pathToContentDifferentVolume, FileRealizationMode.Copy, ContentHashType, null).ShouldBeSuccess();
                            }

                            var result = await store.PutFileAsync(
                                context, pathToContentDifferentVolume, allowedFileRealizationMode, ContentHashType, null);

                            Assert.True(checkResult(result));

                            (await store.ContainsAsync(context, contentHash, null)).Should()
                            .Be(contentShouldBeCached);
                        }
                        finally
                        {
                            FileSystem.DeleteFile(pathToContentDifferentVolume);
                        }

                        await store.ShutdownAsync(context).ShouldBeSuccess();
                    }
                }
                finally
                {
                    FileSystem.DeleteDirectory(testDirectory.Path, DeleteOptions.All);
                }
            }
        }
Example #17
0
        /// <summary>
        /// Performs a melee attack for the monster
        /// </summary>
        /// <returns>The length in seconds for the attack animation</returns>
        public float MeleeAttack()
        {
            var target       = AttackTarget as Creature;
            var targetPlayer = AttackTarget as Player;
            var targetPet    = AttackTarget as CombatPet;
            var combatPet    = this as CombatPet;

            if (target == null || !target.IsAlive)
            {
                FindNextTarget();
                return(0.0f);
            }

            if (CurrentMotionState.Stance == MotionStance.NonCombat)
            {
                DoAttackStance();
            }

            // choose a random combat maneuver
            var maneuver = GetCombatManeuver();

            if (maneuver == null)
            {
                Console.WriteLine($"Combat maneuver null! Stance {CurrentMotionState.Stance}, MotionTable {MotionTableId:X8}");
                return(0.0f);
            }

            AttackHeight = maneuver.AttackHeight;

            DoSwingMotion(AttackTarget, maneuver, out float animLength, out var attackFrames);
            PhysicsObj.stick_to_object(AttackTarget.PhysicsObj.ID);

            var numStrikes = attackFrames.Count;

            var actionChain = new ActionChain();

            var prevTime = 0.0f;

            for (var i = 0; i < numStrikes; i++)
            {
                actionChain.AddDelaySeconds(attackFrames[i] * animLength - prevTime);
                prevTime = attackFrames[i] * animLength;

                actionChain.AddAction(this, () =>
                {
                    if (AttackTarget == null || IsDead)
                    {
                        return;
                    }

                    if (WeenieType == WeenieType.GamePiece)
                    {
                        target.TakeDamage(this, DamageType.Slash, target.Health.Current);
                        (this as GamePiece).OnDealtDamage();
                        return;
                    }

                    var weapon      = GetEquippedWeapon();
                    var damageEvent = DamageEvent.CalculateDamage(this, target, weapon, maneuver);

                    //var damage = CalculateDamage(ref damageType, maneuver, bodyPart, ref critical, ref shieldMod);

                    if (damageEvent.HasDamage)
                    {
                        if (combatPet != null || targetPet != null)
                        {
                            // combat pet inflicting or receiving damage
                            //Console.WriteLine($"{target.Name} taking {Math.Round(damage)} {damageType} damage from {Name}");
                            target.TakeDamage(this, damageEvent.DamageType, damageEvent.Damage);
                            EmitSplatter(target, damageEvent.Damage);
                        }
                        else if (targetPlayer != null)
                        {
                            // this is a player taking damage
                            targetPlayer.TakeDamage(this, damageEvent);

                            if (damageEvent.ShieldMod != 1.0f)
                            {
                                var shieldSkill = targetPlayer.GetCreatureSkill(Skill.Shield);
                                Proficiency.OnSuccessUse(targetPlayer, shieldSkill, shieldSkill.Current); // ?
                            }
                        }
                    }
                    else
                    {
                        target.OnEvade(this, CombatType.Melee);
                    }

                    if (combatPet != null)
                    {
                        combatPet.PetOnAttackMonster(target);
                    }
                });
            }
            actionChain.EnqueueChain();

            // TODO: figure out exact speed / delay formula
            var meleeDelay = ThreadSafeRandom.Next(MeleeDelayMin, MeleeDelayMax);

            NextAttackTime = Timers.RunningTime + animLength + meleeDelay;
            return(animLength);
        }
Example #18
0
        private async Task Run()
        {
            ClusterMembershipSnapshot activeMembersSnapshot = default;

            SiloAddress[] otherNodes    = default;
            TimeSpan?     overrideDelay = ThreadSafeRandom.NextTimeSpan(_clusterMembershipOptions.CurrentValue.ProbeTimeout);

            while (await _pingTimer.NextTick(overrideDelay))
            {
                ProbeResult probeResult;
                overrideDelay = default;

                try
                {
                    // Discover the other active nodes in the cluster, if there are any.
                    var membershipSnapshot = _membershipService.CurrentSnapshot;
                    if (otherNodes is null || !object.ReferenceEquals(activeMembersSnapshot, membershipSnapshot))
                    {
                        activeMembersSnapshot = membershipSnapshot;
                        otherNodes            = membershipSnapshot.Members.Values
                                                .Where(v => v.Status == SiloStatus.Active && v.SiloAddress != this.SiloAddress && v.SiloAddress != _localSiloDetails.SiloAddress)
                                                .Select(s => s.SiloAddress)
                                                .ToArray();
                    }

                    var isDirectProbe = !_clusterMembershipOptions.CurrentValue.EnableIndirectProbes || _failedProbes < _clusterMembershipOptions.CurrentValue.NumMissedProbesLimit - 1 || otherNodes.Length == 0;
                    var timeout       = GetTimeout(isDirectProbe);
                    var cancellation  = new CancellationTokenSource(timeout);

                    if (isDirectProbe)
                    {
                        // Probe the silo directly.
                        probeResult = await this.ProbeDirectly(cancellation.Token).ConfigureAwait(false);
                    }
                    else
                    {
                        // Pick a random other node and probe the target indirectly, using the selected node as an intermediary.
                        var intermediary = otherNodes[ThreadSafeRandom.Next(otherNodes.Length)];

                        // Select a timeout which will allow the intermediary node to attempt to probe the target node and still respond to this node
                        // if the remote node does not respond in time.
                        // Attempt to account for local health degradation by extending the timeout period.
                        probeResult = await this.ProbeIndirectly(intermediary, timeout, cancellation.Token).ConfigureAwait(false);

                        // If the intermediary is not entirely healthy, remove it from consideration and continue to probe.
                        // Note that all recused silos will be included in the consideration set the next time cluster membership changes.
                        if (probeResult.Status != ProbeResultStatus.Succeeded && probeResult.IntermediaryHealthDegradationScore > 0)
                        {
                            _log.LogInformation("Recusing unhealthy intermediary {Intermediary} and trying again with remaining nodes", intermediary);
                            otherNodes    = otherNodes.Where(node => !node.Equals(intermediary)).ToArray();
                            overrideDelay = TimeSpan.FromMilliseconds(250);
                        }
                    }

                    if (!_stoppingCancellation.IsCancellationRequested)
                    {
                        await _onProbeResult(this, probeResult).ConfigureAwait(false);
                    }
                }
                catch (Exception exception)
                {
                    _log.LogError(exception, "Exception monitoring silo {SiloAddress}", SiloAddress);
                }
            }

            TimeSpan GetTimeout(bool isDirectProbe)
            {
                var additionalTimeout = 0;

                if (_clusterMembershipOptions.CurrentValue.ExtendProbeTimeoutDuringDegradation)
                {
                    // Attempt to account for local health degradation by extending the timeout period.
                    var localDegradationScore = _localSiloHealthMonitor.GetLocalHealthDegradationScore(DateTime.UtcNow);
                    additionalTimeout += localDegradationScore;
                }

                if (!isDirectProbe)
                {
                    // Indirect probes need extra time to account for the additional hop.
                    additionalTimeout += 1;
                }

                return(_clusterMembershipOptions.CurrentValue.ProbeTimeout.Multiply(1 + additionalTimeout));
            }
        }
Example #19
0
        public async Task ActivationSched_Turn_Execution_Order_Loop()
        {
            TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;

            const int NumChains   = 100;
            const int ChainLength = 3;
            // Can we add a unit test that basicaly checks that any turn is indeed run till completion before any other turn?
            // For example, you have a long running main turn and in the middle it spawns a lot of short CWs (on Done promise) and StartNew.
            // You test that no CW/StartNew runs until the main turn is fully done. And run in stress.

            var resultHandles = new TaskCompletionSource <bool> [NumChains];

            Task[] taskChains      = new Task[NumChains];
            Task[] taskChainEnds   = new Task[NumChains];
            bool[] executingChain  = new bool[NumChains];
            int[]  stageComplete   = new int[NumChains];
            int    executingGlobal = -1;

            for (int i = 0; i < NumChains; i++)
            {
                int chainNum  = i; // Capture
                int sleepTime = ThreadSafeRandom.Next(100);
                resultHandles[i] = new TaskCompletionSource <bool>();
                taskChains[i]    = new Task(() =>
                {
                    const int taskNum = 0;
                    try
                    {
                        Assert.Equal(-1, executingGlobal);  // "Detected unexpected other execution in chain " + chainNum + " Task " + taskNum
                        Assert.False(executingChain[chainNum], "Detected unexpected other execution on chain " + chainNum + " Task " + taskNum);

                        executingGlobal          = chainNum;
                        executingChain[chainNum] = true;

                        Thread.Sleep(sleepTime);
                    }
                    finally
                    {
                        stageComplete[chainNum]  = taskNum;
                        executingChain[chainNum] = false;
                        executingGlobal          = -1;
                    }
                });
                Task task = taskChains[i];
                for (int j = 1; j < ChainLength; j++)
                {
                    int taskNum = j; // Capture
                    task = task.ContinueWith(t =>
                    {
                        if (t.IsFaulted)
                        {
                            throw t.Exception;
                        }
                        this.output.WriteLine("Inside Chain {0} Task {1}", chainNum, taskNum);
                        try
                        {
                            Assert.Equal(-1, executingGlobal);                  // "Detected unexpected other execution in chain " + chainNum + " Task " + taskNum
                            Assert.False(executingChain[chainNum], "Detected unexpected other execution on chain " + chainNum + " Task " + taskNum);
                            Assert.Equal(taskNum - 1, stageComplete[chainNum]); // "Detected unexpected execution stage on chain " + chainNum + " Task " + taskNum

                            executingGlobal          = chainNum;
                            executingChain[chainNum] = true;

                            Thread.Sleep(sleepTime);
                        }
                        finally
                        {
                            stageComplete[chainNum]  = taskNum;
                            executingChain[chainNum] = false;
                            executingGlobal          = -1;
                        }
                    }, scheduler);
                }
                taskChainEnds[chainNum] = task.ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        throw t.Exception;
                    }
                    this.output.WriteLine("Inside Chain {0} Final Task", chainNum);
                    resultHandles[chainNum].SetResult(true);
                }, scheduler);
            }

            for (int i = 0; i < NumChains; i++)
            {
                taskChains[i].Start(scheduler);
            }

            for (int i = 0; i < NumChains; i++)
            {
                TimeSpan waitCheckTime = TimeSpan.FromMilliseconds(150 * ChainLength * NumChains * WaitFactor);

                try
                {
                    await resultHandles[i].Task.WithTimeout(waitCheckTime);
                }
                catch (TimeoutException)
                {
                    Assert.True(false, "Result did not arrive before timeout " + waitCheckTime);
                }

                bool ok = resultHandles[i].Task.Result;

                try
                {
                    // since resultHandle being complete doesn't directly imply that the final chain was completed (there's a chance for a race condition), give a small chance for it to complete.
                    await taskChainEnds[i].WithTimeout(TimeSpan.FromMilliseconds(10));
                }
                catch (TimeoutException)
                {
                    Assert.True(false, $"Task chain end {i} should complete very shortly after after its resultHandle");
                }

                Assert.True(taskChainEnds[i].IsCompleted, "Task chain " + i + " should be completed");
                Assert.False(taskChainEnds[i].IsFaulted, "Task chain " + i + " should not be Faulted: " + taskChainEnds[i].Exception);
                Assert.Equal(ChainLength - 1, stageComplete[i]);  // "Task chain " + i + " should have completed all stages"
                Assert.True(ok, "Successfully waited for ResultHandle for Task chain " + i);
            }
        }
Example #20
0
        public async Task ActivationSched_WhenAny_Busy_Timeout()
        {
            TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;

            var        pause1  = new TaskCompletionSource <bool>();
            var        pause2  = new TaskCompletionSource <bool>();
            var        finish  = new TaskCompletionSource <bool>();
            Task <int> task1   = null;
            Task <int> task2   = null;
            Task       join    = null;
            Task       wrapper = new Task(() =>
            {
                task1 = Task <int> .Factory.StartNew(() =>
                {
                    this.output.WriteLine("Task-1 Started");
                    Assert.Equal(scheduler, TaskScheduler.Current);
                    int num1 = 1;
                    while (!pause1.Task.Result) // Infinite busy loop
                    {
                        num1 = ThreadSafeRandom.Next();
                    }
                    this.output.WriteLine("Task-1 Done");
                    return(num1);
                });
                task2 = Task <int> .Factory.StartNew(() =>
                {
                    this.output.WriteLine("Task-2 Started");
                    Assert.Equal(scheduler, TaskScheduler.Current);
                    int num2 = 2;
                    while (!pause2.Task.Result) // Infinite busy loop
                    {
                        num2 = ThreadSafeRandom.Next();
                    }
                    this.output.WriteLine("Task-2 Done");
                    return(num2);
                });

                join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2)));

                finish.SetResult(true);
            });

            wrapper.Start(scheduler);

            var timeoutLimit = TimeSpan.FromSeconds(1);

            try
            {
                await finish.Task.WithTimeout(timeoutLimit);
            }
            catch (TimeoutException)
            {
                Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
            }

            Assert.NotNull(join); // Joined promise assigned
            await join;

            Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status);
            Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception);
            Assert.False(task1.IsCompleted, "Task-1 Status " + task1.Status);
            Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception);
            Assert.False(task2.IsCompleted, "Task-2 Status " + task2.Status);
        }
Example #21
0
        private static IReadOnlyCollection <Parameter> BuildParametersWithAllCombinationsOfFlags(
            Type valueType       = null,
            bool valueCanBeNull  = true,
            bool valueMustBeNull = false)
        {
            if (valueType == null)
            {
                valueType = typeof(object);
            }

            var flags  = new[] { true, false };
            var result = new List <Parameter>();

            foreach (var nameFlag in flags)
            {
                foreach (var mustFlag in flags)
                {
                    foreach (var eachFlag in flags)
                    {
                        foreach (var validatedFlag in flags)
                        {
                            var parameter = new Parameter
                            {
                                Value            = valueMustBeNull ? null : valueCanBeNull ? (ThreadSafeRandom.Next(0, 2) == 0 ? AD.ummy(valueType) : null) : AD.ummy(valueType),
                                ValueType        = valueType,
                                Name             = ThreadSafeRandom.Next(0, 2) == 0 ? A.Dummy <string>() : null,
                                HasBeenNamed     = nameFlag,
                                HasBeenMusted    = mustFlag,
                                HasBeenEached    = eachFlag,
                                HasBeenValidated = validatedFlag,
                            };

                            result.Add(parameter);
                        }
                    }
                }
            }

            return(result);
        }
Example #22
0
 public static bool CanChangeStyle(BaseRoom game, GSPacketIn pkg)
 {
     FightRateInfo[] allFightRateInfo = FightRateMgr.GetAllFightRateInfo();
     try
     {
         FightRateInfo[] array = allFightRateInfo;
         for (int i = 0; i < array.Length; i++)
         {
             FightRateInfo fightRateInfo = array[i];
             if (fightRateInfo.BeginDay.Year <= DateTime.Now.Year && DateTime.Now.Year <= fightRateInfo.EndDay.Year && fightRateInfo.BeginDay.DayOfYear <= DateTime.Now.DayOfYear && DateTime.Now.DayOfYear <= fightRateInfo.EndDay.DayOfYear && fightRateInfo.BeginTime.TimeOfDay <= DateTime.Now.TimeOfDay && DateTime.Now.TimeOfDay <= fightRateInfo.EndTime.TimeOfDay && ThreadSafeRandom.NextStatic(1000000) < fightRateInfo.Rate)
             {
                 return(true);
             }
         }
     }
     catch
     {
     }
     pkg.WriteBoolean(false);
     return(false);
 }
Example #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExceptionDescriptor"/> class.
 /// </summary>
 public ExceptionDescriptor()
 {
     Id = ThreadSafeRandom.GenerateHexNumber(ExceptionDescriptor.ExceptionDescriptorIdLength);
 }
Example #24
0
 public static Ability Thunder(Element damageElement)
 {
     return(new Ability
     {
         Name = "Thunder",
         Description = string.Empty,
         Cooldown = 6,
         Type = Ability.Types.AbilityType.Offensive,
         ModelMetadata = new ModelMetadata
         {
             ConstructorName = "mc_ab_all_3040078000_03",
             JsAssetPath = "npc/60d4c46a-f1bd-4d11-b39b-e18835d5e21d/abilities/2/ab_all_3040078000_03.js",
             ImageAssets =
             {
                 new ImageAsset
                 {
                     Name = "ab_all_3040078000_03",
                     Path = "npc/60d4c46a-f1bd-4d11-b39b-e18835d5e21d/abilities/2/ab_all_3040078000_03.png",
                 },
             },
         },
         AnimationName = "ab_motion",
         Effects =
         {
             new AbilityEffect
             {
                 Type = AbilityEffect.Types.AbilityEffectType.MultihitDamage,
                 ExtraData = new MultihitDamage
                 {
                     Element = damageElement,
                     HitNumber = 1,
                     HitAllTargets = true,
                     DamageModifier = 2,
                     DamageCap = 470000,
                 }.ToByteString(),
             },
         },
         ProcessEffects = (zooey, target, raidActions) =>
         {
             var random = ThreadSafeRandom.NextDouble();
             foreach (var enemy in zooey.Raid.Enemies)
             {
                 if (enemy.IsAlive() && enemy.PositionInFrontline < 4)
                 {
                     enemy.ApplyStatusEffect(
                         new StatusEffectSnapshot
                     {
                         Id = random <= 1.0 / 3
                                 ? StatusEffectLibrary.StackableDefenseDownNpc
                                 : (random <= 2.0 / 3
                                     ? StatusEffectLibrary.StackableAttackDownNpc
                                     : StatusEffectLibrary.StackableDebuffResistanceDownNpc),
                         Strength = -10,
                         IsStackable = true,
                         StackingCap = random <= 1.0 / 3 ? -25 : -30,
                         BaseAccuracy = 100,
                         RemainingDurationInSeconds = 180,
                     },
                         raidActions);
                 }
             }
         },
     });
 }
        public DatabaseDummyFactory()
        {
            // ------------------------------- EVENTS -------------------------------------
            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new HandlingForStreamDisabledEvent(
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new HandlingForStreamEnabledEvent(
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new HandlingForRecordDisabledEvent(
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var record = A.Dummy <StreamRecord>();

                return(new RecordHandlingAvailableEvent(
                           record.InternalRecordId,
                           A.Dummy <string>(),
                           record,
                           A.Dummy <UtcDateTime>(),
                           A.Dummy <string>()));
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new RecordHandlingCanceledEvent(
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new RecordHandlingCompletedEvent(
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new RecordHandlingFailedEvent(
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new RecordHandlingFailureResetEvent(
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new RecordHandlingRunningEvent(
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new RecordHandlingSelfCanceledEvent(
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new PruneOperationExecutedEvent(
                    A.Dummy <IPruneOp>(),
                    A.Dummy <PruneSummary>(),
                    A.Dummy <UtcDateTime>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new PruneOperationRequestedEvent(
                    A.Dummy <IPruneOp>(),
                    A.Dummy <UtcDateTime>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new PruneRequestCanceledEvent(
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new UniqueLongIssuedEvent(
                    A.Dummy <long>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var result = new IdDeprecatedEvent(
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>());

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new IdDeprecatedEvent <Version, Version>(
                    A.Dummy <Version>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new IdDeprecatedEvent <Version>(
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            // ------------------------------- MODELS -------------------------------------
            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new StreamRecordHandlingEntry(
                    A.Dummy <long>(),
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <HandlingStatus>(),
                    A.Dummy <IReadOnlyCollection <NamedValue <string> > >(),
                    A.Dummy <string>(),
                    A.Dummy <UtcDateTime>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var scenario = ThreadSafeRandom.Next(1, 4);

                switch (scenario)
                {
                case 1:
                    return(new CreateStreamResult(false, true));

                case 2:
                    return(new CreateStreamResult(true, false));

                case 3:
                    return(new CreateStreamResult(true, true));

                default:
                    throw new NotSupportedException(
                        FormattableString.Invariant($"Invalid scenario {scenario} for creating a dummy {nameof(CreateStreamResult)}."));
                }
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new StreamRecordMetadata(
                    A.Dummy <string>(),
                    A.Dummy <SerializerRepresentation>(),
                    A.Dummy <TypeRepresentationWithAndWithoutVersion>(),
                    A.Dummy <TypeRepresentationWithAndWithoutVersion>(),
                    A.Dummy <IReadOnlyCollection <NamedValue <string> > >(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <UtcDateTime>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new StreamRecordMetadata <Version>(
                    A.Dummy <Version>(),
                    A.Dummy <SerializerRepresentation>(),
                    A.Dummy <TypeRepresentationWithAndWithoutVersion>(),
                    A.Dummy <TypeRepresentationWithAndWithoutVersion>(),
                    A.Dummy <IReadOnlyCollection <NamedValue <string> > >(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <UtcDateTime>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new GetStreamFromRepresentationOp <FileStreamRepresentation, MemoryStandardStream>(
                    A.Dummy <FileStreamRepresentation>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var scenario = ThreadSafeRandom.Next(1, 5);

                switch (scenario)
                {
                case 1:
                    return(new PutRecordResult(A.Dummy <long>(), null));

                case 2:
                    return(new PutRecordResult(null, Some.ReadOnlyDummies <long>().ToList()));

                case 3:
                    return(new PutRecordResult(null, Some.ReadOnlyDummies <long>().ToList(), Some.ReadOnlyDummies <long>().ToList()));

                case 4:
                    return(new PutRecordResult(A.Dummy <long>(), Some.ReadOnlyDummies <long>().ToList(), Some.ReadOnlyDummies <long>().ToList()));

                default:
                    throw new NotSupportedException(FormattableString.Invariant($"Invalid scenario {scenario} for creating a dummy {nameof(PutRecordResult)}."));
                }
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var scenario = ThreadSafeRandom.Next(1, 4);

                switch (scenario)
                {
                case 1:
                    return(new TryHandleRecordResult(null, false));

                case 2:
                    return(new TryHandleRecordResult(A.Dummy <StreamRecord>(), false));

                case 3:
                    return(new TryHandleRecordResult(null, true));

                default:
                    throw new NotSupportedException(FormattableString.Invariant($"Invalid scenario {scenario} for creating a dummy {nameof(TryHandleRecordResult)}."));
                }
            });

            // ------------------------------- ENUMS --------------------------------------
            AutoFixtureBackedDummyFactory.ConstrainDummyToBeOneOf(VersionMatchStrategy.Any, VersionMatchStrategy.SpecifiedVersion);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(CompositeHandlingStatus.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(ExistingDatabaseStrategy.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(ExistingRecordStrategy.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(ExistingStreamStrategy.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(HandlingStatus.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(OrderRecordsBy.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(RecordNotFoundStrategy.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(StreamNotFoundStrategy.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(StreamRecordItemsToInclude.Unknown);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(TagMatchStrategy.Unknown);

            // ------------------------------- MODEL INTERFACES --------------------------------------
            AutoFixtureBackedDummyFactory.UseRandomInterfaceImplementationForDummy <IResourceLocator>();
            AutoFixtureBackedDummyFactory.UseRandomInterfaceImplementationForDummy <IStreamRepresentation>();

            // ------------------------------- OPERATIONS -------------------------------------
            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new PruneBeforeInternalRecordDateOp(
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new StandardPruneStreamOp(
                    A.Dummy <long>(),
                    A.Dummy <UtcDateTime>(),
                    A.Dummy <string>(),
                    A.Dummy <IResourceLocator>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new StandardUpdateHandlingStatusForRecordOp(
                    A.Dummy <long>(),
                    A.Dummy <string>(),
                    A.Dummy <HandlingStatus>().ThatIsNot(HandlingStatus.DisabledForStream),
                    Some.ReadOnlyDummies <HandlingStatus>().ToList(),
                    A.Dummy <string>(),
                    Some.ReadOnlyDummies <NamedValue <string> >().ToList(),
                    A.Dummy <bool>(),
                    A.Dummy <IResourceLocator>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () => new StandardUpdateHandlingStatusForStreamOp(
                    A.Dummy <HandlingStatus>().ThatIsIn(new[] { HandlingStatus.DisabledForStream, HandlingStatus.AvailableByDefault }),
                    A.Dummy <string>(),
                    Some.ReadOnlyDummies <NamedValue <string> >().ToList(),
                    A.Dummy <IResourceLocator>()));

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var existingRecordStrategy = A.Dummy <ExistingRecordStrategy>();

                var result = new PutAndReturnInternalRecordIdOp <Version>(
                    A.Dummy <Version>(),
                    A.Dummy <IReadOnlyCollection <NamedValue <string> > >(),
                    existingRecordStrategy,
                    existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundById || existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundByIdAndType
                            ? (int?)A.Dummy <ZeroOrPositiveInteger>()
                            : null,
                    A.Dummy <VersionMatchStrategy>());

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var existingRecordStrategy = A.Dummy <ExistingRecordStrategy>();

                var result = new PutOp <Version>(
                    A.Dummy <Version>(),
                    A.Dummy <IReadOnlyCollection <NamedValue <string> > >(),
                    existingRecordStrategy,
                    existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundById || existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundByIdAndType
                            ? (int?)A.Dummy <ZeroOrPositiveInteger>()
                            : null,
                    A.Dummy <VersionMatchStrategy>());

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var existingRecordStrategy = A.Dummy <ExistingRecordStrategy>();

                var result = new PutWithIdAndReturnInternalRecordIdOp <Version, Version>(
                    A.Dummy <Version>(),
                    A.Dummy <Version>(),
                    A.Dummy <IReadOnlyCollection <NamedValue <string> > >(),
                    existingRecordStrategy,
                    existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundById || existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundByIdAndType
                            ? (int?)A.Dummy <ZeroOrPositiveInteger>()
                            : null,
                    A.Dummy <VersionMatchStrategy>());

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var existingRecordStrategy = A.Dummy <ExistingRecordStrategy>();

                var result = new PutWithIdOp <Version, Version>(
                    A.Dummy <Version>(),
                    A.Dummy <Version>(),
                    A.Dummy <IReadOnlyCollection <NamedValue <string> > >(),
                    existingRecordStrategy,
                    existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundById || existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundByIdAndType
                            ? (int?)A.Dummy <ZeroOrPositiveInteger>()
                            : null,
                    A.Dummy <VersionMatchStrategy>());

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var existingRecordStrategy = A.Dummy <ExistingRecordStrategy>();

                var result = new StandardPutRecordOp(
                    A.Dummy <StreamRecordMetadata>(),
                    A.Dummy <DescribedSerializationBase>(),
                    existingRecordStrategy,
                    existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundById || existingRecordStrategy == ExistingRecordStrategy.PruneIfFoundByIdAndType
                            ? (int?)A.Dummy <ZeroOrPositiveInteger>()
                            : null,
                    A.Dummy <VersionMatchStrategy>(),
                    A.Dummy <long?>(),
                    A.Dummy <IResourceLocator>());

                return(result);
            });

            // ------------------------------- OPERATION INTERFACES -------------------------------------
            AutoFixtureBackedDummyFactory.UseRandomInterfaceImplementationForDummy <IPruneOp>();
        }
Example #26
0
 private static MemoryStream RandomStream(long size)
 {
     return(new MemoryStream(ThreadSafeRandom.GetBytes((int)size)));
 }
Example #27
0
        /// <summary>
        /// Starts the process of monster turning towards target
        /// </summary>
        public void StartTurn()
        {
            //if (Timers.RunningTime < NextMoveTime)
            //return;
            if (!MoveReady())
            {
                return;
            }

            if (DebugMove)
            {
                Console.WriteLine($"{Name} ({Guid}) - StartTurn, ranged={IsRanged}");
            }

            if (MoveSpeed == 0.0f)
            {
                GetMovementSpeed();
            }

            //Console.WriteLine($"[{Timers.RunningTime}] - {Name} ({Guid}) - starting turn");

            IsTurning = true;

            // send network actions
            var targetDist = GetDistanceToTarget();
            var turnTo     = IsRanged || (CurrentAttack == CombatType.Magic && targetDist <= GetSpellMaxRange());

            if (turnTo)
            {
                TurnTo(AttackTarget);
            }
            else
            {
                MoveTo(AttackTarget, RunRate);
            }

            // need turning listener?
            IsTurning      = false;
            IsMoving       = true;
            LastMoveTime   = Timers.RunningTime;
            NextCancelTime = LastMoveTime + ThreadSafeRandom.Next(2, 4);

            var mvp = GetMovementParameters();

            if (turnTo)
            {
                PhysicsObj.TurnToObject(AttackTarget.PhysicsObj.ID, mvp);
            }
            else
            {
                PhysicsObj.MoveToObject(AttackTarget.PhysicsObj, mvp);
            }

            if (!InitSticky)
            {
                PhysicsObj.add_moveto_listener(OnMoveComplete);

                PhysicsObj.add_sticky_listener(OnSticky);
                PhysicsObj.add_unsticky_listener(OnUnsticky);
                InitSticky = true;
            }
        }
Example #28
0
 internal static IGrainContext PickRandom(List <IGrainContext> local) => local[local.Count == 1 ? 0 : ThreadSafeRandom.Next(local.Count)];
Example #29
0
        public static bool RandomizeExport(ExportEntry export, RandomizationOption option)
        {
            if (!CanRandomize(export))
            {
                return(false);
            }
            MERLog.Information($"[{Path.GetFileNameWithoutExtension(export.FileRef.FilePath)}] Randomizing movement interpolations for " + export.UIndex + ": " + export.InstancedFullPath);
            var props    = export.GetProperties();
            var posTrack = props.GetProp <StructProperty>("PosTrack");

            if (posTrack != null)
            {
                var points = posTrack.GetProp <ArrayProperty <StructProperty> >("Points");
                if (points != null)
                {
                    foreach (StructProperty s in points)
                    {
                        var outVal = s.GetProp <StructProperty>("OutVal");
                        if (outVal != null)
                        {
                            FloatProperty x = outVal.GetProp <FloatProperty>("X");
                            FloatProperty y = outVal.GetProp <FloatProperty>("Y");
                            FloatProperty z = outVal.GetProp <FloatProperty>("Z");
                            x.Value = x.Value * ThreadSafeRandom.NextFloat(1 - option.SliderValue, 1 + option.SliderValue);
                            y.Value = y.Value * ThreadSafeRandom.NextFloat(1 - option.SliderValue, 1 + option.SliderValue);
                            z.Value = z.Value * ThreadSafeRandom.NextFloat(1 - option.SliderValue, 1 + option.SliderValue);
                        }
                    }
                }
            }

            var eulerTrack = props.GetProp <StructProperty>("EulerTrack");

            if (eulerTrack != null)
            {
                var points = eulerTrack.GetProp <ArrayProperty <StructProperty> >("Points");
                if (points != null)
                {
                    foreach (StructProperty s in points)
                    {
                        var outVal = s.GetProp <StructProperty>("OutVal");
                        if (outVal != null)
                        {
                            FloatProperty x = outVal.GetProp <FloatProperty>("X");
                            FloatProperty y = outVal.GetProp <FloatProperty>("Y");
                            FloatProperty z = outVal.GetProp <FloatProperty>("Z");
                            if (x.Value != 0)
                            {
                                x.Value = x.Value * ThreadSafeRandom.NextFloat(1 - option.SliderValue, 1 + option.SliderValue);
                            }
                            else
                            {
                                x.Value = ThreadSafeRandom.NextFloat(0, ThreadSafeRandom.NextFloat(-1000 * option.SliderValue, 1000 * option.SliderValue));
                            }

                            if (y.Value != 0)
                            {
                                y.Value = y.Value * ThreadSafeRandom.NextFloat(1 - option.SliderValue, 1 + option.SliderValue);
                            }
                            else
                            {
                                y.Value = ThreadSafeRandom.NextFloat(0, ThreadSafeRandom.NextFloat(-1000 * option.SliderValue, 1000 * option.SliderValue));
                            }

                            if (z.Value != 0)
                            {
                                z.Value = z.Value * ThreadSafeRandom.NextFloat(1 - option.SliderValue, 1 + option.SliderValue);
                            }
                            else
                            {
                                z.Value = ThreadSafeRandom.NextFloat(0, ThreadSafeRandom.NextFloat(-1000 * option.SliderValue, 1000 * option.SliderValue));
                            }
                        }
                    }
                }
            }

            export.WriteProperties(props);
            return(true);
        }
        public Task PutSameContentManyTimesTest(bool useRedundantPutFileShortcut)
        {
            var context = new Context(Logger);

            ContentStoreSettings = new ContentStoreSettings()
            {
                UseRedundantPutFileShortcut = useRedundantPutFileShortcut
            };

            return(TestStore(context, Clock, async store =>
            {
                byte[] bytes = ThreadSafeRandom.GetBytes(ValueSize);
                ContentHash contentHash = bytes.CalculateHash(ContentHashType);

                // Verify content doesn't exist yet in store
                Assert.False(await store.ContainsAsync(context, contentHash, null));

                using (var tempDirectory = new DisposableDirectory(FileSystem))
                {
                    ContentHash hashFromPut;
                    using (var pinContext = store.CreatePinContext())
                    {
                        var concurrency = 24;
                        var iterations = 100;

                        var items = Enumerable.Range(0, concurrency).Select(i =>
                        {
                            AbsolutePath pathToContent = tempDirectory.Path / $"tempContent{i}.txt";
                            FileSystem.WriteAllBytes(pathToContent, bytes);
                            return (pathToContent, iterations);
                        }).ToArray();

                        int nonDuplicatedPuts = 0;

                        await ParallelAlgorithms.WhenDoneAsync(24, CancellationToken.None, async(scheduleItem, item) =>
                        {
                            // Put the content into the store w/ hard link
                            var r = await store.PutFileAsync(
                                context, item.pathToContent, FileRealizationMode.Any, ContentHashType, new PinRequest(pinContext));
                            hashFromPut = r.ContentHash;

                            if (!r.ContentAlreadyExistsInCache)
                            {
                                Interlocked.Increment(ref nonDuplicatedPuts);
                            }

                            Clock.Increment();
                            Assert.True(pinContext.Contains(hashFromPut));

                            if (item.iterations != 0)
                            {
                                scheduleItem((item.pathToContent, item.iterations - 1));
                            }
                        },
                                                               items);

                        Assert.Equal(1, nonDuplicatedPuts);
                    }
                }
            }));
        }
Example #31
0
        public void SetCaptain()
        {
            List<int> list = new List<int>();
            ThreadSafeRandom random = new ThreadSafeRandom();
            GamePlayer[] players = Data.FlagPlayer.ToArray();
            int rand = random.Next(players.Length);
            for (int i = rand; i < players.Length + rand; i++)
            {
                if (Data.Players[players[i % players.Length]].State == TankGameState.LOSE)
                    continue;

                if (players[i % players.Length].CurrentTeamIndex != 0)
                {
                    if (!list.Contains(players[i % players.Length].CurrentTeamIndex))
                    {
                        list.Add(players[i % players.Length].CurrentTeamIndex);
                        Data.Players[players[i % players.Length]].IsCaptain = true;
                    }
                    else
                    {
                        Data.Players[players[i % players.Length]].IsCaptain = false;
                    }
                }
                else
                {
                    list.Add(0);
                    Data.Players[players[i % players.Length]].IsCaptain = true;
                }
            }

            players = Data.Players.Keys.ToArray();
            rand = random.Next(players.Length);
            for (int i = rand; i < players.Length + rand; i++)
            {
                if (Data.Players[players[i % players.Length]].State == TankGameState.LOSE)
                    continue;

                if (!list.Contains(players[i % players.Length].CurrentTeamIndex))
                {
                    list.Add(players[i % players.Length].CurrentTeamIndex);
                    Data.Players[players[i % players.Length]].IsCaptain = true;
                }
            }
        }
Example #32
0
        private float DoCalculateDamage(Creature attacker, Creature defender, WorldObject damageSource)
        {
            var playerAttacker = attacker as Player;
            var playerDefender = defender as Player;

            Attacker = attacker;
            Defender = defender;

            CombatType = attacker.GetCombatType();

            DamageSource = damageSource;

            Weapon = attacker.GetEquippedWeapon();

            AttackType   = attacker.GetAttackType(Weapon, CombatManeuver);
            AttackHeight = attacker.AttackHeight ?? AttackHeight.Medium;

            // check lifestone protection
            if (playerDefender != null && playerDefender.UnderLifestoneProtection)
            {
                LifestoneProtection = true;
                playerDefender.HandleLifestoneProtection();
                return(0.0f);
            }

            if (defender.Invincible)
            {
                return(0.0f);
            }

            // evasion chance
            EvasionChance = GetEvadeChance(attacker, defender);
            if (EvasionChance > ThreadSafeRandom.Next(0.0f, 1.0f))
            {
                Evaded = true;
                return(0.0f);
            }

            // get base damage
            if (playerAttacker != null)
            {
                GetBaseDamage(playerAttacker, CombatManeuver);
            }
            else
            {
                GetBaseDamage(attacker, CombatManeuver);
            }

            if (GeneralFailure)
            {
                return(0.0f);
            }

            // get damage modifiers
            PowerMod     = attacker.GetPowerMod(Weapon);
            AttributeMod = attacker.GetAttributeMod(Weapon);
            SlayerMod    = WorldObject.GetWeaponCreatureSlayerModifier(attacker, defender);

            // ratings
            DamageRatingBaseMod = Creature.GetPositiveRatingMod(attacker.GetDamageRating());
            RecklessnessMod     = Creature.GetRecklessnessMod(attacker, defender);
            SneakAttackMod      = attacker.GetSneakAttackMod(defender);
            HeritageMod         = attacker.GetHeritageBonus(Weapon) ? 1.05f : 1.0f;

            DamageRatingMod = Creature.AdditiveCombine(DamageRatingBaseMod, RecklessnessMod, SneakAttackMod, HeritageMod);

            // damage before mitigation
            DamageBeforeMitigation = BaseDamage * AttributeMod * PowerMod * SlayerMod * DamageRatingMod;

            // critical hit?
            var attackSkill = attacker.GetCreatureSkill(attacker.GetCurrentWeaponSkill());

            CriticalChance = WorldObject.GetWeaponCritChanceModifier(attacker, attackSkill, defender);
            if (CriticalChance > ThreadSafeRandom.Next(0.0f, 1.0f))
            {
                var criticalDefended = false;
                if (playerDefender != null && playerDefender.AugmentationCriticalDefense > 0)
                {
                    var criticalDefenseMod    = playerAttacker != null ? 0.05f : 0.25f;
                    var criticalDefenseChance = playerDefender.AugmentationCriticalDefense * criticalDefenseMod;

                    if (criticalDefenseChance > ThreadSafeRandom.Next(0.0f, 1.0f))
                    {
                        criticalDefended = true;
                    }
                }

                if (!criticalDefended)
                {
                    IsCritical = true;

                    CriticalDamageMod = 1.0f + WorldObject.GetWeaponCritDamageMod(attacker, attackSkill, defender);

                    // recklessness excluded from crits
                    RecklessnessMod        = 1.0f;
                    DamageRatingMod        = Creature.AdditiveCombine(DamageRatingBaseMod, SneakAttackMod, HeritageMod);
                    DamageBeforeMitigation = BaseDamageMod.MaxDamage * AttributeMod * PowerMod * SlayerMod * DamageRatingMod * CriticalDamageMod;
                }
            }

            // Armor Rending reduces physical armor too?
            var armorRendingMod = 1.0f;

            if (Weapon != null && Weapon.HasImbuedEffect(ImbuedEffectType.ArmorRending))
            {
                armorRendingMod = WorldObject.GetArmorRendingMod(attackSkill);
            }

            // get body part / armor pieces / armor modifier
            if (playerDefender != null)
            {
                // select random body part @ current attack height
                GetBodyPart(AttackHeight);

                // get player armor pieces
                Armor = attacker.GetArmorLayers(playerDefender, BodyPart);

                // get armor modifiers
                ArmorMod = attacker.GetArmorMod(DamageType, Armor, Weapon, armorRendingMod);
            }
            else
            {
                // select random body part @ current attack height
                GetBodyPart(AttackHeight, defender);
                if (Evaded)
                {
                    return(0.0f);
                }

                Armor = CreaturePart.GetArmorLayers((CombatBodyPart)BiotaPropertiesBodyPart.Key);

                // get target armor
                ArmorMod = CreaturePart.GetArmorMod(DamageType, Armor, Weapon, armorRendingMod);
            }

            if (Weapon != null && Weapon.HasImbuedEffect(ImbuedEffectType.IgnoreAllArmor))
            {
                ArmorMod = 1.0f;
            }

            // get resistance modifiers
            WeaponResistanceMod = WorldObject.GetWeaponResistanceModifier(attacker, attackSkill, DamageType);

            if (playerDefender != null)
            {
                ResistanceMod = playerDefender.GetResistanceMod(DamageType, Weapon, WeaponResistanceMod);
            }
            else
            {
                var resistanceType = Creature.GetResistanceType(DamageType);
                ResistanceMod = (float)defender.GetResistanceMod(resistanceType, Weapon, WeaponResistanceMod);
            }

            // damage resistance rating
            DamageResistanceRatingMod = Creature.GetNegativeRatingMod(defender.GetDamageResistRating(CombatType));

            // get shield modifier
            ShieldMod = defender.GetShieldMod(attacker, DamageType, Weapon);

            // calculate final output damage
            Damage          = DamageBeforeMitigation * ArmorMod * ShieldMod * ResistanceMod * DamageResistanceRatingMod;
            DamageMitigated = DamageBeforeMitigation - Damage;

            return(Damage);
        }
        static StoredProcedureExecutionResultTest()
        {
            ConstructorArgumentValidationTestScenarios
            .RemoveAllScenarios()
            .AddScenario(() =>
                         new ConstructorArgumentValidationTestScenario <StoredProcedureExecutionResult>
            {
                Name             = "constructor should throw ArgumentNullException when parameter 'operation' is null scenario",
                ConstructionFunc = () =>
                {
                    var referenceObject = A.Dummy <StoredProcedureExecutionResult>();

                    var result = new StoredProcedureExecutionResult(
                        null,
                        referenceObject.OutputParameters);

                    return(result);
                },
                ExpectedExceptionType            = typeof(ArgumentNullException),
                ExpectedExceptionMessageContains = new[] { "operation", },
            })
            .AddScenario(() =>
                         new ConstructorArgumentValidationTestScenario <StoredProcedureExecutionResult>
            {
                Name             = "constructor should throw ArgumentNullException when parameter 'outputParameters' is null scenario",
                ConstructionFunc = () =>
                {
                    var referenceObject = A.Dummy <StoredProcedureExecutionResult>();

                    var result = new StoredProcedureExecutionResult(
                        referenceObject.Operation,
                        null);

                    return(result);
                },
                ExpectedExceptionType            = typeof(ArgumentNullException),
                ExpectedExceptionMessageContains = new[] { "outputParameters", },
            })
            .AddScenario(() =>
                         new ConstructorArgumentValidationTestScenario <StoredProcedureExecutionResult>
            {
                Name             = "constructor should throw ArgumentException when parameter 'outputParameters' contains a key-value pair with a null value scenario",
                ConstructionFunc = () =>
                {
                    var referenceObject = A.Dummy <StoredProcedureExecutionResult>();

                    var dictionaryWithNullValue = referenceObject.OutputParameters.ToDictionary(_ => _.Key, _ => _.Value);

                    var randomKey = dictionaryWithNullValue.Keys.ElementAt(ThreadSafeRandom.Next(0, dictionaryWithNullValue.Count));

                    dictionaryWithNullValue[randomKey] = null;

                    var result = new StoredProcedureExecutionResult(
                        referenceObject.Operation,
                        dictionaryWithNullValue);

                    return(result);
                },
                ExpectedExceptionType            = typeof(ArgumentException),
                ExpectedExceptionMessageContains = new[] { "outputParameters", "contains at least one key-value pair with a null value", },
            });
        }
Example #34
0
        public static void Train(string udSource, string ontonotesSource)
        {
            var trainFiles = Directory.GetFiles(udSource, "*-train.conllu", SearchOption.AllDirectories);
            var testFiles  = Directory.GetFiles(udSource, "*-dev.conllu", SearchOption.AllDirectories);

            List <string> trainFilesOntonotesEnglish = null;

            if (!string.IsNullOrWhiteSpace(ontonotesSource))
            {
                trainFilesOntonotesEnglish = Directory.GetFiles(ontonotesSource, "*.parse.ddg", SearchOption.AllDirectories)
                                             .Where(fn => !fn.Contains("sel_") || int.Parse(Path.GetFileNameWithoutExtension(fn).Split(new char[] { '_', '.' }).Skip(1).First()) < 3654)
                                             .ToList();
            }

            var trainFilesPerLanguage = trainFiles.Select(f => new { lang = Path.GetFileNameWithoutExtension(f).Replace("_", "-").Split(new char[] { '-' }).First(), file = f }).GroupBy(f => f.lang).ToDictionary(g => g.Key, g => g.Select(f => f.file).ToList());
            var testFilesPerLanguage  = testFiles.Select(f => new { lang = Path.GetFileNameWithoutExtension(f).Replace("_", "-").Split(new char[] { '-' }).First(), file = f }).GroupBy(f => f.lang).ToDictionary(g => g.Key, g => g.Select(f => f.file).ToList());
            var languages             = trainFilesPerLanguage.Keys.ToList();

            Logger.LogInformation($"Found these languages for training: {string.Join(", ", languages)}");

            int N_training = 5;

            Parallel.ForEach(languages, lang =>
            {
                Language language;
                try
                {
                    language = Languages.CodeToEnum(lang);
                }
                catch
                {
                    Logger.LogWarning($"Unknown language {lang}");
                    return;
                }

                var arcNames = new HashSet <string>();

                if (trainFilesPerLanguage.TryGetValue(lang, out var langTrainFiles) && testFilesPerLanguage.TryGetValue(lang, out var langTestFiles))
                {
                    var trainDocuments = ReadCorpus(langTrainFiles, arcNames, language);
                    var testDocuments  = ReadCorpus(langTestFiles, arcNames, language);

                    if (language == Language.English)
                    {
                        //Merge with Ontonotes 5.0 corpus
                        trainDocuments.AddRange(ReadCorpus(trainFilesOntonotesEnglish, arcNames, language, isOntoNotes: true));
                    }

                    double bestScore = double.MinValue;

                    for (int i = 0; i < N_training; i++)
                    {
                        var Tagger = new AveragePerceptronTagger(language, 0);
                        Tagger.Train(trainDocuments.AsEnumerable(), (int)(5 + ThreadSafeRandom.Next(15)));
                        var scoreTrain = TestTagger(trainDocuments, Tagger);
                        var scoreTest  = TestTagger(testDocuments, Tagger);
                        if (scoreTest > bestScore)
                        {
                            Logger.LogInformation($"\n>>>>> {lang}: NEW POS BEST: {scoreTest:0.0}%");
                            try
                            {
                                Tagger.StoreAsync().Wait();
                            }
                            catch (Exception E)
                            {
                                Logger.LogError(E, $"\n>>>>> {lang}: Failed to store model");
                            }
                            bestScore = scoreTest;
                        }
                        else
                        {
                            Logger.LogInformation($"\n>>>>> {lang}: POS BEST IS STILL : {bestScore:0.0}%");
                        }
                    }


                    bestScore = double.MinValue;
                    for (int i = 0; i < N_training; i++)
                    {
                        var Parser = new AveragePerceptronDependencyParser(language, 0 /*, arcNames.ToList()*/);
                        try
                        {
                            Parser.Train(trainDocuments.AsEnumerable(), (int)(5 + ThreadSafeRandom.Next(10)), (float)(1D - ThreadSafeRandom.NextDouble() * ThreadSafeRandom.NextDouble()));
                        }
                        catch (Exception E)
                        {
                            Logger.LogInformation("FAIL: " + E.Message);
                            continue;
                        }

                        trainDocuments = ReadCorpus(langTrainFiles, arcNames, language);
                        testDocuments  = ReadCorpus(langTestFiles, arcNames, language);

                        if (language == Language.English)
                        {
                            //Merge with Ontonotes 5.0 corpus
                            trainDocuments.AddRange(ReadCorpus(trainFilesOntonotesEnglish, arcNames, language, isOntoNotes: true));
                        }

                        var scoreTrain = TestParser(trainDocuments, Parser);
                        var scoreTest  = TestParser(testDocuments, Parser);

                        if (scoreTest > bestScore)
                        {
                            Logger.LogInformation($"\n>>>>> {lang}: NEW DEP BEST: {scoreTest:0.0}%");
                            try
                            {
                                Parser.StoreAsync().Wait();
                            }
                            catch (Exception E)
                            {
                                Logger.LogError(E, $"\n>>>>> {lang}: Failed to store model");
                            }
                            bestScore = scoreTest;
                        }
                        else
                        {
                            Logger.LogInformation($"\n>>>>> {lang}: DEP BEST IS STILL : {bestScore:0.0}%");
                        }
                        Parser = null;
                    }
                }
            });

            foreach (var lang in languages)
            {
                Language language;
                try
                {
                    language = Languages.CodeToEnum(lang);
                }
                catch
                {
                    Logger.LogInformation($"Unknown language {lang}");
                    return;
                }

                var arcNames = new HashSet <string>();

                var trainDocuments = ReadCorpus(trainFilesPerLanguage[lang], arcNames, language);
                var testDocuments  = ReadCorpus(testFilesPerLanguage[lang], arcNames, language);

                if (language == Language.English)
                {
                    //Merge with Ontonotes 5.0 corpus
                    var ontonotesDocuments = ReadCorpus(trainFilesOntonotesEnglish, arcNames, language, isOntoNotes: true);
                    trainDocuments.AddRange(ontonotesDocuments);
                }

                var Tagger = AveragePerceptronTagger.FromStoreAsync(language, 0, "").WaitResult();
                Logger.LogInformation($"\n{lang} - TAGGER / TRAIN");
                TestTagger(trainDocuments, Tagger);

                Logger.LogInformation($"\n{lang} - TAGGER / TEST");
                TestTagger(testDocuments, Tagger);

                trainDocuments = ReadCorpus(trainFilesPerLanguage[lang], arcNames, language);
                testDocuments  = ReadCorpus(testFilesPerLanguage[lang], arcNames, language);

                var Parser = AveragePerceptronDependencyParser.FromStoreAsync(language, 0, "").WaitResult();
                Logger.LogInformation($"\n{lang} - PARSER / TRAIN");
                TestParser(trainDocuments, Parser);

                Logger.LogInformation($"\n{lang} - PARSER / TEST");
                TestParser(testDocuments, Parser);
            }
        }
Example #35
0
        // The percentages for variances need to be fixed
        /// <summary>
        /// Gets Melee Weapon Variance
        /// </summary>
        /// <param name="category"></param><param name="type"></param>
        /// <returns>Returns Melee Weapon Variance</returns>
        private static double GetVariance(Skill category, LootWeaponType type)
        {
            double variance = 0;
            int    chance   = ThreadSafeRandom.Next(0, 99);

            switch (category)
            {
            case Skill.HeavyWeapons:
                switch (type)
                {
                case LootWeaponType.Axe:
                    if (chance < 10)
                    {
                        variance = .90;
                    }
                    else if (chance < 30)
                    {
                        variance = .93;
                    }
                    else if (chance < 70)
                    {
                        variance = .95;
                    }
                    else if (chance < 90)
                    {
                        variance = .97;
                    }
                    else
                    {
                        variance = .99;
                    }
                    break;

                case LootWeaponType.Dagger:
                    if (chance < 10)
                    {
                        variance = .47;
                    }
                    else if (chance < 30)
                    {
                        variance = .50;
                    }
                    else if (chance < 70)
                    {
                        variance = .53;
                    }
                    else if (chance < 90)
                    {
                        variance = .57;
                    }
                    else
                    {
                        variance = .62;
                    }
                    break;

                case LootWeaponType.DaggerMulti:
                    if (chance < 10)
                    {
                        variance = .40;
                    }
                    else if (chance < 30)
                    {
                        variance = .43;
                    }
                    else if (chance < 70)
                    {
                        variance = .48;
                    }
                    else if (chance < 90)
                    {
                        variance = .53;
                    }
                    else
                    {
                        variance = .58;
                    }
                    break;

                case LootWeaponType.Mace:
                    if (chance < 10)
                    {
                        variance = .30;
                    }
                    else if (chance < 30)
                    {
                        variance = .33;
                    }
                    else if (chance < 70)
                    {
                        variance = .37;
                    }
                    else if (chance < 90)
                    {
                        variance = .42;
                    }
                    else
                    {
                        variance = .46;
                    }
                    break;

                case LootWeaponType.Spear:
                    if (chance < 10)
                    {
                        variance = .59;
                    }
                    else if (chance < 30)
                    {
                        variance = .63;
                    }
                    else if (chance < 70)
                    {
                        variance = .68;
                    }
                    else if (chance < 90)
                    {
                        variance = .72;
                    }
                    else
                    {
                        variance = .75;
                    }
                    break;

                case LootWeaponType.Staff:
                    if (chance < 10)
                    {
                        variance = .38;
                    }
                    else if (chance < 30)
                    {
                        variance = .42;
                    }
                    else if (chance < 70)
                    {
                        variance = .45;
                    }
                    else if (chance < 90)
                    {
                        variance = .50;
                    }
                    else
                    {
                        variance = .52;
                    }
                    break;

                case LootWeaponType.Sword:
                    if (chance < 10)
                    {
                        variance = .47;
                    }
                    else if (chance < 30)
                    {
                        variance = .50;
                    }
                    else if (chance < 70)
                    {
                        variance = .53;
                    }
                    else if (chance < 90)
                    {
                        variance = .57;
                    }
                    else
                    {
                        variance = .62;
                    }
                    break;

                case LootWeaponType.SwordMulti:
                    if (chance < 10)
                    {
                        variance = .40;
                    }
                    else if (chance < 30)
                    {
                        variance = .43;
                    }
                    else if (chance < 70)
                    {
                        variance = .48;
                    }
                    else if (chance < 90)
                    {
                        variance = .53;
                    }
                    else
                    {
                        variance = .60;
                    }
                    break;

                case LootWeaponType.UA:
                    if (chance < 10)
                    {
                        variance = .44;
                    }
                    else if (chance < 30)
                    {
                        variance = .48;
                    }
                    else if (chance < 70)
                    {
                        variance = .53;
                    }
                    else if (chance < 90)
                    {
                        variance = .58;
                    }
                    else
                    {
                        variance = .60;
                    }
                    break;
                }
                break;

            case Skill.LightWeapons:
            case Skill.FinesseWeapons:
                switch (type)
                {
                case LootWeaponType.Axe:
                    // Axe
                    if (chance < 10)
                    {
                        variance = .80;
                    }
                    else if (chance < 30)
                    {
                        variance = .83;
                    }
                    else if (chance < 70)
                    {
                        variance = .85;
                    }
                    else if (chance < 90)
                    {
                        variance = .90;
                    }
                    else
                    {
                        variance = .95;
                    }
                    break;

                case LootWeaponType.Dagger:
                    // Dagger
                    if (chance < 10)
                    {
                        variance = .42;
                    }
                    else if (chance < 30)
                    {
                        variance = .47;
                    }
                    else if (chance < 70)
                    {
                        variance = .52;
                    }
                    else if (chance < 90)
                    {
                        variance = .56;
                    }
                    else
                    {
                        variance = .60;
                    }
                    break;

                case LootWeaponType.DaggerMulti:
                    // Dagger MultiStrike
                    if (chance < 10)
                    {
                        variance = .24;
                    }
                    else if (chance < 30)
                    {
                        variance = .28;
                    }
                    else if (chance < 70)
                    {
                        variance = .35;
                    }
                    else if (chance < 90)
                    {
                        variance = .40;
                    }
                    else
                    {
                        variance = .45;
                    }
                    break;

                case LootWeaponType.Mace:
                    // Mace
                    if (chance < 10)
                    {
                        variance = .23;
                    }
                    else if (chance < 30)
                    {
                        variance = .28;
                    }
                    else if (chance < 70)
                    {
                        variance = .32;
                    }
                    else if (chance < 90)
                    {
                        variance = .37;
                    }
                    else
                    {
                        variance = .43;
                    }
                    break;

                case LootWeaponType.Jitte:
                    // Jitte
                    if (chance < 10)
                    {
                        variance = .325;
                    }
                    else if (chance < 30)
                    {
                        variance = .35;
                    }
                    else if (chance < 70)
                    {
                        variance = .40;
                    }
                    else if (chance < 90)
                    {
                        variance = .45;
                    }
                    else
                    {
                        variance = .50;
                    }
                    break;

                case LootWeaponType.Spear:
                    // Spear
                    if (chance < 10)
                    {
                        variance = .65;
                    }
                    else if (chance < 30)
                    {
                        variance = .68;
                    }
                    else if (chance < 70)
                    {
                        variance = .71;
                    }
                    else if (chance < 90)
                    {
                        variance = .75;
                    }
                    else
                    {
                        variance = .80;
                    }
                    break;

                case LootWeaponType.Staff:
                    // Staff
                    if (chance < 10)
                    {
                        variance = .325;
                    }
                    else if (chance < 30)
                    {
                        variance = .35;
                    }
                    else if (chance < 70)
                    {
                        variance = .40;
                    }
                    else if (chance < 90)
                    {
                        variance = .45;
                    }
                    else
                    {
                        variance = .50;
                    }
                    break;

                case LootWeaponType.Sword:
                    // Sword
                    if (chance < 10)
                    {
                        variance = .42;
                    }
                    else if (chance < 30)
                    {
                        variance = .47;
                    }
                    else if (chance < 70)
                    {
                        variance = .52;
                    }
                    else if (chance < 90)
                    {
                        variance = .56;
                    }
                    else
                    {
                        variance = .60;
                    }
                    break;

                case LootWeaponType.SwordMulti:
                    // Sword Multistrike
                    if (chance < 10)
                    {
                        variance = .24;
                    }
                    else if (chance < 30)
                    {
                        variance = .28;
                    }
                    else if (chance < 70)
                    {
                        variance = .35;
                    }
                    else if (chance < 90)
                    {
                        variance = .40;
                    }
                    else
                    {
                        variance = .45;
                    }
                    break;

                case LootWeaponType.UA:
                    // UA
                    if (chance < 10)
                    {
                        variance = .44;
                    }
                    else if (chance < 30)
                    {
                        variance = .48;
                    }
                    else if (chance < 70)
                    {
                        variance = .53;
                    }
                    else if (chance < 90)
                    {
                        variance = .58;
                    }
                    else
                    {
                        variance = .60;
                    }
                    break;
                }
                break;

            case Skill.TwoHandedCombat:
                // Two Handed only have one set of variances
                if (chance < 5)
                {
                    variance = .30;
                }
                else if (chance < 20)
                {
                    variance = .35;
                }
                else if (chance < 50)
                {
                    variance = .40;
                }
                else if (chance < 80)
                {
                    variance = .45;
                }
                else if (chance < 95)
                {
                    variance = .50;
                }
                else
                {
                    variance = .55;
                }
                break;

            default:
                return(0);
            }

            return(variance);
        }
Example #36
0
        /// <summary>
        /// Calculates the damage for a spell projectile
        /// Used by war magic, void magic, and life magic projectiles
        /// </summary>
        public float?CalculateDamage(WorldObject source, WorldObject caster, Creature target, ref bool criticalHit, ref bool critDefended, ref bool overpower)
        {
            var sourcePlayer = source as Player;
            var targetPlayer = target as Player;

            if (source == null || !target.IsAlive || targetPlayer != null && targetPlayer.Invincible)
            {
                return(null);
            }

            // check lifestone protection
            if (targetPlayer != null && targetPlayer.UnderLifestoneProtection)
            {
                if (sourcePlayer != null)
                {
                    sourcePlayer.Session.Network.EnqueueSend(new GameMessageSystemChat($"The Lifestone's magic protects {targetPlayer.Name} from the attack!", ChatMessageType.Magic));
                }

                targetPlayer.HandleLifestoneProtection();
                return(null);
            }

            var critDamageBonus     = 0.0f;
            var weaponCritDamageMod = 1.0f;
            var weaponResistanceMod = 1.0f;
            var resistanceMod       = 1.0f;

            // life magic
            var lifeMagicDamage = 0.0f;

            // war/void magic
            var baseDamage  = 0;
            var skillBonus  = 0.0f;
            var finalDamage = 0.0f;

            var resistanceType = Creature.GetResistanceType(Spell.DamageType);

            var sourceCreature = source as Creature;

            if (sourceCreature?.Overpower != null)
            {
                overpower = Creature.GetOverpower(sourceCreature, target);
            }

            var resisted = source.TryResistSpell(target, Spell, caster, true);

            if (resisted && !overpower)
            {
                return(null);
            }

            CreatureSkill attackSkill = null;

            if (sourceCreature != null)
            {
                attackSkill = sourceCreature.GetCreatureSkill(Spell.School);
            }

            // critical hit
            var criticalChance = GetWeaponMagicCritFrequency(sourceCreature, attackSkill, target);

            if (ThreadSafeRandom.Next(0.0f, 1.0f) < criticalChance)
            {
                if (targetPlayer != null && targetPlayer.AugmentationCriticalDefense > 0)
                {
                    var criticalDefenseMod    = sourcePlayer != null ? 0.05f : 0.25f;
                    var criticalDefenseChance = targetPlayer.AugmentationCriticalDefense * criticalDefenseMod;

                    if (criticalDefenseChance > ThreadSafeRandom.Next(0.0f, 1.0f))
                    {
                        critDefended = true;
                    }
                }

                if (!critDefended)
                {
                    criticalHit = true;
                }
            }

            var absorbMod = GetAbsorbMod(target);

            bool isPVP = sourcePlayer != null && targetPlayer != null;

            if (isPVP && Spell.IsHarmful)
            {
                Player.UpdatePKTimers(sourcePlayer, targetPlayer);
            }

            var elementalDamageMod = GetCasterElementalDamageModifier(sourceCreature, target, Spell.DamageType);

            // Possible 2x + damage bonus for the slayer property
            var slayerMod = GetWeaponCreatureSlayerModifier(sourceCreature, target);

            // life magic projectiles: ie., martyr's hecatomb
            if (Spell.MetaSpellType == ACE.Entity.Enum.SpellType.LifeProjectile)
            {
                lifeMagicDamage = LifeProjectileDamage * Spell.DamageRatio;

                // could life magic projectiles crit?
                // if so, did they use the same 1.5x formula as war magic, instead of 2.0x?
                if (criticalHit)
                {
                    weaponCritDamageMod = GetWeaponCritDamageMod(sourceCreature, attackSkill, target);
                    critDamageBonus     = lifeMagicDamage * 0.5f * weaponCritDamageMod;
                }

                weaponResistanceMod = GetWeaponResistanceModifier(sourceCreature, attackSkill, Spell.DamageType);

                // if attacker/weapon has IgnoreMagicResist directly, do not transfer to spell projectile
                // only pass if SpellProjectile has it directly, such as 2637 - Invoking Aun Tanua

                resistanceMod = (float)Math.Max(0.0f, target.GetResistanceMod(resistanceType, this, null, weaponResistanceMod));

                finalDamage = (lifeMagicDamage + critDamageBonus) * elementalDamageMod * slayerMod * resistanceMod * absorbMod;
            }
            // war/void magic projectiles
            else
            {
                if (criticalHit)
                {
                    // Original:
                    // http://acpedia.org/wiki/Announcements_-_2002/08_-_Atonement#Letter_to_the_Players

                    // Critical Strikes: In addition to the skill-based damage bonus, each projectile spell has a 2% chance of causing a critical hit on the target and doing increased damage.
                    // A magical critical hit is similar in some respects to melee critical hits (although the damage calculation is handled differently).
                    // While a melee critical hit automatically does twice the maximum damage of the weapon, a magical critical hit will do an additional half the minimum damage of the spell.
                    // For instance, a magical critical hit from a level 7 spell, which does 110-180 points of damage, would add an additional 55 points of damage to the spell.

                    // Later updated for PvE only:

                    // http://acpedia.org/wiki/Announcements_-_2004/07_-_Treaties_in_Stone#Letter_to_the_Players

                    // Currently when a War Magic spell scores a critical hit, it adds a multiple of the base damage of the spell to a normal damage roll.
                    // Starting in July, War Magic critical hits will instead add a multiple of the maximum damage of the spell.
                    // No more crits that do less damage than non-crits!

                    if (isPVP) // PvP: 50% of the MIN damage added to normal damage roll
                    {
                        critDamageBonus = Spell.MinDamage * 0.5f;
                    }
                    else   // PvE: 50% of the MAX damage added to normal damage roll
                    {
                        critDamageBonus = Spell.MaxDamage * 0.5f;
                    }

                    weaponCritDamageMod = GetWeaponCritDamageMod(sourceCreature, attackSkill, target);

                    critDamageBonus *= weaponCritDamageMod;
                }

                /* War Magic skill-based damage bonus
                 * http://acpedia.org/wiki/Announcements_-_2002/08_-_Atonement#Letter_to_the_Players
                 */
                if (sourcePlayer != null)
                {
                    // per retail stats, level 8 difficulty is capped to 350 instead of 400
                    // without this, level 7s have the potential to deal more damage than level 8s
                    var difficulty = Math.Min(Spell.Power, 350);    // was skillMod possibility capped to 1.3x for level 7 spells in retail, instead of level 8 difficulty cap?
                    var magicSkill = sourcePlayer.GetCreatureSkill(Spell.School).Current;

                    if (magicSkill > difficulty)
                    {
                        // Bonus clamped to a maximum of 50%
                        //var percentageBonus = Math.Clamp((magicSkill - Spell.Power) / 100.0f, 0.0f, 0.5f);
                        var percentageBonus = (magicSkill - difficulty) / 1000.0f;

                        skillBonus = Spell.MinDamage * percentageBonus;
                    }
                }
                baseDamage = ThreadSafeRandom.Next(Spell.MinDamage, Spell.MaxDamage);

                weaponResistanceMod = GetWeaponResistanceModifier(sourceCreature, attackSkill, Spell.DamageType);

                // if attacker/weapon has IgnoreMagicResist directly, do not transfer to spell projectile
                // only pass if SpellProjectile has it directly, such as 2637 - Invoking Aun Tanua

                resistanceMod = (float)Math.Max(0.0f, target.GetResistanceMod(resistanceType, this, null, weaponResistanceMod));

                if (sourcePlayer != null && targetPlayer != null && Spell.DamageType == DamageType.Nether)
                {
                    // for direct damage from void spells in pvp,
                    // apply void_pvp_modifier *on top of* the player's natural resistance to nether

                    // this supposedly brings the direct damage from void spells in pvp closer to retail
                    resistanceMod *= (float)PropertyManager.GetDouble("void_pvp_modifier").Item;
                }

                finalDamage = baseDamage + critDamageBonus + skillBonus;

                finalDamage *= elementalDamageMod * slayerMod * resistanceMod * absorbMod;
            }

            // show debug info
            if (sourceCreature != null && sourceCreature.DebugDamage.HasFlag(Creature.DebugDamageType.Attacker))
            {
                ShowInfo(sourceCreature, Spell, attackSkill, criticalChance, criticalHit, critDefended, overpower, weaponCritDamageMod, skillBonus, baseDamage, critDamageBonus, elementalDamageMod, slayerMod, weaponResistanceMod, resistanceMod, absorbMod, LifeProjectileDamage, lifeMagicDamage, finalDamage);
            }
            if (target.DebugDamage.HasFlag(Creature.DebugDamageType.Defender))
            {
                ShowInfo(target, Spell, attackSkill, criticalChance, criticalHit, critDefended, overpower, weaponCritDamageMod, skillBonus, baseDamage, critDamageBonus, elementalDamageMod, slayerMod, weaponResistanceMod, resistanceMod, absorbMod, LifeProjectileDamage, lifeMagicDamage, finalDamage);
            }
            return(finalDamage);
        }
Example #37
0
        private static void MutateMeleeWeapon(WorldObject wo, TreasureDeath profile, bool isMagical, int weaponType, int subtype)
        {
            Skill wieldSkillType = Skill.None;

            int    damage         = 0;
            double damageVariance = 0;
            double weaponDefense  = 0;
            double weaponOffense  = 0;

            // Properties for weapons
            double           magicD           = GetMagicMissileDMod(profile.Tier);
            double           missileD         = GetMagicMissileDMod(profile.Tier);
            int              gemCount         = ThreadSafeRandom.Next(1, 5);
            int              gemType          = ThreadSafeRandom.Next(10, 50);
            int              workmanship      = GetWorkmanship(profile.Tier);
            int              wieldDiff        = GetWieldDifficulty(profile.Tier, WieldType.MeleeWeapon);
            WieldRequirement wieldRequirments = WieldRequirement.RawSkill;

            // Weapon Types
            // 0 = Heavy
            // 1 = Light
            // 2 = Finesse
            // default = Two Handed
            switch (weaponType)
            {
            case 0:
                // Heavy Weapons
                wieldSkillType = Skill.HeavyWeapons;

                switch (subtype)
                {
                case 0:
                case 1:
                case 2:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 18);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 22);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Axe);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Axe);
                    break;

                case 3:
                case 4:
                case 5:
                    weaponDefense = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense = GetMaxDamageMod(profile.Tier, 20);

                    damage = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Dagger);

                    if (subtype == 3)
                    {
                        damageVariance = GetVariance(wieldSkillType, LootWeaponType.Dagger);
                    }
                    if (subtype == 4 || subtype == 5)
                    {
                        damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.DaggerMulti);
                        damageVariance = GetVariance(wieldSkillType, LootWeaponType.DaggerMulti);
                    }
                    break;

                case 6:
                case 7:
                case 8:
                case 9:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 22);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 18);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Mace);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Mace);
                    break;

                case 10:
                case 11:
                case 12:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 15);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 25);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Spear);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Spear);
                    break;

                case 13:
                case 14:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 25);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 15);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Staff);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Staff);
                    break;

                case 15:
                case 16:
                case 17:
                case 18:
                case 19:
                case 20:
                    weaponDefense = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense = GetMaxDamageMod(profile.Tier, 20);

                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Sword);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Sword);

                    if (subtype == 20)
                    {
                        damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.SwordMulti);
                        damageVariance = GetVariance(wieldSkillType, LootWeaponType.SwordMulti);
                    }
                    break;

                case 21:
                default:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 20);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.UA);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.UA);
                    break;
                }
                break;

            case 1:
                // Light Weapons;
                wieldSkillType = Skill.LightWeapons;

                switch (subtype)
                {
                case 0:
                case 1:
                case 2:
                case 3:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 18);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 22);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Axe);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Axe);
                    break;

                case 4:
                case 5:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 20);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.DaggerMulti);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.DaggerMulti);
                    break;

                case 6:
                case 7:
                case 8:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 22);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 18);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Mace);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Mace);
                    break;

                case 9:
                case 10:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 15);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 25);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Spear);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Spear);
                    break;

                case 11:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 25);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 15);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Staff);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Staff);
                    break;

                case 12:
                case 13:
                case 14:
                case 15:
                case 16:
                case 17:
                    weaponDefense = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense = GetMaxDamageMod(profile.Tier, 20);

                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Sword);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Sword);

                    if (subtype == 14)
                    {
                        damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.SwordMulti);
                        damageVariance = GetVariance(wieldSkillType, LootWeaponType.SwordMulti);
                    }
                    break;

                case 18:
                default:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 20);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.UA);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.UA);
                    break;
                }
                break;

            case 2:
                // Finesse Weapons;
                wieldSkillType = Skill.FinesseWeapons;

                switch (subtype)
                {
                case 0:
                case 1:
                case 2:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 18);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 22);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Axe);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Axe);
                    break;

                case 3:
                case 4:
                case 5:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 20);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Dagger);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Dagger);

                    if (subtype == 3 || subtype == 4)
                    {
                        damageVariance = GetVariance(wieldSkillType, LootWeaponType.DaggerMulti);
                        damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.DaggerMulti);
                    }
                    break;

                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 22);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 18);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Mace);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Mace);

                    if (subtype == 9)
                    {
                        damageVariance = GetVariance(wieldSkillType, LootWeaponType.Jitte);
                    }
                    break;

                case 11:
                case 12:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 15);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 25);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Spear);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Spear);
                    break;

                case 13:
                case 14:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 25);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 15);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Staff);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Staff);
                    break;

                case 15:
                case 16:
                case 17:
                case 18:
                case 19:
                case 20:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 20);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Sword);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.Sword);

                    if (subtype == 15)
                    {
                        damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.SwordMulti);
                        damageVariance = GetVariance(wieldSkillType, LootWeaponType.SwordMulti);
                    }
                    break;

                case 21:
                default:
                    weaponDefense  = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense  = GetMaxDamageMod(profile.Tier, 20);
                    damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.UA);
                    damageVariance = GetVariance(wieldSkillType, LootWeaponType.UA);
                    break;
                }
                break;

            default:
                // Two handed
                wieldSkillType = Skill.TwoHandedCombat;

                damage         = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Cleaving);
                damageVariance = GetVariance(wieldSkillType, LootWeaponType.TwoHanded);

                switch (subtype)
                {
                case 0:
                case 1:
                case 2:
                    weaponDefense = GetMaxDamageMod(profile.Tier, 20);
                    weaponOffense = GetMaxDamageMod(profile.Tier, 20);
                    break;

                case 3:
                case 4:
                case 5:
                case 6:
                    weaponDefense = GetMaxDamageMod(profile.Tier, 22);
                    weaponOffense = GetMaxDamageMod(profile.Tier, 18);
                    break;

                case 7:
                    weaponDefense = GetMaxDamageMod(profile.Tier, 18);
                    weaponOffense = GetMaxDamageMod(profile.Tier, 22);
                    break;

                case 8:
                case 9:
                case 10:
                default:
                    weaponDefense = GetMaxDamageMod(profile.Tier, 15);
                    weaponOffense = GetMaxDamageMod(profile.Tier, 25);
                    damage        = GetMeleeMaxDamage(wieldSkillType, wieldDiff, LootWeaponType.Spears);
                    break;
                }
                break;
            }

            // Description
            wo.AppraisalLongDescDecoration = AppraisalLongDescDecorations.PrependWorkmanship | AppraisalLongDescDecorations.AppendGemInfo;
            wo.LongDesc = wo.Name;

            // GemTypes, Material, Workmanship
            wo.GemCount = gemCount;
            wo.GemType  = (MaterialType)gemType;
            int materialType = GetMaterialType(wo, profile.Tier);

            if (materialType > 0)
            {
                wo.MaterialType = (MaterialType)materialType;
            }
            wo.ItemWorkmanship = workmanship;

            // Burden
            MutateBurden(wo, profile.Tier, true);

            // Weapon Stats
            wo.Damage               = damage;
            wo.DamageVariance       = damageVariance;
            wo.WeaponDefense        = weaponDefense;
            wo.WeaponOffense        = weaponOffense;
            wo.WeaponMissileDefense = missileD;
            wo.WeaponMagicDefense   = magicD;

            // Adding Wield Reqs if required
            if (wieldDiff > 0)
            {
                wo.WieldDifficulty   = wieldDiff;
                wo.WieldRequirements = wieldRequirments;
                wo.WieldSkillType    = (int)wieldSkillType;
            }
            else
            {
                // If no wield, remove wield reqs
                wo.WieldDifficulty   = null;
                wo.WieldRequirements = WieldRequirement.Invalid;
                wo.WieldSkillType    = null;
            }

            // Adding Magic Spells
            if (isMagical)
            {
                wo = AssignMagic(wo, profile);
            }
            else
            {
                // If no spells remove magic properites
                wo.ItemManaCost   = null;
                wo.ItemMaxMana    = null;
                wo.ItemCurMana    = null;
                wo.ItemSpellcraft = null;
                wo.ItemDifficulty = null;
            }

            double materialMod    = LootTables.getMaterialValueModifier(wo);
            double gemMaterialMod = LootTables.getGemMaterialValueModifier(wo);
            var    value          = GetValue(profile.Tier, workmanship, gemMaterialMod, materialMod);

            wo.Value = value;

            RandomizeColor(wo);
        }
Example #38
0
 private static bool CanRandomize(ExportEntry export) => !export.IsDefaultObject && export.ClassName == @"InterpTrackMove" && ThreadSafeRandom.Next(1) == 0;
Example #39
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (!gatewayListProviderInitialized)
            {
                await this.gatewayListProvider.InitializeGatewayListProvider();

                gatewayListProviderInitialized = true;
            }

            this.gatewayRefreshTimer = new AsyncTaskSafeTimer(
                this.timerLogger,
                RefreshSnapshotLiveGateways_TimerCallback,
                null,
                this.gatewayOptions.GatewayListRefreshPeriod,
                this.gatewayOptions.GatewayListRefreshPeriod);

            var knownGateways = await this.gatewayListProvider.GetGateways();

            if (knownGateways.Count == 0)
            {
                var err = $"Could not find any gateway in {this.gatewayListProvider.GetType().FullName}. Orleans client cannot initialize.";
                this.logger.LogError((int)ErrorCode.GatewayManager_NoGateways, err);
                throw new SiloUnavailableException(err);
            }

            this.logger.LogInformation(
                (int)ErrorCode.GatewayManager_FoundKnownGateways,
                "Found {GatewayCount} gateways: {Gateways}",
                knownGateways.Count,
                Utils.EnumerableToString(knownGateways));

            this.roundRobinCounter     = this.gatewayOptions.PreferedGatewayIndex >= 0 ? this.gatewayOptions.PreferedGatewayIndex : ThreadSafeRandom.Next(knownGateways.Count);
            this.knownGateways         = this.cachedLiveGateways = knownGateways.Select(gw => gw.ToGatewayAddress()).ToList();
            this.cachedLiveGatewaysSet = new HashSet <SiloAddress>(cachedLiveGateways);
            this.lastRefreshTime       = DateTime.UtcNow;
        }
 /// <summary>
 /// Set seed of the random numbers generator.
 /// </summary>
 /// 
 /// <param name="seed">Seed value.</param>
 /// 
 /// <remarks>Resets random numbers generator initializing it with
 /// specified seed value.</remarks>
 /// 
 public void SetSeed( int seed )
 {
     rand = new ThreadSafeRandom( seed );
 }
        private static WorldObject CreateArmor(int tier, bool isMagical, LootBias lootBias = LootBias.UnBiased)
        {
            int lowSpellTier  = 0;
            int highSpellTier = 0;

            int equipSetId = 0;

            int materialType = 0;

            int armorPiece  = 0;
            int armorType   = 0;
            int armorWeenie = 0;

            switch (tier)
            {
            case 1:
                lowSpellTier  = 1;
                highSpellTier = 3;
                armorType     = ThreadSafeRandom.Next((int)LootTables.ArmorType.MiscClothing, (int)LootTables.ArmorType.ChainmailArmor);
                break;

            case 2:
                lowSpellTier  = 3;
                highSpellTier = 5;
                armorType     = ThreadSafeRandom.Next((int)LootTables.ArmorType.MiscClothing, (int)LootTables.ArmorType.DiforsaArmor);
                break;

            case 3:
                lowSpellTier  = 4;
                highSpellTier = 6;
                armorType     = ThreadSafeRandom.Next((int)LootTables.ArmorType.MiscClothing, (int)LootTables.ArmorType.CovenantArmor);
                break;

            case 4:
                lowSpellTier  = 5;
                highSpellTier = 6;
                armorType     = ThreadSafeRandom.Next((int)LootTables.ArmorType.MiscClothing, (int)LootTables.ArmorType.CovenantArmor);
                break;

            case 5:
                lowSpellTier  = 5;
                highSpellTier = 7;
                armorType     = ThreadSafeRandom.Next((int)LootTables.ArmorType.MiscClothing, (int)LootTables.ArmorType.AlduressaArmor);
                break;

            case 6:
                lowSpellTier  = 6;
                highSpellTier = 7;
                armorType     = ThreadSafeRandom.Next((int)LootTables.ArmorType.MiscClothing, (int)LootTables.ArmorType.HaebreanArmor);
                break;

            case 7:
                lowSpellTier  = 6;
                highSpellTier = 8;
                armorType     = ThreadSafeRandom.Next((int)LootTables.ArmorType.MiscClothing, (int)LootTables.ArmorType.OlthoiAlduressaArmor);
                break;

            default:
                lowSpellTier  = 7;
                highSpellTier = 8;
                if (lootBias == LootBias.Armor)     // Armor Mana Forge Chests don't include clothing type items
                {
                    armorType = ThreadSafeRandom.Next((int)LootTables.ArmorType.Helms, (int)LootTables.ArmorType.OlthoiAlduressaArmor);
                }
                else
                {
                    armorType = ThreadSafeRandom.Next((int)LootTables.ArmorType.MiscClothing, (int)LootTables.ArmorType.OlthoiAlduressaArmor);
                }
                break;
            }

            switch (armorType)
            {
            case (int)LootTables.ArmorType.MiscClothing:
                armorPiece  = ThreadSafeRandom.Next(0, 47);
                armorWeenie = LootTables.MiscClothing[armorPiece];
                break;

            case (int)LootTables.ArmorType.Helms:
                armorPiece  = ThreadSafeRandom.Next(0, 8);
                armorWeenie = LootTables.Helms[armorPiece];
                break;

            case (int)LootTables.ArmorType.Shields:
                armorPiece  = ThreadSafeRandom.Next(0, 4);
                armorWeenie = LootTables.Shields[armorPiece];
                break;

            case (int)LootTables.ArmorType.LeatherArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 15);
                armorWeenie = LootTables.LeatherArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.StuddedLeatherArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 14);
                armorWeenie = LootTables.StuddedLeatherArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.ChainmailArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 12);
                armorWeenie = LootTables.ChainmailArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.PlatemailArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 10);
                armorWeenie = LootTables.PlatemailArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.ScalemailArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 13);
                armorWeenie = LootTables.ScalemailArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.YoroiArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 7);
                armorWeenie = LootTables.YoroiArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.DiforsaArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 12);
                armorWeenie = LootTables.DiforsaArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.CeldonArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 3);
                armorWeenie = LootTables.CeldonArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.AmuliArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 1);
                armorWeenie = LootTables.AmuliArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.KoujiaArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 2);
                armorWeenie = LootTables.KoujiaArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.TenassaArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 2);
                armorWeenie = LootTables.TenassaArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.CovenantArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 9);
                armorWeenie = LootTables.CovenantArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.LoricaArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 5);
                armorWeenie = LootTables.LoricaArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.NariyidArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 6);
                armorWeenie = LootTables.NariyidArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.ChiranArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 4);
                armorWeenie = LootTables.ChiranArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.AlduressaArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 4);
                armorWeenie = LootTables.AlduressaArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.KnorrAcademyArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 7);
                armorWeenie = LootTables.KnorrAcademyArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.SedgemailLeatherArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 5);
                armorWeenie = LootTables.SedgemailLeatherArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.HaebreanArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 8);
                armorWeenie = LootTables.HaebreanArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.OlthoiArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 9);
                armorWeenie = LootTables.OlthoiArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.OlthoiAmuliArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 4);
                armorWeenie = LootTables.OlthoiAmuliArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.OlthoiCeldonArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 6);
                armorWeenie = LootTables.OlthoiCeldonArmor[armorPiece];
                break;

            case (int)LootTables.ArmorType.OlthoiKoujiaArmor:
                armorPiece  = ThreadSafeRandom.Next(0, 4);
                armorWeenie = LootTables.OlthoiKoujiaArmor[armorPiece];
                break;

            default:     // Olthoi Alduressa
                armorPiece  = ThreadSafeRandom.Next(0, 4);
                armorWeenie = LootTables.OlthoiAlduressaArmor[armorPiece];
                break;
            }

            WorldObject wo = WorldObjectFactory.CreateNewWorldObject((uint)armorWeenie);

            if (wo == null)
            {
                return(null);
            }

            wo.SetProperty(PropertyString.LongDesc, wo.GetProperty(PropertyString.Name));

            wo.SetProperty(PropertyInt.AppraisalItemSkill, 7);
            wo.SetProperty(PropertyInt.AppraisalLongDescDecoration, 1);

            materialType = GetMaterialType(wo, tier);
            if (materialType > 0)
            {
                wo.MaterialType = (MaterialType)materialType;
            }

            int gemCount = ThreadSafeRandom.Next(1, 6);
            int gemType  = ThreadSafeRandom.Next(10, 50);

            wo.SetProperty(PropertyInt.GemCount, gemCount);
            wo.SetProperty(PropertyInt.GemType, gemType);

            int workmanship = GetWorkmanship(tier);

            wo.SetProperty(PropertyInt.ItemWorkmanship, workmanship);

            double materialMod    = LootTables.getMaterialValueModifier(wo);
            double gemMaterialMod = LootTables.getGemMaterialValueModifier(wo);
            var    value          = GetValue(tier, workmanship, gemMaterialMod, materialMod);

            wo.Value = value;

            int wield;

            if (tier > 6 && armorType != (int)LootTables.ArmorType.CovenantArmor)
            {
                wo.SetProperty(PropertyInt.WieldRequirements, (int)WieldRequirement.Level);
                wo.SetProperty(PropertyInt.WieldSkillType, (int)Skill.Axe);  // Set by examples from PCAP data

                switch (tier)
                {
                case 7:
                    wield = 150;     // In this instance, used for indicating player level, rather than skill level
                    break;

                default:
                    wield = 180;     // In this instance, used for indicating player level, rather than skill level
                    break;
                }

                wo.SetProperty(PropertyInt.WieldDifficulty, wield);
            }

            if (armorType == (int)LootTables.ArmorType.CovenantArmor)
            {
                Skill wieldSkill;

                int chance = ThreadSafeRandom.Next(1, 3);
                switch (chance)
                {
                case 1:     // Magic Def
                    wieldSkill = Skill.MagicDefense;
                    break;

                case 2:     // Missile Def
                    wieldSkill = Skill.MissileDefense;
                    break;

                default:     // Melee Def
                    wieldSkill = Skill.MeleeDefense;
                    break;
                }

                wield = GetCovenantWieldReq(tier, wieldSkill);

                wo.SetProperty(PropertyInt.WieldRequirements, (int)WieldRequirement.RawSkill);
                wo.SetProperty(PropertyInt.WieldSkillType, (int)wieldSkill);
                wo.SetProperty(PropertyInt.WieldDifficulty, wield);
            }

            // Setting random color
            wo.SetProperty(PropertyInt.PaletteTemplate, ThreadSafeRandom.Next(1, 2047));
            double shade = .1 * ThreadSafeRandom.Next(0, 9);

            wo.SetProperty(PropertyFloat.Shade, shade);

            var baseArmorLevel = wo.GetProperty(PropertyInt.ArmorLevel) ?? 0;

            if (baseArmorLevel > 0)
            {
                int adjustedArmorLevel = baseArmorLevel + GetArmorLevelModifier(tier, armorType);
                wo.SetProperty(PropertyInt.ArmorLevel, adjustedArmorLevel);
            }

            wo.SetProperty(PropertyInt.EquipmentSetId, equipSetId);

            if (isMagical)
            {
                wo.SetProperty(PropertyInt.UiEffects, (int)UiEffects.Magical);
                int numSpells = GetNumSpells(tier);

                int spellcraft = GetSpellcraft(numSpells, tier);
                wo.SetProperty(PropertyInt.ItemSpellcraft, spellcraft);
                wo.SetProperty(PropertyInt.ItemDifficulty, GetDifficulty(tier, spellcraft));

                int maxMana = GetMaxMana(numSpells, tier);
                wo.SetProperty(PropertyInt.ItemMaxMana, maxMana);
                wo.SetProperty(PropertyInt.ItemCurMana, maxMana);

                int[][] spells;
                int[][] cantrips;

                spells   = LootTables.ArmorSpells;
                cantrips = LootTables.ArmorCantrips;

                int[] shuffledValues = new int[spells.Length];
                for (int i = 0; i < spells.Length; i++)
                {
                    shuffledValues[i] = i;
                }

                Shuffle(shuffledValues);

                int minorCantrips     = GetNumMinorCantrips(tier);
                int majorCantrips     = GetNumMajorCantrips(tier);
                int epicCantrips      = GetNumEpicCantrips(tier);
                int legendaryCantrips = GetNumLegendaryCantrips(tier);
                int numCantrips       = minorCantrips + majorCantrips + epicCantrips + legendaryCantrips;

                if (numSpells - numCantrips > 0)
                {
                    for (int a = 0; a < numSpells - numCantrips; a++)
                    {
                        int col     = ThreadSafeRandom.Next(lowSpellTier - 1, highSpellTier - 1);
                        int spellID = spells[shuffledValues[a]][col];
                        wo.Biota.GetOrAddKnownSpell(spellID, wo.BiotaDatabaseLock, wo.BiotaPropertySpells, out _);
                    }
                }

                if (numCantrips > 0)
                {
                    shuffledValues = new int[cantrips.Length];
                    for (int i = 0; i < cantrips.Length; i++)
                    {
                        shuffledValues[i] = i;
                    }
                    Shuffle(shuffledValues);
                    int shuffledPlace = 0;
                    //minor cantripps
                    for (int a = 0; a < minorCantrips; a++)
                    {
                        int spellID = cantrips[shuffledValues[shuffledPlace]][0];
                        shuffledPlace++;
                        wo.Biota.GetOrAddKnownSpell(spellID, wo.BiotaDatabaseLock, wo.BiotaPropertySpells, out _);
                    }
                    //major cantrips
                    for (int a = 0; a < majorCantrips; a++)
                    {
                        int spellID = cantrips[shuffledValues[shuffledPlace]][1];
                        shuffledPlace++;
                        wo.Biota.GetOrAddKnownSpell(spellID, wo.BiotaDatabaseLock, wo.BiotaPropertySpells, out _);
                    }
                    // epic cantrips
                    for (int a = 0; a < epicCantrips; a++)
                    {
                        int spellID = cantrips[shuffledValues[shuffledPlace]][2];
                        shuffledPlace++;
                        wo.Biota.GetOrAddKnownSpell(spellID, wo.BiotaDatabaseLock, wo.BiotaPropertySpells, out _);
                    }
                    //legendary cantrips
                    for (int a = 0; a < legendaryCantrips; a++)
                    {
                        int spellID = cantrips[shuffledValues[shuffledPlace]][3];
                        shuffledPlace++;
                        wo.Biota.GetOrAddKnownSpell(spellID, wo.BiotaDatabaseLock, wo.BiotaPropertySpells, out _);
                    }
                }
            }
            else
            {
                wo.RemoveProperty(PropertyInt.ItemManaCost);
                wo.RemoveProperty(PropertyInt.ItemMaxMana);
                wo.RemoveProperty(PropertyInt.ItemCurMana);
                wo.RemoveProperty(PropertyInt.ItemSpellcraft);
                wo.RemoveProperty(PropertyInt.ItemDifficulty);
            }

            wo = RandomizeColor(wo);

            return(wo);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UniformOneGenerator"/> class.
 /// </summary>
 /// 
 /// <param name="seed">Seed value to initialize random numbers generator.</param>
 /// 
 public UniformOneGenerator( int seed )
 {
     rand = new ThreadSafeRandom( seed );
 }
        private static int GetCovenantWieldReq(int tier, Skill skill)
        {
            int index, wield;

            switch (tier)
            {
            case 3:
                index = ThreadSafeRandom.Next(1, 3);
                break;

            case 4:
                index = ThreadSafeRandom.Next(1, 4);
                break;

            case 5:
                index = ThreadSafeRandom.Next(1, 5);
                break;

            case 6:
                index = ThreadSafeRandom.Next(1, 6);
                break;

            case 7:
                index = ThreadSafeRandom.Next(1, 7);
                break;

            default:
                index = ThreadSafeRandom.Next(1, 8);
                break;
            }

            switch (skill)
            {
            case Skill.MagicDefense:
                switch (index)
                {
                case 1:
                    wield = 145;
                    break;

                case 2:
                    wield = 185;
                    break;

                case 3:
                    wield = 225;
                    break;

                case 4:
                    wield = 245;
                    break;

                case 5:
                    wield = 270;
                    break;

                case 6:
                    wield = 290;
                    break;

                case 7:
                    wield = 310;
                    break;

                default:
                    wield = 320;
                    break;
                }
                break;

            case Skill.MissileDefense:
                switch (index)
                {
                case 1:
                    wield = 160;
                    break;

                case 2:
                    wield = 205;
                    break;

                case 3:
                    wield = 245;
                    break;

                case 4:
                    wield = 270;
                    break;

                case 5:
                    wield = 290;
                    break;

                case 6:
                    wield = 305;
                    break;

                case 7:
                    wield = 330;
                    break;

                default:
                    wield = 340;
                    break;
                }
                break;

            default:
                switch (index)
                {
                case 1:
                    wield = 200;
                    break;

                case 2:
                    wield = 250;
                    break;

                case 3:
                    wield = 300;
                    break;

                case 4:
                    wield = 325;
                    break;

                case 5:
                    wield = 350;
                    break;

                case 6:
                    wield = 370;
                    break;

                case 7:
                    wield = 400;
                    break;

                default:
                    wield = 410;
                    break;
                }
                break;
            }

            return(wield);
        }