Example #1
0
    // Pick craters to be shaded with radial streaks emanating from them
    void SetCraters(MoonShape moonShape)
    {
        PRNG random = new PRNG(ejectaRaySeed);
        //int desiredNumCraterRays = random.Range (5, 15);
        //desiredNumCraterRays = 2;

        // Sort craters from largest to smallest
        var sortedCraters = new List <CraterSettings.Crater> (moonShape.craterSettings.cachedCraters);

        sortedCraters.Sort((a, b) => b.size.CompareTo(a.size));
        int poolSize = Mathf.Clamp((int)((sortedCraters.Count - 1) * candidatePoolSize), 1, sortedCraters.Count);

        sortedCraters = sortedCraters.GetRange(0, poolSize);
        random.Shuffle(sortedCraters);

        // Choose craters
        var chosenCraters = new List <CraterSettings.Crater> ();

        for (int i = 0; i < sortedCraters.Count; i++)
        {
            var currentCrater = sortedCraters[i];

            // Reject those which are too close to already chosen craters as the textures may not overlap
            bool overlapsOtherEjecta = false;
            for (int j = 0; j < chosenCraters.Count; j++)
            {
                float dst             = (currentCrater.centre - chosenCraters[j].centre).magnitude;
                float ejectaRadiusSum = (currentCrater.size + chosenCraters[j].size) * ejectaRaysScale / 2;

                if (dst < ejectaRadiusSum)
                {
                    overlapsOtherEjecta = true;
                    break;
                }
            }

            //Debug.DrawRay (currentCrater.centre, currentCrater.centre * 0.2f, (overlapsOtherEjecta) ? Color.red : Color.green);
            if (!overlapsOtherEjecta)
            {
                chosenCraters.Add(currentCrater);
            }
            if (chosenCraters.Count >= desiredNumCraterRays)
            {
                break;
            }
        }

        // Set
        var ejectaCraters = new Vector4[chosenCraters.Count];

        for (int i = 0; i < chosenCraters.Count; i++)
        {
            var crater = chosenCraters[i];
            ejectaCraters[i] = new Vector4(crater.centre.x, crater.centre.y, crater.centre.z, crater.size * ejectaRaysScale);
            //CustomDebug.DrawSphere (crater.centre, crater.size * ejectaRaysScale / 2, Color.yellow);
        }

        ComputeHelper.CreateAndSetBuffer <Vector4> (ref craterBuffer, ejectaCraters, shadingDataCompute, "ejectaCraters");
        shadingDataCompute.SetInt("numEjectaCraters", chosenCraters.Count);
    }
Example #2
0
        private void GenerateDestination()
        {
            Grid  grid       = LevelGenerator.LevelGenerator.INSTANCE.Grid;
            float halfWidth  = grid.Width / 2f;
            float halfHeight = grid.Height / 2f;

            while (!destination.HasValue || !grid.IsWalkable(destination.Value.x, destination.Value.z))
            {
                destination = new Vector3(PRNG.GetFloatNumber(-halfWidth, halfWidth), 0, PRNG.GetFloatNumber(-halfHeight, halfHeight));
            }

            interpolation = 0f;


            // Calculate the total time to walk the distance
            float time         = PersonManager.INSTANCE.TimePerSquare;
            float distanceTime = Vector3.Distance(position, destination.Value) * (time < 0f ? 0.5f : time);

            speed = 1f / distanceTime;

            startPosition = position;
            timeSinceLast = 0f;

            //Debug.DrawLine(destination.Value, destination.Value + Vector3.up, Color.red, 3, false);
        }
Example #3
0
    void SetShadingNoise()
    {
        const string biomeWarpNoiseSuffix  = "_biomeWarp";
        const string detailWarpNoiseSuffix = "_detailWarp";
        const string detailNoiseSuffix     = "_detail";

        PRNG prng  = new PRNG(seed);
        PRNG prng2 = new PRNG(seed);

        if (randomize)
        {
            // warp 1
            var randomizedBiomeWarpNoise = new SimpleNoiseSettings();
            randomizedBiomeWarpNoise.elevation = prng.Range(0.8f, 3f);
            randomizedBiomeWarpNoise.scale     = prng.Range(1f, 3f);
            randomizedBiomeWarpNoise.SetComputeValues(shadingDataCompute, prng2, biomeWarpNoiseSuffix);

            // warp 2
            var randomizedDetailWarpNoise = new SimpleNoiseSettings();
            randomizedDetailWarpNoise.scale     = prng.Range(1f, 3f);
            randomizedDetailWarpNoise.elevation = prng.Range(1f, 5f);
            randomizedDetailWarpNoise.SetComputeValues(shadingDataCompute, prng2, detailWarpNoiseSuffix);

            detailNoise.SetComputeValues(shadingDataCompute, prng2, detailNoiseSuffix);
        }
        else
        {
            biomeWarpNoise.SetComputeValues(shadingDataCompute, prng2, biomeWarpNoiseSuffix);
            detailWarpNoise.SetComputeValues(shadingDataCompute, prng2, detailWarpNoiseSuffix);
            detailNoise.SetComputeValues(shadingDataCompute, prng2, detailNoiseSuffix);
        }
    }
Example #4
0
    public void SpawnEnemy(Vector2 firstDestination)
    {
        // List<Vector2> enemyRoute = GenerateRoute();
        List <Vector2> enemyRoute = new List <Vector2>();

        //enemyRoute.Add(GetSpawnPoint());
        enemyRoute.Add(firstDestination);
        enemyRoute.Add(ClosestPoint(firstDestination));
        GameObject newEnemy = Instantiate(Globals.ENEMY, GetSpawnPoint(), Quaternion.identity);

        newEnemy.transform.SetParent(ObjectContainer.instance.enemies.transform);
        AutoMover autoMover = newEnemy.GetComponent <AutoMover>();
        Inventory inventory = newEnemy.GetComponent <Inventory>();

        autoMover.route        = enemyRoute;
        autoMover.randomPatrol = true;
        autoMover.pointMemory  = PRNG.Range(0, 3);

        Inventory.ItemType[]     types    = (Inventory.ItemType[])System.Enum.GetValues(typeof(Inventory.ItemType));
        Inventory.ItemType       dropType = types[PRNG.Range(0, types.Length)];
        Inventory.InventoryEntry item     = new Inventory.InventoryEntry(dropType, 1);
        inventory.Add(item);

        StartCoroutine(DelayedCall(autoMover, firstDestination));
        //autoMover.SoundToPosition(firstDestination, true, Noise.Source.Gun, Vector2.zero);
    }
        public void Start()
        {
            PRNG.ChangeSeed(Seed);
            grid = new Grid();

            GenerateLevel();
        }
Example #6
0
    private void SpawnEnemy(Vector2 cell)
    {
        List <Vector2> enemyRoute = new List <Vector2>();

        enemyRoute.Add(RandomTileFromCell(cell));

        foreach (Vector2 neighbor in neighborList[cell])
        {
            enemyRoute.Add(RandomTileFromCell(neighbor));
        }


        GameObject newEnemy = Instantiate(Globals.ENEMY, enemyRoute[0], Quaternion.identity);

        // newEnemy.name = newEnemy.name + i;
        newEnemy.transform.SetParent(ObjectContainer.instance.enemies.transform);
        AutoMover autoMover = newEnemy.GetComponent <AutoMover>();
        Inventory inventory = newEnemy.GetComponent <Inventory>();

        autoMover.spawnsWounded = true;
        autoMover.route         = enemyRoute;
        autoMover.randomPatrol  = PRNG.Range(0, 2) == 0;
        autoMover.pointMemory   = PRNG.Range(0, 3);

        Inventory.ItemType[]     types    = (Inventory.ItemType[])System.Enum.GetValues(typeof(Inventory.ItemType));
        Inventory.ItemType       dropType = types[PRNG.Range(0, types.Length)];
        Inventory.InventoryEntry item     = new Inventory.InventoryEntry(dropType, 1);
        inventory.Add(item);

        // Position, route, weaponequipped, leashlength, randompatrol, pointmemory, inventory
    }
Example #7
0
        private int TakePopulationDamage(Hit hit, int damage, PRNG dice = null)
        {
            int inflicted = 0;

            for (int i = 0; i < damage; i++)
            {
                // pick a race and kill some population
                var race = Population.PickWeighted(dice);
                if (race == null)
                {
                    break;                     // no more population
                }
                double popHPPerPerson = Mod.Current.Settings.PopulationHitpoints;
                // TODO - don't ceiling the popKilled, just stack it up
                int popKilled = (int)Math.Ceiling(hit.Shot.DamageType.PopulationDamage.Evaluate(hit.Shot) / popHPPerPerson);
                Population[race] -= popKilled;
                if (Population[race] < 0)
                {
                    Population[race] = 0;
                }
                inflicted += 1;
            }
            // clear population that was emptied out
            foreach (var race in Population.Where(kvp => kvp.Value <= 0).Select(kvp => kvp.Key).ToArray())
            {
                Population.Remove(race);
            }
            return(damage - inflicted);
        }
    void Awake()
    {
        prng = GetComponent <PRNG>();
        GenerateSeeds();
        GenerateRandomGaussianNumbers();

        // the same weight influences for all agents
        BuildPersonalityWeightInfluences();
        BuildStateVarDictionary();


        BuildPersonalityModifierInfluences();
        GenerateActionModifiers();

        // for adding new relationships
        //RelationshipsHolder = transform.Find("Relationships").gameObject;


        //Debug.Log(CheckWeight("timeofday"));
        //Debug.Log(CheckWeight("hunger"));
        //Debug.Log(CheckWeight("energy"));
        //Debug.Log(CheckWeight("wealth"));
        //Debug.Log(CheckWeight("mood"));
        //Debug.Log(CheckWeight("temper"));
        //Debug.Log(CheckWeight("sociability"));
        //Debug.Log(CheckWeight("soberness"));
        //Debug.Log(CheckWeight("resources"));
    }
        /// <summary>
        /// Picks a random element from a weighted sequence.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src"></param>
        /// <returns></returns>
        public static T PickWeighted <T>(this IDictionary <T, double> src, PRNG prng = null)
        {
            var    total = src.Sum(kvp => kvp.Value);
            double num;

            if (prng == null)
            {
                num = RandomHelper.Next(total);
            }
            else
            {
                num = prng.Next(total);
            }
            double sofar = 0;

            foreach (var kvp in src)
            {
                sofar += kvp.Value;
                if (num < sofar)
                {
                    return(kvp.Key);
                }
            }
            return(default(T));            // nothing to pick...
        }
Example #10
0
    /// <summary>
    /// Generates random nested X.690 node.
    /// </summary>
    /// <param name="branches">Maximum number of branches to use.</param>
    /// <param name="leaves">Maximum number of leaves to use.</param>
    /// <param name="depth">Maximum nessting level.</param>
    /// <param name="lengthEncoding">Definite, indefinite or random.</param>
    /// <returns>Random X.690 node.</returns>
    static public X690.Node RandomBranch(int branches, int leaves, int depth, LengthEncoding lengthEncoding = LengthEncoding.Definite)
    {
        var stack = new Stack <X690.Node>();

        for (int i = 0; i < PRNG.Next(branches + 1); i++)
        {
            stack.Push(RandomBranch(lengthEncoding));
        }
        for (int i = 0; i < PRNG.Next(leaves + 1); i++)
        {
            stack.Push(RandomLeaf(lengthEncoding));
        }
        var root = RandomBranch(lengthEncoding);

        foreach (var node in stack.ToArray().Shuffled())
        {
            root.Nodes.Add(node);
        }
        IEnumerable <X690.Node> target = root.Nodes.Where(i => i.IsConstructed);

        while (--depth > 0)
        {
            foreach (var node in target)
            {
                node.Nodes.Add(RandomBranch(branches, leaves, 0, lengthEncoding));
            }
            target = target.SelectMany(i => i.Nodes.Where(j => j.HasNodes));
        }
        return(root);
    }
    protected override void Run()
    {
        var prng   = new PRNG(seed);
        var offset = new Vector4(prng.Value(), prng.Value(), prng.Value(), prng.Value()) * 10;

        ComputeHelper.CreateStructuredBuffer <int> (ref minMaxBuffer, 2);
        minMaxBuffer.SetData(new int[] { int.MaxValue, 0 });
        compute.SetBuffer(0, "minMax", minMaxBuffer);
        compute.SetBuffer(1, "minMax", minMaxBuffer);

        int threadGroupSize = ComputeHelper.GetThreadGroupSizes(compute, 0).x;
        int numThreadGroups = Mathf.CeilToInt((float)textureSize / threadGroupSize);

        compute.SetVector("offset", offset);
        compute.SetTexture(0, "Result", renderTexture);
        noiseSettings.SetComputeValues(compute, prng, "_simple");
        warpNoiseSettings.SetComputeValues(compute, prng, "_warp");

        compute.SetInt("resolution", (int)textureSize);
        compute.SetFloat("valueFloor", valueFloor);
        compute.Dispatch(0, numThreadGroups, numThreadGroups, 1);

        // Normalize
        if (normalize)
        {
            compute.SetTexture(1, "Result", renderTexture);
            compute.Dispatch(1, numThreadGroups, numThreadGroups, 1);
        }

        ComputeHelper.Release(minMaxBuffer);
    }
Example #12
0
        /// <summary>
        /// Creates a new long term cookie
        /// </summary>
        public LongTermCookie()
        {
            m_rawtoken = PRNG.GetRandomBytes(new byte[MAGIC_HEADER.Length + 1 + (TOKEN_BYTES * 2)]);

            Array.Copy(MAGIC_HEADER, m_rawtoken, MAGIC_HEADER.Length);
            m_rawtoken[MAGIC_HEADER.Length] = VERSION;
        }
Example #13
0
        private int TakeFacilityDamage(Hit hit, PRNG dice = null)
        {
            if (Colony == null)
            {
                return(hit.NominalDamage);
            }
            int damage = hit.NominalDamage;

            // TODO - take into account damage types, and make sure we have facilities that are not immune to the damage type so we don't get stuck in an infinite loop
            while (damage > 0 && Colony.Facilities.Any())
            {
                var facil = Colony.Facilities.Where(f =>
                {
                    // skip facilities that are completely pierced by this hit
                    var hit2 = new Hit(hit.Shot, f, damage);
                    return(hit2.Shot.DamageType.ComponentPiercing.Evaluate(hit2) < 100);
                }).ToDictionary(f => f, f => f.HitChance).PickWeighted(dice);
                if (facil == null)
                {
                    break;                     // no more facilities to hit
                }
                var facilhit = new Hit(hit.Shot, facil, damage);
                damage = facil.TakeDamage(facilhit, dice);
            }
            return(damage);
        }
Example #14
0
    void SetShapeNoiseSettings(PRNG prng, bool randomizeValues)
    {
        const string suffix = "_shape";

        if (randomizeValues)
        {
            var chance = new Chance(prng);
            SimpleNoiseSettings randomizedShapeNoise = new SimpleNoiseSettings()
            {
                numLayers = 4, lacunarity = 2, persistence = 0.5f
            };

            if (chance.Percent(80))                // Minor deformation
            {
                randomizedShapeNoise.elevation = Mathf.Lerp(0.2f, 3, prng.ValueBiasLower(0.3f));
                randomizedShapeNoise.scale     = prng.Range(1.5f, 2.5f);
            }
            else if (chance.Percent(20))                  // Major deformation
            {
                randomizedShapeNoise.elevation = Mathf.Lerp(3, 8, prng.ValueBiasLower(0.4f));
                randomizedShapeNoise.scale     = prng.Range(0.3f, 1);
            }

            // Assign settings
            randomizedShapeNoise.SetComputeValues(heightMapCompute, prng, suffix);
        }
        else
        {
            shapeNoise.SetComputeValues(heightMapCompute, prng, suffix);
        }
    }
Example #15
0
    static void Main()
    {
        Console.SetOut(new HexColor());
        ConsoleEx.AssemblyHeader(useColor: true);
        Console.WriteLine("Testing `066`Woof.Console`:");
        Console.WriteLine();
        var tasksCount = TasksLeft = 8;

        for (int i = 0; i < tasksCount; i++)
        {
            lock (L1) {
                Console.Write($"Starting test task #{i + 1}...");
                var progress = new ConsoleProgress();
                Task.Run(async() => await TestTask(progress));
                Task.Delay(1).Wait();
            }
        }
        Semaphore.Wait();
        Console.WriteLine();
        using var hexDump = new HexDump { Format = HexDump.Formats.HexColor };
        var testData = new byte[48];

        PRNG.NextBytes(testData);
        hexDump.Write(testData);
        Console.WriteLine();
        var delayFilter = new Delay();

        Console.SetOut(delayFilter);
        Console.WriteLine("Testing `0ff`Delay` filter..............`070`OK!`");
        Console.SetOut(delayFilter.Out); // remove the delay filter.
        Console.WriteLine();
        ConsoleEx.WaitForCtrlC("All test completed successfully, press Ctrl+C to exit...");
    }
Example #16
0
	void SetRandomColours (Material material) {
		PRNG random = new PRNG (seed);
		//randomizedCols.shoreCol = ColourHelper.Random (random, 0.3f, 0.7f, 0.4f, 0.8f);
		randomizedCols.flatColLowA = ColourHelper.Random (random, 0.45f, 0.6f, 0.7f, 0.8f);
		randomizedCols.flatColHighA = ColourHelper.TweakHSV (
			randomizedCols.flatColLowA,
			random.SignedValue () * 0.2f,
			random.SignedValue () * 0.15f,
			random.Range (-0.25f, -0.2f)
		);

		randomizedCols.flatColLowB = ColourHelper.Random (random, 0.45f, 0.6f, 0.7f, 0.8f);
		randomizedCols.flatColHighB = ColourHelper.TweakHSV (
			randomizedCols.flatColLowB,
			random.SignedValue () * 0.2f,
			random.SignedValue () * 0.15f,
			random.Range (-0.25f, -0.2f)
		);

		randomizedCols.shoreColLow = ColourHelper.Random (random, 0.2f, 0.3f, 0.9f, 1);
		randomizedCols.shoreColHigh = ColourHelper.TweakHSV (
			randomizedCols.shoreColLow,
			random.SignedValue () * 0.2f,
			random.SignedValue () * 0.2f,
			random.Range (-0.3f, -0.2f)
		);

		randomizedCols.steepLow = ColourHelper.Random (random, 0.3f, 0.7f, 0.4f, 0.6f);
		randomizedCols.steepHigh = ColourHelper.TweakHSV (
			randomizedCols.steepLow,
			random.SignedValue () * 0.2f,
			random.SignedValue () * 0.2f,
			random.Range (-0.35f, -0.2f)
		);
	}
Example #17
0
        public Point Resolve(StarSystem sys, PRNG dice)
        {
            if (Radius < 0)
            {
                throw new Exception("Invalid location \"Circle Radius " + Radius + "\" specified.");
            }
            var pts = new List <Point>();

            for (int x = -Math.Min(Radius, sys.Radius); x <= Math.Min(Radius, sys.Radius); x++)
            {
                for (int y = -Math.Min(Radius, sys.Radius); y <= Math.Min(Radius, sys.Radius); y++)
                {
                    // Don't let stellar objects overlap
                    if (Math.Round(Math.Sqrt(x * x + y * y)) == Radius && sys.GetSector(x, y).SpaceObjects.Count() == 0)
                    {
                        pts.Add(new Point(x, y));
                    }
                }
            }
            if (!pts.Any())
            {
                throw new Exception("Cannot place stellar object - no empty sectors are available at radius " + Radius + ".");
            }
            LastResult = pts.PickRandom(dice);
            return(LastResult.Value);
        }
Example #18
0
	protected override void SetShadingDataComputeProperties () {
		PRNG random = new PRNG (seed);
		detailNoise.SetComputeValues (shadingDataCompute, random, "_detail");
		detailWarpNoise.SetComputeValues (shadingDataCompute, random, "_detailWarp");
		largeNoise.SetComputeValues (shadingDataCompute, random, "_large");
		smallNoise.SetComputeValues (shadingDataCompute, random, "_small");
	}
Example #19
0
    private void SpawnLoot(int numLoot)
    {
        for (int i = 0; i < height; ++i)
        {
            for (int j = 0; j < width; ++j)
            {
                Vector2 cell = new Vector2(i, j);
                if (Vector2.Distance(new Vector2(2, 2), cell) > 1)
                {
                    GameObject newEnemy = Instantiate(Globals.LOOT, new Vector2(), Quaternion.identity);
                    newEnemy.transform.SetParent(ObjectContainer.instance.loot.transform);
                    newEnemy.transform.position = RandomTileFromCell(cell);
                }
            }
        }

        int numToDelete = (height * width) - numLoot - 5;

        for (int i = 0; i < numToDelete; ++i)
        {
            List <GameObject> lootList      = ObjectContainer.GetAllLoot();
            GameObject        enemyToDelete = lootList[PRNG.Range(0, lootList.Count)];
            DestroyImmediate(enemyToDelete);
        }
    }
Example #20
0
File: Shot.cs Project: ekolis/FrEee
        public int InflictDamage(IDamageable target, PRNG dice = null)
        {
            var hit = new Hit(this, target, DamageLeft);

            DamageLeft = target.TakeDamage(hit, dice);
            return(DamageLeft);
        }
Example #21
0
    // Set values using custom numCraters and sizeMinMax
    public void SetComputeValues(ComputeShader computeShader, int masterSeed, int numCraters, Vector2 craterSizeMinMax, float sizeDistribution)
    {
        if (!enabled)
        {
            numCraters       = 1;
            craterSizeMinMax = Vector2.zero;
        }

        Random.InitState(craterSeed + masterSeed);
        Crater[] craters = new Crater[numCraters];
        PRNG     prng    = new PRNG(masterSeed);

        // Create craters
        for (int i = 0; i < numCraters; i++)
        {
            float t = prng.ValueBiasLower(sizeDistribution);

            float size        = Mathf.Lerp(craterSizeMinMax.x, craterSizeMinMax.y, t);
            float floorHeight = Mathf.Lerp(-1.2f, -0.2f, t + prng.ValueBiasLower(0.3f));
            float smooth      = Mathf.Lerp(smoothMinMax.x, smoothMinMax.y, 1 - t);
            craters[i] = new Crater()
            {
                centre = Random.onUnitSphere, size = size, floorHeight = floorHeight, smoothness = smooth
            };
        }
        cachedCraters = craters;

        // Set shape data
        ComputeHelper.CreateAndSetBuffer <Crater> (ref craterBuffer, craters, computeShader, "craters");
        computeShader.SetInt("numCraters", numCraters);

        computeShader.SetFloat(nameof(rimSteepness), rimSteepness);
        computeShader.SetFloat(nameof(rimWidth), rimWidth);
        //computeShader.SetFloat (nameof (smoothFactor), smoothFactor);
    }
    public void Spawn(int seed)
    {
        var sw = System.Diagnostics.Stopwatch.StartNew();

        PRNG prng = new PRNG(seed);

        CelestialBody[] bodies = FindObjectsOfType <CelestialBody> ();

        foreach (var body in bodies)
        {
            if (body.bodyType == CelestialBody.BodyType.Sun)
            {
                continue;
            }

            BodyPlaceholder placeholder = body.gameObject.GetComponentInChildren <BodyPlaceholder> ();
            var             template    = placeholder.bodySettings;

            Destroy(placeholder.gameObject);

            GameObject holder    = new GameObject("Body Generator");
            var        generator = holder.AddComponent <CelestialBodyGenerator> ();
            generator.transform.parent        = body.transform;
            generator.gameObject.layer        = body.gameObject.layer;
            generator.transform.localRotation = Quaternion.identity;
            generator.transform.localPosition = Vector3.zero;
            generator.transform.localScale    = Vector3.one * body.radius;
            generator.resolutionSettings      = resolutionSettings;

            generator.body = template;
        }

        Debug.Log("Generation time: " + sw.ElapsedMilliseconds + " ms.");
    }
Example #23
0
        public Point Resolve(StarSystem sys, PRNG dice)
        {
            if (Ring < 1 || Ring > sys.Radius + 1)
            {
                throw new Exception("Invalid location \"Ring " + Ring + "\" specified for system of radius " + sys.Radius + ".");
            }
            var pts  = new List <Point>();
            var dist = Ring - 1;

            for (int x = -dist; x <= dist; x++)
            {
                for (int y = -dist; y <= dist; y++)
                {
                    // Don't let stellar objects overlap
                    if ((Math.Abs(x) == dist || Math.Abs(y) == dist) && !sys.GetSector(x, y).SpaceObjects.Any())
                    {
                        pts.Add(new Point(x, y));
                    }
                }
            }
            if (!pts.Any())
            {
                throw new Exception("Cannot place stellar object - no empty sectors are available in ring " + Ring + ".");
            }
            LastResult = pts.PickRandom(dice);
            return(LastResult.Value);
        }
        public void OnTriggerEnter(Collider collider)
        {
            PersonIdentifier identifier = collider.GetComponentInChildren <PersonIdentifier>();

            if (identifier != null)
            {
                person.Trigger(TriggerType.PersonCollision);
                int rand = PRNG.GetNumber(0, 100);
                if (rand < 15 && identifier.person.GetType() == typeof(Walker) && person.GetType() == typeof(Walker))
                {
                    Talker t1 = new Talker(person);
                    Talker t2 = new Talker(identifier.person);
                    t1.TalksTo = t2;
                    t2.TalksTo = t1;
                    PersonManager.INSTANCE.UpdatePerson(person, t1);
                    PersonManager.INSTANCE.UpdatePerson(identifier.person, t2);
                    SetEditorValues();
                    identifier.SetEditorValues();
                    t1.Trigger(TriggerType.PersonStartTalking);
                }
            }
            else
            {
                person.Trigger(TriggerType.Collision);
            }
        }
 public override float Start()
 {
     m_started = TimeService.Wall;
     m_delay   = PRNG.NextFloat(0.01f, 0.05f);
     JobService.Enqueue(m_name, Execute, m_name, m_delay);
     return(m_delay + 1.0f);
 }
        private JobTest StartRandomTest()
        {
            JobTest test;
            var     nr = PRNG.Next(0, 9);

            m_runs[nr]++;
            switch (nr)
            {
            case 0:
            case 1:
            case 2:
            case 3:
                test = new Simple();
                break;

            case 4:
            case 5:
                test = new Wide();
                break;

            case 6:
            case 7:
                test = new WideArg();
                break;

            case 8:
                test = new Delayed();
                break;

            default:
                throw new NotImplementedException();
            }
            test.Timeout = TimeService.Wall + test.Start();
            return(test);
        }
Example #27
0
        /*/// <summary>
         * /// was missilefirecontrol in battlespace.
         * /// </summary>
         * /// <param name="battletick"></param>
         * /// <param name="comSek"></param>
         *
         * public override void firecontrol(int battletick)
         * {
         *  Fix16 locdistance = Trig.distance(comSek.cmbt_loc, comSek.weaponTarget[0].cmbt_loc);
         *  if (locdistance <= comSek.cmbt_vel.Length)//erm, I think? (if we're as close as we're going to get in one tick) could screw up at high velocities.
         *  {
         *      if (!IsReplay)
         *      {
         *          CombatTakeFireEvent evnt = comSek.seekertargethit;
         *          evnt.IsHit = true;
         *          evnt.Tick = battletick;
         *      }
         *      Component launcher = comSek.launcher.weapon;
         *      CombatObject target = comSek.weaponTarget[0];
         *      if (target is ControlledCombatObject)
         *      {
         *          ControlledCombatObject ccTarget = (ControlledCombatObject)target;
         *          var target_icomobj = ccTarget.WorkingObject;
         *          var shot = new Combat.Shot(launcher, target_icomobj, 0);
         *          //defender.TakeDamage(weapon.Template.ComponentTemplate.WeaponInfo.DamageType, shot.Damage, battle);
         *          int damage = shot.Damage;
         *          combatDamage(battletick, target, comSek.launcher, damage, comSek.getDice());
         *          if (target_icomobj.MaxNormalShields < target_icomobj.NormalShields)
         *              target_icomobj.NormalShields = target_icomobj.MaxNormalShields;
         *          if (target_icomobj.MaxPhasedShields < target_icomobj.PhasedShields)
         *              target_icomobj.PhasedShields = target_icomobj.MaxPhasedShields;
         *      }
         *
         *      DeadNodes.Add(comSek);
         *      CombatNodes.Remove(comSek);
         *  }
         *  else if (battletick > comSek.deathTick)
         *  {
         *      DeadNodes.Add(comSek);
         *      CombatNodes.Remove(comSek);
         *  }
         * }
         */

        public override void TakeSpecialDamage(Battle_Space battle, Hit hit, PRNG dice)
        {
            // find out who hit us
            var atkr = battle.FindCombatObject(hit.Shot.Attacker);

            // find out how too
            var dmgType = hit.Shot.DamageType;

            // push/pull effects
            if (atkr.CanPushOrPull(this))
            {
                var deltaV = dmgType.TargetPush.Value * hit.Shot.DamageLeft / 100;
                var vector = atkr.cmbt_loc - this.cmbt_loc;
                if (vector.Length == 0)
                {
                    // pick a random direction to push/pull
                    vector = new Compass(dice.Next(360), false).Point(1);
                }
                vector        /= vector.Length;                                                  // normalize to unit vector
                vector        *= Battle_Space.KilometersPerSquare / Battle_Space.TicksPerSecond; // scale to combat map
                vector        *= deltaV;                                                         // scale to push/pull acceleration factor
                this.cmbt_vel += deltaV;                                                         // apply force
            }

            // teleport effects
            {
                var deltaPos = dmgType.TargetTeleport.Value * hit.Shot.DamageLeft / 100;
                var vector   = new Compass(dice.Next(360), false).Point(deltaPos);
                this.cmbt_loc += deltaPos;                 // apply teleport
            }
        }
Example #28
0
    public void SetProperties(Material material, int seed, bool randomize)
    {
        material.SetFloat("depthMultiplier", depthMultiplier);
        material.SetFloat("alphaMultiplier", alphaMultiplier);

        material.SetTexture("waveNormalA", waveNormalA);
        material.SetTexture("waveNormalB", waveNormalB);
        material.SetFloat("waveStrength", waveStrength);
        material.SetFloat("waveNormalScale", waveScale);
        material.SetFloat("waveSpeed", waveSpeed);
        material.SetFloat("smoothness", smoothness);
        material.SetVector("params", testParams);

        if (randomize)
        {
            var random     = new PRNG(seed);
            var randomColA = Color.HSVToRGB(random.Value(), random.Range(0.6f, 0.8f), random.Range(0.65f, 1));
            var randomColB = ColourHelper.TweakHSV(randomColA,
                                                   random.SignedValue() * 0.2f,
                                                   random.SignedValue() * 0.2f,
                                                   random.Range(-0.5f, -0.4f)
                                                   );

            material.SetColor("colA", randomColA);
            material.SetColor("colB", randomColB);
            material.SetColor("specularCol", Color.white);
        }
        else
        {
            material.SetColor("colA", colA);
            material.SetColor("colB", colB);
            material.SetColor("specularCol", specularCol);
        }
    }
    // Set values using custom scale and elevation
    public void SetComputeValues(ComputeShader cs, PRNG prng, string varSuffix, float scale, float elevation, float power)
    {
        Vector3 seededOffset = new Vector3(prng.Value(), prng.Value(), prng.Value()) * prng.Value() * 10000;

        float[] noiseParams =
        {
            // [0]
            seededOffset.x + offset.x,
            seededOffset.y + offset.y,
            seededOffset.z + offset.z,
            numLayers,
            // [1]
            persistence,
            lacunarity,
            scale,
            elevation,
            // [2]
            power,
            gain,
            verticalShift,
            peakSmoothing
        };

        cs.SetFloats("noiseParams" + varSuffix, noiseParams);
    }
Example #30
0
        protected Person()
        {
            if (!PRNG.IsInitialized)
            {
                PRNG.ChangeSeed(0);
            }

            // Generate some random values
            gender  = (Gender)PRNG.GetNumber(0, 1);
            hearing = PRNG.GetFloatNumber(0, 1);
            scared  = PRNG.GetFloatNumber(0, 1);
            buying  = PRNG.GetFloatNumber(0, 1);
            angry   = PRNG.GetFloatNumber(0, 1);
            sad     = PRNG.GetFloatNumber(0, 1);
            speed   = PRNG.GetFloatNumber(5, 10);
            voice   = gender == Gender.Male ? PRNG.GetFloatNumber(0.90f, 1.00f) : PRNG.GetFloatNumber(1.05f, 1.15f);

            walking  = false;
            paranoid = false;
            robbed   = false;
            running  = false;

            walkingInterval = PRNG.GetFloatNumber(0.5f, 0.9f);
            stepPitch       = PRNG.GetFloatNumber(1f, 1.2f, 3);

            hasPosition = false;
            timePassed  = 0f;

            // Generate a random name
            GenerateRandomName();
        }
Example #31
0
    // init_magics() computes all rook and bishop attacks at startup. Magic
    // bitboards are used to look up attacks of sliding pieces. As a reference see
    // chessprogramming.wikispaces.com/Magic+Bitboards. In particular, here we
    // use the so called "fancy" approach.

    private static void init_magics(
        BitboardT[][] attacks,
        BitboardT[] magics,
        BitboardT[] masks,
        uint[] shifts,
        SquareT[] deltas,
        Utils.Fn index)
    {
        int[][] seeds =
        {
            new[] {8977, 44560, 54343, 38998, 5731, 95205, 104912, 17020},
            new[] {728, 10316, 55013, 32803, 12281, 15100, 16645, 255}
        };

        var occupancy = new BitboardT[4096];
        var reference = new BitboardT[4096];

        var age = new int[4096];
        int current = 0;

        for (var s = Square.SQ_A1; s <= Square.SQ_H8; ++s)
        {
            // Board edges are not considered in the relevant occupancies
            var edges = ((Bitboard.Rank1BB | Bitboard.Rank8BB) & ~Utils.rank_bb_St(s)
                              | ((Bitboard.FileABB | Bitboard.FileHBB) & ~Utils.file_bb_St(s)));

            // Given a square 's', the mask is the bitboard of sliding attacks from
            // 's' computed on an empty board. The index must be big enough to contain
            // all the attacks for each possible subset of the mask and so is 2 power
            // the number of 1s of the mask. Hence we deduce the size of the shift to
            // apply to the 64 or 32 bits word to get the index.
            masks[s] = sliding_attack(deltas, s, Bitboard.Create(0)) & ~edges;

#if X64
            shifts[(int)s] = (uint) (64 - Bitcount.popcount_Max15(masks[(int)s]));
#else
            shifts[s] = (uint)(32 - Bitcount.popcount_Max15(masks[s]));
#endif

            // Use Carry-Rippler trick to enumerate all subsets of masks[s] and
            // store the corresponding sliding attack bitboard in reference[].
            var b = Bitboard.Create(0);
            var size = 0;
            do
            {
                occupancy[size] = b;
                reference[size] = sliding_attack(deltas, s, b);

                // if (HasPext)
                // attacks[s][pext(b, masks[s])] = reference[size];

                size++;
                b = (b - masks[s]) & masks[s];
            } while (b != 0);

            // Set the offset for the table of the next square. We have individual
            // table sizes for each square with "Fancy Magic Bitboards".
            attacks[s] = new BitboardT[size];

            // if (HasPext)
            //  continue;

#if X64
            var rng = new PRNG((ulong) seeds[1][(int)Square.rank_of(s)]);
#else
            var rng = new PRNG((ulong)seeds[0][Square.rank_of(s)]);
#endif

            // Find a magic for square 's' picking up an (almost) random number
            // until we find the one that passes the verification test.
            int i;
            do
            {
                do
                {
                    magics[s] = Bitboard.Create(rng.sparse_rand());
                }
                while (Bitcount.popcount_Max15((magics[s]*masks[s]) >> 56) < 6);
            
                Array.Clear(attacks[s], 0, size);

                // A good magic must map every possible occupancy to an index that
                // looks up the correct sliding attack in the attacks[s] database.
                // Note that we build up the database for square 's' as a side
                // effect of verifying the magic.
                for (++current, i = 0; i < size; ++i)
                {
                    var idx = index(s, occupancy[i]);

                    if (age[idx] < current)
                    {
                        age[idx] = current;
                        attacks[s][idx] = reference[i];
                    }
                    else if (attacks[s][idx] != reference[i])
                    {
                        break;
                    }
                }
            } while (i < size);
        }
    }
Example #32
0
    /// Position::init() initializes at startup the various arrays used to compute
    /// hash keys.
    internal static void init()
    {
        var rng = new PRNG(1070372);

        foreach (var c in Color.AllColors)
        {
            foreach (var pt in PieceType.AllPieceTypes)
            {
                for (var s = Square.SQ_A1; s <= Square.SQ_H8; ++s)
                {
                    Zobrist.psq[c, pt, s] = rng.rand();
                }
            }
        }

        foreach (var f in File.AllFiles)
        {
            Zobrist.enpassant[f] = rng.rand();
        }

        for (var cr = (int) CastlingRight.NO_CASTLING; cr <= (int) CastlingRight.ANY_CASTLING; ++cr)
        {
            Zobrist.castling[cr] = 0;
            var b = Bitboard.Create((ulong) cr);
            while (b != 0)
            {
                var k = Zobrist.castling[1 << Utils.pop_lsb(ref b)];
                Zobrist.castling[cr] ^= (k != 0 ? k : rng.rand());
            }
        }

        Zobrist.side = rng.rand();
        Zobrist.exclusion = rng.rand();
    }