public void InitInputArrays(NativeArray <PointAndIndex> points, NativeArray <Aabb> aabbs, NativeArray <CollisionFilter> filters)
        {
            Random.InitState(1234);

            const int posRange       = 1000;
            const int radiusRangeMin = 1;
            const int radiusRangeMax = 10;

            for (int i = 0; i < points.Length; i++)
            {
                float3 pos;
                pos.x     = Random.Range(-posRange, posRange);
                pos.y     = Random.Range(-posRange, posRange);
                pos.z     = Random.Range(-posRange, posRange);
                points[i] = new PointAndIndex {
                    Position = pos, Index = i
                };

                float3 radius = new float3(Random.Range(radiusRangeMin, radiusRangeMax));
                aabbs[i] = new Aabb {
                    Min = pos - radius, Max = pos + radius
                };

                filters[i] = CollisionFilter.Default;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Wave-function-collapse algorithm
        /// TODO: Multithreading?
        /// </summary>
        /// <param name="cells">The grid`s cells</param>
        /// <param name="seed">RNG seed</param>
        public void GenerateLevelWFC(ref Cell[,] cells, int seed)
        {
            // Set RNG seed
            Random.InitState(seed);

            // Instantiate cells heap
            OrderedCells = new Heap <Cell>(cells.GetLength(0) * cells.GetLength(1));

            for (int i = 0; i < cells.GetLength(0); i++)
            {
                for (int j = 0; j < cells.GetLength(1); j++)
                {
                    OrderedCells.Add(cells[i, j]);
                }
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            Debug.LogWarning("Start Wave-function-collapse algorithm");

            ApplyInitialConstraints(ref cells);

            while (true)
            {
                //Debug.Log("Starting another iteration! Removing next module.");

                // Remove finished cells from heap
                while (OrderedCells.Count > 0)
                {
                    var cell = OrderedCells.GetFirst();

                    if (cell.SolvedScore == 1)
                    {
                        OrderedCells.RemoveFirst();
                    }
                    else
                    {
                        break;
                    }
                }

                // Remove random module from cell
                if (OrderedCells.Count > 0)
                {
                    var cell = OrderedCells.GetFirst();
                    cell.RemoveModule(cell.possibleModulesIndices[Random.Range(0, cell.possibleModulesIndices.Count)]);
                }
                else
                {
                    // Finished
                    break;
                }
            }

            stopwatch.Stop();
            Debug.LogWarning(
                $"Wave-function-collapse algorithm finished in {stopwatch.Elapsed.TotalMilliseconds}ms (Seed: {seed})");
        }
Beispiel #3
0
        public void Setup()
        {
            Random.InitState(0);

            NativeBVHDebugDrawer.LastTree           = default;
            NativeBVHDebugDrawer.LastTreeHits       = default;
            NativeBVHDebugDrawer.LastTreeRayVisited = default;
            NativeBVHDebugDrawer.LastRay            = default;
        }
        public void CreationAndRaycastPerformanceTest()
        {
            Random.InitState(0);

            // Warm-up
            DoTest();
            DoTest();
            enableLog = true;
            DoTest();
        }
Beispiel #5
0
        public static void PushSeed(int seed)
        {
            if (RandomEx.SeedStack.Count == 0)
            {
                RandomEx.SeedStack.Push(Random.state);
            }

            Random.InitState(seed);
            RandomEx.SeedStack.Push(Random.state);
        }
Beispiel #6
0
        public UnityRandom(int seed)
        {
            var state = Random.state;

            Random.InitState(seed);

            _seed  = seed;
            _state = Random.state;

            Random.state = state;
        }
Beispiel #7
0
 public static void Shuffle <T>(this T[] array, int?seed = null)
 {
     if (seed != null)
     {
         Random.InitState((int)seed);
     }
     for (var i = 0; i < array.Length; i++)
     {
         Swap(ref array[i], ref array[Random.Range(i, array.Length)]);
     }
 }
Beispiel #8
0
        public void InitInputWithCopyArrays(NativeArray <PointAndIndex> points, NativeArray <Aabb> aabbs,
                                            NativeArray <CollisionFilter> filters, NativeArray <bool> respondsToCollision)
        {
            Random.InitState(1234);

            const int posRange       = 1000;
            const int radiusRangeMin = 1;
            const int radiusRangeMax = 10;

            for (int i = 0; i < points.Length; i++)
            {
                float3 pos;
                pos.x     = Random.Range(-posRange, posRange);
                pos.y     = Random.Range(-posRange, posRange);
                pos.z     = Random.Range(-posRange, posRange);
                points[i] = new PointAndIndex {
                    Position = pos, Index = i
                };

                float3 radius = new float3(Random.Range(radiusRangeMin, radiusRangeMax));
                aabbs[i] = new Aabb {
                    Min = pos - radius, Max = pos + radius
                };

                points[i + 1] = new PointAndIndex {
                    Position = pos, Index = i + 1
                };

                aabbs[i + 1] = new Aabb {
                    Min = pos - radius, Max = pos + radius
                };

                filters[i] = new CollisionFilter
                {
                    GroupIndex   = 0,
                    BelongsTo    = (uint)Random.Range(0, 16),
                    CollidesWith = (uint)Random.Range(0, 16)
                };

                filters[i + 1] = new CollisionFilter
                {
                    GroupIndex   = 0,
                    BelongsTo    = (uint)Random.Range(0, 16),
                    CollidesWith = (uint)Random.Range(0, 16)
                };

                respondsToCollision[i]     = true;
                respondsToCollision[i + 1] = true;

                i++;
            }
        }
Beispiel #9
0
 public void random()
 {
     int[] test = null;
     Assert.Catch <ArgumentNullException>(() => test.Random());
     test = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
     Assert.DoesNotThrow(() => test.Random());
     Assert.DoesNotThrow(() => test.Random(-1, test.Length * 2));
     Random.InitState(42);
     Assert.AreEqual(4, test.Random());
     Assert.AreEqual(3, test.Random());
     Assert.AreEqual(6, test.Random());
     Assert.AreEqual(8, test.Random());
 }
Beispiel #10
0
            public static bool Prefix(EnvMan __instance, long sec, Heightmap.Biome biome)
            {
                if (HasEnvChanged(Helheim.HelheimLevel, biome, __instance.GetCurrentEnvironment().m_name))
                {
                    Helheim.Log($"Helheim: {Helheim.HelheimLevel}, Biome: {biome}, Current: {__instance.GetCurrentEnvironment().m_name}, Wet: {__instance.IsWet()}, Freezing: {__instance.IsFreezing()}");
                }

                var allowBaseMethod = true;
                var forceSwitch     = Helheim.HelheimLevel != PreviousHelheimLevel;

                __instance.m_firstEnv = forceSwitch;

                if (Helheim.HelheimLevel > 0)
                {
                    var num = sec / __instance.m_environmentDuration;
                    if (!forceSwitch && __instance.m_currentEnv.m_name.StartsWith("Helheim") && __instance.m_environmentPeriod == num && __instance.m_currentBiome == biome)
                    {
                        return(false);
                    }

                    __instance.m_environmentPeriod = num;
                    __instance.m_currentBiome      = biome;
                    var state = Random.state;
                    Random.InitState((int)num);
                    var availableEnvironments = __instance.GetAvailableEnvironments(biome);
                    if (availableEnvironments != null && availableEnvironments.Count > 0)
                    {
                        var biomeEnv   = __instance.SelectWeightedEnvironment(availableEnvironments);
                        var helheimEnv = GetHelheimEnvironment(__instance, biomeEnv, Helheim.HelheimLevel);
                        __instance.QueueEnvironment(helheimEnv);
                        Helheim.LogWarning($"Changing Environment: {helheimEnv.m_name}");
                    }
                    Random.state    = state;
                    allowBaseMethod = false;
                }
                else
                {
                    if (forceSwitch)
                    {
                        __instance.m_currentBiome = Heightmap.Biome.None;
                    }
                }

                PreviousHelheimLevel = Helheim.HelheimLevel;
                PreviousBiome        = biome;
                PreviousEnvName      = __instance.GetCurrentEnvironment().m_name;
                return(allowBaseMethod);
            }
Beispiel #11
0
        // Executes action for the controlling player.
        public void ExecuteAction(ActionParameters param)
        {
            // If action is not specified.
            if (param.Tag == ActionTag.None)
            {
                return;
            }

            // If no specified action.
            if (!_players[Control].ControlledUnit.Actions.ContainsKey(param.Tag))
            {
                return;
            }

            // If no targets.
            if (param.Targets == null)
            {
                _players[Control].ControlledUnit.Actions[param.Tag].Execute(Map);
                return;
            }

            // synchronize the random state
            Random.InitState(param.randomSeed);

            // Forms cells list.
            List <Cell> cells = new List <Cell>();

            foreach (Coordinates pos in param.Targets)
            {
                // If no cell for position.
                if (!Map.Cells.ContainsKey(pos) || Map.Cells[pos] == null)
                {
                    return;
                }
                cells.Add(Map.Cells[pos]);
            }

            // Executes action.
            _players[Control].ControlledUnit.Actions[param.Tag].Execute(cells, Map);


            // Notifies GameController that move was made.
            this.PostNotification(DidExecuteActionNotification);
        }
        public static void InitPairs(int minIndex, int maxIndex, int count, NativeArray <ulong> pairs)
        {
            Random.InitState(1234);

            for (var i = 0; i < pairs.Length; ++i)
            {
                ulong indexA = (ulong)Random.Range(minIndex, maxIndex);
                ulong indexB = (ulong)Random.Range(minIndex, maxIndex);

                if (indexB == indexA)
                {
                    if (indexB < (ulong)maxIndex)
                    {
                        indexB++;
                    }
                }

                pairs[i] = indexB << 40 | indexA << 16;
            }
        }
Beispiel #13
0
        public static void InitPairs(int minIndex, int maxIndex, int count, NativeArray <ulong> pairs)
        {
            Random.InitState(1234);

            for (var i = 0; i < pairs.Length; ++i)
            {
                ulong indexA = (ulong)Random.Range(minIndex, maxIndex);
                ulong indexB = (ulong)Random.Range(minIndex, maxIndex);

                if (indexB == indexA)
                {
                    if (indexB < (ulong)maxIndex)
                    {
                        indexB++;
                    }
                }

                pairs[i] =
                    indexA << DispatchPairSequencer.DispatchPair.k_BodyAIndexShift |
                        indexB << DispatchPairSequencer.DispatchPair.k_BodyBIndexShift;
            }
        }
        public GameLevelGridModel(LevelStageConfig levelStageConfig)
        {
            _size = math.int2(levelStageConfig.ColumnsNumber, levelStageConfig.RowsNumber);
            Assert.IsTrue(math.all(_size % 2 != int2.zero));

            var playersSpawnCorners = levelStageConfig.PlayersSpawnCorners;
            var softBlocksCoverage = levelStageConfig.SoftBlocksCoverage;

            var reservedCellsIndices = new HashSet<int>(
                playersSpawnCorners
                    .SelectMany(
                        corner =>
                        {
                            var coordinate = corner * (_size - 1);
                            var offset = math.select(-1, 1, corner == int2.zero);

                            return new[]
                            {
                                GetFlattenCellCoordinate(coordinate),
                                GetFlattenCellCoordinate(math.mad(math.int2(1, 0), offset, coordinate)),
                                GetFlattenCellCoordinate(math.mad(math.int2(0, 1), offset, coordinate))
                            };
                        }
                    )
            );

            var reservedCellsNumber = reservedCellsIndices.Count;

            var totalCellsNumber = _size.x * _size.y - reservedCellsNumber;

            var hardBlocksNumber = (_size.x - 1) * (_size.y - 1) / 4;
            var softBlocksNumber = (int) math.round((totalCellsNumber - hardBlocksNumber) * softBlocksCoverage / 100.0f);
            var floorCellsNumber = totalCellsNumber - softBlocksNumber - hardBlocksNumber;

            var cellTypeNumbers = math.int2(floorCellsNumber, softBlocksNumber);

            var powerUpItems = levelStageConfig.PowerUpItems;
            var softBlocksPerPowerUpItem = softBlocksNumber / powerUpItems.Length;

            Random.InitState(levelStageConfig.RandomSeed);
            var powerItemsIndices = new HashSet<int>(
                Enumerable
                    .Range(0, powerUpItems.Length)
                    .Select(i => Random.Range(i * softBlocksPerPowerUpItem, (i + 1) * softBlocksPerPowerUpItem))
            );

            _grid = Enumerable
                .Range(0, totalCellsNumber + reservedCellsNumber)
                .Select(
                    index =>
                    {
                        if (reservedCellsIndices.Contains(index))
                            return GridTileType.FloorTile;

                        var coordinate = math.int2(index % _size.x, index / _size.x);
                        if (math.all(coordinate % 2 == 1))
                            return GridTileType.HardBlock;

                        var range = (int2) (cellTypeNumbers == int2.zero);

                        var softBlockOdds = (int) (cellTypeNumbers.y * 100.0f / (cellTypeNumbers.x + cellTypeNumbers.y));

                        var typeIndex = Convert.ToInt32(Random.Range(0, 100) < softBlockOdds);
                        typeIndex = math.clamp(typeIndex, range.x, 2 - range.y);

                        var tileType = typeIndex == 0 ? GridTileType.FloorTile : GridTileType.SoftBlock;

                        if (tileType == GridTileType.SoftBlock && powerItemsIndices.Contains(cellTypeNumbers[typeIndex]))
                            tileType |= GridTileType.PowerUpItem;

                        --cellTypeNumbers[typeIndex];

                        return tileType;
                    }
                )
                .ToArray();

            // Random.InitState(new System.Random().Next());
        }
Beispiel #15
0
 public void SetSeed(int seed) => Random.InitState(seed);
Beispiel #16
0
        public static void CreateStarPlanetsRework(GalaxyData galaxy, StarData star, GameDesc gameDesc, PlanetGeneratorSettings genSettings)
        {
            star.name = SystemsNames.systems[star.index];

            Patch.Debug("System " + star.name + " - " + star.type + " - " + star.spectr, LogLevel.Debug,
                        Patch.DebugStarGen);

            // Random Generators Inits
            UnityRandom.InitState(star.seed);
            var mainSeed  = new Random(star.seed);
            var annexSeed = new Random(mainSeed.Next());

            // InnerCount for the System
            var planetsToGenerate = new List <PlanetForGenerator>();

            // settings from the config
            PatchForStarSystemGeneration.StarSystemSetting currentSettings;

            if (star.type == EStarType.BlackHole || star.type == EStarType.GiantStar ||
                star.type == EStarType.NeutronStar || star.type == EStarType.WhiteDwarf)
            {
                currentSettings = Patch.GeneratorSpecialsSystemConfig[star.type];
            }
            else
            {
                currentSettings = Patch.GeneratorMainSystemConfig[star.spectr];
            }

            //Debugging configs
            Patch.Debug("*************************** : \n" +
                        "ChanceMoonGasGiant : " + currentSettings.ChanceGasGiantMoon + "\n" +
                        "ChanceMoonTelluric : " + currentSettings.ChanceMoonTelluric + "\n" +
                        "ChancePlanetTelluric : " + currentSettings.ChanceTelluricPlanet + "\n" +
                        "ChancePlanetGasGiant : " + currentSettings.ChanceGasGiant + "\n" +
                        "MaxMoonTelluricNb : " + currentSettings.MaxMoonTelluricNb + "\n" +
                        "MaxMoonGasGiantNb : " + currentSettings.MaxMoonGasGiantNb + "\n" +
                        "MaxTelluricNb : " + currentSettings.MaxTelluricNb + "\n" +
                        "MaxGasGiantNb : " + currentSettings.MaxGasGiantNb + "\n" +
                        "ChanceJumpOrbitMoons : " + currentSettings.ChanceJumpOrbitMoons + "\n" +
                        "ChanceJumpOrbitPlanets : " + currentSettings.ChanceJumpOrbitPlanets + "\n" +
                        "*************************** ", LogLevel.Debug, Patch.DebugStarGenDeep);

            Patch.Debug("Definition of Nb of planets In the system :", LogLevel.Debug, Patch.DebugStarGenDeep);

            DefineNumberOfBodies(currentSettings, annexSeed, genSettings);

            if (star.IsStartingStar())
            {
                // check if minimum number of planet is met
                genSettings.nbOfTelluricPlanets = genSettings.nbOfTelluricPlanets < Patch.StartingSystemMinPlanetTelluricNb.Value ? Patch.StartingSystemMinPlanetTelluricNb.Value : genSettings.nbOfTelluricPlanets;
                genSettings.nbOfMoonsTelluric   = genSettings.nbOfMoonsTelluric < Patch.StartingSystemMinTelluricMoonNb.Value ? Patch.StartingSystemMinTelluricMoonNb.Value : genSettings.nbOfMoonsTelluric;
                genSettings.nbOfGasGiantPlanets = genSettings.nbOfGasGiantPlanets < Patch.StartingSystemMinGasGiantNb.Value ? Patch.StartingSystemMinGasGiantNb.Value : genSettings.nbOfGasGiantPlanets;
                genSettings.nbOfMoonsGasGiant   = genSettings.nbOfMoonsGasGiant < Patch.StartingSystemMinGasGiantMoonNb.Value ? Patch.StartingSystemMinGasGiantMoonNb.Value : genSettings.nbOfMoonsGasGiant;

                genSettings.nbOfMoons         = genSettings.nbOfMoonsTelluric + genSettings.nbOfMoonsGasGiant;
                genSettings.nbOfPlanets       = genSettings.nbOfTelluricPlanets + genSettings.nbOfGasGiantPlanets;
                genSettings.nbOfStellarBodies = genSettings.nbOfPlanets + genSettings.nbOfMoons;
            }

            star.planets = new PlanetData[genSettings.nbOfStellarBodies];

            Patch.Debug("*************************** :", LogLevel.Debug, Patch.DebugStarGen);
            Patch.Debug("\nSystem Presets : ", LogLevel.Debug, Patch.DebugStarGen);

            var preset =
                "nbOfPlanets : " + genSettings.nbOfPlanets + "\n" +
                "nbOfTelluricPlanets : " + genSettings.nbOfTelluricPlanets + "\n" +
                "nbOfGasGiantPlanets : " + genSettings.nbOfGasGiantPlanets + "\n" +
                "nbOfMoons : " + genSettings.nbOfMoons + "\n" +
                "nbOfMoonsTelluric : " + genSettings.nbOfMoonsTelluric + "\n" +
                "nbOfMoonsGasGiant : " + genSettings.nbOfMoonsGasGiant + "\n\n";

            Patch.Debug(preset, LogLevel.Debug, Patch.DebugStarGen);

            PreGenerateAllBodies(star, planetsToGenerate, annexSeed, genSettings, currentSettings);

            GenerateAllPlanets(galaxy, star, gameDesc, planetsToGenerate);


            if (star.IsStartingStar())
            {
                Patch.Debug(star.name + " --recap-- : ", LogLevel.Debug, Patch.DebugStarGen);
                var nbOfHabitablePlanets = 0;
                foreach (var planet in star.planets)
                {
                    if (planet.orbitAround != 0)
                    {
                        Patch.Debug("moon type : " + planet.type, LogLevel.Debug, Patch.DebugStarGen);
                    }
                    else
                    {
                        Patch.Debug("planet type : " + planet.type, LogLevel.Debug, Patch.DebugStarGen);
                    }

                    if (planet.type == EPlanetType.Ocean)
                    {
                        nbOfHabitablePlanets++;
                    }
                }

                if (nbOfHabitablePlanets == 0)
                {
                    Patch.Debug("Nb of habitable == 0 --> Override one planet ", LogLevel.Debug, Patch.DebugStarGen);
                    var @override = true;
                    while (@override)
                    {
                        var indexStartingPlanet = UnityRandom.Range(0, star.planets.Length - 1);

                        if (star.planets[indexStartingPlanet].type != EPlanetType.Gas)
                        {
                            star.planets[indexStartingPlanet].ShouldBeHabitable();
                            galaxy.birthPlanetId = star.planets[indexStartingPlanet].id;
                            @override            = false;
                        }
                    }


                    Patch.Debug(" galaxy.birthPlanetId --> " + galaxy.birthPlanetId, LogLevel.Debug, Patch.DebugStarGen);
                }
            }

            // Apply themes
            foreach (var planet in star.planets)
            {
                PlanetGen.SetPlanetTheme(planet, star, gameDesc, 0, 0, mainSeed.NextDouble(), mainSeed.NextDouble(), mainSeed.NextDouble(), mainSeed.NextDouble(), mainSeed.Next());
                Patch.Debug("planet.algoId --> " + planet.algoId, LogLevel.Debug, Patch.DebugStarGen);
            }

            star.planetCount = star.planets.Length;
        }
        private void DoTest()
        {
            var amount = PerformanceComparisonConfig.ObjectCount;
            var world  = new BVHTreeWorld(amount, Allocator.Persistent);

            Random.InitState(0);
            var colliders  = new NativeArray <Collider>(amount, Allocator.TempJob);
            var transforms = new NativeArray <RigidTransform>(amount, Allocator.TempJob);

            for (int i = 0; i < PerformanceComparisonConfig.ObjectCount; i++)
            {
                colliders[i]  = BoxCollider.Create(float3.zero, PerformanceComparisonConfig.GetRandomSize());
                transforms[i] = new RigidTransform(quaternion.identity, PerformanceComparisonConfig.GetRandomPosition());
            }


            var s = Stopwatch.StartNew();

            Profiler.BeginSample("broad");
            new BVHTreeWorld.InsertCollidersAndTransformsJob {
                Tree       = world.tree,
                Bodies     = world.bodies,
                Colliders  = colliders,
                Transforms = transforms
            }.Run();
            Profiler.EndSample();
            if (enableLog)
            {
                Debug.Log("Building broad phase took: " + s.Elapsed.TotalMilliseconds);
            }

            var rayResult = new NativeList <int>(64, Allocator.TempJob);

            var start = PerformanceComparisonConfig.RayStart;
            var end   = PerformanceComparisonConfig.RayEnd;

            var rayJob = new RayJob {
                Tree     = world.tree,
                RayInput = new NativeBVHTree.Ray {
                    origin      = start,
                    direction   = math.normalize(end - start),
                    maxDistance = math.distance(start, end),
                },
                Results = rayResult
            };

            s.Restart();
            rayJob.Run();
            if (enableLog)
            {
                Debug.Log("Raycasts took: " + s.Elapsed.TotalMilliseconds + " results: " + rayResult.Length);
            }

            s.Restart();
            world.Update();
            if (enableLog)
            {
                Debug.Log("Building broad phase again after no changes took: " + s.Elapsed.TotalMilliseconds);
            }

            for (int i = 0; i < 100; i++)
            {
                int randomIndex = Random.Range(1, PerformanceComparisonConfig.ObjectCount);
                world.UpdateTransform(randomIndex, new RigidTransform(quaternion.identity, PerformanceComparisonConfig.GetRandomPosition()));
            }
            s.Restart();
            world.Update();
            if (enableLog)
            {
                Debug.Log("Building broad phase again after some changes took: " + s.Elapsed.TotalMilliseconds);
            }
        }
Beispiel #18
0
 public RandomSeedScope(int seed)
 {
     m_OldState = URandom.state;
     URandom.InitState(seed);
 }
Beispiel #19
0
 public TemporaryRandomSeed(int seed)
 {
     _orignialState = Random.state;
     Random.InitState(seed);
 }