Exemplo n.º 1
0
        /// <summary>
        /// Do swipe sword effects
        /// </summary>
        /// <param name="type"></param>
        /// <param name="facingDirection"></param>
        /// <param name="c"></param>
        public void DoSwipe(int type, int facingDirection, Character c)
        {
            this.WeaponUpdate(facingDirection, 0, c);

            if (Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
            {
                c.currentLocation.localSound("dwop");
                return;
            }

            switch (type)
            {
            case 0:
            case 1:
                c.currentLocation.localSound("daggerswipe");
                break;

            case 2:
                c.currentLocation.localSound("clubswipe");
                break;

            case 3:
                c.currentLocation.localSound("swordswipe");
                break;
            }
        }
Exemplo n.º 2
0
        private void GameLoop_GameLaunched(object sender, GameLaunchedEventArgs e)
        {
            // Setup third party mod compatibility bridge
            Compat.Setup(this.Helper.ModRegistry, this.Monitor);
            IQuestApi questApi    = this.Helper.ModRegistry.GetApi <IQuestApi>("purrplingcat.questframework");
            var       storyHelper = new StoryHelper(this.ContentLoader, questApi.GetManagedApi(this.ModManifest));

            questApi.Events.GettingReady += (_, args) => storyHelper.LoadQuests(this.GameMaster);
            questApi.Events.Ready        += (_, args) => storyHelper.SanitizeOldAdventureQuestsInLog();

            // Mod's services and drivers
            this.QuestApi         = questApi;
            this.SpecialEvents    = new SpecialModEvents();
            this.DialogueDriver   = new DialogueDriver(this.Helper.Events);
            this.HintDriver       = new HintDriver(this.Helper.Events);
            this.StuffDriver      = new StuffDriver(this.Helper.Data, this.Monitor);
            this.MailDriver       = new MailDriver(this.ContentLoader, this.Monitor);
            this.GameMaster       = new GameMaster(this.Helper, storyHelper, this.Monitor);
            this.CompanionHud     = new CompanionDisplay(this.Config, this.ContentLoader);
            this.CompanionManager = new CompanionManager(this.GameMaster, this.DialogueDriver, this.HintDriver, this.CompanionHud, this.Config, this.Monitor);

            this.StuffDriver.RegisterEvents(this.Helper.Events);
            this.MailDriver.RegisterEvents(this.SpecialEvents);

            this.ApplyPatches(); // Apply harmony patches
            this.InitializeScenarios();
        }
 protected virtual Type GetType(string typeName)
 {
     if (typeName == null)
     {
         throw new ArgumentNullException("typeName");
     }
     return(Compat.GetType(typeName));
 }
Exemplo n.º 4
0
        public static void ApplyPatches()
        {
            if (Features.EnabledAtAll)
            {
                Compat.ApplyCompat(Harm);
                Pawn_TryGetAttackVerb.DoPatches(Harm);
                VerbUtilityPatches.DoPatches(Harm);
                BatteLog.DoPatches(Harm);
                VerbPatches.DoPatches(Harm);
                MiscPatches.DoBasePatches(Harm);
            }

            if (Features.HumanoidVerbs)
            {
                Brawlers.DoPatches(Harm);
                Hunting.DoPatches(Harm);
                Gizmos.DoHumanoidPatches(Harm);
            }

            if (Features.ExtraEquipmentVerbs)
            {
                Gizmos.DoExtraEquipmentPatches(Harm);
                ExtraEquipment.DoPatches(Harm);
            }

            if (Features.RangedAnimals)
            {
                Gizmos.DoAnimalPatches(Harm);
                MiscPatches.DoAnimalPatches(Harm);
            }

            if (Features.IntegratedToggle)
            {
                Gizmos.DoIntegratedTogglePatches(Harm);
            }

            if (Features.IndependentFire)
            {
                VerbPatches.DoIndependentPatches(Harm);
                IndependentVerbs.DoPatches(Harm);
            }

            if (Features.Drawing)
            {
                MiscPatches.DoDrawPatches(Harm);
            }

            if (Features.TickVerbs)
            {
                VerbPatches.DoTickPatches(Harm);
            }

            if (Features.HediffVerbs)
            {
                VerbPatches.DoHediffPatches(Harm);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Deserialize a stream
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="stream"></param>
        /// <param name="closeStream"></param>
        /// <returns></returns>
        public static T Deserialize <T>(Stream stream, bool closeStream) where T : class
        {
            object obj = Compat.Deserialize(typeof(T), stream, closeStream);

            if (obj == null)
            {
                return(default(T));
            }
            else
            {
                return((T)obj);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Deserialize content of URI
        /// </summary>
        /// <typeparam name="T">Class type to parse as</typeparam>
        /// <param name="path">URI to deserialize</param>
        /// <returns></returns>
        public static T Deserialize <T>(Uri path) where T : class
        {
            object obj = Compat.Deserialize(typeof(T), path);

            if (obj == null)
            {
                return(default(T));
            }
            else
            {
                return((T)obj);
            }
        }
Exemplo n.º 7
0
Arquivo: Base.cs Projeto: Ecu/MVCF
        public Base(ModContentPack content) : base(content)
        {
            var harm = new HarmonyLib.Harmony("legodude17.mvcf");

            harm.PatchAll(Assembly.GetExecutingAssembly());
            SearchLabel = harm.Id + Rand.Value;
            Prepatcher  = ModLister.HasActiveModWithName("Prepatcher");
            if (Prepatcher)
            {
                Log.Message("[MVCF] Prepatcher installed, switching");
            }
            Compat.ApplyCompat(harm);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Deserialize a file
        /// </summary>
        /// <typeparam name="T">What class type to parse file as</typeparam>
        /// <param name="path">Path to the file</param>
        /// <param name="gzip">Whether or not the file is gzip-compressed</param>
        /// <returns></returns>
        public static T Deserialize <T>(FileInfo path, bool gzip) where T : class
        {
            object obj = Compat.Deserialize(typeof(T), path, gzip);

            if (obj == null)
            {
                return(default(T));
            }
            else
            {
                return((T)obj);
            }
        }
        public DataSourceLoaderImpl(IQueryable<S> source, DataSourceLoadOptionsBase options) {
            var isLinqToObjects = source is EnumerableQuery;

            // Until https://github.com/aspnet/EntityFramework/issues/2341 is implemented
            // local grouping is more efficient for EF Core
            var preferLocalGrouping = Compat.IsEFCore(source.Provider);

            Builder = new DataSourceExpressionBuilder<S>(options, isLinqToObjects);
            ShouldEmptyGroups = options.HasGroups && !options.Group.Last().GetIsExpanded();
            CanUseRemoteGrouping = options.RemoteGrouping ?? !(isLinqToObjects || preferLocalGrouping);
            SummaryIsTotalCountOnly = !options.HasGroupSummary && options.HasSummary && options.TotalSummary.All(i => i.SummaryType == AggregateName.COUNT);

            Source = source;
            Options = options;
        }
Exemplo n.º 10
0
    public void shuffle()
    {
        this.newDeck();

        for (int index = 52; index != 0;)
        {
            // Select a random card
            var randomIndex = (int)Math.Floor(Compat.random() * index);
            index--;

            // Swap the current card with the random card
            var tempCard = this._cards[index];
            this._cards[index]       = this._cards[randomIndex];
            this._cards[randomIndex] = tempCard;
        }
    }
Exemplo n.º 11
0
        public void Draw(SpriteBatch spriteBatch)
        {
            if (this.weapon != null && this.weaponSwingCooldown > this.SwingThreshold && !this.defendFistUsed)
            {
                int frames       = this.weapon.type.Value == 3 ? 4 : 7;
                int duration     = this.CooldownTimeout - this.SwingThreshold;
                int tick         = Math.Abs(this.weaponSwingCooldown - this.CooldownTimeout);
                int currentFrame = this.CurrentFrame(tick, duration, frames);

                if (Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
                {
                    currentFrame = 1;
                }

                Helper.DrawDuringUse(currentFrame, this.follower.FacingDirection, spriteBatch, this.follower.getLocalPosition(Game1.viewport), this.follower, MeleeWeapon.getSourceRect(this.weapon.InitialParentTileIndex), this.weapon.type.Value, this.weapon.isOnSpecial);
            }
        }
Exemplo n.º 12
0
        public FightController(AI_StateMachine ai, IContentLoader content, IModEvents events, int sword) : base(ai)
        {
            this.attackRadius             = 1.25f * Game1.tileSize;
            this.backupRadius             = 0.9f * Game1.tileSize;
            this.realLeader               = ai.player;
            this.leader                   = null;
            this.pathFinder.GoalCharacter = null;
            this.events                   = events;
            this.weapon                   = this.GetSword(sword);
            this.bubbles                  = content.LoadStrings("Strings/SpeechBubbles");
            this.fightSpeechTriggerThres  = ai.Csm.HasSkill("warrior") ? 0.25 : 0.7;

            if (Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
            {
                this.kissFrames = this.ai.ContentLoader.LoadData <string, string>("Data/FightFrames");
            }

            this.attackAnimation = new List <FarmerSprite.AnimationFrame>[4]
            {
                // Up
                new List <FarmerSprite.AnimationFrame>()
                {
                    new FarmerSprite.AnimationFrame(8, 100),
                    new FarmerSprite.AnimationFrame(9, 250),
                },
                // Right
                new List <FarmerSprite.AnimationFrame>()
                {
                    new FarmerSprite.AnimationFrame(6, 100),
                    new FarmerSprite.AnimationFrame(7, 250),
                },
                // Down
                new List <FarmerSprite.AnimationFrame>()
                {
                    new FarmerSprite.AnimationFrame(0, 100),
                    new FarmerSprite.AnimationFrame(1, 250),
                },
                // Left
                new List <FarmerSprite.AnimationFrame>()
                {
                    new FarmerSprite.AnimationFrame(14, 100),
                    new FarmerSprite.AnimationFrame(15, 250),
                },
            };
        }
Exemplo n.º 13
0
        private void GiveLove()
        {
            for (int i = 0; i < this.lovedMonsters.Count; i++)
            {
                if (this.lovedMonsters[i].TTL <= 0)
                {
                    this.lovedMonsters[i].RevokeLove();

                    if (this.lovedMonsters[i].TTL < -this.lovedMonsters[i].LoveInvicibility)
                    {
                        this.lovedMonsters.RemoveAt(i--);
                    }

                    continue;
                }

                if (!Compat.IsModLoaded(ModUids.PACIFISTMOD_UID) && this.lovedMonsters[i].LastHealth != this.lovedMonsters[i].Monster.Health)
                {
                    int lostPoints = 10;

                    this.follower.doEmote(12);

                    if (this.lovedMonsters[i].Monster.Health <= 0)
                    {
                        lostPoints = 75;

                        if (DialogueProvider.GetBubbleString(this.bubbles, this.follower, "spiritualKilledMonster", out string bubble))
                        {
                            this.follower.showTextAboveHead(bubble);
                        }
                    }

                    if (this.leader is Farmer farmer)
                    {
                        farmer.changeFriendship(-lostPoints, this.follower);
                    }
                }

                this.lovedMonsters[i].AcceptLove();
            }
        }
        public static void AddVerbs(this VerbManager man, ThingWithComps eq)
        {
            if (man == null)
            {
                return;
            }
            if (Base.IsIgnoredMod(eq?.def?.modContentPack?.Name))
            {
                return;
            }
            if (Compat.ShouldIgnore(eq))
            {
                return;
            }
            var comp = eq.TryGetComp <CompEquippable>();

            if (comp?.VerbTracker?.AllVerbs == null)
            {
                return;
            }
            if (!Base.Features.ExtraEquipmentVerbs && !Base.IgnoredFeatures.ExtraEquipmentVerbs &&
                comp.VerbTracker.AllVerbs.Count(v => !v.IsMeleeAttack) > 1)
            {
                Log.ErrorOnce(
                    "[MVCF] Found equipment with more than one ranged attack while that feature is not enabled. Enabling now. This is not recommend. Contact the author of " +
                    eq?.def?.modContentPack?.Name + " and ask them to add a MVCF.ModDef.",
                    eq?.def?.modContentPack?.Name?.GetHashCode() ?? -1);
                Base.Features.ExtraEquipmentVerbs = true;
                Base.ApplyPatches();
            }

            foreach (var verb in comp.VerbTracker.AllVerbs)
            {
                man.AddVerb(verb, VerbSource.Equipment, comp.props is CompProperties_VerbProps props
                    ? props.PropsFor(verb)
                    : eq.TryGetComp <Comp_VerbProps>()?.Props?.PropsFor(verb));
            }
        }
Exemplo n.º 15
0
        private void DoFightSpeak(bool onlyEmote = false)
        {
            // Cooldown not expired? Say nothing
            if (this.fightBubbleCooldown != 0)
            {
                return;
            }

            if (!onlyEmote && Game1.random.NextDouble() < this.fightSpeechTriggerThres && DialogueProvider.GetBubbleString(this.bubbles, this.follower, "fight", out string text))
            {
                bool isRed = this.ai.Csm.HasSkill("warrior") && Game1.random.NextDouble() < 0.1;
                this.follower.showTextAboveHead(text, isRed ? 2 : -1);
                this.fightBubbleCooldown = 600;
            }
            else if (this.ai.Csm.HasSkill("warrior") && Game1.random.NextDouble() < this.fightSpeechTriggerThres / 2)
            {
                if (Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
                {
                    return;
                }

                this.follower.clearTextAboveHead();
                this.follower.doEmote(12);
                this.fightBubbleCooldown = 550;
            }
            else if (Game1.random.NextDouble() > (this.fightSpeechTriggerThres + this.fightSpeechTriggerThres * .33f))
            {
                if (Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
                {
                    return;
                }

                this.follower.clearTextAboveHead();
                this.follower.doEmote(16);
                this.fightBubbleCooldown = 500;
            }
        }
Exemplo n.º 16
0
        public override bool OnTouchEvent(MotionEvent e)
        {
            MotionEventActions action = e.Action;

            switch (action & MotionEventActions.Mask)
            {
            case MotionEventActions.Down:
                _activePointerId = e.GetPointerId(0);
                break;

            case MotionEventActions.Cancel:
            case MotionEventActions.Up:
                _activePointerId = INVALID_POINTER_ID;
                break;

            case MotionEventActions.PointerUp:
                // Ignore deprecation, ACTION_POINTER_ID_MASK and
                // ACTION_POINTER_ID_SHIFT has same value and are deprecated
                // You can have either deprecation or lint target api warning
                int pointerIndex = Compat.GetPointerIndex(e.Action);
                int pointerId    = e.GetPointerId(pointerIndex);
                if (pointerId == _activePointerId)
                {
                    // This was our active pointer going up. Choose a new
                    // active pointer and adjust accordingly.
                    int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                    _activePointerId = e.GetPointerId(newPointerIndex);
                    LastTouchX       = e.GetX(newPointerIndex);
                    LastTouchY       = e.GetY(newPointerIndex);
                }
                break;
            }

            _activePointerIndex = e.FindPointerIndex(_activePointerId != INVALID_POINTER_ID ? _activePointerId : 0);

            return(base.OnTouchEvent(e));
        }
Exemplo n.º 17
0
        private static void After_drawCharacters(GameLocation __instance, SpriteBatch b)
        {
            if (__instance.shouldHideCharacters() || Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
            {
                return;
            }
            if (!Game1.eventUp)
            {
                for (int i = 0; i < __instance.characters.Count; i++)
                {
                    if (__instance.characters[i] != null)
                    {
                        NPC npc = __instance.characters[i];
                        if (npc is Monster && npc.IsEmoting)
                        {
                            Vector2 emotePosition = npc.getLocalPosition(Game1.viewport);
                            emotePosition.Y -= (32 + npc.Sprite.SpriteHeight * 4);

                            b.Draw(Game1.emoteSpriteSheet, emotePosition, new Rectangle(npc.CurrentEmoteIndex * 16 % Game1.emoteSpriteSheet.Width, npc.CurrentEmoteIndex * 16 / Game1.emoteSpriteSheet.Width * 16, 16, 16), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, (float)npc.getStandingY() / 10000f);
                        }
                    }
                }
            }
        }
        public static void AddVerbs(this VerbManager man, Apparel apparel)
        {
            if (man == null)
            {
                return;
            }
            if (Base.IsIgnoredMod(apparel?.def?.modContentPack?.Name))
            {
                return;
            }
            if (Compat.ShouldIgnore(apparel))
            {
                return;
            }
            var comp = apparel.TryGetComp <Comp_VerbGiver>();

            if (comp?.VerbTracker?.AllVerbs == null)
            {
                return;
            }
            if (!Base.Features.ApparelVerbs && !Base.IgnoredFeatures.ApparelVerbs)
            {
                Log.ErrorOnce(
                    "[MVCF] Found apparel with a verb while that feature is not enabled. Enabling now. This is not recommend. Contact the author of " +
                    apparel?.def?.modContentPack?.Name + " and ask them to add a MVCF.ModDef.",
                    apparel?.def?.modContentPack?.Name?.GetHashCode() ?? -1);
                Base.Features.ApparelVerbs = true;
                Base.ApplyPatches();
            }

            comp.Notify_Worn(man.Pawn);
            foreach (var verb in comp.VerbTracker.AllVerbs)
            {
                man.AddVerb(verb, VerbSource.Apparel, comp.PropsFor(verb));
            }
        }
Exemplo n.º 19
0
        public static bool DamageMonsterByCompanion(
            this GameLocation location,
            Rectangle areaOfEffect,
            int minDamage,
            int maxDamage,
            float knockBackModifier,
            int addedPrecision,
            float critChance,
            float critMultiplier,
            bool triggerMonsterInvincibleTimer,
            Character who,
            Farmer leader)
        {
            if (Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
            {
                return(CuddleMonster(location, areaOfEffect, minDamage, maxDamage, false, knockBackModifier, addedPrecision, critChance, critMultiplier, triggerMonsterInvincibleTimer, who, leader));
            }

            bool flag1 = false;

            for (int j = location.characters.Count - 1; j >= 0; j--)
            {
                if (
                    j < location.characters.Count && location.characters[j].GetBoundingBox().Intersects(areaOfEffect) &&
                    location.characters[j].IsMonster &&
                    ((Monster)location.characters[j]).Health > 0 &&
                    !location.characters[j].IsInvisible &&
                    !(location.characters[j] as Monster).isInvincible())
                {
                    flag1 = true;
                    Microsoft.Xna.Framework.Rectangle boundingBox = location.characters[j].GetBoundingBox();
                    Vector2 trajectory = Helper.GetAwayFromCharacterTrajectory(boundingBox, who);
                    if (knockBackModifier > 0.0)
                    {
                        trajectory *= knockBackModifier;
                    }
                    else
                    {
                        trajectory = new Vector2(location.characters[j].xVelocity, location.characters[j].yVelocity);
                    }
                    if ((location.characters[j] as Monster).Slipperiness == -1)
                    {
                        trajectory = Vector2.Zero;
                    }
                    bool flag3 = false;
                    int  number;
                    if (maxDamage >= 0)
                    {
                        int num = Game1.random.Next(minDamage, maxDamage + 1);
                        if (who != null && Game1.random.NextDouble() < (double)critChance + (double)leader.LuckLevel * ((double)critChance / 40.0))
                        {
                            flag3 = true;
                            location.playSound("crit");
                        }
                        int damage = Math.Max(1, (flag3 ? (int)((double)num * (double)critMultiplier) : num) + (who != null ? leader.attack * 3 : 0));
                        number = ((Monster)location.characters[j]).takeDamage(damage, (int)trajectory.X, (int)trajectory.Y, false, (double)addedPrecision / 10.0, leader);

                        if (number == -1)
                        {
                            location.debris.Add(new Debris("Miss", 1, new Vector2(boundingBox.Center.X, (float)boundingBox.Center.Y), Color.LightGray, 1f, 0.0f));
                        }
                        else
                        {
                            location.debris.Filter(d =>
                            {
                                if (d.toHover != null && d.toHover.Equals((object)location.characters[j]) && !d.nonSpriteChunkColor.Equals(Color.Yellow))
                                {
                                    return((double)d.timeSinceDoneBouncing <= 900.0);
                                }
                                return(true);
                            });
                            location.debris.Add(new Debris(number, new Vector2((float)(boundingBox.Center.X + 16), (float)boundingBox.Center.Y), flag3 ? Color.Yellow : new Color((int)byte.MaxValue, 130, 0), flag3 ? (float)(1.0 + (double)number / 300.0) : 1f, location.characters[j]));
                        }
                        if (triggerMonsterInvincibleTimer)
                        {
                            (location.characters[j] as Monster).setInvincibleCountdown(450 / 2);
                        }
                    }
                    else
                    {
                        number = -2;
                        location.characters[j].setTrajectory(trajectory);
                        if (((Monster)location.characters[j]).Slipperiness > 10)
                        {
                            location.characters[j].xVelocity /= 2f;
                            location.characters[j].yVelocity /= 2f;
                        }
                    }
                    if (((Monster)location.characters[j]).Health <= 0)
                    {
                        if (!location.IsFarm)
                        {
                            leader.checkForQuestComplete((NPC)null, 1, 1, (Item)null, location.characters[j].Name, 4, -1);
                        }
                        Monster character = location.characters[j] as Monster;
                        location.monsterDrop(character, boundingBox.Center.X, boundingBox.Center.Y, leader);
                        location.characters.Remove(character);
                        ++Game1.stats.MonstersKilled;
                        Game1.stats.monsterKilled(character.Name);
                    }
                    else if (number > 0)
                    {
                        ((Monster)location.characters[j]).shedChunks(Game1.random.Next(1, 3));
                        if (flag3)
                        {
                            location.temporarySprites.Add(new TemporaryAnimatedSprite(362, (float)Game1.random.Next(15, 50), 6, 1, location.characters[j].getStandingPosition() - new Vector2(32f, 32f), false, Game1.random.NextDouble() < 0.5)
                            {
                                scale = 0.75f,
                                alpha = flag3 ? 0.75f : 0.5f
                            });
                            location.temporarySprites.Add(new TemporaryAnimatedSprite(362, (float)Game1.random.Next(15, 50), 6, 1, location.characters[j].getStandingPosition() - new Vector2((float)(32 + Game1.random.Next(-21, 21) + 32), (float)(32 + Game1.random.Next(-21, 21))), false, Game1.random.NextDouble() < 0.5)
                            {
                                scale = 0.5f,
                                delayBeforeAnimationStart = 50,
                                alpha = flag3 ? 0.75f : 0.5f
                            });
                            location.temporarySprites.Add(new TemporaryAnimatedSprite(362, (float)Game1.random.Next(15, 50), 6, 1, location.characters[j].getStandingPosition() - new Vector2((float)(32 + Game1.random.Next(-21, 21) - 32), (float)(32 + Game1.random.Next(-21, 21))), false, Game1.random.NextDouble() < 0.5)
                            {
                                scale = 0.5f,
                                delayBeforeAnimationStart = 100,
                                alpha = flag3 ? 0.75f : 0.5f
                            });
                            location.temporarySprites.Add(new TemporaryAnimatedSprite(362, (float)Game1.random.Next(15, 50), 6, 1, location.characters[j].getStandingPosition() - new Vector2((float)(32 + Game1.random.Next(-21, 21) + 32), (float)(32 + Game1.random.Next(-21, 21))), false, Game1.random.NextDouble() < 0.5)
                            {
                                scale = 0.5f,
                                delayBeforeAnimationStart = 150,
                                alpha = flag3 ? 0.75f : 0.5f
                            });
                            location.temporarySprites.Add(new TemporaryAnimatedSprite(362, (float)Game1.random.Next(15, 50), 6, 1, location.characters[j].getStandingPosition() - new Vector2((float)(32 + Game1.random.Next(-21, 21) - 32), (float)(32 + Game1.random.Next(-21, 21))), false, Game1.random.NextDouble() < 0.5)
                            {
                                scale = 0.5f,
                                delayBeforeAnimationStart = 200,
                                alpha = flag3 ? 0.75f : 0.5f
                            });
                        }
                    }
                }
            }

            return(flag1);
        }
Exemplo n.º 20
0
 /// <summary>
 /// Serialize a class to a file
 /// </summary>
 /// <typeparam name="T">Class type to serialize</typeparam>
 /// <param name="Path"></param>
 /// <param name="Obj"></param>
 /// <param name="GZip">Whether or not the saved file should be GZipped</param>
 /// <returns></returns>
 public static bool Serialize <T>(FileInfo Path, T Obj, bool GZip) where T : class
 {
     return(Compat.Serialize(typeof(T), Path, Obj, GZip));
 }
Exemplo n.º 21
0
 /// <summary>
 /// Serializes an object into an already opened stream
 /// </summary>
 /// <typeparam name="T">Class type to serialize class as</typeparam>
 /// <param name="Stream">Stream to serialize into</param>
 /// <param name="Obj">Class to serialize</param>
 public static bool Serialize <T>(Stream Stream, object Obj, bool CloseStream) where T : class
 {
     return(Compat.Serialize(typeof(T), Stream, Obj, CloseStream));
 }
Exemplo n.º 22
0
 public static T Deserialize <T>(string xml, Encoding encoding)
     where T : class
 {
     return((T)Compat.Deserialize(typeof(T), xml, encoding));
 }
        public LoadResult Load() {
            if(Options.IsCountQuery)
                return new LoadResult { totalCount = ExecCount() };

            var result = new LoadResult();

            if(CanUseRemoteGrouping && ShouldEmptyGroups) {
                var groupingResult = ExecRemoteGrouping();

                EmptyGroups(groupingResult.Groups, Options.Group.Length);

                result.data = Paginate(groupingResult.Groups, Options.Skip, Options.Take);
                result.summary = groupingResult.Totals;
                result.totalCount = groupingResult.TotalCount;

                if(Options.RequireGroupCount)
                    result.groupCount = groupingResult.Groups.Count();
            } else {
                if(!Options.HasPrimaryKey)
                    Options.PrimaryKey = Utils.GetPrimaryKey(typeof(S));

                if(!Options.HasPrimaryKey && (Options.Skip > 0 || Options.Take > 0) && Compat.IsEntityFramework(Source.Provider))
                    Options.DefaultSort = EFSorting.FindSortableMember(typeof(S));

                var deferPaging = Options.HasGroups || !CanUseRemoteGrouping && !SummaryIsTotalCountOnly && Options.HasSummary;
                var loadExpr = Builder.BuildLoadExpr(Source.Expression, !deferPaging);

                if(Options.HasAnySelect) {
                    ContinueWithGrouping(
                        ExecWithSelect(loadExpr).Select(ProjectionToDict),
                        Accessors.Dict,
                        result
                    );
                } else {
                    ContinueWithGrouping(
                        ExecExpr<S>(Source, loadExpr),
                        new DefaultAccessor<S>(),
                        result
                    );
                }

                if(deferPaging)
                    result.data = Paginate(result.data, Options.Skip, Options.Take);

                if(ShouldEmptyGroups)
                    EmptyGroups(result.data, Options.Group.Length);
            }

            return result;
        }
Exemplo n.º 24
0
 /// <summary>
 /// Serializes an object into an already opened stream
 /// </summary>
 /// <typeparam name="T">Class type to serialize class as</typeparam>
 /// <param name="stream">Stream to serialize into</param>
 /// <param name="obj">Class to serialize</param>
 public static bool Serialize <T>(Stream stream, object obj, bool closeStream) where T : class
 {
     return(Compat.Serialize(typeof(T), stream, obj, closeStream));
 }
Exemplo n.º 25
0
        /// <summary>
        /// Try to give damage to a monster
        /// </summary>
        private void DoDamage(bool criticalFist = false)
        {
            if (this.leader == null)
            {
                return;
            }

            Rectangle effectiveArea = this.follower.GetBoundingBox();
            Rectangle enemyBox      = this.leader.GetBoundingBox();
            Rectangle companionBox  = this.follower.GetBoundingBox();

            this.weaponAttrs = new WeaponAttributes(criticalFist ? null : this.weapon);

            if (criticalFist)
            {
                this.weaponAttrs.knockBack   *= 1.7f;
                this.weaponAttrs.smashAround /= 2f;
                this.fistCoolDown             = 240;
            }

            if (this.ai.Csm.HasSkill("warrior"))
            {
                // Enhanced skills ONLY for WARRIORS
                this.weaponAttrs.minDamage          += (int)Math.Round(this.weaponAttrs.minDamage * .02f);           // 2% added min damage
                this.weaponAttrs.knockBack          += this.weaponAttrs.knockBack * (Game1.random.Next(1, 3) / 100); // 1-3% added knock back
                this.weaponAttrs.addedEffectiveArea += (int)Math.Round(this.weaponAttrs.addedEffectiveArea * .01f);  // 1% added effective area
                this.weaponAttrs.critChance         += Math.Max(0, (float)Game1.player.DailyLuck / 2);               // added critical chance is half of daily luck. If luck is negative, no added critical chance
            }

            if (criticalFist && this.follower.FacingDirection != 0)
            {
                if (!Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
                {
                    this.follower.currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite("TileSheets\\animations", new Rectangle(0, 960, 128, 128), 60f, 4, 0, this.follower.Position, false, this.follower.FacingDirection == 3, 1f, 0.0f, Color.White, .5f, 0.0f, 0.0f, 0.0f, false));
                }
                else
                {
                    this.follower.currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Rectangle(211, 428, 7, 6), 2000f, 1, 0, new Vector2((float)this.follower.getTileX(), (float)this.follower.getTileY()) * 64f + new Vector2(16f, -64f), false, false, 1f, 0.0f, Color.White, 4f, 0.0f, 0.0f, 0.0f, false)
                    {
                        motion    = new Vector2(0.0f, -0.5f),
                        alphaFade = 0.01f
                    });
                }
            }

            companionBox.Inflate(4, 4); // Personal space
            effectiveArea.Inflate((int)(effectiveArea.Width * this.weaponAttrs.smashAround + this.weaponAttrs.addedEffectiveArea), (int)(effectiveArea.Height * this.weaponAttrs.smashAround + this.weaponAttrs.addedEffectiveArea));

            if (Compat.IsModLoaded(ModUids.PACIFISTMOD_UID))
            {
                int  frame = -1;
                bool flip  = false;

                if (this.kissFrames.ContainsKey(this.follower.Name))
                {
                    frame = int.Parse(this.kissFrames[this.follower.Name].Split(' ')[0]);
                    flip  = this.kissFrames[this.follower.Name].Split(' ')[1] == "true";
                }

                this.follower.doEmote(20);
            }

            if (!criticalFist && !this.defendFistUsed && this.ai.Csm.HasSkill("warrior") && companionBox.Intersects(enemyBox) && this.weaponSwingCooldown == this.CooldownTimeout && this.fistCoolDown <= 0)
            {
                this.ai.Monitor.Log("Critical dangerous: Using defense fists!");
                this.defendFistUsed = true;
                this.DoDamage(true); // Force fist when monster is too close
                return;
            }

            if (this.follower.currentLocation.DamageMonsterByCompanion(effectiveArea, this.weaponAttrs.minDamage, this.weaponAttrs.maxDamage,
                                                                       this.weaponAttrs.knockBack, this.weaponAttrs.addedPrecision, this.weaponAttrs.critChance, this.weaponAttrs.critMultiplier, !criticalFist,
                                                                       this.follower, this.realLeader as Farmer))
            {
                if (criticalFist)
                {
                    this.follower.currentLocation.playSound(Compat.IsModLoaded(ModUids.PACIFISTMOD_UID) ? "dwop" : "clubSmash");
                    this.ai.Csm.CompanionManager.Hud.GlowSkill("warrior", Color.Red, 1);
                    this.fistCoolDown = 1200;
                }

                if (criticalFist || (Game1.random.NextDouble() > .7f && Game1.random.NextDouble() < .3f))
                {
                    this.DoFightSpeak();
                }
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Serialize a class to a file
 /// </summary>
 /// <typeparam name="T">Class type to serialize</typeparam>
 /// <param name="path"></param>
 /// <param name="obj"></param>
 /// <param name="gzip">Whether or not the saved file should be GZipped</param>
 /// <returns></returns>
 public static bool Serialize <T>(FileInfo path, T obj, bool gzip) where T : class
 {
     return(Compat.Serialize(typeof(T), path, obj, gzip));
 }
        public static object Load <T>(IQueryable <T> source, DataSourceLoadOptionsBase options)
        {
            var isLinqToObjects = source is EnumerableQuery;
            var builder         = new DataSourceExpressionBuilder <T>(options, isLinqToObjects);

            if (options.IsCountQuery)
            {
                return(builder.BuildCountExpr().Compile()(source));
            }

            var accessor             = new DefaultAccessor <T>();
            var result               = new DataSourceLoadResult();
            var emptyGroups          = options.HasGroups && !options.Group.Last().GetIsExpanded();
            var canUseRemoteGrouping = options.RemoteGrouping.HasValue ? options.RemoteGrouping.Value : !isLinqToObjects;

            if (canUseRemoteGrouping && emptyGroups)
            {
                var groupingResult = ExecRemoteGrouping(source, builder, options);

                EmptyGroups(groupingResult.Groups, options.Group.Length);

                result.data       = Paginate(groupingResult.Groups, options.Skip, options.Take);
                result.summary    = groupingResult.Totals;
                result.totalCount = groupingResult.TotalCount;

                if (options.RequireGroupCount)
                {
                    result.groupCount = groupingResult.Groups.Count();
                }
            }
            else
            {
                if (!options.HasPrimaryKey)
                {
                    options.PrimaryKey = Utils.GetPrimaryKey(typeof(T));
                }

                if (!options.HasPrimaryKey && (options.Skip > 0 || options.Take > 0) && Compat.IsEntityFramework(source.Provider))
                {
                    options.DefaultSort = EFSorting.FindSortableMember(typeof(T));
                }

                var deferPaging = options.HasGroups || options.HasSummary && !canUseRemoteGrouping;
                var queryResult = ExecQuery(builder.BuildLoadExpr(!deferPaging).Compile(), source, options);

                IEnumerable data = queryResult;

                if (options.HasGroups)
                {
                    data = new GroupHelper <T>(accessor).Group(queryResult, options.Group);
                    if (options.RequireGroupCount)
                    {
                        result.groupCount = (data as IList).Count;
                    }
                }

                if (canUseRemoteGrouping && options.HasSummary && !options.HasGroups)
                {
                    var groupingResult = ExecRemoteGrouping(source, builder, options);
                    result.totalCount = groupingResult.TotalCount;
                    result.summary    = groupingResult.Totals;
                }
                else
                {
                    if (options.RequireTotalCount)
                    {
                        result.totalCount = builder.BuildCountExpr().Compile()(source);
                    }

                    if (options.HasSummary)
                    {
                        data           = Buffer <T>(data);
                        result.summary = new AggregateCalculator <T>(data, accessor, options.TotalSummary, options.GroupSummary).Run();
                    }
                }

                if (deferPaging)
                {
                    data = Paginate(data, options.Skip, options.Take);
                }

                if (emptyGroups)
                {
                    EmptyGroups(data, options.Group.Length);
                }

                result.data = data;
            }

            if (result.IsDataOnly())
            {
                return(result.data);
            }

            return(result);
        }
Exemplo n.º 28
0
        public LoadResult Load()
        {
            if (Options.IsCountQuery)
            {
                return new LoadResult {
                           totalCount = ExecCount()
                }
            }
            ;

            var result = new LoadResult();

            if (CanUseRemoteGrouping && ShouldEmptyGroups)
            {
                var groupingResult = ExecRemoteGrouping();

                EmptyGroups(groupingResult.Groups, Options.Group.Length);

                result.data       = Paginate(groupingResult.Groups, Options.Skip, Options.Take);
                result.summary    = groupingResult.Totals;
                result.totalCount = groupingResult.TotalCount;

                if (Options.RequireGroupCount)
                {
                    result.groupCount = groupingResult.Groups.Count();
                }
            }
            else
            {
                if (!Options.HasPrimaryKey)
                {
                    Options.PrimaryKey = Utils.GetPrimaryKey(typeof(S));
                }

                if (!Options.HasPrimaryKey && !Options.HasDefaultSort && (Options.Skip > 0 || Options.Take > 0))
                {
                    if (Compat.IsEntityFramework(Source.Provider))
                    {
                        Options.DefaultSort = EFSorting.FindSortableMember(typeof(S));
                    }
                    else if (Compat.IsXPO(Source.Provider))
                    {
                        Options.DefaultSort = "this";
                    }
                }

                var deferPaging = Options.HasGroups || !CanUseRemoteGrouping && !SummaryIsTotalCountOnly && Options.HasSummary;
                var loadExpr    = Builder.BuildLoadExpr(Source.Expression, !deferPaging);

                if (Options.HasAnySelect)
                {
                    ContinueWithGrouping(
                        ExecWithSelect(loadExpr).Select(ProjectionToExpando),
                        result
                        );
                }
                else
                {
                    ContinueWithGrouping(
                        ExecExpr <S>(Source, loadExpr),
                        result
                        );
                }

                if (deferPaging)
                {
                    result.data = Paginate(result.data, Options.Skip, Options.Take);
                }

                if (ShouldEmptyGroups)
                {
                    EmptyGroups(result.data, Options.Group.Length);
                }
            }

            return(result);
        }

        IEnumerable <AnonType> ExecWithSelect(Expression loadExpr)
        {
            if (Options.UseRemoteSelect)
            {
                return(ExecExpr <AnonType>(Source, loadExpr));
            }

            var inMemoryQuery = ForceExecution(ExecExpr <S>(Source, loadExpr)).AsQueryable();
            var selectExpr    = new SelectExpressionCompiler <S>(true).Compile(inMemoryQuery.Expression, Options.GetFullSelect());

            return(ExecExpr <AnonType>(inMemoryQuery, selectExpr));
        }

        void ContinueWithGrouping <R>(IEnumerable <R> loadResult, LoadResult result)
        {
            var accessor = new DefaultAccessor <R>();

            if (Options.HasGroups)
            {
                var groups = new GroupHelper <R>(accessor).Group(loadResult, Options.Group);
                if (Options.RequireGroupCount)
                {
                    result.groupCount = groups.Count;
                }
                ContinueWithAggregation(groups, accessor, result);
            }
            else
            {
                ContinueWithAggregation(loadResult, accessor, result);
            }
        }

        void ContinueWithAggregation <R>(IEnumerable data, IAccessor <R> accessor, LoadResult result)
        {
            if (CanUseRemoteGrouping && !SummaryIsTotalCountOnly && Options.HasSummary && !Options.HasGroups)
            {
                var groupingResult = ExecRemoteGrouping();
                result.totalCount = groupingResult.TotalCount;
                result.summary    = groupingResult.Totals;
            }
            else
            {
                var totalCount = -1;

                if (Options.RequireTotalCount || SummaryIsTotalCountOnly)
                {
                    totalCount = ExecCount();
                }

                if (Options.RequireTotalCount)
                {
                    result.totalCount = totalCount;
                }

                if (SummaryIsTotalCountOnly)
                {
                    result.summary = Enumerable.Repeat((object)totalCount, Options.TotalSummary.Length).ToArray();
                }
                else if (Options.HasSummary)
                {
                    data           = Buffer <R>(data);
                    result.summary = new AggregateCalculator <R>(data, accessor, Options.TotalSummary, Options.GroupSummary).Run();
                }
            }

            result.data = data;
        }

        int ExecCount()
        {
            var expr = Builder.BuildCountExpr(Source.Expression);

#if DEBUG
            Options.ExpressionWatcher?.Invoke(expr);
#endif
            return(Source.Provider.Execute <int>(expr));
        }

        RemoteGroupingResult ExecRemoteGrouping()
        {
            return(RemoteGroupTransformer.Run(
                       ExecExpr <AnonType>(Source, Builder.BuildLoadGroupsExpr(Source.Expression)),
                       Options.HasGroups ? Options.Group.Length : 0,
                       Options.TotalSummary,
                       Options.GroupSummary
                       ));
        }

        IEnumerable <R> ExecExpr <R>(IQueryable <S> source, Expression expr)
        {
            IEnumerable <R> result = source.Provider.CreateQuery <R>(expr);

#if DEBUG
            if (Options.UseEnumerableOnce)
            {
                result = new EnumerableOnce <R>(result);
            }

            Options.ExpressionWatcher?.Invoke(expr);
#endif

            return(result);
        }