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;
/// <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)); } }
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)); } } }
public static string Analyse(INoise3 noiseFct, int iteration) { FastRandom rnd = new FastRandom(); //Generate randomIteration number in array int[,] inputNumber = new int[iteration, 3]; for (int i = 0; i < iteration; i++) { inputNumber[i, 0] = rnd.Next(); inputNumber[i, 1] = rnd.Next(); inputNumber[i, 2] = rnd.Next(); } long from = Stopwatch.GetTimestamp(); double min = double.MaxValue; double max = double.MinValue; for (int i = 0; i < iteration; i++) { double val = noiseFct.Get(inputNumber[i, 0], inputNumber[i, 1], inputNumber[i, 2]); if (val < min) { min = val; } if (val > max) { max = val; } } long to = Stopwatch.GetTimestamp(); return("INoise3 analysed for " + iteration + " iteration. Time needed : " + ((to - from) / (double)Stopwatch.Frequency * 1000.0) + " ms; Min : " + min + " max : " + max); }
private void PlaceDecorations(Point tileOrigin, Microsoft.Xna.Framework.Rectangle magmaMapArea) { FastRandom fastRandom1 = new FastRandom(Main.ActiveWorldFileData.Seed).WithModifier(65440UL); for (int left = magmaMapArea.Left; left < magmaMapArea.Right; ++left) { for (int top = magmaMapArea.Top; top < magmaMapArea.Bottom; ++top) { GraniteBiome.Magma sourceMagma = this._sourceMagmaMap[left, top]; int index1 = left + tileOrigin.X; int index2 = top + tileOrigin.Y; if (sourceMagma.IsActive) { WorldUtils.TileFrame(index1, index2, false); WorldGen.SquareWallFrame(index1, index2, true); FastRandom fastRandom2 = fastRandom1.WithModifier(index1, index2); if (fastRandom2.Next(8) == 0 && GenBase._tiles[index1, index2].active()) { if (!GenBase._tiles[index1, index2 + 1].active()) { WorldGen.PlaceUncheckedStalactite(index1, index2 + 1, fastRandom2.Next(2) == 0, fastRandom2.Next(3), false); } if (!GenBase._tiles[index1, index2 - 1].active()) { WorldGen.PlaceUncheckedStalactite(index1, index2 - 1, fastRandom2.Next(2) == 0, fastRandom2.Next(3), false); } } if (fastRandom2.Next(2) == 0) { Tile.SmoothSlope(index1, index2, true, false); } } } } }
private byte PlayWalkingSound(byte cubeId, DynamicEntitySoundTrack entityTrack) { List <SoundMetaData> sounds; byte soundIndex = 0; // play a water sound if (_stepsSounds.TryGetValue(cubeId, out sounds)) { // choose another sound to avoid playing the same sound one after another while (sounds.Count > 1 && entityTrack.LastSound == soundIndex) { soundIndex = (byte)_rnd.Next(0, sounds.Count); } if (entityTrack.isLocalSound) { _soundEngine.StartPlay2D(sounds[soundIndex].Alias, SourceCategory.FX); } else { _soundEngine.StartPlay3D(sounds[soundIndex].Alias, new Vector3((float)entityTrack.Entity.Position.X, (float)entityTrack.Entity.Position.Y, (float)entityTrack.Entity.Position.Z), SourceCategory.FX); } } return(soundIndex); }
protected override void LoadContent() { var font = Content.Load <BitmapFont>("Sensation"); var texture = Content.Load <Texture2D>("0x72_16x16DungeonTileset.v4"); var tileset = new Tileset(texture, 16, 16); var entityFactory = new EntityFactory(tileset); _spriteBatch = new SpriteBatch(GraphicsDevice); _world = new WorldBuilder() .AddSystem(new MapRenderingSystem(GraphicsDevice, tileset)) .AddSystem(new SpriteRenderingSystem(GraphicsDevice, texture)) .AddSystem(new HudSystem(this, GraphicsDevice, font, tileset)) .AddSystem(new PlayerControlSystem(this, entityFactory)) .AddSystem(new BodyMovementSystem()) .AddSystem(new CollisionSystem()) .AddSystem(new CollisionResponseSystem(entityFactory)) .Build(); entityFactory.World = _world; entityFactory.SpawnPlayer(100, 100); var random = new FastRandom(); for (var i = 0; i < 20; i++) { entityFactory.SpawnZombie(random.Next(150, 800), random.Next(0, 480)); //entityFactory.SpawnSkeleton(random.Next(150, 250), random.Next(110, 250)); //entityFactory.SpawnPurpleThing(random.Next(150, 250), random.Next(110, 250)); } }
private List <LandscapeEntity> PopulateChunksWithTree(Vector3I chunkPosition, Biome biome, byte[] chunkBytes, ChunkColumnInfo[] columndInfo, FastRandom rnd) { if (biome.BiomeTrees.Trees.Count <= 0) { return(null); } //Get Rnd chunk Location. int x = rnd.Next(0, 16); int z = rnd.Next(0, 16); int y = columndInfo[x * AbstractChunk.ChunkSize.Z + z].MaxGroundHeight + 1; //Validate position = Must be Air block (not water) ! if (chunkBytes[((z * AbstractChunk.ChunkSize.X) + x) * AbstractChunk.ChunkSize.Y + y] != WorldConfiguration.CubeId.Air) { return(null); } x += (chunkPosition.X * AbstractChunk.ChunkSize.X); z += (chunkPosition.Z * AbstractChunk.ChunkSize.Z); Vector3I worldPosition = new Vector3I(x, y, z); //Generate Tree mesh ! //Get tree type following distribution chances inside the biome TreeBluePrint treeType = biome.BiomeTrees.GetTreeTemplate(rnd, _worldParameters.Configuration.TreeBluePrintsDico); int generationSeed = rnd.Next(); return(LandscapeEntityParser.GlobalMesh2ChunkMesh(_treeGenerator.Generate(generationSeed, worldPosition, treeType), worldPosition, treeType.Id, generationSeed)); }
public void MoveBall(float elapsedSecs, int screenWidth, int screenHeight) { Position += Velocity * elapsedSecs; var halfHeight = BoundingRectangle.Height / 2; var halfWidth = BoundingRectangle.Width / 2; if (Position.Y - halfHeight < 0) { Position.Y = halfHeight; Velocity.Y = -Velocity.Y; } if (Position.Y + halfHeight > screenHeight) { Position.Y = screenHeight - halfHeight; Velocity.Y = -Velocity.Y; } if (Position.X > screenWidth + halfWidth && Velocity.X > 0) { Position = new Vector2(screenWidth / 2f, screenHeight / 2f); Velocity = new Vector2(random.Next(2, 5) * -100, 100); scored = "player"; } if (Position.X < -halfWidth && Velocity.X < 0) { Position = new Vector2(screenWidth / 2f, screenHeight / 2f); Velocity = new Vector2(random.Next(2, 5) * 100, 100); scored = "ai"; } }
private static Vector2i getRandomColor(FastRandom rnd) { int width = Assets.COLOR_PALETTE.Width; int upperBound = Assets.COLOR_PALETTE.Height >> 1; int num = Assets.COLOR_PALETTE.Height >> 2; return(new Vector2i(rnd.Next(width), rnd.Next(upperBound) + num)); }
private IEnumerable <Tuple <string, int> > GetRandomTuple(int n, FastRandom rand) { for (int i = 0; i < n; i++) { string strValue = GetRandomString(rand.Next(1, 100 + 1), rand); int intValue = intValues[rand.Next(0, intValues.Length)]; yield return(new Tuple <string, int>(strValue, intValue)); } }
private IEnumerable<List<int>> GetRandomVectors(int n, FastRandom rand) { for (int i = 0; i < n; i++) { int length = rand.Next(1, 50); List<int> cur = new List<int>(length) { 0 }; for (int j = 0; j < length - 1; j++) { cur.Add(rand.Next(-50, 50)); } yield return cur.Shuffle(rand).ToList(); } }
/// <summary> /// Add noise points to the data and classify each noise point with the nearest cluster center. /// </summary> /// <param name="noisePointsToAdd">Number of noise points to add.</param> /// <param name="clusterCenters">Cluster centers for each cluster, where the key is the cluster id.</param> /// <param name="clusters">The noise points will be added to these clusters.</param> private void AddNoise(int noisePointsToAdd, Dictionary <string, UnsignedPoint> clusterCenters, Classification <UnsignedPoint, string> clusters) { if (noisePointsToAdd <= 0) { return; } var pccp = new PolyChromaticClosestPoint <string> (clusters); var closest = new List <Tuple <String, String> > (); // Find the nearest neighboring cluster to each cluster. // We will be choosing random noise points positioned in the space between clusters that are near neighbors. foreach (var clusterId in clusters.ClassLabels()) { var cp = pccp.FindClusterApproximately(clusterId).Swap(clusterId); closest.Add(new Tuple <string, string>(cp.Color1, cp.Color2)); } // We need to pick random points from each cluster, so must convert from Sets to Lists for performance. var clustersAsLists = new Dictionary <string, List <UnsignedPoint> > (); foreach (var pair in clusters.LabelToPoints) { clustersAsLists [pair.Key] = pair.Value.ToList(); } // Pick random pairs of clusters that are close neighbors. // Then pick a random point from each cluster and compute a weighted average of the two points. // This will construct noise points that tend to form a filament between two clusters. // Such connecting filaments pose the greatest likelihood of merging two distinct // clusters into one, the very error that must be compensated for by an improved algorithm. for (var i = 0; i < noisePointsToAdd; i++) { var whereToAdd = closest [r.Next(closest.Count)]; // The weight will range from 0.18 to 0.82 so as to keep most noise points from being inside a cluster, // which would make them non-noisy. var weight1 = r.NextDouble() * 0.64 + 0.18; var weight2 = 1.0 - weight1; var c1 = clustersAsLists[whereToAdd.Item1]; var c2 = clustersAsLists[whereToAdd.Item2]; var p1 = c1[r.Next(c1.Count)]; var p2 = c2[r.Next(c2.Count)]; var vRandom = new int[Dimensions]; for (var iDim = 0; iDim < vRandom.Length; iDim++) { vRandom [iDim] = (int)(weight1 * p1.Coordinates [iDim] + weight2 * p2.Coordinates [iDim]); } var pRandom = new UnsignedPoint(vRandom); var d1 = c1.Select(p => pRandom.Measure(p)).Min(); var d2 = c2.Select(p => pRandom.Measure(p)).Min(); var cRandom = d1 < d2 ? whereToAdd.Item1 : whereToAdd.Item2; clusters.Add(pRandom, cRandom); Noise.Add(pRandom); } }
private List <int> GetRandom(FastRandom rand, int minLength = 1) { int length = rand.Next(minLength, 50 + 1); List <int> vector = new List <int>(length); for (int j = 0; j < length; j++) { vector.Add(rand.Next(-1000, 1000 + 1)); } return(vector); }
public override IEnumerable <IDataDescriptor> GetDataDescriptors() { var rand = new FastRandom(Seed); return(new List <IDataDescriptor>() { new RocketFuelFlow(rand.Next()), new AircraftLift(rand.Next()), new FluidDynamics(rand.Next()), new AircraftMaximumLift(rand.Next()) }); }
private static bool ResolveHostname(string hostname, out IPAddress address) { IPAddress[] ipAddresses = Dns.GetHostAddresses(hostname); if (ipAddresses.Length <= 0) { address = default(IPAddress); return(false); } address = ipAddresses[Rnd.Next(0, ipAddresses.Length - 1)]; return(true); }
/// <summary> /// Compute the coarseness, either estimated or exact, depending on pairsToTest. /// /// If Coarseness is called a second time, the previous results are returned unchanged, unless Clear() is called inbetween. /// </summary> /// <param name="pairsToTest">Number of random pairs of points to test. /// If zero or greater than N(N-1)/2, test all pairs of points. /// If there are thirty-two points or fewer, then compute an exact result as well.</param> /// <returns>Coarseness values per number of bits of division. /// The value at index zero is one, the case when a single grid cell is big enough to hold all data. /// At index one is the coarseness if the grid cell size is half of 2^BitsPerDimension. /// At index two is the coarseness if the grid cell size is a quarter of 2^BitsPerDimension. /// etc. /// </returns> public double[] Coarseness(int pairsToTest = 0) { if (CoarsenessPerBits != null) { return(CoarsenessPerBits); } var sameCellPerBits = new int[BitsPerDimension]; var allPermutations = Count * (Count - 1) / 2; if (pairsToTest <= 0 || pairsToTest >= allPermutations || Count <= 32) { pairsToTest = allPermutations; // Exact computation, visiting all permutations. for (var i = 0; i < Count - 1; i++) { var point1 = Points[i]; for (var j = i + 1; j < Count; j++) { var point2 = Points[j]; LoopOverBits(point1, point2, sameCellPerBits); } } } else { // Estimate, visiting a sample of permutations. var alreadyVisited = new HashSet <long>(); var rng = new FastRandom(); while (alreadyVisited.Count < pairsToTest) { var i = rng.Next(Count); var j = rng.Next(Count); if (i == j) { continue; } var key = ((long)i << 32) + j; // Do not visit the same permutation more than once. // HashSet.Add returns false if the key is already present, // so we do not need to call both Contains and Add. if (!alreadyVisited.Add(key)) { continue; } var point1 = Points[i]; var point2 = Points[j]; LoopOverBits(point1, point2, sameCellPerBits); } } sameCellPerBits[0] = pairsToTest; // Ensure that CoarsenessPerBits[0] = 1. CoarsenessPerBits = sameCellPerBits.Select(count => (double)count / (double)pairsToTest).ToArray(); return(CoarsenessPerBits); }
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(); 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: foreach (var nested in juiceStream.NestedHitObjects) { var catchObject = (CatchHitObject)nested; catchObject.XOffset = 0; if (catchObject is TinyDroplet) { catchObject.XOffset = Math.Clamp(rng.Next(-20, 20) / CatchPlayfield.BASE_WIDTH, -catchObject.X, 1 - catchObject.X); } else if (catchObject is Droplet) { rng.Next(); // osu!stable retrieved a random droplet rotation } } break; } } }
private IEnumerable <List <int> > GetAllOdd(int n, FastRandom rand) { for (int i = 0; i < n; i++) { int length = rand.Next(1, 51); List <int> vector = new List <int>(length); for (int j = 0; j < length; j++) { vector.Add(rand.Next(0, 1000) * 2 - 999); } yield return(vector); } }
private IEnumerable <List <int> > GetRandom(int n, FastRandom rand, IEnumerable <int> sizes, int min = -256, int max = 256) { foreach (var s in sizes) { int length = rand.Next(s + 1, 20 + 1); List <int> vector = new List <int>(length); // vector has to be bigger than s for (int j = 0; j < length; j++) { vector.Add(rand.Next(min, max + 1)); } yield return(vector); } }
private IEnumerable <List <int> > GetRandom(int n, FastRandom rand, int min = -1000, int max = 1000 + 1) { for (int i = 1; i <= n; i++) { int length = rand.Next(1, 51); List <int> vector = new List <int>(length); for (int j = 0; j < length; j++) { vector.Add(rand.Next(min, max)); } yield return(vector); } }
/// <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); }
private IEnumerable <List <string> > GetStringsInSortedLengthOrder(int n, FastRandom rand) { for (int i = 0; i < n; i++) { List <string> strings = new List <string>(3) { StringValueGenerator.GetRandomString(rand.Next(0, 50), rand), StringValueGenerator.GetRandomString(rand.Next(0, 50), rand), StringValueGenerator.GetRandomString(rand.Next(0, 50), rand) }; yield return(strings.OrderBy(x => x.Length).ToList()); } }
private IEnumerable <string> GetRandomString(int n, FastRandom rand) { for (int i = 0; i < n; i++) { int length = rand.Next(1, 100 + 1); var value = GetRandomChar(length, rand).ToArray(); if (!value.Any(x => terminators.Contains(x))) { value[rand.Next(0, value.Length)] = terminators[rand.Next(0, terminators.Length)]; } yield return(new String(value)); } }
private IEnumerable <List <string> > GetStrings(int n, FastRandom rand) { for (int i = 0; i < n; i++) { List <string> strings = new List <string>(3) { StringValueGenerator.GetRandomString(rand.Next(0, 50), rand), StringValueGenerator.GetRandomString(rand.Next(0, 50), rand), StringValueGenerator.GetRandomString(rand.Next(0, 50), rand) }; yield return(strings); } }
private void UpdateKeyAnimation() { if (_rnd.Next(0, 500) == 0) { _standBy = false; _animationStep = MathHelper.FullLerp(0.02f, 0.05f, 0, 1, _rnd.NextDouble()); FlatWindFlowNormalizedWithNoise = Vector3.Normalize(new Vector3(WindFlow.X, 0, WindFlow.Z)); } _keyFrameAnimation.Value += (_animationStep); if (_standBy) { if (_keyFrameAnimation.Value > MathHelper.PiOver2 / _standbyLimit) { _animationStep = -1f * MathHelper.FullLerp(0.003f, 0.005f, 0, 1, _rnd.NextDouble()); _standbyLimit = _rnd.Next(10, 11); _keyFrameAnimation.Value = MathHelper.PiOver2 / _standbyLimit; } if (_keyFrameAnimation.Value > -0.002 && _keyFrameAnimation.Value < 0.002) { _flatWindFlowNormalizedWithNoise.Value = Vector3.Normalize(new Vector3((float)(WindFlow.X + _rnd.NextDouble()), 0, (float)(WindFlow.Z + _rnd.NextDouble()))); } if (_keyFrameAnimation.Value < -MathHelper.PiOver2 / _standbyLimit) { _animationStep = MathHelper.FullLerp(0.003f, 0.005f, 0, 1, _rnd.NextDouble()); _standbyLimit = _rnd.Next(10, 11); _keyFrameAnimation.Value = -MathHelper.PiOver2 / _standbyLimit; } } else { if (_keyFrameAnimation.Value > MathHelper.PiOver2 / 2) { _animationStep = -0.01f; _keyFrameAnimation.Value = MathHelper.PiOver2 / 2; } if (_keyFrameAnimation.Value < -MathHelper.PiOver2 / 8) { _standBy = true; _animationStep = 0.008f; _keyFrameAnimation.Value = -MathHelper.PiOver2 / 8; _standbyLimit = 8; } } }
public static void TestQuickSort(int n) { Console.WriteLine("----------------------------------------------------------------"); Console.WriteLine("Test Comparer Quick Sort"); int[] array = new int[n]; Console.WriteLine("Generate data"); RandomIteratorUsafeXorshiftEn rnd1 = new RandomIteratorUsafeXorshiftEn(n + 1); FastRandom rnd = new FastRandom(); dh.StartWatch(); for (int i = 0; i < n; i++) { array[i] = rnd.Next(); } dh.StoptWatch(); Console.WriteLine(dh.GetMessage()); Console.WriteLine("Sort"); dh.StartWatch(); var c = new CustomIntComparerD(); Quicksort(array, 0, n - 1, c.Compare); dh.StoptWatch(); Console.WriteLine(dh.GetMessage()); array = null; GarbachCollectorHelper.GBForceRun(); }
/// <summary> /// Puts the agents into equal-sized subcultural groups. /// /// <param name="numGroups">The number of groups to divide the population into</param> /// </summary> private void CreateSubcultures(int numGroups = 10) { int minGroupSize = _agents.Length / numGroups; _agentGroups = new int[_agents.Length]; // Create a list of all the teacher IDs List <int> agentIds = new List <int>(); for (int i = 0; i < _agentGroups.Length; i++) { _agentGroups[i] = -1; agentIds.Add(i); } // Select each ID for each subculture randomly for (int i = 0; i < _agentGroups.Length; i++) { int temp = _random.Next(agentIds.Count); int idx = agentIds[temp]; _agentGroups[idx] = i % numGroups; agentIds.RemoveAt(temp); } Debug.Assert(_agentGroups.GroupBy(g => g).Min(ag => ag.Count()) >= minGroupSize); Debug.Assert(_agentGroups.GroupBy(g => g).Max(ag => ag.Count()) <= minGroupSize + 1); Debug.Assert(_agentGroups.GroupBy(g => g).Count() == numGroups); }
private async void OnJoinServerButtonPressed() { var entry = SelectedItem.SavedServerEntry; var ips = Dns.GetHostAddresses(entry.Host).ToArray(); IPAddress ip = ips[Rnd.Next(0, ips.Length - 1)]; if (ip == null) { return; } IPEndPoint target = new IPEndPoint(ip, entry.Port); var authenticationService = GetService <IPlayerProfileService>(); var currentProfile = authenticationService.CurrentProfile; if (Alex.ServerTypeManager.TryGet(entry.ServerType, out var typeImplementation)) { if (!await typeImplementation.VerifyAuthentication(currentProfile)) { await typeImplementation.Authenticate(_skyBox, result => { if (result) { Alex.ConnectToServer(typeImplementation, new ServerConnectionDetails(target, entry.Host), authenticationService.CurrentProfile); } }); } else { Alex.ConnectToServer(typeImplementation, new ServerConnectionDetails(target, entry.Host), authenticationService.CurrentProfile); } } }
public static IEnumerable <int> GenerateUniformDistributedValues(int n, int start, int end, FastRandom rand) { for (int i = 0; i < n; i++) { yield return(rand.Next(start, end + 1)); } }
public MsgKeepAlive() : base() { FastRandom fastRand = new FastRandom(); this.Payload = new byte[fastRand.Next(32, 256)]; fastRand.NextBytes(this.Payload); }
private IEnumerable <List <string> > GetRepeatedString(int n, FastRandom rand) { for (int i = 0; i < n; i++) { yield return(Enumerable.Repeat(StringValueGenerator.GetRandomString(rand.Next(1, 50), rand), 3).ToList()); } }
public Problem() : base() { Parameters.Add(new FixedValueParameter<IntValue>(LawnWidthParameterName, "Width of the lawn.", new IntValue(8))); Parameters.Add(new FixedValueParameter<IntValue>(LawnLengthParameterName, "Length of the lawn.", new IntValue(8))); var g = new SimpleSymbolicExpressionGrammar(); g.AddSymbols(new string[] { "Sum", "Prog" }, 2, 2); g.AddSymbols(new string[] { "Frog" }, 1, 1); g.AddTerminalSymbols(new string[] { "Left", "Forward" }); // initialize 20 ephemeral random constants in [0..32[ var fastRand = new FastRandom(314159); for (int i = 0; i < 20; i++) { g.AddTerminalSymbol(string.Format("{0},{1}", fastRand.Next(0, 32), fastRand.Next(0, 32))); } Encoding = new SymbolicExpressionTreeEncoding(g, 1000, 17); }
/// <summary> /// See <see cref="BaseColorCacheQuantizer.OnGetPaletteToCache"/> for more details. /// </summary> protected override List<Color> OnGetPaletteToCache(Int32 colorCount) { // use fast random class FastRandom random = new FastRandom(0); // NOTE: I've added a little randomization here, as it was performing terribly otherwise. // sorts out the list by a pixel presence, takes top N slots, and calculates // the average color from them, thus our new palette. IEnumerable<Color> colors = colorMap. OrderBy(entry => random.Next(colorMap.Count)). OrderByDescending(entry => entry.Value.PixelCount). Take(colorCount). Select(entry => entry.Value.GetAverage()); palette.Clear(); palette.AddRange(colors); return palette; }
public override void ProcessPayload(SSPClient client, OperationalSocket _OpSocket) { RequestHeader reqHeader = Header as RequestHeader; if (reqHeader != null) { Type type = null; lock (client.Connection.RegisteredOperationalSockets) { client.Connection.RegisteredOperationalSockets.TryGetValue(Identifier, out type); } if(type != null) { bool SendedSuccess = false; try { OperationalSocket OpSocket = (OperationalSocket)Activator.CreateInstance(type, client); OpSocket.isConnected = true; lock (client.Connection.OperationalSockets) { FastRandom rnd = new FastRandom(); OpSocket.ConnectionId = (ushort)rnd.Next(1, 65535); while(client.Connection.OperationalSockets.ContainsKey(OpSocket.ConnectionId)) OpSocket.ConnectionId = (ushort)rnd.Next(1, 65535); client.Connection.OperationalSockets.Add(OpSocket.ConnectionId, OpSocket); } try { OpSocket.onBeforeConnect(); client.onOperationalSocket_BeforeConnect(OpSocket); } catch (Exception ex) { SysLogger.Log(ex.Message, SysLogType.Error); OpSocket.onException(ex, ErrorType.UserLand); } client.Connection.SendMessage(new MsgCreateConnectionResponse(OpSocket.ConnectionId, true), new RequestHeader(reqHeader.RequestId, true)); SendedSuccess = true; OpSocket.onConnect(); client.onOperationalSocket_Connected(OpSocket); } catch (Exception ex) { SysLogger.Log(ex.Message, SysLogType.Error); if (!SendedSuccess) { client.Connection.SendMessage(new MsgCreateConnectionResponse(0, false), new RequestHeader(reqHeader.RequestId, true)); } } } else { client.Connection.SendMessage(new MsgCreateConnectionResponse(0, false), new RequestHeader(reqHeader.RequestId, true)); } } }
static Dictionary<string, double> morphEnglish(Dictionary<string, double> english, double[] digitProbs, double[] posProbs, int minLength = 0) { Dictionary<string, double> results = new Dictionary<string, double>(); FastRandom random = new FastRandom(); Console.WriteLine("Probs sum: {0}", digitProbs.Sum()); RouletteWheelLayout digitLayout = new RouletteWheelLayout(digitProbs); RouletteWheelLayout posLayout = new RouletteWheelLayout(posProbs); int alreadyNumbered = 0; foreach (string s in english.Keys) { bool numbered = false; for (int i = 0; i < s.Length; i++) if (s[i] >= '0' && s[i] <= '9') { alreadyNumbered++; numbered = true; break; } string morphedPassword = s; while (!numbered || morphedPassword.Length < minLength) { int toAdd = RouletteWheel.SingleThrow(digitLayout, random); int pos = RouletteWheel.SingleThrow(posLayout, random); if (pos == 0) break; else if (pos == 1) morphedPassword = toAdd + morphedPassword; else if (pos == 2) morphedPassword = morphedPassword + toAdd; else { pos = random.Next(morphedPassword.Length); morphedPassword = morphedPassword.Substring(0, pos) + toAdd + morphedPassword.Substring(pos, morphedPassword.Length - pos); } numbered = true; } double val; if (!results.TryGetValue(morphedPassword, out val)) results.Add(morphedPassword, 1); } Console.WriteLine("Had numbers already: {0}", alreadyNumbered); return results; }
private static void GetNextRandomInstruction(FastRandom rnd, ref InstructionInfo EncInstruction, ref InstructionInfo DecInstruction) { lock (RndInstLock) { Instruction[] InstructionList = new Instruction[] { //Instruction.BitLeft, //unstable do not use Instruction.Minus, Instruction.Plus, //Instruction.ForLoop_PlusMinus, //Instruction.RotateLeft_Big, //Instruction.RotateLeft_Small, Instruction.SwapBits, Instruction.XOR }; Instruction inst = InstructionList[rnd.Next(0, InstructionList.Length)]; switch (inst) { case Instruction.BitLeft: { int bitSize = rnd.Next(1, 3); //maybe needs to be higher ? EncInstruction = new InstructionInfo(inst, bitSize); DecInstruction = new InstructionInfo(Instruction.BitRight, bitSize); break; } case Instruction.Minus: { byte[] TempDate = new byte[32]; rnd.NextBytes(TempDate); EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate)); DecInstruction = new InstructionInfo(Instruction.Plus, new BigInteger(TempDate)); break; } case Instruction.Plus: { byte[] TempDate = new byte[32]; rnd.NextBytes(TempDate); EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate)); DecInstruction = new InstructionInfo(Instruction.Minus, new BigInteger(TempDate)); break; } case Instruction.ForLoop_PlusMinus: { int size = rnd.Next(); int size2 = rnd.Next(); int loops = rnd.Next(2, 255); EncInstruction = new InstructionInfo(inst, (uint)size, (uint)size2, loops); DecInstruction = new InstructionInfo(inst, (uint)size, (uint)size2, loops); break; } case Instruction.RotateLeft_Big: { byte bitSize = (byte)rnd.Next(1, 60); EncInstruction = new InstructionInfo(inst, (uint)bitSize); DecInstruction = new InstructionInfo(Instruction.RotateRight_Big, (uint)bitSize); break; } case Instruction.RotateLeft_Small: { byte bitSize = (byte)rnd.Next(1, 30); EncInstruction = new InstructionInfo(inst, (uint)bitSize); DecInstruction = new InstructionInfo(Instruction.RotateRight_Small, (uint)bitSize); break; } case Instruction.SwapBits: { EncInstruction = new InstructionInfo(inst, 0); DecInstruction = new InstructionInfo(inst, 0); break; } case Instruction.XOR: { byte[] TempDate = new byte[32]; rnd.NextBytes(TempDate); EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate)); DecInstruction = new InstructionInfo(inst, new BigInteger(TempDate)); break; } default: { break; } } } }
private void ShuffleInstructions(InstructionInfo[] insts, int Seed) { FastRandom rnd = new FastRandom(Seed); for (int i = insts.Length, j = 0; i > 1; i--, j++) { int pos = rnd.Next(i); // 0 <= j <= i-1 InstructionInfo tmp = insts[pos]; insts[pos] = insts[i - 1]; insts[i - 1] = tmp; } }
private int SampleTriangleIndex(FastRandom rnd) { return rnd.Next(0, triangleSampleData.Length - 1); }
/// <summary> /// Creates the evolution algorithm container using the given factories and genome lists. /// </summary> /// <param name="genomeFactory1">The agent genome factory.</param> /// <param name="genomeFactory2">The maze genome factory.</param> /// <param name="genomeList1">The agent genome list.</param> /// <param name="genomeList2">The maze genome list.</param> /// <returns>The instantiated coevolution algorithm container.</returns> public override ICoevolutionAlgorithmContainer<NeatGenome, MazeGenome> CreateCoevolutionAlgorithmContainer( IGenomeFactory<NeatGenome> genomeFactory1, IGenomeFactory<MazeGenome> genomeFactory2, List<NeatGenome> genomeList1, List<MazeGenome> genomeList2) { List<NeatGenome> seedAgentPopulation = new List<NeatGenome>(); // Compute the maze max complexity ((MazeGenomeFactory) genomeFactory2).MaxComplexity = MazeUtils.DetermineMaxPartitions(_mazeHeight, _mazeWidth, 200); // Create maze decoder to decode initialization mazes MazeDecoder mazeDecoder = new MazeDecoder(_mazeHeight, _mazeWidth, _mazeScaleMultiplier); // Loop through every maze and evolve the requisite number of viable genomes that solve it for (int idx = 0; idx < genomeList2.Count; idx++) { Console.WriteLine(@"Evolving viable agents for maze population index {0} and maze ID {1}", idx, genomeList2[idx].Id); // Evolve the number of agents required to meet the success MC for the current maze List<NeatGenome> viableMazeAgents = EvolveViableAgents(genomeFactory1, genomeList1.ToList(), mazeDecoder.Decode(genomeList2[idx])); // Add the viable agent genomes who solve the current maze (but avoid adding duplicates, as identified by the genome ID) // Note that it's fine to have multiple mazes solved by the same agent, so in this case, we'll leave the agent // in the pool of seed agent genomes foreach ( NeatGenome viableMazeAgent in viableMazeAgents.Where( viableMazeAgent => seedAgentPopulation.Select(sap => sap.Id).Contains(viableMazeAgent.Id) == false)) { seedAgentPopulation.Add(viableMazeAgent); } } // If we still lack the genomes to fill out agent specie count while still satisfying the maze MC, // iteratively pick a random maze and evolve agents on that maze until we reach the requisite number while (seedAgentPopulation.ToList().Count < _numAgentSuccessCriteria*AgentNumSpecies) { FastRandom rndMazePicker = new FastRandom(); // Pick a random maze on which to evolve agent(s) MazeGenome mazeGenome = genomeList2[rndMazePicker.Next(genomeList2.Count - 1)]; Console.WriteLine( @"Continuing viable agent evolution on maze {0}, with {1} of {2} required agents in place", mazeGenome.Id, seedAgentPopulation.Count, (_numAgentSuccessCriteria*AgentNumSpecies)); // Evolve the number of agents required to meet the success MC for the maze List<NeatGenome> viableMazeAgents = EvolveViableAgents(genomeFactory1, genomeList1.ToList(), mazeDecoder.Decode(mazeGenome)); // Iterate through each viable agent and remove them if they've already solved a maze or add them to the list // of viable agents if they have not foreach (NeatGenome viableMazeAgent in viableMazeAgents) { // If they agent has already solved maze and is in the list of viable agents, remove that agent // from the pool of seed genomes (this is done because here, we're interested in getting unique // agents and want to avoid an endless loop wherein the same viable agents are returned) if (seedAgentPopulation.Select(sap => sap.Id).Contains(viableMazeAgent.Id)) { genomeList1.Remove(viableMazeAgent); } // Otherwise, add that agent to the list of viable agents else { seedAgentPopulation.Add(viableMazeAgent); } } } // Set dummy fitness so that seed maze(s) will be marked as evaluated foreach (MazeGenome mazeGenome in genomeList2) { mazeGenome.EvaluationInfo.SetFitness(0); } // Reset primary NEAT genome parameters on agent genome factory ((NeatGenomeFactory) genomeFactory1).ResetNeatGenomeParameters(NeatGenomeParameters); // Create the NEAT (i.e. navigator) queueing evolution algorithm AbstractEvolutionAlgorithm<NeatGenome> neatEvolutionAlgorithm = new MultiQueueNeatEvolutionAlgorithm<NeatGenome>( new NeatEvolutionAlgorithmParameters { SpecieCount = AgentNumSpecies, MaxSpecieSize = AgentDefaultPopulationSize/AgentNumSpecies }, new ParallelKMeansClusteringStrategy<NeatGenome>(new ManhattanDistanceMetric(1.0, 0.0, 10.0), ParallelOptions), null, NavigatorBatchSize, RunPhase.Primary, _navigatorEvolutionDataLogger, _navigatorLogFieldEnableMap, _navigatorPopulationGenomesDataLogger, _populationLoggingBatchInterval); // Create the maze queueing evolution algorithm AbstractEvolutionAlgorithm<MazeGenome> mazeEvolutionAlgorithm = new MultiQueueNeatEvolutionAlgorithm<MazeGenome>( new NeatEvolutionAlgorithmParameters { SpecieCount = MazeNumSpecies, MaxSpecieSize = MazeDefaultPopulationSize/MazeNumSpecies }, new ParallelKMeansClusteringStrategy<MazeGenome>(new ManhattanDistanceMetric(1.0, 0.0, 10.0), ParallelOptions), null, MazeBatchSize, RunPhase.Primary, _mazeEvolutionDataLogger, _mazeLogFieldEnableMap, _mazePopulationGenomesDataLogger, _populationLoggingBatchInterval); // Create the maze phenome evaluator IPhenomeEvaluator<MazeStructure, BehaviorInfo> mazeEvaluator = new MazeEnvironmentMCSEvaluator( _maxTimesteps, _minSuccessDistance, BehaviorCharacterizationFactory, _numAgentSuccessCriteria, 0); // Create navigator phenome evaluator IPhenomeEvaluator<IBlackBox, BehaviorInfo> navigatorEvaluator = new MazeNavigatorMCSEvaluator( _maxTimesteps, _minSuccessDistance, BehaviorCharacterizationFactory, _numMazeSuccessCriteria); // Create maze genome decoder IGenomeDecoder<MazeGenome, MazeStructure> mazeGenomeDecoder = new MazeDecoder(_mazeHeight, _mazeWidth, _mazeScaleMultiplier); // Create navigator genome decoder IGenomeDecoder<NeatGenome, IBlackBox> navigatorGenomeDecoder = new NeatGenomeDecoder(ActivationScheme); // Create the maze genome evaluator IGenomeEvaluator<MazeGenome> mazeFitnessEvaluator = new ParallelGenomeBehaviorEvaluator<MazeGenome, MazeStructure>(mazeGenomeDecoder, mazeEvaluator, SelectionType.Queueing, SearchType.MinimalCriteriaSearch, ParallelOptions); // Create navigator genome evaluator IGenomeEvaluator<NeatGenome> navigatorFitnessEvaluator = new ParallelGenomeBehaviorEvaluator<NeatGenome, IBlackBox>(navigatorGenomeDecoder, navigatorEvaluator, SelectionType.Queueing, SearchType.MinimalCriteriaSearch, ParallelOptions); // Create the coevolution container ICoevolutionAlgorithmContainer<NeatGenome, MazeGenome> coevolutionAlgorithmContainer = new CoevolutionAlgorithmContainer<NeatGenome, MazeGenome>(neatEvolutionAlgorithm, mazeEvolutionAlgorithm); // Initialize the container and component algorithms coevolutionAlgorithmContainer.Initialize(navigatorFitnessEvaluator, genomeFactory1, seedAgentPopulation, AgentDefaultPopulationSize, mazeFitnessEvaluator, genomeFactory2, genomeList2, MazeDefaultPopulationSize, MaxGenerations, MaxEvaluations); return coevolutionAlgorithmContainer; }
internal SyncObject RegisterRequest(ref int RequestId) { lock (Requests) { SyncObject syncObj = new SyncObject(this); FastRandom rnd = new FastRandom(); do { RequestId = rnd.Next(); } while (Requests.ContainsKey(RequestId)); Requests.Add(RequestId, syncObj); return syncObj; } }
private void ShuffleValues(byte[] values, int Seed) { FastRandom rnd = new FastRandom(Seed); for (int i = values.Length, j = 0; i > 1; i--, j++) { int pos = rnd.Next(i); byte tmp = values[pos]; values[pos] = values[i - 1]; values[i - 1] = tmp; } }
/// <summary> /// Initializes a new instance of the <see cref="FreezingArcher.Game.MazeTest"/> class. /// </summary> /// <param name="messageProvider">The message provider for this instance.</param> /// <param name="objmnr">The object manager for this instance.</param> /// <param name="rendererContext">The renderer context for the maze scenes.</param> /// <param name="game">The game the maze should be generated in.</param> public MazeTest (MessageProvider messageProvider, ObjectManager objmnr, RendererContext rendererContext, Content.Game game, Application app, CompositorNodeScene sceneNode, CompositorImageOverlayNode healthOverlayNode, CompositorColorCorrectionNode colorCorrectionNode, CompositorNodeOutput outputNode, CompositorWarpingNode warpingNode) { ValidMessages = new[] { (int) MessageId.Input, (int) MessageId.Update, (int) MessageId.HealthChanged, (int) MessageId.CollisionDetected, (int) MessageId.StaminaChanged, (int) MessageId.ItemUse, (int) MessageId.FlashlightToggled }; messageProvider += this; mazeGenerator = new MazeGenerator (objmnr); MazeSceneNode = sceneNode; HealthOverlayNode = healthOverlayNode; ColorCorrectionNode = colorCorrectionNode; OutputNode = outputNode; WarpingNode = warpingNode; this.game = game; application = app; FPS_Text = new Gwen.ControlInternal.Text (app.RendererContext.Canvas); FPS_Text.String = "0 FPS"; FPS_Text.Font = new Gwen.Font (app.RendererContext.GwenRenderer); FPS_Text.SetPosition (5, 5); FPS_Text.Font.Size = 15; FPS_Text.Hide (); HealthOverlayNode.OverlayTexture = rendererContext.CreateTexture2D ("bloodsplatter", true, "Content/bloodsplatter.png"); HealthOverlayNode.Factor = 0; HealthOverlayNode.Blending = OverlayBlendMode.Multiply; warpingNode.WarpTexture = rendererContext.CreateTexture2D ("warp", true, "Content/warp.jpg"); game.SceneNode = MazeSceneNode; game.AddGameState ("maze_overworld", Content.Environment.Default, null); var state = game.GetGameState ("maze_overworld"); state.Scene = new CoreScene (rendererContext, messageProvider); state.Scene.SceneName = "MazeOverworld"; state.Scene.Active = false; state.Scene.BackgroundColor = Color4.Fuchsia; state.Scene.DistanceFogIntensity = 0.07f; state.Scene.AmbientColor = Color4.White; state.Scene.AmbientIntensity = 0.3f; state.Scene.MaxRenderingDistance = 1000.0f; state.AudioContext = new AudioContext (state.MessageProxy); state.MessageProxy.StartProcessing (); loadingScreen = new LoadingScreen (application, messageProvider, "Content/loading.png", "MazeLoadingScreen", new[] { new Tuple<string, GameStateTransition> ("main_menu", GameStateTransition.DefaultTransition) }, new[] { new Tuple<string, GameStateTransition> (state.Name, new GameStateTransition (0)) }); endScreen = new EndScreen (application, rendererContext, new Tuple<string, GameStateTransition>[] { new Tuple<string, GameStateTransition> ("maze_overworld", GameStateTransition.DefaultTransition), new Tuple<string, GameStateTransition> ("maze_underworld", GameStateTransition.DefaultTransition) }); game.SwitchToGameState ("MazeLoadingScreen"); Player = EntityFactory.Instance.CreateWith ("player", state.MessageProxy, new[] { typeof(HealthComponent), typeof(StaminaComponent) }, new[] { typeof(MovementSystem), typeof(KeyboardControllerSystem), typeof(MouseControllerSystem), typeof(SkyboxSystem), typeof(PhysicsSystem) }); inventoryGui = new InventoryGUI (app, state, Player, messageProvider, warpingNode); var inventory = new Inventory (messageProvider, state, Player, new Vector2i (5, 7), 9); inventoryGui.Init (rendererContext.Canvas, inventory); PauseMenu = new PauseMenu (application, ColorCorrectionNode, rendererContext.Canvas, () => maze [currentMaze].AIManager.StartThinking (), () => maze [currentMaze].AIManager.StopThinking ()); AddAudio (state); // embed new maze into game state logic and create a MoveEntityToScene SkyboxSystem.CreateSkybox (state.Scene, Player); Player.GetComponent<TransformComponent> ().Position = new Vector3 (0, 1.85f, 0); var maze_cam_entity = EntityFactory.Instance.CreateWith ("maze_cam_transform", state.MessageProxy, new[] { typeof(TransformComponent) }); var maze_cam_transform = maze_cam_entity.GetComponent<TransformComponent> (); var maze_cam = new BaseCamera (maze_cam_entity, state.MessageProxy, orthographic: true); state.Scene.CameraManager.AddCamera (maze_cam, "maze"); maze_cam_transform.Position = new Vector3 (115, 240, 110); maze_cam_transform.Rotation = Quaternion.FromAxisAngle (Vector3.UnitX, MathHelper.PiOver2); state.Scene.CameraManager.AddCamera (new BaseCamera (Player, state.MessageProxy), "player"); RigidBody playerBody = new RigidBody (new SphereShape (1f)); playerBody.Position = Player.GetComponent<TransformComponent> ().Position.ToJitterVector (); playerBody.AllowDeactivation = false; playerBody.Material.StaticFriction = 0f; playerBody.Material.KineticFriction = 0f; playerBody.Material.Restitution = 0.1f; //playerBody.Mass = 1000000.0f; playerBody.Update (); Player.GetComponent<PhysicsComponent> ().RigidBody = playerBody; Player.GetComponent<PhysicsComponent> ().World = state.PhysicsManager.World; Player.GetComponent<PhysicsComponent> ().PhysicsApplying = AffectedByPhysics.Position; #if PRESENTATION Player.GetComponent<HealthComponent>().MaximumHealth = 500; Player.GetComponent<HealthComponent>().Health = 500; #endif state.PhysicsManager.World.AddBody (playerBody); int seed = new FastRandom ().Next (); var rand = new FastRandom (seed); Logger.Log.AddLogEntry (LogLevel.Debug, "MazeTest", "Seed: {0}", seed); #if PRESENTATION maze [0] = mazeGenerator.CreateMaze<OverworldMazeTheme> (rand.Next (), state.MessageProxy, state.PhysicsManager, app.AudioManager, 10, 10); #else maze [0] = mazeGenerator.CreateMaze<OverworldMazeTheme> (rand.Next (), state.MessageProxy, state.PhysicsManager, app.AudioManager, 30, 30); #endif maze [0].PlayerPosition += Player.GetComponent<TransformComponent> ().Position; maze [0].AIManager.RegisterEntity (Player); for (int i = 0; i < OverworldScobisCount; i++) { ScobisInstances.Add (new Scobis (state, maze [0].AIManager, rendererContext)); } for (int i = 0; i < OverworldCaligoCount; i++) { CaligoInstances.Add (new Caligo (state, maze [0].AIManager, rendererContext, warpingNode)); } for (int i = 0; i < OverworldViridionCount; i++) { ViridionInstances.Add (new Viridion (state, maze [0].AIManager, rendererContext, ColorCorrectionNode)); } for (int i = 0; i < OverworldGhostCount; i++) { GhostInstances.Add (new Ghost (state, maze [0].AIManager, rendererContext, ColorCorrectionNode)); } game.AddGameState ("maze_underworld", Content.Environment.Default, new[] { new Tuple<string, GameStateTransition> ("maze_overworld", new GameStateTransition (0)) }, new[] { new Tuple<string, GameStateTransition> ("maze_overworld", new GameStateTransition (0)), new Tuple<string, GameStateTransition> ("endscreen_state", new GameStateTransition (0)) }); state = game.GetGameState ("maze_underworld"); state.Scene = new CoreScene (rendererContext, messageProvider); state.Scene.SceneName = "MazeUnderworld"; state.Scene.Active = false; state.Scene.BackgroundColor = Color4.AliceBlue; state.Scene.DistanceFogIntensity = 0.07f; state.Scene.AmbientColor = Color4.White; state.Scene.AmbientIntensity = 0.3f; state.Scene.MaxRenderingDistance = 1000.0f; state.AudioContext = new AudioContext (state.MessageProxy); AddAudio (state); state.Scene.CameraManager.AddCamera (new BaseCamera (Player, state.MessageProxy), "player"); #if PRESENTATION maze [1] = mazeGenerator.CreateMaze<UnderworldMazeTheme> (rand.Next (), state.MessageProxy, state.PhysicsManager, app.AudioManager, 10, 10); #else maze [1] = mazeGenerator.CreateMaze<UnderworldMazeTheme> (rand.Next (), state.MessageProxy, state.PhysicsManager, app.AudioManager, 30, 30); #endif maze [1].PlayerPosition += Player.GetComponent<TransformComponent> ().Position; maze [1].AIManager.RegisterEntity (Player); Func<int, int, bool> containsPortalFunc = (x, y) => { foreach (var m in maze) { var cell = m.entities [x, y].GetComponent<PhysicsComponent> ().RigidBody.Tag as MazeCell; if (cell != null && cell.IsPortal) { return true; } } return false; }; mazeWallMover = new MazeWallMover (maze [0], maze [1], game.GetGameState ("maze_overworld"), containsPortalFunc); state.MessageProxy.StopProcessing (); //game.SwitchToGameState("maze_overworld"); for (int i = 0; i < UnderworldCaligoCount; i++) { CaligoInstances.Add (new Caligo (state, maze [1].AIManager, rendererContext, warpingNode)); } for (int i = 0; i < UnderworldPassusCount; i++) { PassusInstances.Add (new Passus (ColorCorrectionNode, state, maze [1].AIManager, rendererContext)); } for (int i = 0; i < UnderworldRoachesCount; i++) { RoachesInstances.Add(new Roaches (state, maze [0].AIManager, rendererContext)); } for (int i = 0; i < UnderworldFenFireCount; i++) { FenFireInstances.Add (new FenFire (state, maze [1].AIManager, rendererContext)); } }
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; } }
private void PreviewSplatFilm(IFilmFrame frame, int curY = -1, int pixelsInPreview = 10000) { var bmpWidth = frame.Width; var bmpHeight = (curY > 0 ? curY : frame.Height); var rnd = new FastRandom(); RgbSpectrum.Gamma = true; for (int n = 0; n < pixelsInPreview; n++) //for (int i = 0; i < bmpHeight; i++) { //for (int j = 0; j < bmpWidth; j++) { var i = rnd.Next(0, bmpHeight); var j = rnd.Next(0, bmpWidth); var pixOffset = frame.Width * ((bmpHeight - i - 1)) + j; var color = ((frame.Data[pixOffset] / frame.Weight[pixOffset])).Transform(); this.imagePlane.Data[pixOffset] = color; } } }