private bool AirSpawnLogic(int x, int z, ChunkSpawnableEntity entity, AbstractChunk chunk, ByteChunkCursor cursor, FastRandom rnd, out Vector3D entitySpawnLocation)
        {
            entitySpawnLocation = default(Vector3D);
            int y;
            int columnInfoIndex = x * AbstractChunk.ChunkSize.Z + z;

            //Y base = Original world generated ground height (Before any player modification)
            y = rnd.Next(chunk.BlockData.ColumnsInfo[columnInfoIndex].MaxHeight + 5, AbstractChunk.ChunkSize.Y);

            if (y <= 0 || y >= AbstractChunk.ChunkSize.Y)
            {
                return(false);
            }

            cursor.SetInternalPosition(x, y, z);

            if (cursor.Read() != WorldConfiguration.CubeId.Air)
            {
                return(false);
            }

            // Hurray it can spawn ! :D
            //Add some randomnes on the cube where it will spawn
            double XOffset, ZOffset;

            XOffset = rnd.NextDouble(0.2, 0.8);
            ZOffset = rnd.NextDouble(0.2, 0.8);

            entitySpawnLocation = new Vector3D(chunk.BlockPosition.X + x + XOffset, cursor.InternalPosition.Y, chunk.BlockPosition.Z + z + ZOffset);
            return(true);
        }
Пример #2
0
 /// <summary>
 /// For activation functions that accept auxiliary arguments; generates random initial values for aux arguments for newly
 /// added nodes (from an 'add neuron' mutation).
 /// </summary>
 public double[] GetRandomAuxArgs(FastRandom rng, double connectionWeightRange)
 {
     double[] auxArgs = new double[2];
     auxArgs[0] = (rng.NextDouble() - 0.5) * 2.0;
     auxArgs[1] = rng.NextDouble();
     return(auxArgs);
 }
Пример #3
0
        private IEnumerable <char> GetRandomChar(int n, FastRandom rand)
        {
            for (int i = 0; i < n; i++)
            {
                double prob           = rand.NextDouble();
                double tabProb        = 0.01 + 0.02 * rand.NextDouble(); //prob of tab is between 0.01 and 0.03
                double newlineProb    = 0.02 + 0.05 * rand.NextDouble(); //prob of newline is between 0.02 and 0.07
                double spaceProb      = 0.05 + 0.3 * rand.NextDouble();  //prob of space is between 0.05 and 0.35
                double terminatorProb = 0.01 + 0.19 * rand.NextDouble(); //prob of sentence terminator is between 0.01 and 0.2

                if (prob < tabProb)
                {
                    yield return('\t');
                }
                if (prob < tabProb + newlineProb)
                {
                    yield return('\n');
                }
                if (prob < tabProb + newlineProb + spaceProb)
                {
                    yield return(' ');
                }
                if (prob < tabProb + newlineProb + spaceProb + terminatorProb)
                {
                    yield return(terminators[rand.Next(0, terminators.Length)]);
                }
                else
                {
                    yield return((char)rand.Next(33, 126 + 1));
                }
            }
        }
        private bool CaveSpawnLogic(int x, int z, ChunkSpawnableEntity entity, AbstractChunk chunk, ByteChunkCursor cursor, FastRandom rnd, out Vector3D entitySpawnLocation)
        {
            entitySpawnLocation = default(Vector3D);
            int y;
            int columnInfoIndex = x * AbstractChunk.ChunkSize.Z + z;

            cursor.SetInternalPosition(x, 1, z);
            //Move up until Air Block
            while (cursor.Read() != WorldConfiguration.CubeId.Air)
            {
                //Move up, if top chunk height exit
                if (cursor.Move(CursorRelativeMovement.Up) == false)
                {
                    return(false);
                }
            }

            int YFloorSpawning = cursor.InternalPosition.Y;

            int MaximumSpawningHeight = chunk.BlockData.ColumnsInfo[columnInfoIndex].MaxGroundHeight - 10;

            if (MaximumSpawningHeight <= 0)
            {
                MaximumSpawningHeight = 1;
            }
            //Move up until "solid" Block
            while (cursor.Read() == WorldConfiguration.CubeId.Air && cursor.InternalPosition.Y <= MaximumSpawningHeight)
            {
                //Move up, if top chunk height exit
                if (cursor.Move(CursorRelativeMovement.Up) == false)
                {
                    return(false);
                }
            }

            if (cursor.InternalPosition.Y > MaximumSpawningHeight)
            {
                return(false);
            }

            // Hurray it can spawn ! :D
            //Add some randomnes on the cube where it will spawn
            double XOffset, ZOffset;

            XOffset = rnd.NextDouble(0.2, 0.8);
            ZOffset = rnd.NextDouble(0.2, 0.8);

            if (entity.SpawningPlace == ChunkSpawningPlace.FloorInsideCave)
            {
                entitySpawnLocation = new Vector3D(chunk.BlockPosition.X + x + XOffset, YFloorSpawning, chunk.BlockPosition.Z + z + ZOffset);
            }
            else
            {
                entitySpawnLocation = new Vector3D(chunk.BlockPosition.X + x + XOffset, cursor.InternalPosition.Y - 1, chunk.BlockPosition.Z + z + ZOffset);
            }

            return(true);
        }
Пример #5
0
        private double gaussianMutation(double mean, double stddev)
        {
            double x1 = 1 - _random.NextDouble();
            double x2 = 1 - _random.NextDouble();

            double y1 = Math.Sqrt(-2.0 * Math.Log(x1)) * Math.Cos(2.0 * Math.PI * x2);

            return(y1 * stddev + mean);
        }
        private bool SurfaceSpawnLogic(int x, int z, ChunkSpawnableEntity entity, AbstractChunk chunk, ByteChunkCursor cursor, FastRandom rnd, out Vector3D entitySpawnLocation)
        {
            entitySpawnLocation = default(Vector3D);

            int y;
            int columnInfoIndex = x * AbstractChunk.ChunkSize.Z + z;

            //Y base = Original world generated ground height (Before any player modification)
            y = chunk.BlockData.ColumnsInfo[columnInfoIndex].MaxGroundHeight;
            cursor.SetInternalPosition(x, y, z);

            // verify that we can spawn here
            var canSpawn = cursor.Read() != WorldConfiguration.CubeId.Air && cursor.Move(CursorRelativeMovement.Up) &&
                           cursor.Read() == WorldConfiguration.CubeId.Air && cursor.Move(CursorRelativeMovement.Up) &&
                           cursor.Read() == WorldConfiguration.CubeId.Air;

            // return cursor to the spawn point
            cursor.Move(CursorRelativeMovement.Down);

            if (!canSpawn)
            {
                return(false);
            }

            // Check that the block is well "Solid to entity"
            BlockProfile blockSpawnProfile = _config.BlockProfiles[cursor.Peek(CursorRelativeMovement.Down)];

            if (!blockSpawnProfile.IsSolidToEntity)
            {
                return(false);
            }
            if (entity.IsWildChunkNeeded)
            {
                //Get Chunk master biome
                byte masterBiomeId = chunk.BlockData.ChunkMetaData.ChunkMasterBiomeType;
                //Get biome surface block layer
                byte surfaceBiomeCube = _config.ProcessorParam.Biomes[masterBiomeId].SurfaceCube;
                //If the entity need a Wild chunk, then it can only spawn on a cube surface equal to the default biome surface cube !
                if (surfaceBiomeCube != blockSpawnProfile.Id)
                {
                    return(false);
                }
            }

            // Hurray it can spawn ! :D
            //Add some randomnes on the cube where it will spawn
            double XOffset, ZOffset;

            XOffset = rnd.NextDouble(0.2, 0.8);
            ZOffset = rnd.NextDouble(0.2, 0.8);

            entitySpawnLocation = new Vector3D(chunk.BlockPosition.X + x + XOffset, cursor.InternalPosition.Y, chunk.BlockPosition.Z + z + ZOffset);

            return(true);
        }
Пример #7
0
        private void PopulateChunkWithCave(ByteChunkCursor cursor, int x, int y, int z, int layers, byte cubeId, FastRandom rnd)
        {
            cursor.SetInternalPosition(x, y, z);

            int caveRadius = rnd.Next(3, 8);

            int layerRadiusModifier = 0;

            for (int l = 0; l < layers; l++)
            {
                //Generate Lake Layers
                for (int X = x - (caveRadius - layerRadiusModifier); X <= x + (caveRadius - layerRadiusModifier); X++)
                {
                    for (int Z = z - (caveRadius - layerRadiusModifier); Z <= z + (caveRadius - layerRadiusModifier); Z++)
                    {
                        //Create "Noise" at Cave border
                        if ((X == x - (caveRadius - layerRadiusModifier) ||
                             X == x + (caveRadius - layerRadiusModifier) ||
                             Z == z - (caveRadius - layerRadiusModifier) ||
                             Z == z + (caveRadius - layerRadiusModifier)) &&
                            rnd.NextDouble() < 0.2)
                        {
                            continue;
                        }

                        cursor.SetInternalPosition(X, y + l, Z);
                        if (l <= 1 && rnd.NextDouble() < 0.3)
                        {
                            cursor.Write(cubeId);
                        }
                        else
                        {
                            if (l != 0)
                            {
                                if (l == layers - 1)
                                {
                                    if (cursor.Read() == UtopiaProcessorParams.CubeId.Stone)
                                    {
                                        cursor.Write(UtopiaProcessorParams.CubeId.LightWhite);
                                    }
                                }
                                else
                                {
                                    cursor.Write(UtopiaProcessorParams.CubeId.Air);
                                }
                            }
                        }
                    }
                }
                if (layerRadiusModifier < caveRadius)
                {
                    layerRadiusModifier++;
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Initialise agent and prey positions. The prey is positioned randomly with at least 4 empty squares between it and a wall (in all directions).
        /// The agent is positioned randomly but such that the prey is within sensor range (distance 2 or less).
        /// </summary>
        public void InitPositions()
        {
            // Random pos at least 4 units away from any wall.
            _preyPos._x = 4 + _rng.Next(_gridSize - 8);
            _preyPos._y = 4 + _rng.Next(_gridSize - 8);

            // Agent position. Within range of the prey.
            double t = 2.0 * Math.PI * _rng.NextDouble();   // Random angle.
            double r = 2.0 + _rng.NextDouble() * 2.0;       // Distance between 2 and 4.

            _agentPos._x = _preyPos._x + (int)Math.Floor(Math.Cos(t) * r);
            _agentPos._y = _preyPos._y + (int)Math.Floor(Math.Sin(t) * r);
        }
Пример #9
0
 private void initialize(double delta) // randomly initialize the weights for this individual, with a maximum perterbance of delta
 {
     for (int i = 0; i < weights.Length; i++)
     {
         for (int j = 0; j < weights[i].Length; j++)
         {
             for (int k = 0; k < weights[i][j].Length; k++)
             {
                 weights[i][j][k] = (float)(r.NextDouble() * delta * 2 - delta);
             }
         }
     }
 }
        public static void Initialize(uint seed)
        {
            _generator     = new GlobalGenerator(seed);
            _treePositions = new List <Vector3Int>();
            var rand = new FastRandom(seed);

            for (var i = 0; i < 5000; i++)
            {
                var sample = new Vector2Int((int)((rand.NextDouble() * 100 - 50) * 32),
                                            (int)((rand.NextDouble() * 100 - 50) * 32));
                var height = _generator.GetHeight(sample.x, sample.y);
                _treePositions.Add(new Vector3Int(sample.x, height, sample.y));
            }
        }
Пример #11
0
        private char GetRandomChar(FastRandom rand)
        {
            if (rand.NextDouble() < 0.15)
            {
                return(' ');
            }
            if (rand.NextDouble() < 0.2)
            {
                return('\n');
            }
            int value = rand.Next(0, 94 + 1);

            return((char)(value + 32));
        }
Пример #12
0
        internal int GetRandomValue(float noteNeed2, float noteNeed3, float noteNeed4 = 1, float noteNeed5 = 1, float noteNeed6 = 1)
        {
            double val = random.NextDouble();

            if (val >= noteNeed6)
            {
                return(6);
            }
            else if (val >= noteNeed5)
            {
                return(5);
            }
            else if (val >= noteNeed4)
            {
                return(4);
            }
            else if (val >= noteNeed3)
            {
                return(3);
            }
            else if (val >= noteNeed2)
            {
                return(2);
            }
            else
            {
                return(1);
            }
        }
Пример #13
0
        public UnitLock SelectOptimalLockTargetFor(ActiveModule module)
        {
            var locks = GetLocks().OfType <UnitLock>().Where(l =>
            {
                if (l.State != LockState.Locked)
                {
                    return(false);
                }

                var isInOptimalRange = IsInRangeOf3D(l.Target, module.OptimalRange);
                return(isInOptimalRange);
            }).ToArray();

            var primaryLock = locks.FirstOrDefault(l => l.Primary);

            if (module.ED.AttributeFlags.PrimaryLockedTarget)
            {
                return(primaryLock);
            }

            var chance = FastRandom.NextDouble() <= PRIMARY_LOCK_CHANCE_FOR_SECONDARY_MODULE;

            if (primaryLock != null && chance)
            {
                return(primaryLock);
            }

            return(locks.RandomElement());
        }
Пример #14
0
        protected virtual void BatchDraw(Microsoft.Xna.Framework.Graphics.SpriteBatch batch)
        {
            rnd.Reinitialise(seed);
            r1 = (float)rnd.NextDouble();
            r2 = (float)rnd.NextDouble();
            r3 = (float)rnd.NextDouble();

            for (int i = 0; i < particleCount; i++)
            {
                r0 = (float)rnd.NextDouble();
                ParticleDraw(i, batch);
                r3 = r2;
                r2 = r1;
                r1 = r0;
            }
        }
Пример #15
0
        private int CalculateEp()
        {
            var activeGathererModules = ParentRobot.ActiveModules.OfType <GathererModule>().Where(m => m.State.Type != ModuleStateType.Idle).ToArray();

            if (activeGathererModules.Length == 0)
            {
                return(0);
            }

            var avgCycleTime = activeGathererModules.Select(m => m.CycleTime).Average();

            var t      = TimeSpan.FromDays(1).Divide(avgCycleTime);
            var chance = (double)MAX_EP_PER_DAY / t;

            chance /= activeGathererModules.Length;

            var rand = FastRandom.NextDouble();

            if (rand <= chance)
            {
                return(1);
            }

            return(0);
        }
Пример #16
0
            public void Visit(Player player)
            {
                if (_npc.Behavior.Type != NpcBehaviorType.Aggressive)
                {
                    return;
                }

                if (player.HasTeleportSicknessEffect)
                {
                    return;
                }

                if (!_npc.ThreatManager.Hostiles.IsEmpty)
                {
                    return;
                }

                if (!_npc.IsInAggroRange(player))
                {
                    return;
                }

                var threat = Threat.BODY_PULL + FastRandom.NextDouble(0, 5);

                _npc.AddThreat(player, new Threat(ThreatType.Bodypull, threat));
            }
Пример #17
0
        protected virtual bool CheckAccuracy(Unit victim)
        {
            var rnd    = FastRandom.NextDouble();
            var isMiss = rnd * _accuracy.Value > victim.SignatureRadius;

            return(isMiss);
        }
Пример #18
0
        /// <summary>
        /// A random item will be pickes using its chanse.
        /// </summary>
        public T GetRandomItem()
        {
            if (TotalProbability == 0.0d)
            {
                throw new ArgumentNullException(typeof(ProbabilityList <T>).ToString(), "There is no item in list");
            }

            if (TotalProbability < 1.0d)
            {
                T lastItem = items.Last().Key;
                items[lastItem] += (1.0d - TotalProbability);
                TotalProbability = 1.0d;
            }
            double randomPercent = random.NextDouble();
            double currentItemProbabilityMaxValue = 0.0d;


            foreach (var item in items)
            {
                currentItemProbabilityMaxValue += item.Value;
                if (currentItemProbabilityMaxValue > 1.0d)
                {
                    currentItemProbabilityMaxValue = 1.0d;
                }

                if (randomPercent <= currentItemProbabilityMaxValue)
                {
                    return(item.Key);
                }
            }

            throw new ArgumentException("Reassign " + nameof(ProbabilityList <T>));
        }
Пример #19
0
            public void Visit(AreaBomb bomb)
            {
                if (!_npc.IsInAggroRange(bomb))
                {
                    return;
                }

                // csak akkor ha van is mivel tamadni
                if (!_npc.ActiveModules.Any(m => m is WeaponModule))
                {
                    return;
                }

                // ha valaki mar foglalkozik a bombaval akkor ne csinaljon semmit

                var g = _npc._group;

                if (g != null && g.Members.Any(m => m.ThreatManager.Contains(bomb)))
                {
                    return;
                }

                var threat = Threat.BODY_PULL;

                if (!_npc.ThreatManager.Hostiles.IsEmpty)
                {
                    var h = _npc.ThreatManager.GetMostHatedHostile();
                    if (h != null)
                    {
                        threat = h.Threat * 100;
                    }
                }

                _npc.AddThreat(bomb, new Threat(ThreatType.Bodypull, threat + FastRandom.NextDouble(0, 5)));
            }
        protected override bool CheckAccuracy(Unit victim)
        {
            var rnd    = FastRandom.NextDouble();
            var isMiss = rnd > ParentRobot.MissileHitChance;

            return(isMiss);
        }
Пример #21
0
        private PlantRule GetNewPlantRule(int globalX, int globalY)
        {
            var area          = Area.FromRadius(globalX, globalY, _neighbourRadius);
            var excludedTypes = GetPlayerSeededTypes;

            var neighbouringPlants = GetPlantTypeCountFromRange(area, excludedTypes);

            PlantType resultPlantType;

            if (neighbouringPlants.Count == 0)
            {
                //no plants, then fertility decides
                resultPlantType = GetAllPlantRules.GetWinnerPlantTypeBasedOnFertility();
            }
            else
            {
                var rulingPlant = neighbouringPlants.OrderBy(k => k.Value).Last().Key;

                var plantTypeBySpreading = GetAllPlantRules.GetSpreadingBasedWinnerPlantType(neighbouringPlants);

                //50% currently ruling plant OR spreading types
                resultPlantType = FastRandom.NextDouble() < 0.5 ? rulingPlant : plantTypeBySpreading;
            }

            return(GetAllPlantRules.FirstOrDefault(p => p.Type == resultPlantType));
        }
Пример #22
0
        public static void ApplyPositionOffsets(IBeatmap beatmap, params Mod[] mods)
        {
            var rng = new FastRandom(RNG_SEED);

            bool   shouldApplyHardRockOffset = mods.Any(m => m is ModHardRock);
            float? lastPosition  = null;
            double lastStartTime = 0;

            foreach (var obj in beatmap.HitObjects.OfType <CatchHitObject>())
            {
                obj.XOffset = 0;

                switch (obj)
                {
                case Fruit fruit:
                    if (shouldApplyHardRockOffset)
                    {
                        applyHardRockOffset(fruit, ref lastPosition, ref lastStartTime, rng);
                    }
                    break;

                case BananaShower bananaShower:
                    foreach (var banana in bananaShower.NestedHitObjects.OfType <Banana>())
                    {
                        banana.XOffset = (float)(rng.NextDouble() * CatchPlayfield.WIDTH);
                        rng.Next();     // osu!stable retrieved a random banana type
                        rng.Next();     // osu!stable retrieved a random banana rotation
                        rng.Next();     // osu!stable retrieved a random banana colour
                    }

                    break;

                case JuiceStream juiceStream:
                    // Todo: BUG!! Stable used the last control point as the final position of the path, but it should use the computed path instead.
                    lastPosition = juiceStream.X + juiceStream.Path.ControlPoints[^ 1].Position.Value.X;
        private ArtifactType GetNextArtifactType()
        {
            if (!HasArtifacts())
            {
                return(ArtifactType.undefined);
            }

            var spawnRates = _artifactSpawnRates[_zone.Id].ToArray();

            var sumRate = spawnRates.Sum(r => r.rate);
            var minRate = 0.0;
            var chance  = FastRandom.NextDouble();

            foreach (var spawnRate in spawnRates)
            {
                var rate    = spawnRate.rate / sumRate;
                var maxRate = rate + minRate;

                if (minRate < chance && chance <= maxRate)
                {
                    return(spawnRate.artifactType);
                }

                minRate += rate;
            }

            return(ArtifactType.undefined);
        }
        /// <summary>
        /// Function that will try to get a place where the entity can spawn, it will apply spawning restrictions.
        /// </summary>
        /// <param name="entity">The entity</param>
        /// <param name="chunk">The chunk where the entity must be placed</param>
        /// <param name="cursor">A cursor on the chunk block data</param>
        /// <param name="rnd">Randomnes generator</param>
        /// <param name="entitySpawnLocation">Returned spawn location, will be [0;0;0] if entity cannot be placed</param>
        /// <returns>False if the entity cannot be placed</returns>
        public bool TryGetSpawnLocation(ChunkSpawnableEntity entity, AbstractChunk chunk, ByteChunkCursor cursor, FastRandom rnd, out Vector3D entitySpawnLocation)
        {
            entitySpawnLocation = default(Vector3D);

            //Test spawning chance
            if (rnd.NextDouble() <= entity.SpawningChance)
            {
                return(false);
            }
            //Get Rnd chunk Location X/Z
            int x = rnd.Next(0, 16);
            int z = rnd.Next(0, 16);
            //Column Info index
            int columnInfoIndex = x * AbstractChunk.ChunkSize.Z + z;

            int y;

            switch (entity.SpawningPlace)
            {
            case ChunkSpawningPlace.FloorInsideCave:
            case ChunkSpawningPlace.CeilingInsideCave:
                return(CaveSpawnLogic(x, z, entity, chunk, cursor, rnd, out entitySpawnLocation));

            case ChunkSpawningPlace.AirAboveSurface:
                return(AirSpawnLogic(x, z, entity, chunk, cursor, rnd, out entitySpawnLocation));

            case ChunkSpawningPlace.Surface:
            default:
                return(SurfaceSpawnLogic(x, z, entity, chunk, cursor, rnd, out entitySpawnLocation));
            }
        }
Пример #25
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static string GetRandomChar()
        {
            var _loc2 = Math.Ceiling(Random.NextDouble() * 100);

            if (_loc2 <= 40)
            {
                return(((char)Math.Floor(Random.NextDouble() * 26) + 65).ToString());
            }
            else if (_loc2 <= 80)
            {
                return(((char)Math.Floor(Random.NextDouble() * 26) + 97).ToString());
            }
            else
            {
                return(((char)Math.Floor(Random.NextDouble() * 10) + 48).ToString());
            }
        }
 public RandomPolynomial(int degree, double maxCoefficientMagnitude, FastRandom r)
 {
     Coefficients = new double[degree + 1];
     for (var i = 0; i <= degree; i++)
     {
         Coefficients[i] = (r.NextDouble() - 0.5) * maxCoefficientMagnitude * 2; // Permit range [-maxCoefficientMagnitude, +maxCoefficientMagnitude)
     }
 }
        private double RandomizeDirection(double direction)
        {
            var randomModifier = (FastRandom.NextDouble(-(1 - _module.ScanAccuracy), (1 - _module.ScanAccuracy))) * RANDOM_INTERVAL;

            direction += randomModifier;
            MathHelper.NormalizeDirection(ref direction);
            return(direction);
        }
Пример #28
0
        public IntervalTimer(TimeSpan interval, bool random = false)
        {
            Interval = interval;

            if (random)
            {
                Elapsed = TimeSpan.FromMilliseconds(FastRandom.NextDouble() * interval.TotalMilliseconds);
            }
        }
Пример #29
0
        public void ReplaceIndicesByRandomValue(IDictionary <int, IList <int> > cells, bool considerSelection = false)
        {
            var rand = new FastRandom();

            ReplaceIndicesByValues(cells,
                                   col => {
                double min   = PreprocessingData.GetMin <double>(col, considerSelection);
                double max   = PreprocessingData.GetMax <double>(col, considerSelection);
                double range = max - min;
                return(cells[col].Select(_ => rand.NextDouble() * range + min));
            },
                                   col => {
                var min      = PreprocessingData.GetMin <DateTime>(col, considerSelection);
                var max      = PreprocessingData.GetMax <DateTime>(col, considerSelection);
                double range = (max - min).TotalSeconds;
                return(cells[col].Select(_ => min + TimeSpan.FromSeconds(rand.NextDouble() * range)));
            });
        }
Пример #30
0
 public static IEnumerable <long> GenerateUniformDistributedValues(int n, long start, long end, FastRandom rand)
 {
     for (int i = 0; i < n; i++)
     {
         double r = rand.NextDouble();        // r \in [0, 1)
         r = r * ((end + 1) - start) + start; // r \in [start, end + 1), the "+ 1" makes sure that it is uniformlly distibuted when using floor in the next line
         yield return((long)Math.Floor(r));
     }
 }
Пример #31
0
        private static void TestExpressions()
        {
            /* Wood
             double	s = pow ( SineWave ( RingSpacing*sqrt ( x*x+y*y ) + TurbScale * Turbulence ( p, 3 ) ), Squeeze );
         	 t.Color = ( 1 - s ) * LightWood + s * DarkWood;
            string wood = "unit-$pow<$saw<3*sqrt<x*x+y*y*>+1.8*$t<c,3>>,5>";
             */
            string wood = "(unit-($saw<3*$sqrt<x*x+y*y*>>+$t<c,3>))*lw + ( ($saw<3*$sqrt<x*x+y*y*>>+$t<c,3>)*dw)";
            string expression = wood;
            //@"unit*$sqrt<x*x+y*y>";
            float x = 0.5f;
            float y = 0.7f;
            var p = new Vector(x, y, 2 - x - y);
            var p0 = new Vector(x, y, 0);
            var u = new RgbSpectrum(1f);

            var rnd = new FastRandom();
            var c = new RgbSpectrum(NoiseProvider.Instance.Noise3D(p));
            var evaluator = new GenericExpressionEvaluator<RgbSpectrum>((i) =>
                {
                    if (i is float)
                    {
                        return new RgbSpectrum((float)i);
                    }
                    if (i is double)
                    {
                        return new RgbSpectrum((float)((double)i));
                    }
                    if (i is int)
                    {
                        return new RgbSpectrum((int)i);
                    }
                    if (i is Int64)
                    {
                        return new RgbSpectrum((int)i);
                    }
                    return (RgbSpectrum)i;
                }, RgbSpectrum.FromStringData);

            var func = evaluator.Compile(expression);
            var f = rnd.NextDouble();
            Console.WriteLine("Script version: {0}", func(new
                {
                    e = f,
                    c,
                    u,
                    unit = RgbSpectrum.UnitSpectrum(),
                    lw = new RgbSpectrum(0.5f, 0.2f, 0.3f),
                    dw = new RgbSpectrum(0.3f, 0.1f, 0.1f),
                    x,
                    y,
                    arr = new[] { 0.5, 0.6, 0.6 },
                    n = c * 0.5f,
                }));

            Console.WriteLine("C# version : {0}", c * Math.Sqrt(x * x + y * y));

            return;
        }
Пример #32
0
 /// <summary>
 /// For activation functions that accept auxiliary arguments; generates random initial values for aux arguments for newly
 /// added nodes (from an 'add neuron' mutation).
 /// </summary>
 public double[] GetRandomAuxArgs(FastRandom rng, double connectionWeightRange)
 {
     double[] auxArgs = new double[2];
     auxArgs[0] = (rng.NextDouble()-0.5) * 2.0;
     auxArgs[1] = rng.NextDouble();
     return auxArgs;
 }
Пример #33
0
        public override void SetSpawnPosition (Vector3 playerSpawn, PhysicsComponent ownPhysics, object map, FastRandom rand)
        {
            Maze.Maze maze = map as Maze.Maze;
            if (maze != null)
            {
                bool gotit = false;

                while (!gotit)
                {
                    int pos = rand.Next (0, maze.graph.Nodes.Count);
                    Vector3 spawn_pos;
                    float distance;
                    for (int i = pos; i < maze.graph.Nodes.Count; i++)
                    {
                        spawn_pos = maze.graph.Nodes[i].Data.WorldPosition;
                        Vector3.Distance(ref playerSpawn, ref spawn_pos, out distance);
                        if (maze.graph.Nodes[i].Data.MazeCellType == MazeCellType.Ground && distance > 50 &&
                            !maze.graph.Nodes[i].Data.IsExit)
                        {
                            gotit = true;
                            ownPhysics.RigidBody.Position = new JVector (maze.graph.Nodes[i].Data.WorldPosition.X, height,
                                maze.graph.Nodes[i].Data.WorldPosition.Z);
                            break;
                        }
                    }
                }

                if (!gotit)
                {
                    Logger.Log.AddLogEntry (LogLevel.Severe, "GhostAI", "Failed to generate spawn position!");
                }

                fallback = JVector.Transform (JVector.Backward, JMatrix.CreateFromAxisAngle (JVector.Up,
                    (float) rand.NextDouble() * 2 * MathHelper.Pi));
                direction = fallback;

                Spawned = true;
            }
        }
Пример #34
0
 public Particle(FastRandom rnd)
 {
     Deviation0 = (float)rnd.NextDouble() * 2f - 1f;
     //Deviation1 = (float)rnd.NextDouble() * 2f - 1f;
     //TextureIndex = (ushort)rnd.Next(4);
 }