public override string ToString()
        {
            s = (Rand)base.Tag;

            Binding myBinding = new Binding("result");
            myBinding.Mode = BindingMode.TwoWay;
            myBinding.Source = s;
            txtres.SetBinding(TextBox.TextProperty, myBinding);

            Binding myBinding2 = new Binding("min");
            myBinding2.Mode = BindingMode.TwoWay;
            myBinding2.Source = s;
            txtmin.SetBinding(TextBox.TextProperty, myBinding2);

            Binding myBinding3 = new Binding("max");
            myBinding3.Mode = BindingMode.TwoWay;
            myBinding3.Source = s;
            txtmax.SetBinding(TextBox.TextProperty, myBinding3);

            Binding descbinding = new Binding("Description");
            descbinding.Mode = BindingMode.TwoWay;
            descbinding.Source = s;
            txtdesc.SetBinding(TextBox.TextProperty, descbinding);

            return base.ToString();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates a new Deck with the initial set of cards, and shuffles them using the specified random number generator.
        /// </summary>
        public Deck(Rand rand)
        {
            if(rand == null)
                throw new ArgumentNullException("rand");

            _rand = rand;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates a new Game that uses the specified random number generator.
        /// </summary>
        public Game(Rand rand)
        {
            if(rand == null)
                throw new ArgumentNullException("rand");

            _rand = rand;
            _deck = new Deck(_rand);
            _board = new Board();

            InitializeBoard();

            _prevBoard = new Board(_board);
            _tempBoard = new Board();
        }
Ejemplo n.º 4
0
    private int SIZE = 1; // number of blocks accross (min = 1, max = 128)

    #endregion Fields

    #region Constructors

    public Chunk(int _world_x, int _world_z)
    {
        name = string.Format("Chunk [{0},{1}]",_world_x, _world_z);
        go = new GameObject(name);

        mesh_filter = go.AddComponent<MeshFilter>();
        mesh_renderer = go.AddComponent<MeshRenderer>();
        mesh_collider = go.AddComponent<MeshCollider>();

        // initialize properties
        world_x = _world_x;
        world_z = _world_z;
        heights = new int[SIZE+1, SIZE+1];

        // need a RNG for each corner
        Rand rand_00 = new Rand((GLOBAL_SEED << 12) ^ ((world_x-1) << 8) ^ ((world_z-1) << 4));
        Rand rand_10 = new Rand((GLOBAL_SEED << 12) ^ (world_x << 8) ^ ((world_z-1) << 4));
        Rand rand_01 = new Rand((GLOBAL_SEED << 12) ^ ((world_x-1) << 8) ^ (world_z << 4));
        Rand rand_11 = new Rand((GLOBAL_SEED << 12) ^ (world_x << 8) ^ (world_z << 4));
        if(rand_00.nextf() < noisiness * corner_proclivity){
            heights[0,0] += (rand_00.next() & 1)*2 - 1;
        }
        if(rand_10.nextf() < noisiness * corner_proclivity){
            heights[SIZE,0] += (rand_10.next() & 1)*2 - 1;
        }
        if(rand_01.nextf() < noisiness * corner_proclivity){
            heights[0,SIZE] += (rand_01.next() & 1)*2 - 1;
        }
        if(rand_11.nextf() < noisiness * corner_proclivity){
            heights[SIZE,SIZE] += (rand_11.next() & 1)*2 - 1;
        }
        Initialize(true);
        // put in correct position
        go.transform.Translate(SIZE_RX * (world_x-0.5f), 0, SIZE_RZ * (world_z-0.5f) + (world_x-0.5f)*0.577350269189626f*SIZE_RX);
        // add collider
    }
Ejemplo n.º 5
0
        protected override bool TryCastShot()
        {
            Pawn caster = base.CasterPawn;
            Pawn pawn   = this.currentTarget.Thing as Pawn;

            MagicPowerSkill pwr = caster.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_CureDisease.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_CureDisease_pwr");
            MagicPowerSkill ver = caster.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_CureDisease.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_CureDisease_ver");

            verVal         = ver.level;
            pwrVal         = pwr.level;
            this.arcaneDmg = caster.GetComp <CompAbilityUserMagic>().arcaneDmg;
            if (caster.story.traits.HasTrait(TorannMagicDefOf.Faceless))
            {
                MightPowerSkill mpwr = caster.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                MightPowerSkill mver = caster.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                pwrVal = mpwr.level;
                verVal = mver.level;
            }
            bool flag = pawn != null;

            if (flag)
            {
                int   num           = 1;
                float sevAdjustment = 0;
                if (pwrVal >= 2)
                {
                    //apply immunity buff, 60k ticks in a day
                    if (pwrVal == 3)
                    {
                        HealthUtility.AdjustSeverity(pawn, TorannMagicDefOf.TM_DiseaseImmunity2HD, 5);
                        pawn.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_DiseaseImmunity2HD).TryGetComp <HediffComp_DiseaseImmunity>().verVal = verVal;
                    }
                    else
                    {
                        HealthUtility.AdjustSeverity(pawn, TorannMagicDefOf.TM_DiseaseImmunityHD, 3);
                    }
                }

                if (pwrVal >= 1)
                {
                    sevAdjustment = 5;
                }
                else
                {
                    sevAdjustment = (Rand.Range(0f, 1f) * this.arcaneDmg);
                }
                if (sevAdjustment >= .25f)
                {
                    bool success = false;
                    using (IEnumerator <Hediff> enumerator = pawn.health.hediffSet.GetHediffs <Hediff>().GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            Hediff rec   = enumerator.Current;
                            bool   flag2 = num > 0;


                            if (rec.def.defName == "WoundInfection" || rec.def.defName.Contains("Flu") || rec.def.defName == "Animal_Flu" || rec.def.defName.Contains("Infection"))
                            {
                                //rec.Severity -= sevAdjustment;
                                pawn.health.RemoveHediff(rec);
                                success = true;
                            }
                            if (verVal >= 1 && (rec.def.defName == "GutWorms" || rec.def == HediffDefOf.Malaria || rec.def == HediffDefOf.FoodPoisoning))
                            {
                                //rec.Severity -= sevAdjustment;
                                pawn.health.RemoveHediff(rec);
                                success = true;
                            }
                            if (verVal >= 2 && (rec.def.defName == "SleepingSickness" || rec.def.defName == "MuscleParasites") || rec.def == HediffDefOf.Scaria)
                            {
                                //rec.Severity -= sevAdjustment;
                                pawn.health.RemoveHediff(rec);
                                success = true;
                            }
                            if (verVal == 3 && (rec.def.makesSickThought && rec.def.isBad))
                            {
                                //rec.Severity -= sevAdjustment;
                                if (rec.def.defName == "BloodRot")
                                {
                                    rec.Severity = 0.01f;
                                    MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Tended Blood Rot", -1f);
                                    TM_MoteMaker.ThrowRegenMote(pawn.Position.ToVector3(), pawn.Map, 1.5f);
                                    return(false);
                                }
                                else if (rec.def.defName == "Abasia")
                                {
                                    //do nothing
                                }
                                else
                                {
                                    pawn.health.RemoveHediff(rec);
                                    success = true;
                                }
                            }
                        }
                    }
                    if (success == true)
                    {
                        TM_MoteMaker.ThrowRegenMote(pawn.Position.ToVector3(), pawn.Map, 1.5f);
                        MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Cure Disease" + ": " + StringsToTranslate.AU_CastSuccess, -1f);
                    }
                    else
                    {
                        Messages.Message("TM_CureDiseaseTypeFail".Translate(), MessageTypeDefOf.NegativeEvent);
                        MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Cure Disease" + ": " + StringsToTranslate.AU_CastFailure, -1f);
                    }
                }
                else
                {
                    MoteMaker.ThrowText(pawn.DrawPos, pawn.Map, "Cure Disease" + ": " + StringsToTranslate.AU_CastFailure, -1f);
                }
            }
            return(false);
        }
Ejemplo n.º 6
0
        public CollisionProcessing()
        {
            // Ground body
            {
                PolygonShape shape = new PolygonShape();
                shape.SetAsEdge(new Vector2(-50.0f, 0.0f), new Vector2(50.0f, 0.0f));

                FixtureDef sd = new FixtureDef();
                sd.shape = shape;

                BodyDef bd     = new BodyDef();
                Body    ground = _world.CreateBody(bd);
                ground.CreateFixture(sd);
            }

            float xLo = -5.0f, xHi = 5.0f;
            float yLo = 2.0f, yHi = 35.0f;

            // Small triangle
            Vector2[] vertices = new Vector2[3];
            vertices[0] = new Vector2(-1.0f, 0.0f);
            vertices[1] = new Vector2(1.0f, 0.0f);
            vertices[2] = new Vector2(0.0f, 2.0f);

            PolygonShape polygon = new PolygonShape();

            polygon.Set(vertices, 3);

            FixtureDef triangleShapeDef = new FixtureDef();

            triangleShapeDef.shape   = polygon;
            triangleShapeDef.density = 1.0f;

            BodyDef triangleBodyDef = new BodyDef();

            triangleBodyDef.type     = BodyType.Dynamic;
            triangleBodyDef.position = new Vector2(Rand.RandomFloat(xLo, xHi), Rand.RandomFloat(yLo, yHi));

            Body body1 = _world.CreateBody(triangleBodyDef);

            body1.CreateFixture(triangleShapeDef);

            // Large triangle (recycle definitions)
            vertices[0] *= 2.0f;
            vertices[1] *= 2.0f;
            vertices[2] *= 2.0f;
            polygon.Set(vertices, 3);

            triangleBodyDef.position = new Vector2(Rand.RandomFloat(xLo, xHi), Rand.RandomFloat(yLo, yHi));

            Body body2 = _world.CreateBody(triangleBodyDef);

            body2.CreateFixture(triangleShapeDef);

            // Small box
            polygon.SetAsBox(1.0f, 0.5f);

            FixtureDef boxShapeDef = new FixtureDef();

            boxShapeDef.shape   = polygon;
            boxShapeDef.density = 1.0f;

            BodyDef boxBodyDef = new BodyDef();

            boxBodyDef.type     = BodyType.Dynamic;
            boxBodyDef.position = new Vector2(Rand.RandomFloat(xLo, xHi), Rand.RandomFloat(yLo, yHi));

            Body body3 = _world.CreateBody(boxBodyDef);

            body3.CreateFixture(boxShapeDef);

            // Large box (recycle definitions)
            polygon.SetAsBox(2.0f, 1.0f);
            boxBodyDef.position = new Vector2(Rand.RandomFloat(xLo, xHi), Rand.RandomFloat(yLo, yHi));

            Body body4 = _world.CreateBody(boxBodyDef);

            body4.CreateFixture(boxShapeDef);

            // Small circle
            CircleShape circle = new CircleShape();

            circle._radius = 1.0f;

            FixtureDef circleShapeDef = new FixtureDef();

            circleShapeDef.shape   = circle;
            circleShapeDef.density = 1.0f;

            BodyDef circleBodyDef = new BodyDef();

            circleBodyDef.type     = BodyType.Dynamic;
            circleBodyDef.position = new Vector2(Rand.RandomFloat(xLo, xHi), Rand.RandomFloat(yLo, yHi));

            Body body5 = _world.CreateBody(circleBodyDef);

            body5.CreateFixture(circleShapeDef);

            // Large circle
            circle._radius        *= 2.0f;
            circleBodyDef.position = new Vector2(Rand.RandomFloat(xLo, xHi), Rand.RandomFloat(yLo, yHi));

            Body body6 = _world.CreateBody(circleBodyDef);

            body6.CreateFixture(circleShapeDef);
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            int  tile;
            bool result;

            if (!this.TryFindTile(out tile))
            {
                result = false;
            }
            else
            {
                Site site = SiteMaker.TryMakeSite_SingleSitePart(SiteCoreDefOf.DownedRefugee, (!Rand.Chance(0.3f)) ? IncidentWorker_QuestDownedRefugee.DownedRefugeeQuestThreatTag : null, null, true, null, true);
                if (site == null)
                {
                    result = false;
                }
                else
                {
                    site.Tile           = tile;
                    site.sitePartsKnown = true;
                    Pawn pawn = DownedRefugeeQuestUtility.GenerateRefugee(tile);
                    site.GetComponent <DownedRefugeeComp>().pawn.TryAdd(pawn, true);
                    int randomInRange = IncidentWorker_QuestDownedRefugee.TimeoutDaysRange.RandomInRange;
                    site.GetComponent <TimeoutComp>().StartTimeout(randomInRange * 60000);
                    Find.WorldObjects.Add(site);
                    string text  = this.def.letterLabel;
                    string text2 = string.Format(this.def.letterText.AdjustedFor(pawn, "PAWN"), new object[]
                    {
                        randomInRange,
                        pawn.ageTracker.AgeBiologicalYears,
                        pawn.story.Title,
                        SitePartUtility.GetDescriptionDialogue(site, site.parts.FirstOrDefault <SitePart>())
                    }).CapitalizeFirst();
                    Pawn mostImportantColonyRelative = PawnRelationUtility.GetMostImportantColonyRelative(pawn);
                    if (mostImportantColonyRelative != null)
                    {
                        PawnRelationDef mostImportantRelation = mostImportantColonyRelative.GetMostImportantRelation(pawn);
                        if (mostImportantRelation != null && mostImportantRelation.opinionOffset > 0)
                        {
                            pawn.relations.relativeInvolvedInRescueQuest = mostImportantColonyRelative;
                            text2 = text2 + "\n\n" + "RelatedPawnInvolvedInQuest".Translate(new object[]
                            {
                                mostImportantColonyRelative.LabelShort,
                                mostImportantRelation.GetGenderSpecificLabel(pawn)
                            }).AdjustedFor(pawn, "PAWN");
                        }
                        else
                        {
                            PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text2, pawn);
                        }
                        text = text + " " + "RelationshipAppendedLetterSuffix".Translate();
                    }
                    if (pawn.relations != null)
                    {
                        pawn.relations.everSeenByPlayer = true;
                    }
                    Find.LetterStack.ReceiveLetter(text, text2, this.def.letterDef, site, null, null);
                    result = true;
                }
            }
            return(result);
        }
Ejemplo n.º 8
0
        // Token: 0x0600000C RID: 12 RVA: 0x00002420 File Offset: 0x00000620
        protected void DetermineImpactExactPosition()
        {
            var vector       = destination - origin;
            var num          = (int)vector.magnitude;
            var vector2      = vector / vector.magnitude;
            var destination1 = origin;
            var vector3      = origin;

            for (var i = 1; i <= num; i++)
            {
                vector3 += vector2;
                var intVec = vector3.ToIntVec3();
                if (!vector3.InBounds(Map))
                {
                    destination = destination1;
                    break;
                }

                if (!def.projectile.flyOverhead && def.projectile.alwaysFreeIntercept && i >= 5)
                {
                    var list = Map.thingGrid.ThingsListAt(Position);
                    foreach (var thing in list)
                    {
                        if (thing.def.Fillage == FillCategory.Full)
                        {
                            destination = intVec.ToVector3Shifted() +
                                          new Vector3(Rand.Range(-0.3f, 0.3f), 0f, Rand.Range(-0.3f, 0.3f));
                            hitThing = thing;
                            break;
                        }

                        if (thing.def.category != ThingCategory.Pawn)
                        {
                            continue;
                        }

                        var pawn   = thing as Pawn;
                        var num2   = 0.45f;
                        var downed = pawn != null && pawn.Downed;
                        if (downed)
                        {
                            num2 *= 0.1f;
                        }

                        var num3 = (ExactPosition - origin).MagnitudeHorizontal();
                        if (num3 < 4f)
                        {
                            num2 *= 0f;
                        }
                        else
                        {
                            if (num3 < 7f)
                            {
                                num2 *= 0.5f;
                            }
                            else
                            {
                                if (num3 < 10f)
                                {
                                    num2 *= 0.75f;
                                }
                            }
                        }

                        if (pawn == null)
                        {
                            continue;
                        }

                        num2 *= pawn.RaceProps.baseBodySize;
                        if (!(Rand.Value < num2))
                        {
                            continue;
                        }

                        destination = intVec.ToVector3Shifted() +
                                      new Vector3(Rand.Range(-0.3f, 0.3f), 0f, Rand.Range(-0.3f, 0.3f));
                        hitThing = pawn;
                        break;
                    }
                }

                destination1 = vector3;
            }
        }
    public void Randomize(int seed, bool newTheme = true)
    {
        if (!Application.isPlaying) {
            Debug.LogError ("You may only randomize in play mode.");
            return;
        }

        if (referenceParameters == null) {
            gameObject.SetActive (false);
            var go = Instantiate (gameObject);
            var gen = Instantiate (generator.gameObject);
            gameObject.SetActive (true);
            referenceParameters = go.GetComponent<ObjectPlacer> ();
            referenceGenerator = gen.GetComponent<LSystem> ();
        }

        Rand hash = new Rand (seed);

        RandomizePlacement (hash, newTheme);
        RandomizeColors (hash, newTheme);
        RandomizeTrees (hash, newTheme);

        Place ();
        UpdateGlobals ();
    }
Ejemplo n.º 10
0
 public UniqueIDsManager()
 {
     this.nextThingID = Rand.Range(0, 1000);
 }
Ejemplo n.º 11
0
 public void InitPoints()
 {
     Points = Rand.Range(300, 800) * (int)OffensiveFaction.def.techLevel;
 }
 Vector2 RandomVariation(Rand hash, Vector2 reference, float fraction)
 {
     float variationMin = reference.x * fraction;
     float variationMax = reference.y * fraction;
     return new Vector2 (
         hash.Range (reference.x - variationMin, reference.x + variationMin),
         hash.Range (reference.y - variationMax, reference.y + variationMax)
     );
 }
 float RandomVariation(Rand hash, float reference, float fraction)
 {
     float variation = reference * fraction;
     return hash.Range (reference - variation, reference + variation);
 }
    void RandomizeTrees(Rand hash, bool newTheme = true)
    {
        generator.initialLength = RandomVariation (hash, referenceGenerator.initialLength, 0.3f);
        generator.initialWidth = RandomVariation (hash, referenceGenerator.initialWidth, 0.7f);
        generator.smallBranchBias = RandomVariation (hash, referenceGenerator.smallBranchBias, 1.0f);
        generator.turn1 = RandomVariation (hash, referenceGenerator.turn1, 1.3f);
        generator.turn2 = RandomVariation (hash, referenceGenerator.turn2, 1.3f);
        generator.turn3 = RandomVariation (hash, referenceGenerator.turn3, 1.3f);
        generator.roll1 = RandomVariation (hash, referenceGenerator.roll1, 1.3f);
        generator.roll2 = RandomVariation (hash, referenceGenerator.roll2, 1.3f);
        generator.roll3 = RandomVariation (hash, referenceGenerator.roll3, 1.3f);
        generator.lengthScale1 = RandomVariation (hash, referenceGenerator.lengthScale1, 0.3f);
        generator.lengthScale2 = RandomVariation (hash, referenceGenerator.lengthScale2, 0.3f);
        generator.lengthScale3 = RandomVariation (hash, referenceGenerator.lengthScale3, 0.3f);
        generator.lengthScale1 = Clamp (generator.lengthScale1, 0.05f, 0.95f);
        generator.lengthScale2 = Clamp (generator.lengthScale2, 0.05f, 0.95f);
        generator.lengthScale3 = Clamp (generator.lengthScale3, 0.05f, 0.95f);
        generator.e = RandomVariation (hash, referenceGenerator.e, 0.2f);
        generator.branchNo = referenceGenerator.branchNo;
        generator.iter = hash.Range (9, 10+1);

        if (newTheme)
            generator.showLeaves = (hash.value < 0.85f);

        generator.leafMid = RandomVariation (hash, referenceGenerator.leafMid, 0.9f);
        generator.leafRotate = RandomVariation (hash, referenceGenerator.leafRotate, 0.5f);
        generator.gravity = RandomVariation (hash, referenceGenerator.gravity, 1.5f);
    }
    void RandomizePlacement(Rand hash, bool newTheme = true)
    {
        placementSeed = hash.Next () % 1000;

        if (newTheme)
            baseDist = hash.Range (0.50f, 0.75f);

        noiseSize1 = RandomVariation (hash, referenceParameters.noiseSize1, 0.3f);
        noiseSize2 = RandomVariation (hash, referenceParameters.noiseSize2, 0.5f);
        threshold = RandomVariation (hash, referenceParameters.threshold, 0.15f);
        randomness = RandomVariation (hash, referenceParameters.randomness, 0.5f);
        scaleBase = RandomVariation (hash, referenceParameters.scaleBase, 0.3f);
    }
    void RandomizeColors(Rand hash, bool newTheme = true)
    {
        if (newTheme) {
            paletteValue = hash.value;
            paletteValue = paletteValue * Mathf.Sqrt (3 - 2 * paletteValue);
            paletteSaturation = 0.2f + 0.5f * Mathf.Sqrt (hash.value);

            // It seems low value combined with high saturation generally looks bad,
            // so limit saturation somewhat based on value.
            paletteSaturation = Mathf.Lerp (
                // For low value, use satuartion = value.
                paletteValue,
                // For high value, multiply saturation with value.
                paletteSaturation * paletteValue,
                paletteValue
            );

            fogDensity = Mathf.Pow (hash.value, 2);
        }

        Color baseColor = ColorUtility.HSVToRGB (hash.value, paletteSaturation, paletteValue);

        List<Color> primaryColors = GetPrimaryColors (baseColor, hash);
        AddVariationColors (primaryColors, hash);

        branchesVariation.color1 = PickBestColor (primaryColors, referenceParameters.branchesVariation.color1);
        branchesVariation.color2 = PickBestColor (primaryColors, referenceParameters.branchesVariation.color2);
        leavesVariation.color1   = PickBestColor (primaryColors, referenceParameters.leavesVariation.color1);
        leavesVariation.color2   = PickBestColor (primaryColors, referenceParameters.leavesVariation.color2);

        groundColor              = PickBestColor (primaryColors, referenceParameters.groundColor);

        starsColor               = CalculateColor (primaryColors, referenceParameters.starsColor, e => {
            e.y *= 0.5f; // decrease saturation
            e.z = 0.7f + 0.3f * Mathf.Sqrt (e.z); // increase value
            return e;
        });

        skyColor                 = CalculateColor (primaryColors, referenceParameters.skyColor, e => {
            e.y *= 0.9f; // decrease saturation
            e.z = Mathf.Pow (e.z, 0.7f); // increase value
            return e;
        });
        horizonColor             = CalculateColor (primaryColors, referenceParameters.horizonColor, e => {
            e.y *= 0.5f; // decrease saturation
            e.z = 0.1f + Mathf.Pow (e.z, 0.7f); // increase value
            return e;
        });
        lightColor               = PickBestColor (primaryColors, referenceParameters.lightColor);
    }
    List<Color> GetPrimaryColors(Color baseColor, Rand hash)
    {
        List<Color> colors = new List<Color> ();
        colors.Add (baseColor);

        Vector4 hsv = ColorUtility.RGBToHSV (baseColor);

        int selector = hash.Range (0, 2);
        if (selector == 0) {
            hsv.x += 0.49f;
            colors.Add (ColorUtility.HSVToRGB (hsv));
        }
        else if (selector == 1) {
            hsv.x += 1/3f;
            colors.Add (ColorUtility.HSVToRGB (hsv));
            hsv.x += 1/3f;
            colors.Add (ColorUtility.HSVToRGB (hsv));
        }

        return colors;
    }
 void AddVariationColors(List<Color> colors, Rand rand)
 {
     int index = rand.Range (0, colors.Count);
     float t = rand.Range (0.3f, 0.7f);
     Color newColor = LerpColorInHSV (
         colors[index],
         colors[(index + 1) % colors.Count],
         t
     );
     colors.Add (newColor);
 }
Ejemplo n.º 19
0
        // Token: 0x06002628 RID: 9768 RVA: 0x001222BC File Offset: 0x001206BC
        public override void Tick()
        {
            if (!base.Spawned)
            {
                return;
            }
            this.sustainer.Maintain();
            Vector3    vector      = base.Position.ToVector3Shifted();
            TargetInfo localTarget = new TargetInfo(this);

            Rand.PushState();
            if (Rand.MTBEventOccurs(FilthSpawnMTB, 1f, 1.TicksToSeconds()) && CellFinder.TryFindRandomReachableCellNear(base.Position, base.Map, FilthSpawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors), null, null, out IntVec3 result) && !filthTypes.NullOrEmpty())
            {
                FilthMaker.TryMakeFilth(result, base.Map, filthTypes.RandomElement());
            }
            if (Rand.MTBEventOccurs(DustMoteSpawnMTB, 1f, 1.TicksToSeconds()))
            {
                Vector3 loc = new Vector3(vector.x, 0f, vector.z);
                loc.y = AltitudeLayer.MoteOverhead.AltitudeFor();
                FleckMaker.ThrowDustPuffThick(loc, base.Map, Rand.Range(1.5f, 3f), Ext?.dustColor ?? new Color(1f, 1f, 1f, 2.5f));

                if (Ext != null && Ext.thowSparksinDust)
                {
                    if (Rand.MTBEventOccurs((EMPMoteSpawnMTB * TimeRemaining), 1f, 0.25f))
                    {
                        FleckMaker.ThrowMicroSparks(loc, base.Map);
                    }
                }
            }
            if (Ext?.effecter != null)
            {
                if (Rand.MTBEventOccurs((EMPMoteSpawnMTB * TimeRemaining), 0.5f, 0.25f))
                {
                    if (this.Effecter == null && Ext.effecter != null)
                    {
                        this.Effecter = new Effecter(Ext.effecter);
                    }
                    if (Effecter != null)
                    {
                        Effecter.EffectTick(localTarget, localTarget);
                    }
                    else
                    {
                        this.Effecter.EffectTick(localTarget, localTarget);
                    }
                }
            }
            if (Rand.MTBEventOccurs(TeleportSpawner.FilthSpawnMTB, 1f, 1.TicksToSeconds()) && CellFinder.TryFindRandomReachableCellNear(base.Position, base.Map, TeleportSpawner.FilthSpawnRadius, TraverseParms.For(TraverseMode.NoPassClosedDoors, Danger.Deadly, false), null, null, out IntVec3 c, 999999))
            {
                FilthMaker.TryMakeFilth(c, base.Map, TeleportSpawner.filthTypes.RandomElement <ThingDef>(), 1);
            }
            if (Rand.MTBEventOccurs(TeleportSpawner.DustMoteSpawnMTB, 1f, 1.TicksToSeconds()))
            {
                FleckMaker.ThrowDustPuffThick(new Vector3(vector.x, 0f, vector.z)
                {
                    y = AltitudeLayer.MoteOverhead.AltitudeFor()
                }, base.Map, Rand.Range(1.5f, 3f), new Color(1f, 1f, 1f, 2.5f));
            }
            Rand.PopState();
            if (secondarySpawnTick > Find.TickManager.TicksGame)
            {
                return;
            }
            if (this.Effecter != null)
            {
                this.Effecter.Cleanup();
            }
            this.sustainer.End();
            Map     map      = base.Map;
            IntVec3 position = base.Position;

            if (Ext != null)
            {
                if (Ext.strikespreexplode)
                {
                    FireEvent(map, position);
                }
                if (Ext.explodesprespawn)
                {
                    GenExplosion.DoExplosion(position, map, Ext.blastradius, Ext.damageDef, null, -1, -1f, null, null, null, null, null, 0f, 1, false, null, 0f, 1, 0f, false);
                }
            }
            if (!this.innerContainer.NullOrEmpty())
            {
                //    Log.Message(string.Format("{0} to drop", innerContainer.ContentsString));
                this.innerContainer.TryDropAll(position, map, ThingPlaceMode.Near);
            }
            this.Destroy(DestroyMode.Vanish);
        }
Ejemplo n.º 20
0
            private static bool Prefix(PawnGroupMakerParms parms, PawnGroupMaker groupMaker, Pawn trader, List <Thing> wares, List <Pawn> outPawns)
            {
                Func <Thing, float> massTotaler = t => t.stackCount * t.GetStatValue(StatDefOf.Mass, true);

                List <Thing> list = wares.Where(t => !(t is Pawn)).ToList();

                list.SortByDescending(massTotaler);

                float ttlMassThings = list.Sum(massTotaler);
                float ttlCapacity   = 0f;
                float ttlBodySize   = 0f;
                int   numCarriers   = 0;

                IEnumerable <PawnGenOption> carrierKinds = groupMaker.carriers.Where(p => {
                    if (parms.tile != -1)
                    {
                        return(Find.WorldGrid[parms.tile].biome.IsPackAnimalAllowed(p.kind.race));
                    }
                    return(true);
                });

                PawnKindDef kind = carrierKinds.RandomElementByWeight(x => x.selectionWeight).kind;

                // No slow or small juveniles
                Predicate <Pawn> validator = (p =>
                                              p.ageTracker.CurLifeStage.bodySizeFactor >= 1 &&
                                              p.GetStatValue(StatDefOf.MoveSpeed, true) >= p.kindDef.race.GetStatValueAbstract(StatDefOf.MoveSpeed)
                                              );

                // 50/50 chance of uniform carriers (like vanilla) or mixed carriers
                bool mixedCarriers = Rand.RangeInclusive(0, 1) == 1;

                // Generate all of the carrier pawns (empty).  Either we spawn as many pawns as we need to cover
                // 120% of the weight of the items, or enough pawns before it seems "unreasonable" based on body
                // size.
                for (; ttlCapacity < ttlMassThings * 1.2 && ttlBodySize < 20; numCarriers++)
                {
                    PawnGenerationRequest request = new PawnGenerationRequest(
                        kind:             kind,
                        faction:          parms.faction,
                        tile:             parms.tile,
                        inhabitant:       parms.inhabitants,
                        validatorPreGear: validator
                        );
                    Pawn pawn = PawnGenerator.GeneratePawn(request);
                    outPawns.Add(pawn);

                    ttlCapacity += MassUtility.Capacity(pawn);
                    // Still can't have 100 chickenmuffalos.  That might slow down some PCs.
                    ttlBodySize += Mathf.Max(pawn.BodySize, 0.5f);

                    if (mixedCarriers)
                    {
                        kind = carrierKinds.RandomElementByWeight(x => x.selectionWeight).kind;
                    }
                }

                // Add items (in descending order of weight) to randomly chosen pack animals.  This isn't the most
                // efficient routine, as we're trying to be a bit random.  If I was trying to be efficient, I would
                // use something like SortByDescending(p.Capacity) against the existing thing list.
                foreach (Thing thing in list)
                {
                    List <Pawn> validPawns = outPawns.FindAll(p => !MassUtility.WillBeOverEncumberedAfterPickingUp(p, thing, thing.stackCount));

                    if (validPawns.Count() != 0)
                    {
                        validPawns.RandomElement().inventory.innerContainer.TryAdd(thing, true);
                    }
                    else if (thing.stackCount > 1)
                    {
                        // No carrier can handle the full stack; split it up
                        int countLeft = thing.stackCount;
                        int c         = 0; // safety counter (while loops can be dangerous)
                        while (countLeft > 0)
                        {
                            validPawns = outPawns.FindAll(p => MassUtility.CountToPickUpUntilOverEncumbered(p, thing) >= 1);
                            if (validPawns.Count() != 0 && c < thing.stackCount)
                            {
                                Pawn pawn       = validPawns.RandomElement();
                                int  countToAdd = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(pawn, thing), countLeft);
                                countLeft -= pawn.inventory.innerContainer.TryAdd(thing, countToAdd, true);
                            }
                            else
                            {
                                // Either no carrier can handle a single item, or we're just in some bad while loop breakout.  In
                                // any case, force it in, evenly split among all carriers.
                                int splitCount = Mathf.FloorToInt(countLeft / outPawns.Count());
                                if (splitCount > 0)
                                {
                                    outPawns.ForEach(p => p.inventory.innerContainer.TryAdd(thing, splitCount, true));
                                    countLeft -= splitCount * outPawns.Count();
                                }

                                // Give the remainer to the ones with space (one at a time)
                                while (countLeft > 0)
                                {
                                    validPawns = new List <Pawn>(outPawns);
                                    validPawns.SortByDescending(p => MassUtility.FreeSpace(p));
                                    validPawns.First().inventory.innerContainer.TryAdd(thing, 1, true);
                                    countLeft--;
                                }
                                break;
                            }
                            c++;
                        }
                    }
                    else
                    {
                        // No way to split it; force it in
                        validPawns = new List <Pawn>(outPawns);
                        validPawns.SortByDescending(p => MassUtility.FreeSpace(p));
                        validPawns.First().inventory.innerContainer.TryAdd(thing, true);
                    }
                }

                // Always skip the original method
                return(false);
            }
Ejemplo n.º 21
0
            private List<Family> BuildFamilyPool(int deltaYear, Rand rand)
            {
                var pool = new List<Family>();
                // Index of data loaded in ILUTE standardized variables
                //	0	icma		Census Metropolitian Area (CMA)
                //	1	icfstruc	Census Family Structure
                //	2	icfsize		Number of Persons in the Census Family
                //	3	inuchild	Number of Never-married S/D in CF at Home
                //	4	ichilda		No. of NevMar S/D in CF at Home < 6 Years of Age
                //	5	ichildb		No. of NevMar S/D in CF at Home 6-14 Years of Age
                //	6	ichildc		No. of NevMar S/D in CF at Home 15-17 Years of A
                //	7	ichildd		No. of NevMar S/D in CF at Home 18-24 Years of A
                //	8	ichilde		No. of NevMar S/D in CF at Home 25 Years or Over
                //	9	itotalc		Total Income of CF or Non-family Person
                //	10	inucfinc	No. of Income Recipients in CF or Non-family Per
                //	11	iwagesc		Wages and Salaries of CF or Non-family Person
                //	12	itotalm		Total Income of H/MCLP/MLP in CF
                //	13	iwagem		Wages and Salaries of H/MCLP/MLP in CF
                //	14	iagem		Age of H/MCLP/MLP/Male NF Person (85=85+)
                //	15	imarsthm	Hist. Comparison Legal Marital Status of Male - Husbands, Common Law Parent/Male Lone Parent or Male NonFam Person
                //	16	ihgradm		Highest Grade Elem/Sec. of H/MCLP/MLP/MNF Person ( ALL MALES)
                //	17	ihlosm		Highest Level of Sch. of H/MCLP/MLP or Male NFP (ALL MALES)
                //	18	itruncm		Trades/Other Non-univ. Cert. of H/MCLP/MLP/MNFP (sec. Cert = high school)
                //	19	idgmfsm		Major Field of Study of H/MCLP/MLP or Male NFP
                //	20	itotschm	Total Years of Schooling of H/MCLP/MLP or Male N
                //	21	imob1m		Mobility Status - 1 Year Ago of H/MCLP/MLP/MNFP
                //	22	ilfactm		LF Activity of H/MCLP/MLP or Male NF Person
                //	23	iocc80m		Occupation (1980 Class.) of H/MCLP/MLP/MNFP
                //	24	iind80m		Industry (1980 SIC) of H/MCLP/MLP/MNFP
                //	25	iagef		Age of W/FCLP/FLP/Female NF Person (85=85+)
                //	26	imarsthf	Hist. Comparison Legal Marital Status of Female - Wives, Common Law Parent/Female Lone Parent or Female NonFam Person
                //	27	itotalf		Total Income of W/FCLP/FLP in CF (ALL FEMALES)
                //	28	iwagef		Wages and Salaries of H/MCLP/MLP in CF
                //	29	ihgradf		Highest Grade Elem/Sec. of W/FCLP/FLP/FNF Person ( ALL FEMALES)
                //	30	ihlosf		Highest Level of Sch. of W/FCLP/FLP or Female NFP (ALL FEMALES)
                //	31	itruncm		Trades/Other Non-univ. Cert. of W/FCLP/FLP/FNFP (sec. Cert = high school)
                //	32	idgmfsf		Major Field of Study of W/FCLP/FLP or Female NFP
                //	33	itotschf    Total Years of Schooling of W/FCLP/FLP or Female NFP
                //	34	imob1f		Mobility Status - 1 Year Ago of W/FCLP/FLP/FNFP
                //	35	ilfactf		LF Activity of W/FCLP/FLP or Female NF Person
                //	36	iocc80f		Occupation (1980 Class.) of W/FCLP/FLP/FNFP
                //	37	iind80f		Industry (1980 SIC) of W/FCLP/FLP/FNFP
                //	38	itenurc		Tenure
                //	39	igrosrtc	Monthly Gross Rent

                using (var reader = new CsvReader(YearlyFamilyData[deltaYear], true))
                {
                    int columns;
                    List<Person> children = new List<Person>();
                    while (reader.LoadLine(out columns))
                    {
                        if (columns >= 39)
                        {
                            var createMale = false;
                            var createFemale = false;
                            int familyStructure, ageM, ageF, childrenA, childrenB, childrenC, childrenD, childrenE;
                            reader.Get(out familyStructure, 1);
                            reader.Get(out ageM, 14);
                            reader.Get(out ageF, 25);
                            if (familyStructure > 0 && familyStructure < 5)
                            {
                                createMale = createFemale = true;
                            }
                            else if (familyStructure == 5 && ageM != 99)
                            {
                                createMale = true;
                            }
                            else if (familyStructure == 6 && ageF != 99)
                            {
                                createFemale = true;
                            }
                            else
                            {
                                // this household record is invalid, just continue
                                continue;
                            }
                            // get the number of children
                            reader.Get(out childrenA, 4);
                            reader.Get(out childrenB, 5);
                            reader.Get(out childrenC, 6);
                            reader.Get(out childrenD, 7);
                            reader.Get(out childrenE, 8);
                            var family = new Family();
                            Person male = null, female = null;
                            if (createMale)
                            {
                                male = CreatePerson(0, AgeFromAdultAgeCategory(rand.Take(), ageM), 2, (createMale && createFemale ? 2 : 4));
                                family.Persons.Add(male);
                                male.Family = family;
                                family.MaleHead = male;
                            }
                            if (createFemale)
                            {
                                female = CreatePerson(0, AgeFromAdultAgeCategory(rand.Take(), ageF), 1, (createMale && createFemale ? 2 : 4));
                                family.Persons.Add(female);
                                female.Family = family;
                                family.FemaleHead = female;
                            }
                            if (male != null && female != null)
                            {
                                male.Spouse = female;
                                female.Spouse = male;
                            }
                            pool.Add(family);
                            // Create children for each age range rand.NextFloat = [0,1)
                            if (childrenA > 0 || childrenB > 0 || childrenC > 0 || childrenD > 0 || childrenE > 0)
                            {
                                for (int i = 0; i < childrenA; i++)
                                {
                                    children.Add(
                                        CreatePerson(0, (int)(0.0f + rand.Take() * 6.0f), rand.Take() < 0.5f ? 2 : 1, 4));
                                }
                                for (int i = 0; i < childrenB; i++)
                                {
                                    children.Add(
                                        CreatePerson(0, (int)(6.0f + rand.Take() * 9.0f), rand.Take() < 0.5f ? 2 : 1, 4));
                                }
                                for (int i = 0; i < childrenC; i++)
                                {
                                    children.Add(
                                        CreatePerson(0, (int)(15.0f + rand.Take() * 3.0f), rand.Take() < 0.5f ? 2 : 1, 4));
                                }
                                for (int i = 0; i < childrenD; i++)
                                {
                                    children.Add(
                                        CreatePerson(0, (int)(18.0f + rand.Take() * 7.0f), rand.Take() < 0.5f ? 2 : 1, 4));

                                }
                                for (int i = 0; i < childrenE; i++)
                                {
                                    children.Add(CreatePerson(0, 25, rand.Take() < 0.5f ? 2 : 1, 4));
                                }
                                male?.Children.AddRange(children);
                                female?.Children.AddRange(children);
                                foreach (var child in children)
                                {
                                    child.Father = male;
                                    child.Mother = female;
                                    child.Family = family;
                                    foreach (var otherChild in children)
                                    {
                                        if (child != otherChild)
                                        {
                                            child.Siblings.Add(otherChild);
                                        }
                                    }
                                    family.Persons.Add(child);
                                }
                                // now that everything is copied over we can release the children
                                children.Clear();
                            }
                        }
                    }
                }
                return pool;
            }
Ejemplo n.º 22
0
        static void Prefix(ref ThingOwner <Thing> __instance, Thing item)
        {
            if (!Config_Cities.Instance.enableLooting)
            {
                var pawn =
                    (__instance.Owner as Pawn_InventoryTracker)?.pawn ??
                    (__instance.Owner as Pawn_ApparelTracker)?.pawn ??
                    (__instance.Owner as Pawn_EquipmentTracker)?.pawn;

                if (pawn != null && pawn.IsColonistPlayerControlled && item.IsOwnedByCity(pawn.Map))
                {
                    if (pawn.Map.Parent is City city && !city.Abandoned && city.Faction != pawn.Faction)
                    {
                        city.Faction.TryAffectGoodwillWith(pawn.Faction,
                                                           -Mathf.RoundToInt(Mathf.Sqrt(item.stackCount * item.MarketValue) * Rand.Range(1.5F, 2)) - 2);
                    }
                }
            }
        }
Ejemplo n.º 23
0
 private List<Family> BuildIndividualPool(int deltaYear, Rand rand)
 {
     var pool = new List<Family>();
     // Index of data loaded in ILUTE standardized variables
     //	0		Census Metropolitian Area (CMA)
     //	1		Household Type
     //	2		Houshold Size
     //	3		Census Family Status
     //	4		Number of Persons in the Census Family
     //	5		Age
     //	6		Sex
     //	7		Legal Marital Status for individual (HISTORICAL INDICATOR)
     //	8		Highest Grade of Elementary/Sec School
     //	9		Highest Level of Schooling (note: non-univ = college)
     //	10		Trades and Other Non-University Certification (sec. cert = high school graduation, non univ = college)
     //	11		Highest Degree, Certificate or Diploma
     //	12		Major Field of Study
     //	13		Total Years of Schooling
     //	14		Mobility Status - 1 Year Ago (Place of Residence)
     //	15		Labour Force Activity
     //	16		Occupation (1980 Classification Basis)
     //	17		Industry (1980 Standard Industrial Classification)
     //	18		Total Income
     //	19		Wages and Salaries
     //	20		Tenure
     //	21		Monthly Gross Rent
     using (var reader = new CsvReader(YearlyIndividualsData[deltaYear]))
     {
         int columns;
         while (reader.LoadLine(out columns))
         {
             if (columns >= 22)
             {
                 int age, sex, maritalStatus;
                 // read in the age
                 reader.Get(out age, 5);
                 // make sure that this record is old enough before loading it in
                 if (age < Parent.AgeOfMaturity)
                 {
                     continue;
                 }
                 // get sex
                 reader.Get(out sex, 6);
                 reader.Get(out maritalStatus, 7);
                 var person = CreatePerson(rand.Take(), age, sex, maritalStatus);
                 if (person.MaritalStatus == MaritalStatus.Married)
                 {
                     person.MaritalStatus = MaritalStatus.Single;
                 }
                 var family = new Family();
                 family.Persons.Add(person);
                 pool.Add(family);
             }
         }
     }
     return pool;
 }
Ejemplo n.º 24
0
        // ===================== Setup Work =====================
        /// <summary>
        /// Initialize instance variables.
        /// </summary>
        public override void SpawnSetup()
        {
            base.SpawnSetup();

            this.lifeCounterInTicks = Rand.RangeInclusive(minSporeSpawningDurationInTicks, maxSporeSpawningDurationInTicks);
        }
Ejemplo n.º 25
0
            internal void Execute(int deltaYear, Repository<Household> householdRepository, Repository<Family> familyRepository, Repository<Person> personRepo)
            {
                // get the pool of individuals to use
                List<Family> familyPool = null, individualPool = null;
                var familySeed = (uint)(Parent.RandomGenerator.Take() * uint.MaxValue);
                var individualSeed = (uint)(Parent.RandomGenerator.Take() * uint.MaxValue);
                Parallel.Invoke(
                    () =>
                    {
                        Rand rand = new Rand(familySeed);
                        familyPool = BuildFamilyPool(deltaYear, rand);
                    }, () =>
                    {
                        Rand rand = new Rand(individualSeed);
                        individualPool = BuildIndividualPool(deltaYear, rand);
                    });
                var targetPersons = (int)(Parent.NumberOfImmigrantsBySimulationYear[deltaYear + (RegionNumber - 1) * 20] * Scale);
                Repository.GetRepository(Parent.LogSource).WriteToLog($"Number of persons to add in {Name} in {deltaYear} target additions are {targetPersons}.");
                Parent.RandomGenerator.ExecuteWithProvider((rand) =>
                {
                    while (targetPersons > 0)
                    {
                        float chance = rand.Take();
                        float acc = 0.0f;
                        int householdType = 0;
                        for (; acc < chance; householdType++)
                        {
                            acc += Parent.HouseholdTypeData[deltaYear * 5 + CMA * 100 + householdType];
                        }
                        Household household = new Household();
                        switch (householdType)
                        {
                            default:
                            case 1:
                                {
                                    household.HouseholdType = HouseholdComposition.SingleIndividuals;
                                    household.Families.Add(GetFamilyFromPool(individualPool, rand.Take()));
                                }
                                break;
                            case 2:
                                {
                                    household.HouseholdType = HouseholdComposition.MultiIndividuals;
                                    // create at least 2 individuals
                                    household.Families.Add(GetFamilyFromPool(individualPool, rand.Take()));
                                    do
                                    {
                                        household.Families.Add(GetFamilyFromPool(individualPool, rand.Take()));
                                    } while (rand.Take() < ProbabilityOfAdditionalMultiIndividuals);
                                }
                                break;
                            case 3:
                                {
                                    household.HouseholdType = HouseholdComposition.SingleFamily;
                                    household.Families.Add(GetFamilyFromPool(familyPool, rand.Take()));
                                }
                                break;
                            case 4:
                                {
                                    household.HouseholdType = HouseholdComposition.SingleFamilyIndividuals;
                                    household.Families.Add(GetFamilyFromPool(familyPool, rand.Take()));
                                    //TODO: Assumption is that there is only 1 additional individual
                                    household.Families.Add(GetFamilyFromPool(individualPool, rand.Take()));
                                }
                                break;
                            case 5:
                                {
                                    household.HouseholdType = HouseholdComposition.MultiFamily;
                                    //TODO: Assumption is that there are two families for this type
                                    household.Families.Add(GetFamilyFromPool(familyPool, rand.Take()));
                                    household.Families.Add(GetFamilyFromPool(familyPool, rand.Take()));
                                }
                                break;

                        }
                        targetPersons -= AddHouseholdToRepositories(household, householdRepository, familyRepository, personRepo);
                    }
                });
            }
Ejemplo n.º 26
0
 private void NewTarget()
 {
     _target.X  = Rand.Next(-1f, 1f) * mag * 0.01f;
     _target.Y  = Rand.Next(-1f, 1f) * mag * 0.01f;
     targetWait = 150f;
 }
Ejemplo n.º 27
0
        public void GenerateBoat(int amount)
        {
            for (int boat = 0; boat < amount; boat++)
            {
                int avaliableSpace = 0;

                switch (Rand.Next(1, 5 + 1))
                {
                case 1:
                    SailBoat s = new SailBoat();


                    for (int i = 0; i < DockTwo.Length; i += 2)
                    {
                        if (DockTwo[i] == null)
                        {
                            avaliableSpace += 2;

                            if (avaliableSpace == s.Slots)
                            {
                                Array.Fill(DockTwo, s, i + 2 - s.Slots, s.Slots);
                                Boats.Add(s);
                                s.Docked = true;

                                break;
                            }
                        }
                        else
                        {
                            avaliableSpace = 0;
                        }
                    }
                    avaliableSpace = 0;
                    if (s.Docked == false)
                    {
                        for (int i = 0; i < DockOne.Length; i += 2)
                        {
                            if (DockOne[i] == null)
                            {
                                avaliableSpace += 2;
                                if (avaliableSpace == s.Slots)
                                {
                                    Array.Fill(DockOne, s, i + 2 - s.Slots, s.Slots);
                                    Boats.Add(s);
                                    s.Docked = true;

                                    break;
                                }
                            }
                            else
                            {
                                avaliableSpace = 0;
                            }
                        }
                    }
                    _ = Boats.Contains(s) ? AddedBoats++ : RejectedBoats++;


                    break;

                case 2:
                    RowingBoat r = new RowingBoat();


                    for (int i = 0; i < DockOne.Length; i++)
                    {
                        if (DockOne[i] == null)
                        {
                            Array.Fill(DockOne, r, i, r.Slots);
                            Boats.Add(r);
                            r.Docked = true;
                            break;
                        }
                        else
                        {
                            avaliableSpace = 0;
                        }
                    }
                    avaliableSpace = 0;
                    if (r.Docked == false)
                    {
                        for (int i = 0; i < DockTwo.Length; i++)
                        {
                            if (DockTwo[i] == null)
                            {
                                Array.Fill(DockTwo, r, i, r.Slots);
                                Boats.Add(r);
                                r.Docked = true;
                                break;
                            }
                            else
                            {
                                avaliableSpace = 0;
                            }
                        }
                    }
                    _ = Boats.Contains(r) ? AddedBoats++ : RejectedBoats++;


                    break;

                case 3:
                    PowerBoat p = new PowerBoat();


                    for (int i = 0; i < DockOne.Length; i += 2)
                    {
                        if (DockOne[i] == null)
                        {
                            avaliableSpace += 2;
                            if (avaliableSpace > p.Slots)
                            {
                                Array.Fill(DockOne, p, i - p.Slots, p.Slots);
                                Boats.Add(p);
                                p.Docked = true;
                                break;
                            }
                        }
                        else
                        {
                            avaliableSpace = 0;
                        }
                    }
                    avaliableSpace = 0;
                    if (p.Docked == false)
                    {
                        for (int i = 0; i < DockTwo.Length; i += 2)
                        {
                            if (DockTwo[i] == null)
                            {
                                avaliableSpace += 2;
                                if (avaliableSpace > p.Slots)
                                {
                                    Array.Fill(DockTwo, p, i - p.Slots, p.Slots);
                                    Boats.Add(p);
                                    p.Docked = true;
                                    break;
                                }
                            }
                            else
                            {
                                avaliableSpace = 0;
                            }
                        }
                    }
                    _ = Boats.Contains(p) ? AddedBoats++ : RejectedBoats++;


                    break;

                case 4:
                    Catamaran k = new Catamaran();


                    for (int i = 0; i < DockOne.Length; i += 2)
                    {
                        if (DockOne[i] == null)
                        {
                            avaliableSpace += 2;
                            if (avaliableSpace == k.Slots)
                            {
                                Array.Fill(DockOne, k, i + 2 - k.Slots, k.Slots);
                                Boats.Add(k);
                                k.Docked = true;
                                break;
                            }
                        }
                        else
                        {
                            avaliableSpace = 0;
                        }
                    }
                    if (k.Docked == false)
                    {
                        avaliableSpace = 0;
                        for (int i = 0; i < DockTwo.Length; i += 2)
                        {
                            if (DockTwo[i] == null)
                            {
                                avaliableSpace += 2;
                                if (avaliableSpace == k.Slots)
                                {
                                    Array.Fill(DockTwo, k, i + 2 - k.Slots, k.Slots);
                                    Boats.Add(k);
                                    k.Docked = true;
                                    break;
                                }
                            }
                            else
                            {
                                avaliableSpace = 0;
                            }
                        }
                    }
                    _ = Boats.Contains(k) ? AddedBoats++ : RejectedBoats++;


                    break;

                case 5:
                    CargoShip c = new CargoShip();

                    for (int i = DockTwo.Length - 1; i > 0; i -= 2)
                    {
                        if (DockTwo[i] == null)
                        {
                            avaliableSpace += 2;
                            if (avaliableSpace == c.Slots)
                            {
                                Array.Fill(DockTwo, c, i - 2 + 1, c.Slots);
                                Boats.Add(c);
                                c.Docked = true;

                                break;
                            }
                        }
                        else
                        {
                            avaliableSpace = 0;
                        }
                    }
                    if (c.Docked == false)
                    {
                        avaliableSpace = 0;
                        for (int i = DockOne.Length - 1; i > 0; i -= 2)
                        {
                            if (DockOne[i] == null)
                            {
                                avaliableSpace += 2;
                                if (avaliableSpace == c.Slots)
                                {
                                    Array.Fill(DockOne, c, i - 2 + 1, c.Slots);
                                    Boats.Add(c);
                                    c.Docked = true;

                                    break;
                                }
                            }
                            else
                            {
                                avaliableSpace = 0;
                            }
                        }
                    }
                    _ = Boats.Contains(c) ? AddedBoats++ : RejectedBoats++;

                    break;
                }
            }
        }
Ejemplo n.º 28
0
        // Token: 0x0600000F RID: 15 RVA: 0x000026FC File Offset: 0x000008FC
        private void ImpactSomething()
        {
            var flyOverhead = def.projectile.flyOverhead;

            if (flyOverhead)
            {
                var roofDef = Map.roofGrid.RoofAt(Position);
                if (roofDef != null)
                {
                    var isThickRoof = roofDef.isThickRoof;
                    if (isThickRoof)
                    {
                        def.projectile.soundHitThickRoof.PlayOneShot(new TargetInfo(Position, Map));
                        Destroy();
                        return;
                    }

                    if (Position.GetEdifice(Map) == null ||
                        Position.GetEdifice(Map).def.Fillage != FillCategory.Full)
                    {
                        RoofCollapserImmediate.DropRoofInCells(Position, Map);
                    }
                }
            }

            if (!usedTarget.HasThing || !CanHit(usedTarget.Thing))
            {
                var list = new List <Thing>();
                list.Clear();
                var thingList = Position.GetThingList(Map);
                foreach (var thing in thingList)
                {
                    if ((thing.def.category == ThingCategory.Building ||
                         thing.def.category == ThingCategory.Pawn || thing.def.category == ThingCategory.Item ||
                         thing.def.category == ThingCategory.Plant) && CanHit(thing))
                    {
                        list.Add(thing);
                    }
                }

                list.Shuffle();
                for (var j = 0; j < list.Count; j++)
                {
                    var   thing2 = list[j];
                    float num;
                    if (thing2 is Pawn pawn)
                    {
                        num = 0.5f * Mathf.Clamp(pawn.BodySize, 0.1f, 2f);
                        if (pawn.GetPosture() != PawnPosture.Standing &&
                            (origin - destination).MagnitudeHorizontalSquared() >= 20.25f)
                        {
                            num *= 0.2f;
                        }

                        if (launcher != null && pawn.Faction != null && launcher.Faction != null &&
                            !pawn.Faction.HostileTo(launcher.Faction))
                        {
                            num *= VerbUtility.InterceptChanceFactorFromDistance(origin, Position);
                        }
                    }
                    else
                    {
                        num = 1.5f * thing2.def.fillPercent;
                    }

                    if (!Rand.Chance(num))
                    {
                        continue;
                    }

                    Impact(list.RandomElement());
                    return;
                }

                Impact(null);
            }
            else
            {
                if (usedTarget.Thing is Pawn pawn2 && pawn2.GetPosture() != PawnPosture.Standing &&
                    (origin - destination).MagnitudeHorizontalSquared() >= 20.25f && !Rand.Chance(0.2f))
                {
                    Impact(null);
                }
Ejemplo n.º 29
0
        public static void Init(Map map)
        {
            Rot4 a = Find.World.CoastDirectionAt(map.Tile);

            if (!a.IsValid)
            {
                BeachMaker.beachNoise = null;
            }
            else
            {
                ModuleBase moduleBase = new Perlin(0.029999999329447746, 2.0, 0.5, 3, Rand.Range(0, int.MaxValue), QualityMode.Medium);
                moduleBase = new ScaleBias(0.5, 0.5, moduleBase);
                NoiseDebugUI.StoreNoiseRender(moduleBase, "BeachMaker base", new IntVec2(map.Size.x, map.Size.z));
                ModuleBase moduleBase2 = new DistFromAxis(BeachMaker.CoastWidthRange.RandomInRange);
                if (a == Rot4.North)
                {
                    moduleBase2 = new Rotate(0.0, 90.0, 0.0, moduleBase2);
                    moduleBase2 = new Translate(0.0, 0.0, (double)(-(double)map.Size.z), moduleBase2);
                }
                else if (a == Rot4.East)
                {
                    moduleBase2 = new Translate((double)(-(double)map.Size.x), 0.0, 0.0, moduleBase2);
                }
                else if (a == Rot4.South)
                {
                    moduleBase2 = new Rotate(0.0, 90.0, 0.0, moduleBase2);
                }
                moduleBase2 = new ScaleBias(1.0, -1.0, moduleBase2);
                moduleBase2 = new Clamp(-1.0, 2.5, moduleBase2);
                NoiseDebugUI.StoreNoiseRender(moduleBase2, "BeachMaker axis bias");
                BeachMaker.beachNoise = new Add(moduleBase, moduleBase2);
                NoiseDebugUI.StoreNoiseRender(BeachMaker.beachNoise, "beachNoise");
            }
        }
Ejemplo n.º 30
0
        private void SetNextBlink(int tickManagerTicksGame)
        {
            // Eye blinking controller
            float ticksTillNextBlink = Rand.Range(60f, 240f);
            float blinkDuration      = Rand.Range(10f, 40f);

            // Log.Message(
            // "FS Blinker: " + this.pawn + " - ticksTillNextBlinkORG: " + ticksTillNextBlink.ToString("N0")
            // + " - blinkDurationORG: " + blinkDuration.ToString("N0"));

            // TODO: use a curve for evaluation => more control, precise setting of blinking
            Pawn_HealthTracker health = this._pawn.health;
            float pain = 0f;

            if (health != null)
            {
                if (health.capacities != null)
                {
                    float consciousness = this._consciousnessCurve.Evaluate(health.capacities.GetLevel(PawnCapacityDefOf.Consciousness));

                    ticksTillNextBlink /= consciousness;
                    blinkDuration      *= consciousness;
                }

                if (health.hediffSet != null)
                {
                    pain = this._painCurve.Evaluate(health.hediffSet.PainTotal);
                }
            }

            ticksTillNextBlink /= pain;
            blinkDuration      *= pain;

            // float factor = Mathf.Lerp(0.1f, 1f, dynamic);
            // ticksTillNextBlink *= factor;
            // blinkDuration /= Mathf.Pow(factor, 3f);

            // Log.Message(
            // "FS Blinker: " + this.pawn + " - Consc: " + dynamic.ToStringPercent() + " - factorC: " + factor.ToString("N2") + " - ticksTillNextBlink: " + ticksTillNextBlink.ToString("N0")
            // + " - blinkDuration: " + blinkDuration.ToString("N0"));
            this._nextBlink   = (int)(tickManagerTicksGame + ticksTillNextBlink);
            this.NextBlinkEnd = (int)(this._nextBlink + blinkDuration);

            // this.JitterLeft = 1f;
            // this.JitterRight = 1f;

            // blinkRate = Mathf.Lerp(2f, 0.25f, this.pawn.needs.rest.CurLevel);

            // range *= (int)blinkRate;
            // blinkDuration /= (int)this.blinkRate;
            if (Rand.Value > 0.9f)
            {
                // early "nerous" blinking. I guss positive values have no effect ...
                this._jitterLeft  = (int)Rand.Range(-10f, 90f);
                this._jitterRight = (int)Rand.Range(-10f, 90f);
            }
            else
            {
                this._jitterLeft  = 0;
                this._jitterRight = 0;
            }

            // only animate eye movement if animation lasts at least 2.5 seconds
            if (ticksTillNextBlink > 80f)
            {
                this._moveX     = Rand.Value > 0.7f;
                this._moveY     = Rand.Value > 0.85f;
                this._halfAnimX = Rand.Value > 0.3f;
                this._halfAnimY = Rand.Value > 0.3f;
                this._flippedX  = Rand.Range(-1f, 1f);
                this._flippedY  = Rand.Range(-1f, 1f);
            }
            else
            {
                this._moveX = this._moveY = false;
            }

            this._lastBlinkended = tickManagerTicksGame;
        }
Ejemplo n.º 31
0
        static void Test5()
        {
            var set = XCode.Setting.Current;

            set.Debug   = true;
            set.ShowSQL = true;

            Console.WriteLine("1,服务端;2,客户端");
            if (Console.ReadKey().KeyChar == '1')
            {
                var n = UserOnline.Meta.Count;

                var svr = new DbServer();
                svr.Log        = XTrace.Log;
                svr.StatPeriod = 5;
                svr.Start();
            }
            else
            {
                DAL.AddConnStr("net", "Server=tcp://admin:[email protected]:3305/Log", null, "network");
                var dal = DAL.Create("net");

                UserOnline.Meta.ConnName = "net";

                var count = UserOnline.Meta.Count;
                Console.WriteLine("count={0}", count);

                var entity = new UserOnline();
                entity.Name       = "新生命";
                entity.OnlineTime = 12345;
                entity.Insert();

                Console.WriteLine("id={0}", entity.ID);

                var entity2 = UserOnline.FindByKey(entity.ID);
                Console.WriteLine("user={0}", entity2);

                entity2.Page = Rand.NextString(8);
                entity2.Update();

                entity2.Delete();

                for (var i = 0; i < 100; i++)
                {
                    entity2      = new UserOnline();
                    entity2.Name = Rand.NextString(8);
                    entity2.Page = Rand.NextString(8);
                    entity2.Insert();

                    Thread.Sleep(5000);
                }
            }

            //var client = new DbClient();
            //client.Log = XTrace.Log;
            //client.EncoderLog = client.Log;
            //client.StatPeriod = 5;

            //client.Servers.Add("tcp://127.0.0.1:3305");
            //client.Open();

            //var db = "Membership";
            //var rs = client.LoginAsync(db, "admin", "newlife").Result;
            //Console.WriteLine((DatabaseType)rs["DbType"].ToInt());

            //var ds = client.QueryAsync("Select * from User").Result;
            //Console.WriteLine(ds);

            //var count = client.QueryCountAsync("User").Result;
            //Console.WriteLine("count={0}", count);

            //var ps = new Dictionary<String, Object>
            //{
            //    { "Logins", 3 },
            //    { "id", 1 }
            //};
            //var es = client.ExecuteAsync("update user set Logins=Logins+@Logins where id=@id", ps).Result;
            //Console.WriteLine("Execute={0}", es);
        }
Ejemplo n.º 32
0
        //private bool WallHasDoor(CellRect rect, Rot4 dir)
        //{
        //    Map map = BaseGen.globalSettings.map;
        //    foreach (IntVec3 current in rect.GetEdgeCells(dir))
        //    {
        //        if (current.GetDoor(map) != null)
        //        {
        //            return true;
        //        }
        //    }
        //    return false;
        //}

        private bool TryFindRandomDoorCell(CellRect rect, Rot4 dir, out IntVec3 found)
        {
            var map = BaseGen.globalSettings.map;

            if (dir == Rot4.North)
            {
                if (rect.Width <= 2)
                {
                    found = IntVec3.Invalid;
                    return(false);
                }

                if (!Rand.TryRangeInclusiveWhere(rect.minX + 1, rect.maxX - 1, delegate(int x)
                {
                    var c = new IntVec3(x, 0, rect.maxZ + 1);
                    return(c.InBounds(map) && c.Walkable(map) && !c.Fogged(map));
                }, out var newX))
                {
                    found = IntVec3.Invalid;
                    return(false);
                }

                found = new IntVec3(newX, 0, rect.maxZ);
                return(true);
            }

            if (dir == Rot4.South)
            {
                if (rect.Width <= 2)
                {
                    found = IntVec3.Invalid;
                    return(false);
                }

                if (!Rand.TryRangeInclusiveWhere(rect.minX + 1, rect.maxX - 1, delegate(int x)
                {
                    var c = new IntVec3(x, 0, rect.minZ - 1);
                    return(c.InBounds(map) && c.Walkable(map) && !c.Fogged(map));
                }, out var newX2))
                {
                    found = IntVec3.Invalid;
                    return(false);
                }

                found = new IntVec3(newX2, 0, rect.minZ);
                return(true);
            }

            if (dir == Rot4.West)
            {
                if (rect.Height <= 2)
                {
                    found = IntVec3.Invalid;
                    return(false);
                }

                if (!Rand.TryRangeInclusiveWhere(rect.minZ + 1, rect.maxZ - 1, delegate(int z)
                {
                    var c = new IntVec3(rect.minX - 1, 0, z);
                    return(c.InBounds(map) && c.Walkable(map) && !c.Fogged(map));
                }, out var newZ))
                {
                    found = IntVec3.Invalid;
                    return(false);
                }

                found = new IntVec3(rect.minX, 0, newZ);
                return(true);
            }

            if (rect.Height <= 2)
            {
                found = IntVec3.Invalid;
                return(false);
            }

            if (!Rand.TryRangeInclusiveWhere(rect.minZ + 1, rect.maxZ - 1, delegate(int z)
            {
                var c = new IntVec3(rect.maxX + 1, 0, z);
                return(c.InBounds(map) && c.Walkable(map) && !c.Fogged(map));
            }, out var newZ2))
            {
                found = IntVec3.Invalid;
                return(false);
            }

            found = new IntVec3(rect.maxX, 0, newZ2);
            return(true);
        }
Ejemplo n.º 33
0
        public IEnumerable <ResearchProjectDef> GetExpertiseDefsFor(Pawn pawn, FactionDef faction)
        {
            //1. Gather info on that pawn

            //a. tech level
            TechLevel factionTechLevel = faction?.techLevel ?? 0;
            TechLevel childhoodLevel   = 0;
            SkillDef  childhoodSkill   = null;
            bool      isPlayer         = pawn.Faction?.IsPlayer ?? false;

            techLevel = TechPoolIncludesBackground || !isPlayer?FindBGTechLevel(pawn, out childhoodLevel, out childhoodSkill) : factionTechLevel;

            TechLevel workingTechLevel = startingTechLevel = techLevel;

            //b. higest skills
            SkillRecord highestSkillRecord             = pawn.skills.skills.Aggregate(AccessHighestSkill);
            SkillDef    highestSkill                   = highestSkillRecord.def;
            IEnumerable <SkillRecord> secondCandidates = pawn.skills.skills.Except(highestSkillRecord).Where(x => SkillIsRelevant(x.def, techLevel));
            SkillDef secondSkill = secondCandidates.Aggregate(AccessHighestSkill).def;

            //c. age
            float middleAge    = pawn.RaceProps.lifeExpectancy / 2;
            int   matureAge    = pawn.RaceProps.lifeStageAges.FindLastIndex(x => x.minAge < middleAge); //not always the last possible age because there are mods with an "eldery" stage
            int   growthAdjust = 0;
            int   oldBonus     = 0;

            if (pawn.ageTracker.CurLifeStageIndex < matureAge)
            {
                growthAdjust = matureAge - pawn.ageTracker.CurLifeStageIndex;
            }
            else if (pawn.ageTracker.AgeBiologicalYears > middleAge)
            {
                oldBonus = 1;
            }

            //d. special cases
            isFighter = highestSkill == SkillDefOf.Melee;
            isShooter = highestSkill == SkillDefOf.Shooting;
            int  fighterHandicap = (isFighter | isShooter) ? 1 : 0;
            bool guru            = techLevel < TechLevel.Archotech && highestSkill == SkillDefOf.Intellectual && highestSkillRecord.Level >= Rand.Range(7, 10);

            //2. Calculate how many techs he should know
            int minSlots = techLevel > TechLevel.Medieval ? 1 : oldBonus;
            int slots    = Mathf.Max(minSlots, FactionExpertiseRange(techLevel) - growthAdjust + oldBonus - fighterHandicap);

            if (slots == 0)
            {
                if (Prefs.LogVerbose)
                {
                    Log.Warning($"... No slots for {pawn.gender.GetObjective()}, returning null. (StartingTechLevel is {techLevel}, CurLifeStageIndex is {pawn.ageTracker.CurLifeStageIndex}, fighterHandicap is {fighterHandicap})");
                }
                return(null);
            }

            //3. Info for debugging.

            if (Prefs.LogVerbose)
            {
                StringBuilder stringBuilder = new StringBuilder();
                string        factionName   = faction.label.ToLower() ?? pawn.Possessive().ToLower() + faction;
                if (TechPoolIncludesStarting)
                {
                    stringBuilder.Append($"default for {factionName}");
                }
                if (TechPoolIncludesTechLevel)
                {
                    stringBuilder.AppendWithComma($"{factionTechLevel.ToString().ToLower()} age");
                }
                if (TechPoolIncludesScenario)
                {
                    stringBuilder.AppendWithComma($"{Find.Scenario.name.ToLower()} scenario");
                }
                if (TechPoolIncludesBackground)
                {
                    stringBuilder.AppendWithComma($"{childhoodLevel.ToString().ToLower()} childhood & {techLevel.ToString().ToLower()} background");
                }
                Log.Message($"... Including technologies from: " + stringBuilder.ToString() + ".");
                stringBuilder.Clear();
                string guruText = guru ? " (allowing advanced knowledge)" : "";
                stringBuilder.Append($"... As {pawn.ageTracker.CurLifeStage.label}, {pawn.ProSubj()} gets {slots} slots. {pawn.Possessive().CapitalizeFirst()} highest relevant skills are {highestSkill.label}{guruText} & {secondSkill.label}.");
                Log.Message(stringBuilder.ToString());
            }

            //4. Finally, Distribute knowledge
            bool strict       = false;
            bool useChildhood = childhoodSkill != null && TechPoolIncludesBackground && SkillIsRelevant(childhoodSkill, childhoodLevel) && slots > 1;
            var  filtered     = TechTracker.FindTechs(x => TechPool(isPlayer, x, workingTechLevel, strict));
            int  pass         = 0;
            List <ResearchProjectDef> result = new List <ResearchProjectDef>();

            if (guru)
            {
                workingTechLevel++;
            }
            while (result.Count() < slots)
            {
                pass++;
                filtered.ExecuteEnumerable();
                if (filtered.EnumerableNullOrEmpty())
                {
                    Log.Warning("[HumanResources] Empty technology pool!");
                }
                var remaining = filtered.Where(x => !result.Contains(x));
                if (remaining.EnumerableNullOrEmpty())
                {
                    break;
                }
                SkillDef skill = null;
                if (pass == 1 && remaining.Any(x => x.Skills.Contains(highestSkill)))
                {
                    skill = highestSkill;
                }
                else if (pass == 2 && remaining.Any(x => x.Skills.Contains(secondSkill)))
                {
                    skill = useChildhood ? childhoodSkill : secondSkill;
                }
                ResearchProjectDef selected = remaining.RandomElementByWeightWithDefault(x => TechLikelihoodForSkill(pawn, x.Skills, slots, pass, skill), 1f) ?? remaining.RandomElement();
                result.Add(selected);

                //prepare next pass:
                strict = false;
                if ((guru && pass == 1) | result.NullOrEmpty())
                {
                    workingTechLevel--;
                }
                if (useChildhood)
                {
                    if (pass == 1)
                    {
                        strict           = true;
                        workingTechLevel = childhoodLevel;
                    }
                    if (pass == 2)
                    {
                        workingTechLevel = techLevel;
                    }
                }
                if (workingTechLevel == 0)
                {
                    break;
                }
            }
            if (!result.NullOrEmpty())
            {
                return(result);
            }
            Log.Error($"[HumanResources] Couldn't calculate any expertise for {pawn}");
            return(null);
        }
Ejemplo n.º 34
0
 // Token: 0x06002629 RID: 9769 RVA: 0x001225E4 File Offset: 0x001209E4
 public override void Draw()
 {
     Rand.PushState();
     Rand.Seed = this.thingIDNumber;
     for (int i = 0; i < 6; i++)
     {
         this.DrawDustPart(Rand.Range(0f, 360f), Rand.Range(0.9f, 1.1f) * (float)Rand.Sign * 4f, Rand.Range(1f, 1.5f));
     }
     Rand.PopState();
 }
Ejemplo n.º 35
0
        private void DoCellSteadyEffects(IntVec3 c)
        {
            Room room  = c.GetRoom(map, RegionType.Set_All);
            bool flag  = map.roofGrid.Roofed(c);
            bool flag2 = room?.UsesOutdoorTemperature ?? false;

            if ((room == null) | flag2)
            {
                if (outdoorMeltAmount > 0f)
                {
                    map.snowGrid.AddDepth(c, 0f - outdoorMeltAmount);
                }
                if (!flag && snowRate > 0.001f)
                {
                    AddFallenSnowAt(c, 0.046f * map.weatherManager.SnowRate);
                }
            }
            if (room != null)
            {
                bool         protectedByEdifice = ProtectedByEdifice(c, map);
                TerrainDef   terrain            = c.GetTerrain(map);
                List <Thing> thingList          = c.GetThingList(map);
                for (int i = 0; i < thingList.Count; i++)
                {
                    Thing thing = thingList[i];
                    Filth filth = thing as Filth;
                    if (filth != null)
                    {
                        if (!flag && thing.def.filth.rainWashes && Rand.Chance(rainRate))
                        {
                            filth.ThinFilth();
                        }
                        if (filth.DisappearAfterTicks != 0 && filth.TicksSinceThickened > filth.DisappearAfterTicks)
                        {
                            filth.Destroy();
                        }
                    }
                    else
                    {
                        TryDoDeteriorate(thing, flag, flag2, protectedByEdifice, terrain);
                    }
                }
                if (!flag2)
                {
                    float temperature = room.Temperature;
                    if (temperature > 0f)
                    {
                        float num = MeltAmountAt(temperature);
                        if (num > 0f)
                        {
                            map.snowGrid.AddDepth(c, 0f - num);
                        }
                        if (room.RegionType.Passable() && temperature > AutoIgnitionTemperatureRange.min)
                        {
                            float value = Rand.Value;
                            if (value < AutoIgnitionTemperatureRange.InverseLerpThroughRange(temperature) * 0.7f && Rand.Chance(FireUtility.ChanceToStartFireIn(c, map)))
                            {
                                FireUtility.TryStartFireIn(c, map, 0.1f);
                            }
                            if (value < 0.33f)
                            {
                                MoteMaker.ThrowHeatGlow(c, map, 2.3f);
                            }
                        }
                    }
                }
            }
            map.gameConditionManager.DoSteadyEffects(c, map);
        }
Ejemplo n.º 36
0
        public override bool Use(float deltaTime, Character character = null)
        {
            if (character == null)
            {
                return(false);
            }
            if (!character.IsKeyDown(InputType.Aim))
            {
                return(false);
            }

            //if (DoesUseFail(Character)) return false;

            //targetPosition = targetPosition.X, -targetPosition.Y);

            float degreeOfSuccess = DegreeOfSuccess(character) / 100.0f;

            if (Rand.Range(0.0f, 0.5f) > degreeOfSuccess)
            {
                ApplyStatusEffects(ActionType.OnFailure, deltaTime, character);
                return(false);
            }

            Vector2 targetPosition = item.WorldPosition;

            targetPosition += new Vector2(
                (float)Math.Cos(item.body.Rotation),
                (float)Math.Sin(item.body.Rotation)) * range * item.body.Dir;

            List <Body> ignoredBodies = new List <Body>();

            foreach (Limb limb in character.AnimController.Limbs)
            {
                if (Rand.Range(0.0f, 0.5f) > degreeOfSuccess)
                {
                    continue;
                }
                ignoredBodies.Add(limb.body.FarseerBody);
            }

            IsActive    = true;
            activeTimer = 0.1f;

            Vector2 rayStart = ConvertUnits.ToSimUnits(item.WorldPosition);
            Vector2 rayEnd   = ConvertUnits.ToSimUnits(targetPosition);

            if (character.Submarine == null)
            {
                foreach (Submarine sub in Submarine.Loaded)
                {
                    Repair(rayStart - sub.SimPosition, rayEnd - sub.SimPosition, deltaTime, character, degreeOfSuccess, ignoredBodies);
                }
                Repair(rayStart, rayEnd, deltaTime, character, degreeOfSuccess, ignoredBodies);
            }
            else
            {
                Repair(rayStart - character.Submarine.SimPosition, rayEnd - character.Submarine.SimPosition, deltaTime, character, degreeOfSuccess, ignoredBodies);
            }

#if CLIENT
            GameMain.ParticleManager.CreateParticle(particles, item.WorldPosition + TransformedBarrelPos,
                                                    -item.body.Rotation + ((item.body.Dir > 0.0f) ? 0.0f : MathHelper.Pi), ParticleSpeed);
#endif

            return(true);
        }
Ejemplo n.º 37
0
        protected override bool TryCastShot()
        {
            Pawn caster = base.CasterPawn;

            CompAbilityUserMagic comp = caster.GetComp <CompAbilityUserMagic>();
            MagicPowerSkill      eff  = comp.MagicData.MagicPowerSkill_TechnoWeapon.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_TechnoWeapon_eff");

            bool flag = caster != null && !caster.Dead;

            if (flag)
            {
                HealthUtility.AdjustSeverity(caster, HediffDef.Named("TM_NanoStimulantHD"), (eff.level + .01f) * comp.arcaneDmg);
                SoundInfo info = SoundInfo.InMap(new TargetInfo(caster.Position, caster.Map, false), MaintenanceType.None);
                info.pitchFactor  = 1.0f;
                info.volumeFactor = 1.0f;
                TorannMagicDefOf.TM_FastReleaseSD.PlayOneShot(info);
                TM_MoteMaker.ThrowGenericMote(ThingDef.Named("Mote_PowerWave"), caster.DrawPos, caster.Map, .8f, .2f, .1f, .1f, 0, 1f, 0, Rand.Chance(.5f) ? 0 : 180);
            }
            return(true);
        }
Ejemplo n.º 38
0
    public void CountDown()
    {
        fadeInInstant.Play();

        Invoke("FadeOut", Rand.Range(MIN_BEFORE_FADE, MAX_BEFORE_FADE));
    }
Ejemplo n.º 39
0
        /// <summary>绑定用户,用户未有效绑定或需要强制绑定时</summary>
        /// <param name="uc"></param>
        /// <param name="client"></param>
        public virtual IManageUser OnBind(UserConnect uc, OAuthClient client)
        {
            var log  = LogProvider.Provider;
            var prv  = Provider;
            var mode = "";

            // 如果未登录,需要注册一个
            var user = prv.Current;

            if (user == null)
            {
                // 匹配UnionId
                if (user == null && !client.UnionID.IsNullOrEmpty())
                {
                    var list = UserConnect.FindAllByUnionId(client.UnionID);

                    //// 排除当前项,选择登录次数最多的用户
                    //list = list.Where(e => e.ID != uc.ID && e.UserID > 0).ToList();
                    // 选择登录次数最多的用户
                    var ids   = list.Where(e => e.Enable && e.UserID > 0).Select(e => e.UserID).Distinct().ToArray();
                    var users = ids.Select(e => User.FindByID(e)).Where(e => e != null).ToList();
                    if (users.Count > 0)
                    {
                        mode = "UnionID";
                        user = users.OrderByDescending(e => e.Logins).FirstOrDefault();
                    }
                }

                var set = Setting.Current;
                var cfg = OAuthConfig.FindByName(client.Name);
                //if (!cfg.AutoRegister) throw new InvalidOperationException($"绑定[{cfg}]要求本地已登录!");
                if (user == null && !set.AutoRegister && !cfg.AutoRegister)
                {
                    log?.WriteLog(typeof(User), "SSO登录", false, $"无法找到[{client.Name}]的[{client.NickName}]在本地的绑定,且没有打开自动注册,准备进入登录页面,利用其它登录方式后再绑定", 0, user + "");

                    return(null);
                }

                // 先找用户名,如果存在,就加上提供者前缀,直接覆盖
                var name = client.UserName;
                if (name.IsNullOrEmpty())
                {
                    name = client.NickName;
                }
                if (user == null && !name.IsNullOrEmpty())
                {
                    // 强制绑定本地用户时,没有前缀
                    if (set.ForceBindUser)
                    {
                        mode = "UserName";
                        user = prv.FindByName(name);
                    }
                    else
                    {
                        mode = "Provider-UserName";
                        name = client.Name + "_" + name;
                        user = prv.FindByName(name);
                    }
                }

                // 匹配Code
                if (user == null && set.ForceBindUserCode)
                {
                    mode = "UserCode";
                    if (!client.UserCode.IsNullOrEmpty())
                    {
                        user = User.FindByCode(client.UserCode);
                    }
                }

                // 匹配Mobile
                if (user == null && set.ForceBindUserMobile)
                {
                    mode = "UserMobile";
                    if (!client.Mobile.IsNullOrEmpty())
                    {
                        user = User.FindByMobile(client.Mobile);
                    }
                }

                // 匹配Mail
                if (user == null && set.ForceBindUserMail)
                {
                    mode = "UserMail";
                    if (!client.Mail.IsNullOrEmpty())
                    {
                        user = User.FindByMail(client.Mail);
                    }
                }

                // QQ、微信 等不返回用户名
                if (user == null && name.IsNullOrEmpty())
                {
                    // OpenID和AccessToken不可能同时为空
                    var openid = client.OpenID;
                    if (openid.IsNullOrEmpty())
                    {
                        openid = client.AccessToken;
                    }

                    // 过长,需要随机一个较短的
                    var num = openid.GetBytes().Crc();

                    mode = "OpenID-Crc";
                    name = client.Name + "_" + num.ToString("X8");
                    user = prv.FindByName(name);
                }

                if (user == null)
                {
                    mode = "Register";

                    // 新注册用户采用魔方默认角色
                    var rid = Role.GetOrAdd(set.DefaultRole).ID;
                    //if (rid == 0 && client.Items.TryGetValue("roleid", out var roleid)) rid = roleid.ToInt();
                    //if (rid <= 0) rid = GetRole(client.Items, rid < -1);

                    // 注册用户,随机密码
                    user = prv.Register(name, Rand.NextString(16), rid, true);
                    //if (user is User user2) user2.RoleIDs = GetRoles(client.Items, rid < -2).Join();
                }
            }

            uc.UserID = user.ID;
            uc.Enable = true;

            // 写日志
            log?.WriteLog(typeof(User), "绑定", true, $"[{user}]依据[{mode}]绑定到[{client.Name}]的[{client.NickName}]", user.ID, user + "");

            return(user);
        }
Ejemplo n.º 40
0
        public void GenerateAnimalCorpses()
        {
            Log.Message("GenerateAnimalCorpses");
            int animalCorpsesNumber = Rand.Range(3, 7);

            for (int corpseIndex = 0; corpseIndex < animalCorpsesNumber; corpseIndex++)
            {
                Predicate <IntVec3> validator = delegate(IntVec3 cell)
                {
                    if (cell.Standable() == false)
                    {
                        return(false);
                    }
                    foreach (Thing thing in Find.ThingGrid.ThingsListAt(cell))
                    {
                        if (thing is Corpse)
                        {
                            return(false);
                        }
                    }
                    return(true);
                };

                IntVec3 spawnCell        = IntVec3.Invalid;
                bool    spawnCellIsFound = CellFinder.TryFindRandomCellNear(this.Position, 5, validator, out spawnCell);
                if (spawnCellIsFound)
                {
                    PawnKindDef animalKindDef;
                    float       animalKindSelector = Rand.Value;
                    if (animalKindSelector < 0.33f)
                    {
                        animalKindDef = PawnKindDef.Named("Muffalo");
                    }
                    else if (animalKindSelector < 0.66f)
                    {
                        animalKindDef = PawnKindDef.Named("Caribou");
                    }
                    else
                    {
                        animalKindDef = PawnKindDef.Named("Deer");
                    }
                    Building_VillagerCorpsesGenerator.SpawnPawnCorpse(spawnCell, animalKindDef, null, Rand.Range(5f, 20f) * GenDate.TicksPerDay);
                }
            }
        }
Ejemplo n.º 41
0
 public void ApplyOverdriveHD(Pawn pawn)
 {
     ApplyHediffs(pawn);
     FleckMaker.ThrowLightningGlow(pawn.DrawPos, pawn.Map, 1.5f);
     TM_MoteMaker.ThrowGenericMote(ThingDef.Named("Mote_PowerWave"), pawn.DrawPos, pawn.Map, .6f, .3f, 0, .3f, Rand.Range(-500, 500), 0, 0, Rand.Range(0, 360));
 }
Ejemplo n.º 42
0
        //ResolveParams's GetCustom/SetCustom is broken now, and it is a sealed (WHY??!) struct (WHY??!?!?) so I neither can fix it, nor make a dirty hack.
        //Seems like I have to abandon this approach and make direct calls.
        static public void Scatter(ResolveParams rp, ScatterOptions options, CoverageMap coverage, List <AbstractDefenderForcesGenerator> generators)
        {
            Debug.Log(Debug.Scatter, "Running stand-alone scatterer");
            if (options == null)
            {
                Debug.Warning(Debug.Scatter, "Scatter options are null, aborting");
                return;
            }

            DateTime start = DateTime.UtcNow;

            Debug.Log(Debug.Scatter, "[0 s]: Loading blueprint of size {0} - {1} to deploy at {2}, {3}", options.minRadius, options.maxRadius, rp.rect.minX, rp.rect.minZ);

            Blueprint bp  = null;
            Map       map = BaseGen.globalSettings.map;

            //probably should split scattering options into several distinct objects
            string filename = options.blueprintFileName;

            if (string.IsNullOrEmpty(filename) || !BlueprintLoader.CanLoadBlueprintAtPath(filename))
            {
                bp = BlueprintFinder.FindRandomBlueprintWithParameters(out filename, options.minimumAreaRequired, options.minimumDensityRequired, 15, removeNonQualified: options.deleteLowQuality);
                if (string.IsNullOrEmpty(filename))
                {
                    //still null = no suitable blueprints, fail.
                    Debug.Warning(Debug.Scatter, "Blueprint name was null and could not find another suitable blueprint, skipping");
                    return;
                }
            }

            if (!options.shouldLoadPartOnly) //should not cut => load whole
            {
                if (bp == null)              //if not loaded yet
                {
                    bp = BlueprintLoader.LoadWholeBlueprintAtPath(filename);
                }
            }
            else
            {
                int radius = Rand.Range(options.minRadius, options.maxRadius);
                if (bp == null)
                {
                    bp = BlueprintLoader.LoadWholeBlueprintAtPath(filename).RandomPartCenteredAtRoom(new IntVec3(radius, 0, radius));
                }
                else
                {
                    bp = bp.RandomPartCenteredAtRoom(new IntVec3(radius, 0, radius));
                }
            }

            if (bp == null)
            {
                Debug.Warning(Debug.Scatter, "Blueprint is still null after attempting to load any qualifying, returning");
                return;
            }


            Debug.Extra(Debug.Scatter, "Blueprint loaded, cutting and searching for rooms");
            bp.CutIfExceedsBounds(map.Size);

            // Here we have our blueprint loaded and ready to action. Doing stuff:
            BlueprintPreprocessor.ProcessBlueprint(bp, options); //Preprocess: remove missing and unnecessary items according to options
            bp.FindRooms();                                      //Traverse blueprint and construct rooms map
            options.roomMap = bp.wallMap;

            //Debug.PrintIntMap(bp.wallMap, delta: 1);
            Debug.Extra(Debug.Scatter, "Rooms traversed, initializing transfer utility");

            BlueprintTransferUtility btu = new BlueprintTransferUtility(bp, map, rp, options); //prepare blueprint transferrer

            Debug.Extra(Debug.Scatter, "Initialized, removing incompatible items...");

            btu?.RemoveIncompatibleItems(); //remove incompatible items
            Debug.Extra(Debug.Scatter, "Recalculating stats...");

            bp.UpdateBlueprintStats(true); //Update total cost, items count, etc

            Debug.Extra(Debug.Scatter, "Deteriorating...");
            DeteriorationProcessor.Process(bp, options); //create deterioration maps and do deterioration

            Debug.Extra(Debug.Scatter, "Scavenging...");
            ScavengingProcessor sp = new ScavengingProcessor();

            sp.RaidAndScavenge(bp, options); //scavenge remaining items according to scavenge options

            Debug.Extra(Debug.Scatter, "[{0} s] Prepared, about to start transferring.", DateTime.UtcNow.Subtract(start).TotalSeconds);
            try {
                btu.Transfer(coverage); //transfer blueprint
                Debug.Extra(Debug.Scatter, "[{0} s] Transferred.", DateTime.UtcNow.Subtract(start).TotalSeconds);
            } catch (Exception e) {
                Debug.Error(Debug.BlueprintTransfer, "Failed to transfer blueprint due to {0}", e);
            }

            if (generators != null)
            {
                foreach (AbstractDefenderForcesGenerator generator in generators)
                {
                    try {
                        generator.GenerateForces(map, rp, options);
                    } catch (Exception e) {
                        Debug.Error(Debug.BlueprintTransfer, "Failed to generate forces: {0}", e);
                    }
                }
            }
            Debug.Log(Debug.Scatter, "[{0} s] Generated forces.", DateTime.UtcNow.Subtract(start).TotalSeconds);

            if (options.shouldAddFilth)
            {
                try {
                    btu.AddFilthAndRubble(); //add filth and rubble
                } catch (Exception e) {
                    Debug.Warning(Debug.BlueprintTransfer, "Failed to add filth and rubble: {0}", e);
                }
            }
            Debug.Extra(Debug.Scatter, "[{0} s] Spiced up with rubble. Completed.", DateTime.UtcNow.Subtract(start).TotalSeconds);

            Debug.Log(Debug.Scatter, "Chunk scattering finished, moving");
        }
Ejemplo n.º 43
0
    public static int Main(String[] args)
    {
        if (GCSettings.IsServerGC == true)
        {
            Console.WriteLine("we are using server GC");
        }
        int iter_num = 500000;
        if (args.Length >= 1)
        {
            iter_num = int.Parse(args[0]);
            Console.WriteLine("iterating {0} times", iter_num);
        }

        // ProjectN doesn't support thread! for now just do everything on the main thread.
        //int threadCount = 8;
        //        int threadCount = 1;
        //        if (args.Length >= 2)
        //        {
        //            threadCount = int.Parse(args[1]);
        //            Console.WriteLine ("creating {0} threads", threadCount);
        //        }

        long tStart, tEnd;
        tStart = Environment.TickCount;
        //        MyThread t;
        //        ThreadStart ts;
        //        Thread[] threads = new Thread[threadCount];
        //
        //        for (int i = 0; i < threadCount; i++)
        //        {
        //            t = new MyThread(i, iter_num, old, med);
        //            ts = new ThreadStart(t.TimeTest);
        //            threads[i] = new Thread( ts );
        //            threads[i].Start();
        //        }
        //
        //        for (int i = 0; i < threadCount; i++)
        //        {
        //            threads[i].Join();
        //        }
        //

        Console.WriteLine("start with {0} gen1 GCs", s_iLastGen1Count);

        s_iLastGen0Count = GC.CollectionCount(0);
        s_iLastGen1Count = GC.CollectionCount(1);

        for (int iter = 0; iter < 1; iter++)
        {
            MemoryAlloc[] maArr = new MemoryAlloc[16];

            Rand rand = new Rand();
            for (int i = 0; i < maArr.Length; i++)
            {
                maArr[i] = new MemoryAlloc(rand.getRand(500), rand, i);
                maArr[i].AllocTest();
                //Console.WriteLine("{0} allocated", i);
                InducedGen2();

                for (int iAllocated = 0; iAllocated < i; iAllocated++)
                {
                    //Console.WriteLine("creating fragmentation in obj {0}", iAllocated);
                    maArr[iAllocated].CreateFragmentation();
                    InducedGen2();
                }
            }

            for (int i = 0; i < maArr.Length; i++)
            {
                InducedGen2();
                Console.WriteLine("steady state for " + i);
                maArr[i].SteadyState();
                Console.WriteLine("DONE: steady state for " + i);
            }
        }

        tEnd = Environment.TickCount;
        Console.WriteLine("Test completed; " + (tEnd - tStart) + "ms");
        //        Console.WriteLine("Press any key to exit.");
        //        Console.ReadLine();

        return 100;
    }
Ejemplo n.º 44
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            ThingDef def    = this.def;
            Pawn     victim = hitThing as Pawn;

            Pawn pawn = this.launcher as Pawn;
            CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();

            pwr = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_LightningCloud.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_LightningCloud_pwr");
            ver = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_LightningCloud.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_LightningCloud_ver");
            ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
            pwrVal         = pwr.level;
            verVal         = ver.level;
            this.arcaneDmg = comp.arcaneDmg;
            if (settingsRef.AIHardMode && !pawn.IsColonistPlayerControlled)
            {
                pwrVal = 3;
                verVal = 3;
            }
            radius = (int)this.def.projectile.explosionRadius + (2 * verVal);

            CellRect cellRect = CellRect.CenteredOn(base.Position, radius - 3);

            cellRect.ClipInsideMap(map);
            IntVec3 randomCell = cellRect.RandomCell;

            duration = 900 + (verVal * 360);

            if (this.primed == true)
            {
                if (((this.shockDelay + this.lastStrike) < this.age))
                {
                    for (int i = 0; i < 5; i++)
                    {
                        randomCell = cellRect.RandomCell;
                        if (randomCell.InBounds(map))
                        {
                            victim = randomCell.GetFirstPawn(map);
                            if (victim != null)
                            {
                                damageEntities(victim, Mathf.RoundToInt((this.def.projectile.damageAmountBase + pwrVal) * this.arcaneDmg));
                            }
                        }
                    }

                    Vector3 loc2 = base.Position.ToVector3Shifted();
                    Vector3 loc  = randomCell.ToVector3Shifted();

                    bool rand1 = Rand.Range(0, 100) < 3;
                    bool rand2 = Rand.Range(0, 100) < 16;
                    if (rand1)
                    {
                        MoteMaker.ThrowSmoke(loc2, map, radius);
                        SoundDefOf.AmbientAltitudeWind.sustainFadeoutTime.Equals(30.0f);
                    }
                    if (rand2)
                    {
                        MoteMaker.ThrowSmoke(loc, map, 4f);
                    }

                    MoteMaker.ThrowMicroSparks(loc, map);
                    MoteMaker.ThrowLightningGlow(loc, map, 2f);

                    strikeInt++;
                    this.lastStrike = this.age;
                    this.shockDelay = Rand.Range(1, 3);

                    bool flag1 = this.age <= duration;
                    if (!flag1)
                    {
                        this.primed = false;
                    }
                }
            }
        }
Ejemplo n.º 45
0
    private void Randomize()
    {
        /*
         * Check the range of the neighbours heights;
         * If the neighbours are all the same height or +1,
         * then maybe increase height;
         * Do opposite for decreasing height;
         */
        // RNG for non-edge points
        Rand inside_rand = new Rand((GLOBAL_SEED << 12) ^ (world_x << 8) ^ (world_z << 4) ^ SIZE);

        /* First lets randomize the edges
         * we need to a special RNG for this so that other chunks
         * can generate the same edges
         */
        Rand left_edge = new Rand((GLOBAL_SEED << 12) ^ ((world_z-1) << 8) ^ (heights[0,0] << 4) ^ (heights[SIZE,0]));
        Rand right_edge = new Rand((GLOBAL_SEED << 12) ^ (world_z << 8) ^ (heights[0,SIZE] << 4) ^ (heights[SIZE,SIZE]));
        Rand top_edge = new Rand((GLOBAL_SEED << 12) ^ (world_x << 8) ^ (heights[SIZE,0] << 4) ^ (heights[SIZE,SIZE]));
        Rand bottom_edge = new Rand((GLOBAL_SEED << 12) ^ (world_x-1 << 8) ^ (heights[0,0] << 4) ^ (heights[0,SIZE]));
        /*
         * Note that we can only change odd-numbered edge cells
         * This is because we assume that even-number cells need to line up with
         * another chunk at half resolution next to this chunk
         */

        // do bottom and top edges
        for(int z = 1; z < SIZE; z+=2){
            // first bottom edge
            int positives = 0;
            int negatives = 0;
            positives += heights[0,z-1]-heights[0,z] >= 1 ? 1 : 0;
            positives += heights[0,z+1]-heights[0,z] >= 1 ? 1 : 0;
            negatives += heights[0,z-1]-heights[0,z] <= 1 ? 1 : 0;
            negatives += heights[0,z+1]-heights[0,z] <= 1 ? 1 : 0;
            // try increasing height
            if(negatives == 0  && positives > 0 && bottom_edge.nextf() < noisiness * up_proclivity){
                heights[0,z] += 1;
            }
            // try decreasing height
            else if(positives == 0 && negatives > 0 && bottom_edge.nextf() < noisiness * down_proclivity){
                heights[0,z] -= 1;
            }
            // randomly increase or decrease height on flat terrain
            else if (positives == 0 && negatives == 0 && bottom_edge.nextf() < noisiness * not_flat_proclivity){
                heights[0,z] += (bottom_edge.next() & 1)*2 - 1;
            }
            // now top edge
            positives = 0;
            negatives = 0;
            positives += heights[SIZE,z-1]-heights[SIZE,z] >= 1 ? 1 : 0;
            positives += heights[SIZE,z+1]-heights[SIZE,z] >= 1 ? 1 : 0;
            negatives += heights[SIZE,z-1]-heights[SIZE,z] <= 1 ? 1 : 0;
            negatives += heights[SIZE,z+1]-heights[SIZE,z] <= 1 ? 1 : 0;
            // try increasing height
            if(negatives == 0  && positives > 0 && top_edge.nextf() < noisiness * up_proclivity){
                heights[SIZE,z] += 1;
            }
            // try decreasing height
            else if(positives == 0 && negatives > 0 && top_edge.nextf() < noisiness * down_proclivity){
                heights[SIZE,z] -= 1;
            }
            // randomly increase or decrease height on flat terrain
            else if (positives == 0 && negatives == 0 && top_edge.nextf() < noisiness * not_flat_proclivity){
                heights[SIZE,z] += (top_edge.next() & 1)*2 - 1;
            }
        }
        // do left and right edges
        for(int x = 1; x < SIZE; x+=2){
            // first left edge
            int positives = 0;
            int negatives = 0;
            positives += heights[x-1,0]-heights[x,0] >= 1 ? 1 : 0;
            positives += heights[x+1,0]-heights[x,0] >= 1 ? 1 : 0;
            negatives += heights[x-1,0]-heights[x,0] <= 1 ? 1 : 0;
            negatives += heights[x+1,0]-heights[x,0] <= 1 ? 1 : 0;
            // try increasing height
            if(negatives == 0  && positives > 0 && left_edge.nextf() < noisiness * up_proclivity){
                heights[x,0] += 1;
            }
            // try decreasing height
            else if(positives == 0 && negatives > 0 && left_edge.nextf() < noisiness * down_proclivity){
                heights[x,0] -= 1;
            }
            // randomly increase or decrease height on flat terrain
            else if (positives == 0 && negatives == 0 && left_edge.nextf() < noisiness * not_flat_proclivity){
                heights[x,0] += (left_edge.next() & 1)*2 - 1;
            }
            // now right edge
            positives = 0;
            negatives = 0;
            positives += heights[x-1,SIZE]-heights[x,SIZE] >= 1 ? 1 : 0;
            positives += heights[x+1,SIZE]-heights[x,SIZE] >= 1 ? 1 : 0;
            negatives += heights[x-1,SIZE]-heights[x,SIZE] <= 1 ? 1 : 0;
            negatives += heights[x+1,SIZE]-heights[x,SIZE] <= 1 ? 1 : 0;
            // try increasing height
            if(negatives == 0  && positives > 0 && right_edge.nextf() < noisiness * up_proclivity){
                heights[x,SIZE] += 1;
            }
            // try decreasing height
            else if(positives == 0 && negatives > 0 && right_edge.nextf() < noisiness * down_proclivity){
                heights[x,SIZE] -= 1;
            }
            // randomly increase or decrease height on flat terrain
            else if (positives == 0 && negatives == 0 && right_edge.nextf() < noisiness * not_flat_proclivity){
                heights[x,SIZE] += (right_edge.next() & 1)*2 - 1;
            }
        }

        // now do the insides with the inside RNG
        for(int x = 1; x < SIZE; x+=1){
            for(int z = 1; z < SIZE; z+=1){
                // go clockwise starting at bottom left corner of hexagon
                int positives = 0;
                int negatives = 0;
                //
                positives += heights[x-1,z]-heights[x,z] >= 1 ? 1 : 0;
                negatives += heights[x-1,z]-heights[x,z] <= -1 ? 1 : 0;
                //
                positives += heights[x,z-1]-heights[x,z] >= 1 ? 1 : 0;
                negatives += heights[x,z-1]-heights[x,z] <= -1 ? 1 : 0;
                //
                positives += heights[x+1,z-1]-heights[x,z] >= 1 ? 1 : 0;
                negatives += heights[x+1,z-1]-heights[x,z] <= -1 ? 1 : 0;
                //
                positives += heights[x+1,z]-heights[x,z] >= 1 ? 1 : 0;
                negatives += heights[x+1,z]-heights[x,z] <= -1 ? 1 : 0;
                //
                positives += heights[x,z+1]-heights[x,z] >= 1 ? 1 : 0;
                negatives += heights[x,z+1]-heights[x,z] <= -1 ? 1 : 0;
                //
                positives += heights[x-1,z+1]-heights[x,z] >= 1 ? 1 : 0;
                negatives += heights[x-1,z+1]-heights[x,z] <= -1 ? 1 : 0;

                // try increasing height
                if(negatives == 0  && positives > 0 && inside_rand.nextf() < noisiness * up_proclivity){
                    heights[x,z] += 1;
                }
                // try decreasing height
                else if(positives == 0 && negatives > 0 && inside_rand.nextf() < noisiness * down_proclivity){
                    heights[x,z] -= 1;
                }
                // randomly increase or decrease height on flat terrain
                else if (positives == 0 && negatives == 0 && inside_rand.nextf() < noisiness * not_flat_proclivity){
                    heights[x,z] += (inside_rand.next() & 1)*2 - 1;
                }
            }
        }
    }
Ejemplo n.º 46
0
 public MemoryAlloc(int iter, Rand _rand, int i)
 {
     _iter_count = iter;
     if (_iter_count == 0)
         _iter_count = 1000;
     this._rand = _rand;
     _index = i;
 }
 public void Randomize(bool newTheme = true)
 {
     int seed = new Rand ().Next ();
     Debug.Log ("Randomizing with seed "+seed);
     Randomize (seed, newTheme);
 }
Ejemplo n.º 48
0
        /*
         * @param _funcType Style of the top line that generated
         * @param _res Size of mapunits for one linear segment
         * */
        public PolygonActor(World _world, Vector2 _position, uint _seed, FunctionType _funcType, int _res = 5)
            : base(_world, _position)
        {
            int lineCount = (int)Constants.worldSizeX / _res;

            //make sure to have an even number
            if (lineCount % 2 != 0) lineCount++;
            Vec2[] verts = new Vec2[(int)lineCount + 1 + 4];
            vertexBuffer = new VertexArray(PrimitiveType.LinesStrip);

            Vector2 posScreen = _position.toScreenCoord();

            //repeatable random sequenze
            Rand rnd = new Rand(_seed);

            //start and end have even ground
            verts[0] = new Vec2(0, 6);
            verts[1] = new Vec2(_res, 6);
            verts[2] = new Vec2(_res + _res, 6);

            verts[lineCount - 2] = new Vec2(_res * (lineCount - 2), 6);
            verts[lineCount-1] = new Vec2(_res * (lineCount-1), 6);
            verts[lineCount] = new Vec2(_res * lineCount, 6);

            vertexBuffer.Append(new Vertex(((Vector2)verts[0] + _position).toScreenCoord()));
            //create the function
            if (_funcType == FunctionType.Simple)
            {
                for (int i = 2; i <= lineCount; ++i)
                {
                    //Vector2 pos = new Vec2(i * 5, 10 + Rand.IntValue(10));
                    Vector2 pos = new Vec2(i * _res, System.Math.Max((verts[i - 1].Y + (int)rnd.next(6) - 3), 0));
                    verts[i] = pos;
                }
            }
            else if(_funcType == FunctionType.GradientNoise)
            {
                for (int i = 2; i < lineCount-3;)
                {
                    int nextGrad = i + 4;

                    if (nextGrad < lineCount - 2)
                    {
                        verts[nextGrad] = new Vec2(nextGrad * _res, rnd.next((int)maxHeight));
                    }
                    else nextGrad = lineCount - 2;

                    //interpolate between
                    float relativeA = verts[i].Y / maxHeight;
                    float relativeB = verts[nextGrad].Y / maxHeight;
                    for (int c = i + 1; c < nextGrad; ++c)
                    {
                        verts[c] = new Vec2(c * _res, maxHeight * interpolateCos(relativeA, relativeB, (float)(c - i) / 4));
                    }

                    i = nextGrad;
                }

            }

            Array.Resize<Body>(ref triangleBodys, lineCount);

            PolygonDef triangleDef = new PolygonDef();
            triangleDef.Density = 0.0f;
            triangleDef.Friction = 1.0f;
            triangleDef.VertexCount = 3;

            BodyDef bodydef = new BodyDef();
            bodydef.Position = _position;
            bodydef.Angle = 0.0f;

            //convert to triangles
            for (int i = 0; i < lineCount; ++i)
            {
                //always 3 points of the function form a triangle
                triangleDef.Vertices[0] = verts[i];
                triangleDef.Vertices[1] = verts[i] - new Vec2(0.0f, 50.0f);
                triangleDef.Vertices[2] = verts[i + 1];//.Y < verts[i+1].Y ? verts[i] : verts[i + 1]

                triangleBodys[i] = _world.CreateBody(bodydef);
                triangleBodys[i].CreateShape(triangleDef);

                vertexBuffer.Append(new Vertex(((Vector2)verts[i+1] + _position).toScreenCoord()));
            }
        }
Ejemplo n.º 49
0
        public void WildAnimalSpawnerTick()
        {
            IntVec3 loc;

            if (Find.TickManager.TicksGame % 1213 == 0 && !this.AnimalEcosystemFull && Rand.Chance(0.0269555561f * this.DesiredAnimalDensity) && RCellFinder.TryFindRandomPawnEntryCell(out loc, this.map, CellFinder.EdgeRoadChance_Animal, true, null))
            {
                this.SpawnRandomWildAnimalAt(loc);
            }
        }
Ejemplo n.º 50
0
 public Trigger_VisitorsPleasedMax(float threshold)
 {
     data = new TriggerData_VisitorsPleasedMax {
         threshold = threshold, arriveTick = Find.TickManager.TicksGame, minStayTicks = Rand.Range(40000, 75000)
     };
 }
Ejemplo n.º 51
0
 public MemoryAlloc (int iter, Rand _rand, int i)
 {
     iter_count = iter;
     if (iter_count == 0)
         iter_count = 1000;
     rand = _rand;
     index = i;
 }