public void Equals_GetHashCode_Contract() { var rnd = new System.Random(); var offset = rnd.NextDouble() * 60; if (rnd.NextDouble() < 0.5) { offset *= -1; } var leftLine = new List<LineString>(); leftLine.Add(GetLineString(offset + 1)); leftLine.Add(GetLineString(offset + 2)); var left = new MultiLineString(leftLine); var rightLine = new List<LineString>(); rightLine.Add(GetLineString(offset + 1)); rightLine.Add(GetLineString(offset + 2)); var right = new MultiLineString(rightLine); Assert.AreEqual(left, right); Assert.AreEqual(right, left); Assert.IsTrue(left.Equals(right)); Assert.IsTrue(left.Equals(left)); Assert.IsTrue(right.Equals(left)); Assert.IsTrue(right.Equals(right)); Assert.IsTrue(left == right); Assert.IsTrue(right == left); Assert.AreEqual(left.GetHashCode(), right.GetHashCode()); }
public override void Przetwarzaj(IMapa mapa) { _rand = new Random(_parametryPerlina.Ziarno); var przesuniecieX = (float)_rand.NextDouble() * 4096f; var przesuniecieZ = (float)_rand.NextDouble() * 4096f; float wspolczynnik = 1f; for (int warstwa = 2; warstwa <= _parametryPerlina.IloscWarstw; ++warstwa) { wspolczynnik += Mathf.Pow(_parametryPerlina.ZachowanieSkali, warstwa); } float znormalizowanaSkalaPoczatkowa = _parametryPerlina.Skala/wspolczynnik; foreach (IPunkt punkt in mapa.Punkty) { float wysokosc = 0; for (int warstwa = 0; warstwa < _parametryPerlina.IloscWarstw; ++warstwa) { float gestosc = _parametryPerlina.Gestosc * Mathf.Pow(_parametryPerlina.SkokGestosci, warstwa); // rosnie float skala = znormalizowanaSkalaPoczatkowa * Mathf.Pow(_parametryPerlina.ZachowanieSkali, warstwa); // maleje wysokosc += Mathf.PerlinNoise((punkt.Pozycja.x + przesuniecieX) * gestosc, (punkt.Pozycja.z + przesuniecieZ) * gestosc) *skala; } punkt.Wysokosc = wysokosc; } }
public void Equals_GetHashCode_Contract() { var rnd = new System.Random(); var offset = rnd.NextDouble() * 60; if (rnd.NextDouble() < 0.5) { offset *= -1; } var left = new MultiPoint(GetPoints(offset)); var right = new MultiPoint(GetPoints(offset)); Assert.AreEqual(left, right); Assert.AreEqual(right, left); Assert.IsTrue(left.Equals(right)); Assert.IsTrue(left.Equals(left)); Assert.IsTrue(right.Equals(left)); Assert.IsTrue(right.Equals(right)); Assert.IsTrue(left == right); Assert.IsTrue(right == left); Assert.AreEqual(left.GetHashCode(), right.GetHashCode()); }
public static void BuildSurfaceMesh(ref MeshPlane mesh, ref Random rand) { var brush = Resources.Load("PlanetBuilding/SurfaceBrush"); if (brush == null) { Debug.LogError("Unable to load basic brush prefab"); return; } var rampTex = Resources.Load("Textures/PlanetRamp") as Texture; if (rampTex == null) { Debug.LogError("Unable to load planet colour ramp"); return; } // Apply brush texture somehow // * 0.1f float brushBaseSize = 1.0f; float brushSizeLarge = brushBaseSize * 0.2f; float brushSizeSmall = brushBaseSize * 0.02f; for (int i = 0; i < rand.Next(25, 75); ++i) { var go = (GameObject.Instantiate(brush) as GameObject); var ch = go.transform.GetChild(0); var brushScale = (float)(brushSizeSmall + (rand.NextDouble() * brushSizeLarge)); ch.localScale = new Vector3(brushScale, brushScale, brushScale); go.transform.SetParent(mesh.transform); go.transform.Rotate( (float)rand.NextDouble() * 360.0f, (float)rand.NextDouble() * 360.0f, (float)rand.NextDouble() * 360.0f ); } var localCam = mesh.gameObject.AddComponent<Camera>(); localCam.cullingMask = PlanetBrushLayer; localCam.fieldOfView = 90; localCam.backgroundColor = Color.black; Cubemap c = new Cubemap(2048, TextureFormat.ARGB32, false); localCam.RenderToCubemap(c); mesh.GetComponent<Renderer>().material.SetTexture("_Tex", c); mesh.GetComponent<Renderer>().material.SetTexture("_PlanetRamp", rampTex); Component.Destroy(localCam); foreach ( Transform ch in mesh.transform ){ GameObject.Destroy(ch.gameObject); } }
public Model Generate() { int count = 1000; Vector3[] v = new Vector3[count]; Vector3[] r = new Vector3[count]; Random random = new Random(); Color[] color = new Color[count]; float[] m = new float[count]; v[0] = new Vector3(0, 0, 0); r[0] = new Vector3(0, 0, 0); m[0] = 1000000000; color[0] = Color.white; for (int i = 1; i < count; i++) { v[i] = new Vector3((float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1), (float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1), (float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1)); r[i] = new Vector3((float)random.NextDouble() * 100, (float)random.NextDouble() * 100, (float)random.NextDouble() * 100); m[i] = random.Next(10000, 100000); color[i] = Color.yellow; } Model model = new Model(r, v, m, color); model.G = 0.00001f; model.dt = 0.005f; return model; }
public void CalculateMeanAndVarianceTest() { System.Random random = new System.Random(31415); int n = testData.GetLength(0); int cols = testData.GetLength(1); { for (int col = 0; col < cols; col++) { double scale = random.NextDouble(); IEnumerable<double> x = from rows in Enumerable.Range(0, n) select testData[rows, col] * scale; double[] xs = x.ToArray(); double mean_alglib, variance_alglib; mean_alglib = variance_alglib = 0.0; double tmp = 0; alglib.samplemoments(xs, n, out mean_alglib, out variance_alglib, out tmp, out tmp); var calculator = new OnlineMeanAndVarianceCalculator(); for (int i = 0; i < n; i++) { calculator.Add(xs[i]); } double mean = calculator.Mean; double variance = calculator.Variance; Assert.IsTrue(mean_alglib.IsAlmost(mean)); Assert.IsTrue(variance_alglib.IsAlmost(variance)); } } }
public PlanetNoisePerlin( int seed ) { System.Random rnd = new System.Random( seed ); grad = new Vector3[ 12 ]; grad[ 0 ] = new Vector3( 1, 1, 0 ); grad[ 1 ] = new Vector3( -1, 1, 0 ); grad[ 2 ] = new Vector3( 1, -1, 0 ); grad[ 3 ] = new Vector3( -1, -1, 0 ); grad[ 4 ] = new Vector3( 1, 0, 1 ); grad[ 5 ] = new Vector3( -1, 0, 1 ); grad[ 6 ] = new Vector3( 1, 0, -1 ); grad[ 7 ] = new Vector3( -1, 0, -1 ); grad[ 8 ] = new Vector3( 0, 1, 1 ); grad[ 9 ] = new Vector3( 0, -1, 1 ); grad[ 10 ] = new Vector3( 0, 1, -1 ); grad[ 11 ] = new Vector3( 0, -1, -1 ); perm = new uint[ permStride ]; for( int i = 0; i < permStride / 2; ++i ) perm[ i ] = ( uint ) Mathf.FloorToInt( ( float ) rnd.NextDouble() * ( permStride / 2 ) ); for( int i = permStride / 2; i < permStride; ++i ) perm[ i ] = perm[ i & ( permStride / 2 - 1 ) ]; }
void SpawnBalls() { //clean trailrenderers StartCoroutine(greenBall.TrailRenderDestroy()); StartCoroutine(yellowBall.TrailRenderDestroy()); //randomize balls & set directions System.Random rand = new System.Random(); bool randomBool = rand.NextDouble() >= 0.5; if(previousBool==randomBool){ //prevent randomizing the same value too many times consecutiveBools++; } else { consecutiveBools = 0; } if(randomBool && consecutiveBools < 3){ greenBall.transform.position = topSpawn.transform.position; greenBall.isGoingUp = false; yellowBall.transform.position = bottomSpawn.transform.position; yellowBall.isGoingUp = true; } else { greenBall.transform.position = bottomSpawn.transform.position; greenBall.isGoingUp = true; yellowBall.transform.position = topSpawn.transform.position; yellowBall.isGoingUp = false; } previousBool = randomBool; }
public static float[,] getCellNoise(int height, int width,int seed,int featurePointCount) { noisePrng = new System.Random(seed); float[,] noise = new float[height,width]; Vector2[] featurePoints = new Vector2[featurePointCount]; for(int i =0; i < featurePointCount;i++) { featurePoints[i] = new Vector2((float)noisePrng.NextDouble(),(float)noisePrng.NextDouble()); } for(int y =0; y < height; y++) { for(int x =0; x < height; x++) { noise[x,y] = setCell(featurePoints,x,y,height,width); } } return noise; }
public RandomNumGen(int seed) { Rand = new System.Random(seed); rand_num_ = new List<double>(Environment.mazeSize_ * Environment.mazeSize_ * Evaluator.LIFE_TIME); for (int i=0; i<rand_num_.Capacity; i++) { rand_num_.Add(Rand.NextDouble()); } index_ = 0; }
private static float[,] GenerateNoise(int Seed, int Width, int Height) { float[,] Noise = new float[Width, Height]; System.Random RandomGenerator = new System.Random(Seed); for (int x = 0; x < Width; ++x) { for (int y = 0; y < Height; ++y) { Noise[x, y] = ((float)(RandomGenerator.NextDouble()) - 0.5f) * 2.0f; } } return Noise; }
/// <summary> /// Selects a random, non-red color based on the hashcode of a string /// </summary> /// <param name="stringValue">A string to be used as a seed for the random color</param> /// <returns>A random color based on the input string</returns> public static Color CreateColorFromStringHash(string stringValue) { var color = Color.Yellow; if (!string.IsNullOrEmpty(stringValue)) { // Build random vector representing rgb color based on username var randSeed = stringValue.GetHashCode(); var rand = new System.Random(randSeed); var colorVector = new Vector3D((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()); // Keep the color (vector) from being too close to red (x) so it doesn't conflict with the selection color if (colorVector.Y > colorVector.Z) { if (colorVector.X > colorVector.Y) colorVector = new Vector3D(colorVector.Z, colorVector.Y, colorVector.Z); } else if (colorVector.Z > colorVector.Y) { if (colorVector.X > colorVector.Z) colorVector = new Vector3D(colorVector.Y, colorVector.Y, colorVector.Z); } // Make sure color isn't too dark if (colorVector.Magnitude < 1f) colorVector *= (1f / colorVector.Magnitude); // Make sure color components stay within bounds if (colorVector.X > 1) colorVector = new Vector3D(1f, colorVector.Y, colorVector.Z); if (colorVector.Y > 1) colorVector = new Vector3D(colorVector.X, 1f, colorVector.Z); if (colorVector.Z > 1) colorVector = new Vector3D(colorVector.X, colorVector.Y, 1f); color = Color.FromArgb(255, (int)(colorVector.X * 255), (int)(colorVector.Y * 255), (int)(colorVector.Z * 255)); } return color; }
/// <summary> /// 返回一个介于 0.0 和 1.0 之间的随机数。 /// </summary> /// <returns>大于等于 0.0 并且小于 1.0 的双精度浮点数。</returns> public static double GetRandomDouble() { return(s_Random.NextDouble()); }
public bool IsSuccessfulShot() => _random.NextDouble() < _accuracy;
public override double GetValue(double x, double y, double z) { Random rng = new Random(Seed ^ Mathf.RoundToInt((float)x) * Mathf.RoundToInt((float)y) ^ Mathf.RoundToInt((float)z)); return rng.NextDouble(); }
public double NextDouble() { return(random.NextDouble()); }
public static double GetRandom() { return(2 * Random.NextDouble() - 1); }
/// <summary> /// Generates a random value of the specified type /// </summary> /// <param name="Rand">Random number generator that it can use</param> /// <returns>A randomly generated object of the specified type</returns> public T Next(System.Random Rand) { return(Rand.NextDouble().To(default(T))); }
Rhino.Display.DisplayBitmapDrawList GetItems() { if (m_items == null) { m_items = new Rhino.Display.DisplayBitmapDrawList(); var points = new System.Collections.Generic.List<Point3d>(); var colors = new System.Collections.Generic.List<System.Drawing.Color>(); var random = new System.Random(); for (int i = 0; i < 200; i++) { double x = random.NextDouble(); double y = random.NextDouble(); double z = random.NextDouble(); points.Add(new Point3d(-30 + x * 60, -30 + y * 60, -30 + z * 60)); int r = (int)(x * 255); int g = (int)(y * 255); int b = (int)(z * 255); colors.Add(System.Drawing.Color.FromArgb(r, g, b)); } m_items.SetPoints(points, colors); } return m_items; }
/// <summary> /// Returns a random, single channel (luminance only) 16x16 blue noise texture. /// </summary> /// <returns>A single channel (luminance only) 16x16 blue noise texture.</returns> public Texture2D GetRandom16L() { return(textures16L[(int)(m_Random.NextDouble() * (textures16L.Length - 1))]); }
/// <summary> /// Selects random item based on their weights. /// Uses linear search for random selection. /// </summary> /// <param name="randomValue">Random value from your uniform generator</param> /// <returns>Returns item</returns> public T SelectRandomItem() { float randomValue = (float)random.NextDouble(); return(items[CDA.SelectIndexLinearSearch(randomValue)]); }
private Texture2D generateFirePillar(int width, int height, int interpolatePx, bool mirrored) { Texture2D fp = new Texture2D(width, height); double[] horzIntensity150 = new double[height]; double[] horzOpacity150 = new double[height]; // RNG phase for (int i = 0; i < height; i++) { if (i % interpolatePx != 0) { continue; } horzIntensity150[i] = rng.NextDouble(); horzOpacity150[i] = rng.NextDouble(); // because c# sucks NextDouble can't return arbitrary numbers // so apply a transformation to map verticalIntensity150 -> 0-0.2 // and verticalOpacity150 -> -1 - 0 horzOpacity150[i] = horzOpacity150[i] * 0.2 - 0.2; horzIntensity150[i] = (horzIntensity150[i] * 0.2); } // Interpolation phase for (int i = 0; i < height - interpolatePx; i++) { if (i % interpolatePx == 0) { continue; } int offset = i % interpolatePx; double avgWeighting = (double)offset / (double)interpolatePx; horzIntensity150[i] = horzIntensity150[i - offset + interpolatePx] * avgWeighting + horzIntensity150[i - offset] * (1.0 - avgWeighting); horzOpacity150[i] = horzOpacity150[i - offset + interpolatePx] * avgWeighting + horzOpacity150[i - offset] * (1.0 - avgWeighting); } // Interpolation phase pt 2 (for wrap around) for (int i = height - interpolatePx; i < height; i++) { if (i % interpolatePx == 0) { continue; } int offset = i % interpolatePx; double avgWeighting = (double)offset / (double)interpolatePx; horzIntensity150[i] = horzIntensity150[0] * avgWeighting + horzIntensity150[i - offset] * (1.0 - avgWeighting); horzOpacity150[i] = horzOpacity150[0] * avgWeighting + horzOpacity150[i - offset] * (1.0 - avgWeighting); } // Actually set the colors for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (!mirrored) { fp.SetPixel(x, y, getFireColor ((x), horzIntensity150[y], horzOpacity150[y], width, width * 5, 2.4, 9.0)); } else { fp.SetPixel(x, y, getFireColor ((width - x), horzIntensity150[y], horzOpacity150[y], width, width * 5, 2.4, 9.0)); } } } return(fp); }
public double NextDouble() { return(_rand.NextDouble()); }
/** Returns randomly selected points on the specified nodes with each point being separated by \a clearanceRadius from each other. * Selecting points ON the nodes only works for TriangleMeshNode (used by Recast Graph and Navmesh Graph) and GridNode (used by GridGraph). * For other node types, only the positions of the nodes will be used. * * clearanceRadius will be reduced if no valid points can be found. */ public static List <Vector3> GetPointsOnNodes(List <GraphNode> nodes, int count, float clearanceRadius = 0) { if (nodes == null) { throw new System.ArgumentNullException("nodes"); } if (nodes.Count == 0) { throw new System.ArgumentException("no nodes passed"); } var rnd = new System.Random(); List <Vector3> pts = ListPool <Vector3> .Claim(count); // Square clearanceRadius *= clearanceRadius; if (nodes[0] is TriangleMeshNode || nodes[0] is GridNode ) { //Assume all nodes are triangle nodes or grid nodes List <float> accs = ListPool <float> .Claim(nodes.Count); float tot = 0; for (int i = 0; i < nodes.Count; i++) { var tnode = nodes[i] as TriangleMeshNode; if (tnode != null) { /** \bug Doesn't this need to be divided by 2? */ float a = System.Math.Abs(VectorMath.SignedTriangleAreaTimes2XZ(tnode.GetVertex(0), tnode.GetVertex(1), tnode.GetVertex(2))); tot += a; accs.Add(tot); } else { var gnode = nodes[i] as GridNode; if (gnode != null) { GridGraph gg = GridNode.GetGridGraph(gnode.GraphIndex); float a = gg.nodeSize * gg.nodeSize; tot += a; accs.Add(tot); } else { accs.Add(tot); } } } for (int i = 0; i < count; i++) { //Pick point int testCount = 0; int testLimit = 10; bool worked = false; while (!worked) { worked = true; //If no valid points can be found, progressively lower the clearance radius until such a point is found if (testCount >= testLimit) { clearanceRadius *= 0.8f; testLimit += 10; if (testLimit > 100) { clearanceRadius = 0; } } float tg = (float)rnd.NextDouble() * tot; int v = accs.BinarySearch(tg); if (v < 0) { v = ~v; } if (v >= nodes.Count) { // This shouldn't happen, due to NextDouble being smaller than 1... but I don't trust floating point arithmetic. worked = false; continue; } var node = nodes[v] as TriangleMeshNode; Vector3 p; if (node != null) { // Find a random point inside the triangle float v1; float v2; do { v1 = (float)rnd.NextDouble(); v2 = (float)rnd.NextDouble(); } while (v1 + v2 > 1); p = ((Vector3)(node.GetVertex(1) - node.GetVertex(0))) * v1 + ((Vector3)(node.GetVertex(2) - node.GetVertex(0))) * v2 + (Vector3)node.GetVertex(0); } else { var gnode = nodes[v] as GridNode; if (gnode != null) { GridGraph gg = GridNode.GetGridGraph(gnode.GraphIndex); float v1 = (float)rnd.NextDouble(); float v2 = (float)rnd.NextDouble(); p = (Vector3)gnode.position + new Vector3(v1 - 0.5f, 0, v2 - 0.5f) * gg.nodeSize; } else { //Point nodes have no area, so we break directly instead pts.Add((Vector3)nodes[v].position); break; } } // Test if it is some distance away from the other points if (clearanceRadius > 0) { for (int j = 0; j < pts.Count; j++) { if ((pts[j] - p).sqrMagnitude < clearanceRadius) { worked = false; break; } } } if (worked) { pts.Add(p); break; } testCount++; } } ListPool <float> .Release(accs); } else { for (int i = 0; i < count; i++) { pts.Add((Vector3)nodes[rnd.Next(nodes.Count)].position); } } return(pts); }
public bool Roll(System.Random random, float percent) { return(random.NextDouble() < percent ? true : false); }
/// <summary> /// 返回与x矩阵同名的随机方阵 /// </summary> /// <param name="s">行列数</param> /// <param name="n">命名阵</param> /// <returns>返回生成的矩阵</returns> public static Matrix Random(int s, MNode[,] n) { long tick = System.DateTime.Now.Ticks; //Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32)); System.Random rand = new System.Random((int)(tick & 0xffffffffL) | (int)(tick >> 32)); ArrayList f = new ArrayList(); //for(int i = 0; i < s * s; f.Add(2 * rand.NextDouble() - 1), i++); for (int i = 0; i < s * s; f.Add(rand.NextDouble()), i++) ; //for (int i = 0; i < s * s; System.Console.Write(f[i]+" "), i++); //System.Console.WriteLine(); return Matrix.GenerateMatrix(s, f, n); }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // load texture and create grid filledRect = Content.Load <Texture2D>("test/fillrect"); tilesTexture = Content.Load <Texture2D>("test/floortileset"); skeletonTexture = Content.Load <Texture2D>("test/skeleton"); boneTexture = Content.Load <Texture2D>("test/bone"); treeTexture = Content.Load <Texture2D>("test/tree"); font = Content.Load <SpriteFont>("test/deffont"); staticGrid = new StaticBatch(GraphicsDevice, new Point(512, 512)); // create list of sprites to render in the test scene _sprites = new List <StaticBatch.StaticSprite>(); // some consts int tileSize = 32; Vector2 tileSizeVec = new Vector2(tileSize); Point tileSizePoint = new Point(tileSize, tileSize); // for random System.Random rand = new System.Random(15); // add tiles for (int i = 0; i < LevelSize / tileSize; ++i) { for (int j = 0; j < LevelSize / tileSize; ++j) { Point srcIndex = new Point(rand.Next(5), rand.Next(2)); _sprites.Add(new StaticBatch.StaticSprite(tilesTexture, new Rectangle(tileSizePoint * new Point(i, j), tileSizePoint), new Rectangle(tileSizePoint * srcIndex, tileSizePoint), zindex: 0f)); } } // add random bones for (int i = 0; i < LevelSize * 3; ++i) { var posx = rand.Next(LevelSize); var posy = rand.Next(LevelSize); _sprites.Add(new StaticBatch.StaticSprite(boneTexture, new Rectangle(posx, posy, 16, 16), rotation: (float)rand.NextDouble() * MathHelper.TwoPi, zindex: 0.000001f + (posx + posy) / 100000f)); } // add random skeletons for (int i = 0; i < LevelSize * 3; ++i) { var posx = rand.Next(LevelSize); var posy = rand.Next(LevelSize); _sprites.Add(new StaticBatch.StaticSprite(skeletonTexture, new Rectangle(posx, posy, 32, 32), zindex: (float)(posy + 32) / (float)(LevelSize) + posx / 1000000f, color: rand.Next(5) < 1 ? Color.Red : Color.White)); } // add random trees for (int i = 0; i < LevelSize * 3; ++i) { var posx = rand.Next(LevelSize); var posy = rand.Next(LevelSize); _sprites.Add(new StaticBatch.StaticSprite(treeTexture, new Rectangle(posx, posy, 32, 64), zindex: (float)(posy + 60) / (float)(LevelSize) + posx / 1000000f)); } // total number of sprites spritesCountStr = _sprites.Count.ToString(); // build static grid staticGrid.AddSprites(_sprites); staticGrid.Build(spriteBatch); }
public static float RandomValue() { return((float)Random.NextDouble()); }
/// <summary> /// Generates a random bool, true with the given probability. /// </summary> /// <param name="probability"></param> /// <returns></returns> public static bool Bool(float probability) { return(GlobalRandom.NextDouble() < probability); }
// time both searches (linear and binary (log)), and find optimal breakpoint - where to use which for maximal performance int FindOptimalBreakpointArray() { int optimalBreakpoint = 2; var random = new System.Random(); Stopwatch stopwatchLinear = new Stopwatch(); Stopwatch stopwatchBinary = new Stopwatch(); float lin = 0f; float log = 1f; // continue increasing "optimalBreakpoint" until linear becomes slower than log // result is around 15-16, varies a bit due to random nature of test while (lin <= log) { int numOfDiffArrays = 100; int numOfTestPerArr = 10000; // u = uniform grid, r = uniform random float u, r; ///Linear Search stopwatchLinear.Stop(); stopwatchLinear.Reset(); float[] items = RandomMath.IdentityArray(optimalBreakpoint); float selectedItem; //here just to simulate selecting from array float[] arr = new float[optimalBreakpoint]; for (int k = 0; k < numOfDiffArrays; k++) { RandomMath.RandomWeightsArray(ref arr, random); RandomMath.BuildCumulativeDistribution(arr); stopwatchLinear.Start(); for (int i = 0; i < numOfTestPerArr; i++) { u = i / (numOfTestPerArr - 1f); selectedItem = items[arr.SelectIndexLinearSearch(u)]; r = (float)random.NextDouble(); selectedItem = items[arr.SelectIndexLinearSearch(r)]; } stopwatchLinear.Stop(); } lin = stopwatchLinear.ElapsedMilliseconds; /// Binary Search stopwatchBinary.Stop(); stopwatchBinary.Reset(); for (int k = 0; k < numOfDiffArrays; k++) { RandomMath.RandomWeightsArray(ref arr, random); RandomMath.BuildCumulativeDistribution(arr); stopwatchBinary.Start(); for (int i = 0; i < numOfTestPerArr; i++) { u = i / (numOfTestPerArr - 1f); selectedItem = items[arr.SelectIndexBinarySearch(u)]; r = (float)random.NextDouble(); selectedItem = items[arr.SelectIndexBinarySearch(r)]; } stopwatchBinary.Stop(); } log = stopwatchBinary.ElapsedMilliseconds; optimalBreakpoint++; } return(optimalBreakpoint); }
/// <summary> /// </summary> public static void Main(string[] args) { int i = 0; int n = 10000; bool strong = false; bool evensplit = false; bool pseudorandom = false; if (args.Length>0) { n = System.Convert.ToInt32(args[0]); } if (args.Length>1) { if ("--strong" == args[1]) { strong = true; } else if ("--evensplit" == args[1]) { evensplit = true; } else if ("--pseudorandom" == args[1]) { pseudorandom = true; } } Kitware.mummy.Runtime.MRSmokeTest test = new Kitware.mummy.Runtime.MRSmokeTest(strong); Kitware.mummy.Runtime.MRSmokeTest testClone = test.Clone(); Kitware.mummy.Runtime.Methods.Trace("looping..."); for (i= 0; i<args.Length; ++i) { Kitware.mummy.Runtime.Methods.Trace(System.String.Format("arg{0}: {1}", i, args[i])); } System.Random r = new System.Random(); for (i= 0; i<n; ++i) { if (evensplit) { strong = !strong; } else if (pseudorandom) { strong = (r.NextDouble() > 0.5 ? true : false); } test = new Kitware.mummy.Runtime.MRSmokeTest(strong); } if (null == testClone) { throw new System.Exception("error: testClone is null!"); } test = null; testClone = null; uint teCount = Kitware.mummy.Runtime.Methods.GetTypeEntryCount(); Kitware.mummy.Runtime.Methods.Trace(System.String.Format("teCount: {0}", teCount)); Kitware.mummy.Runtime.Methods.Trace("about to call System.GC.Collect()..."); System.GC.Collect(); Kitware.mummy.Runtime.Methods.Trace("done with System.GC.Collect()..."); }
///<summary> ///Gets a random float from a given set of floats ///</summary> public static float GetRandomFloat(float min, float max) { return(((float)rand.NextDouble() * (max - min)) + min); }
/// <summary> /// Gets a random value between the specified min (inclusive) and max (exclusive). /// </summary> public static float Get(float min, float max) { return((float)(random.NextDouble() * (max - min) + min)); }
/// <summary> /// Called every const X seconds. /// </summary> protected override void OnFixedUpdate() { // get time factor float timeFactor = Managers.TimeManager.FixedTimeFactor * SpawningSpeedFactor; // increase time alive _timeAlive += timeFactor; // check if expired if (TimeToLive != 0f && _timeAlive > TimeToLive) { // destroy parent if needed (note: if destroying parent we don't need to destroy self as well) if (DestroyParentWhenExpired && !_GameObject.WasDestroyed) { _GameObject.Destroy(); return; } // destroy self Destroy(); return; } // check if there's intervals to wait if (_timeForNextInterval > 0f) { _timeForNextInterval -= timeFactor; return; } _timeForNextInterval = Interval; // iterate over particle types and emit them foreach (var particleType in _particles) { // get current spawn frequency float frequency = particleType.GetFrequency(_timeAlive); // negative? skip if (frequency <= 0f) { continue; } // check if should spawn particles if (frequency >= (float)_random.NextDouble()) { // rand quantity to spawn uint toSpawn = (uint)_random.Next((int)particleType.MinParticlesPerSpawn, (int)particleType.MaxParticlesPerSpawn); // spawn particles for (int i = 0; i < toSpawn; ++i) { // create new particle and add to self game object GameObject newPart = particleType.ParticlePrototype.Clone(); newPart.Parent = _GameObject; // if need to add particles to root if (AddParticlesToRoot) { Vector3 position = newPart.SceneNode.WorldPosition; newPart.Parent = Managers.ActiveScene.Root; newPart.SceneNode.Position = position; } } } } }
/// <summary> /// Returns a random number in the range {min, max}. /// </summary> /// <param name="min">Minimum value</param> /// <param name="max">Maximum value</param> /// <returns>Returns the random number</returns> public static float RandomInRange(float min, float max) { // + 1 to include the max value also in the posible values return((float)(m_Random.NextDouble() % (max + 1 - min) + min)); }
public static float Float() => (float)source.NextDouble();
public void CalculatePearsonsRSquaredOfConstantTest() { System.Random random = new System.Random(31415); int n = 12; int cols = testData.GetLength(1); for (int c1 = 0; c1 < cols; c1++) { double c1Scale = random.NextDouble() * 1E7; IEnumerable<double> x = from rows in Enumerable.Range(0, n) select testData[rows, c1] * c1Scale; IEnumerable<double> y = (new List<double>() { 150494407424305.47 }) .Concat(Enumerable.Repeat(150494407424305.47, n - 1)); double[] xs = x.ToArray(); double[] ys = y.ToArray(); double r2_alglib = alglib.pearsoncorrelation(xs, ys, n); r2_alglib *= r2_alglib; var r2Calculator = new OnlinePearsonsRSquaredCalculator(); for (int i = 0; i < n; i++) { r2Calculator.Add(xs[i], ys[i]); } double r2 = r2Calculator.RSquared; Assert.AreEqual(r2_alglib.ToString(), r2.ToString()); } }
private void CallLightning() { if (SpaceBarLabel != null) { SpaceBarLabel.CrossFadeColor(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1.0f, true, true); SpaceBarLabel = null; } UnityEngine.Profiler.BeginSample("CreateLightningBolt"); System.Diagnostics.Stopwatch timer = System.Diagnostics.Stopwatch.StartNew(); lastStart = StartImage.transform.position + (Camera.main.transform.forward * DistanceSlider.value); lastEnd = EndImage.transform.position + (Camera.main.transform.forward * DistanceSlider.value); lastStart = Camera.main.ScreenToWorldPoint(lastStart); lastEnd = Camera.main.ScreenToWorldPoint(lastEnd); int count = (int)BoltCountSlider.value; float duration = DurationSlider.value; float delay = 0.0f; float chaosFactor = ChaosSlider.value; float trunkWidth = TrunkWidthSlider.value; float forkedness = ForkednessSlider.value; if (!int.TryParse(SeedInputField.text, out lastSeed)) { lastSeed = UnityEngine.Random.Range(int.MinValue, int.MaxValue); } System.Random r = new System.Random(lastSeed); float singleDuration = Mathf.Max(1.0f / 30.0f, (duration / (float)count)); float fadePercent = FadePercentSlider.value; float growthMultiplier = GrowthMultiplierSlider.value; while (count-- > 0) { LightningBoltParameters parameters = new LightningBoltParameters { Start = lastStart, End = lastEnd, Generations = (int)GenerationsSlider.value, LifeTime = (count == 1 ? singleDuration : (singleDuration * (((float)r.NextDouble() * 0.4f) + 0.8f))), Delay = delay, ChaosFactor = chaosFactor, TrunkWidth = trunkWidth, GlowIntensity = GlowIntensitySlider.value, GlowWidthMultiplier = GlowWidthSlider.value, Forkedness = forkedness, Random = r, FadePercent = fadePercent, GrowthMultiplier = growthMultiplier }; LightningBoltScript.CreateLightningBolt(parameters); delay += (singleDuration * (((float)r.NextDouble() * 0.8f) + 0.4f)); } timer.Stop(); UnityEngine.Profiler.EndSample(); UpdateStatusLabel(timer.Elapsed); }
public void CalculatePearsonsRSquaredTest() { System.Random random = new System.Random(31415); int n = testData.GetLength(0); int cols = testData.GetLength(1); for (int c1 = 0; c1 < cols; c1++) { for (int c2 = c1 + 1; c2 < cols; c2++) { { double c1Scale = random.NextDouble() * 1E7; double c2Scale = random.NextDouble() * 1E7; IEnumerable<double> x = from rows in Enumerable.Range(0, n) select testData[rows, c1] * c1Scale; IEnumerable<double> y = from rows in Enumerable.Range(0, n) select testData[rows, c2] * c2Scale; double[] xs = x.ToArray(); double[] ys = y.ToArray(); double r2_alglib = alglib.pearsoncorrelation(xs, ys, n); r2_alglib *= r2_alglib; var r2Calculator = new OnlinePearsonsRSquaredCalculator(); for (int i = 0; i < n; i++) { r2Calculator.Add(xs[i], ys[i]); } double r2 = r2Calculator.RSquared; Assert.IsTrue(r2_alglib.IsAlmost(r2)); } } } }
public PackageInfo Single(string name = null, string version = null) { var type = Random.NextDouble() > 0.5 ? PackageSource.Unknown : PackageSource.Registry; return(Single(type, name, version)); }
//Random number to fudge the distance estimate in the screen messages above; extent of fudging based on total distance to the anomaly, +- 2km at 30km away. private double RandomDouble(double min, double max) { System.Random randomd = new System.Random(); double random = randomd.NextDouble(); return (random * max) - min; }
public string GenerateWord(System.Random r) { int noSyllables = r.Next() % (maxSyllables - minSyllables) + minSyllables; List <Syllable> syll = new List <Syllable>(); Syllable s = findRandom(r, Syllable.Prefix); syll.Add(s); for (int i = 0; i < noSyllables - 1; i++) { int fix = Syllable.Infix; if (i == noSyllables - 2) { fix = Syllable.Postfix; } s = findBasedOnSyllable(s, r, i == noSyllables - 2, fix); if (fix == Syllable.Postfix) { // if (s!=null) // Debug.Log(s.syllable + " : " + fix); // else // Debug.Log("COULD NOT FIND POSTFIX"); } if (s != null) { syll.Add(s); } } string word = ""; int remaining = maxDoubleC; for (int i = 0; i < syll.Count; i++) { Syllable sb = syll[i]; if (sb == null) { continue; } if (i > 0 && remaining > 0) { Syllable prev = syll[i - 1]; if (prev.type == Syllable.Types.CV || prev.type == Syllable.Types.V) { if (r.NextDouble() > 0.6) { //bool ok=true; // Double consonant //if (!(i==syll.Count-1 && exceptDoubleEndings.Contains(sb.syllable[0].ToString()))) // Debug.Log("DOUBLE:" + sb.syllable[0]); //if (i==syll.Count-1 && !allowDoubleCEnd) // ok = false; if (!exceptDoubles.Contains(sb.syllable[0].ToString())) { word += sb.syllable[0]; remaining--; } } } } word += sb.syllable; } // return word; return(RemoveIllegalDoubles(word)); }
public void GenerateMap() { currentMap = maps[mapIndex]; tileMap = new Transform[currentMap.mapSize.x, currentMap.mapSize.y]; System.Random prng = new System.Random(currentMap.seed); GetComponent<BoxCollider>().size = new Vector3(currentMap.mapSize.x * tileSize, .05f, currentMap.mapSize.y * tileSize); //Generating Coord allTileCoords = new List<Coord>(); for (int x = 0; x < currentMap.mapSize.x; x++) { for (int y = 0; y < currentMap.mapSize.y; y++) { allTileCoords.Add(new Coord(x, y)); } } shuffleTileCoords = new Queue<Coord>(Utility.ShuffleArray(allTileCoords.ToArray(), currentMap.seed)); //Create MapHolder string holderName = "Generated Map"; if (transform.FindChild(holderName)) { DestroyImmediate(transform.FindChild(holderName).gameObject); } Transform mapHolder = new GameObject(holderName).transform; mapHolder.parent = transform; //Spawning Tiles for (int x = 0; x < currentMap.mapSize.x; x++) { for (int y = 0; y < currentMap.mapSize.y; y++) { Vector3 tilePosition = CoordToPosition(x, y); Transform newTile = Instantiate(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)) as Transform; newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize; newTile.parent = mapHolder; tileMap[x, y] = newTile; } } //Spawning Obstacles bool[,] obstacleMap = new bool[(int)currentMap.mapSize.x, (int)currentMap.mapSize.y]; int obstacleCount = (int)(currentMap.mapSize.x * currentMap.mapSize.y * currentMap.obstaclePercent); int currentObstacleCount = 0; List<Coord> allOpenCoords = new List<Coord>(allTileCoords); for (int i = 0; i < obstacleCount; i++) { Coord randomCoord = GetRandomCoord(); obstacleMap[randomCoord.x, randomCoord.y] = true; currentObstacleCount++; if (randomCoord != currentMap.mapCenter && MapIsAccessible(obstacleMap, currentObstacleCount)) { float obstacleHeight = Mathf.Lerp(currentMap.minimumObstacleHeight, currentMap.maxObstacleHeight, (float)prng.NextDouble()); Vector3 obstaclePosition = CoordToPosition(randomCoord.x, randomCoord.y); Transform newObstacle = Instantiate(obstaclePrefab, obstaclePosition + Vector3.up * obstacleHeight / 2, Quaternion.identity) as Transform; newObstacle.parent = mapHolder; newObstacle.localScale = new Vector3((1 - outlinePercent) * tileSize, obstacleHeight, (1 - outlinePercent) * tileSize); Renderer obstacleRenderer = newObstacle.GetComponent<Renderer>(); Material obstacleMaterial = new Material(obstacleRenderer.sharedMaterial); float colorPercent = randomCoord.y / (float)currentMap.mapSize.y; obstacleMaterial.color = Color.Lerp(currentMap.foreground, currentMap.background, colorPercent); obstacleRenderer.sharedMaterial = obstacleMaterial; allOpenCoords.Remove(randomCoord); } else { obstacleMap[randomCoord.x, randomCoord.y] = false; currentObstacleCount--; } } shuffleOpenTileCoords = new Queue<Coord>(Utility.ShuffleArray(allOpenCoords.ToArray(), currentMap.seed)); //Creating NavMesh Mask //Left Mask Transform maskLeft = Instantiate(navMeshMask, Vector3.left * (currentMap.mapSize.x + maxMapSize.x) / 4f * tileSize, Quaternion.identity) as Transform; maskLeft.parent = mapHolder; maskLeft.localScale = new Vector3((maxMapSize.x - currentMap.mapSize.x) / 2f, 1, currentMap.mapSize.y) * tileSize; //Right Mask Transform maskRight = Instantiate(navMeshMask, Vector3.right * (currentMap.mapSize.x + maxMapSize.x) / 4f * tileSize, Quaternion.identity) as Transform; maskRight.parent = mapHolder; maskRight.localScale = new Vector3((maxMapSize.x - currentMap.mapSize.x) / 2f, 1, currentMap.mapSize.y) * tileSize; //Top Mask Transform maskTop = Instantiate(navMeshMask, Vector3.forward * (currentMap.mapSize.y + maxMapSize.y) / 4f * tileSize, Quaternion.identity) as Transform; maskTop.parent = mapHolder; maskTop.localScale = new Vector3(maxMapSize.x, 1, (maxMapSize.y - currentMap.mapSize.y) / 2f) * tileSize; //Bottom Mask Transform maskBottom = Instantiate(navMeshMask, Vector3.back * (currentMap.mapSize.y + maxMapSize.y) / 4f * tileSize, Quaternion.identity) as Transform; maskBottom.parent = mapHolder; maskBottom.localScale = new Vector3(maxMapSize.x, 1, (maxMapSize.y - currentMap.mapSize.y) / 2f) * tileSize; navMeshFloor.localScale = new Vector3(maxMapSize.x, maxMapSize.y) * tileSize; }
public static void TestFuncs() { ExpressionSolver solver = new ExpressionSolver(); solver.SetGlobalVariable("zero",0); var exp1 = solver.SymbolicateExpression("sin(pi/2)-cos(zero)"); AssertSameValue(exp1.Evaluate(),0); var exp2 = solver.SymbolicateExpression("2*e^zero - exp(zero)"); AssertSameValue(exp2.Evaluate(),1); var exp3 = solver.SymbolicateExpression("log(e^6)"); AssertSameValue(exp3.Evaluate(),6); var exp4 = solver.SymbolicateExpression("sqrt(2)-2^0.5"); AssertSameValue(exp4.Evaluate(),0); var exp5 = solver.SymbolicateExpression("exp(log(6))"); AssertSameValue(exp5.Evaluate(),6); var rnd = new System.Random(); solver.AddCustomFunction("Rnd1",2, delegate(double[] p) { return p[0] + (p[1]-p[0])*(rnd.NextDouble()); },false); var exp6 = solver.SymbolicateExpression("Rnd1(0,1)"); var firstRnd = exp6.Evaluate(); int iter = 0; while (true) { var secondRnd = exp6.Evaluate(); if (firstRnd != secondRnd) { break; } iter++; if (iter==10000) { // Probability of this happening is miniscule if everything works as it should throw new System.Exception("ExpressionSolverTest failed"); } } solver.AddCustomFunction("Rnd2",2, delegate(double[] p) { return p[0] + (p[1]-p[0])*(rnd.NextDouble()); },true); var exp7 = solver.SymbolicateExpression("Rnd2(0,1)"); AssertSameValue(exp7.Evaluate(),exp7.Evaluate()); var exp8 = solver.SymbolicateExpression("cos(0)+1*2"); AssertSameValue(exp8.Evaluate(),3); solver.AddCustomFunction("dist",5, delegate(double[] p) { return System.Math.Pow( (p[2]-p[0])*(p[2]-p[0]) + (p[3]-p[1])*(p[3]-p[1]) ,p[4]); },true); var exp9 = solver.SymbolicateExpression("dist(3*x,(4*x),+6*x,-1*x,sin(x))","x"); double x = 21; exp9.SetVariable("x",x); AssertSameValue(exp9.Evaluate(),System.Math.Pow( (3*x-6*x)*(3*x-6*x)+(4*x+x)*(4*x+x),System.Math.Sin(x) )); }
IEnumerator Start() { pauseUser = false; pauseWait = true; enabled = false; Debug.Log("World begin start"); // if no pools wait for them. if (!PoolBase.Instance) { Debug.Log("Waiting for PoolBase instance."); while (!PoolBase.Instance) { yield return null; } } // wait for UI. yield return StartCoroutine(UIBase.WaitInstance()); UserEnergy = TotalUserEnergy; Random = new System.Random(Startup.Seed); sizeX = (int)transform.localScale.x; sizeXhalf = sizeX / 2; sizeZ = (int)transform.localScale.z; sizeZhalf = sizeZ / 2; if ((float)sizeX != transform.localScale.x || (float)sizeZ != transform.localScale.z) { Debug.LogWarning("World local scale should be a interger."); } // get pools PoolBase pools = PoolBase.Instance; cubers = pools.Cubers; fourths = pools.Fourths; energys = pools.Energys; // spawn cubers int infected = 0; if (Startup.PrecentInfected > 0) { infected = (int)((float)Startup.Cubers * ((float)Startup.PrecentInfected / 100f)); if (infected <= 0) infected = 1; } for (int i = 0; i < Startup.Cubers; ++i) { Vector3 position; if (FindGround(new Ray(transform.position + new Vector3(-sizeXhalf + Random.Next(sizeX), 100f, -sizeZhalf + Random.Next(sizeZ)), Vector3.down), out position)) { cubers.Pull().Init(position, --infected >= 0, 0.5f + (float)Random.NextDouble() * 0.6f);//, Color.black); } } // startup energy for (int i = 0; i < EnergyCount; ++i) { NewEnergy(EnergyMin, EnergyMax); } enabled = true; pauseWait = false; Debug.Log("World end start"); }
public void Generate() { // Setup the cameras m_OrthographicCamera.SetActive(!m_UseTerrain); m_TerrainCamera.SetActive(m_UseTerrain); // Clear existing for (int i = m_Container.childCount - 1; i >= 0; i--) { DestroyImmediate(m_Container.GetChild(i).gameObject); } // If we're not using a seed, make one if (!m_UseSeed) { m_Seed = UnityEngine.Random.Range(0, 10000); } // Use a seed m_Random = new System.Random(m_Seed); // Get the maximum extents Vector2 size = m_Size; if (m_UseTerrain) { Vector3 boundsSize = m_Terrain.GetComponent <MeshRenderer>().bounds.size; size = new Vector2(boundsSize.x, boundsSize.z); } // Spawn nodes List <GameObject> nodes = new List <GameObject>(); for (int i = 0; i < m_NodeCount; i++) { GameObject go = Instantiate(m_NodePrefab, m_Container); go.name = $"Node {i}"; Vector3 position = Vector3.zero; int maxAttempts = 25; while (--maxAttempts > 0) { // Generate a random position position = new Vector3(size.x * (float)m_Random.NextDouble() - size.x / 2f, 0f, size.y * (float)m_Random.NextDouble() - size.y / 2f); // Margin around edges const float MARGIN_PERCENTAGE = 0.05f; Vector2 margin = size * MARGIN_PERCENTAGE; position.x = Mathf.Clamp(position.x, m_Radius + margin.x - size.x / 2f, size.x / 2f - m_Radius - margin.y); position.z = Mathf.Clamp(position.z, m_Radius + margin.x - size.y / 2f, size.y / 2f - m_Radius - margin.y); // Make sure it's sufficiently far away from other nodes bool farAway = true; for (int x = 0; x < nodes.Count; x++) { if (Vector2.Distance(nodes[x].transform.position, position) < 4f) { farAway = false; break; } } if (farAway) { break; } } // Remove existing terrain if (m_SpawnedTerrain) { Destroy(m_SpawnedTerrain); } // If we're using a terrain, set the height appropriately and spawn the object if (m_UseTerrain) { // Spawn the terrain prefab m_SpawnedTerrain = Instantiate(m_Terrain); // Raycast the terrain to get it's height Ray ray = new Ray(position + Vector3.up * 20f, Vector3.down * 100f); Collider col = m_SpawnedTerrain.GetComponent <MeshCollider>(); col.Raycast(ray, out RaycastHit hit, 100f); // Adjust the height plus a margin const float HEIGHT_MARGIN = 1f; position.y = hit.point.y + HEIGHT_MARGIN; } // Set the position go.transform.position = position; // Set the radius go.transform.localScale = Vector3.one * m_Radius; // Save the new node nodes.Add(go); } // Solve the path GameObject origin = DesignateOrigin(nodes); SolvePath(nodes, origin); }
protected override void CalculateStep(long targetTick) { int counter = 0; // Continue to search while there hasn't ocurred an error and the end hasn't been found while (CompleteState == PathCompleteState.NotCalculated) { searchedNodes++; // Close the current node, if the current node is the target node then the path is finished if (currentR.G >= searchLength) { if (currentR.G <= searchLength + spread) { nodesEvaluatedRep++; if (rnd.NextDouble() <= 1.0f / nodesEvaluatedRep) { chosenNodeR = currentR; } } else { // If no node was in the valid range of G scores, then fall back to picking one right outside valid range if (chosenNodeR == null) { chosenNodeR = currentR; } CompleteState = PathCompleteState.Complete; break; } } else if (currentR.G > maxGScore) { maxGScore = (int)currentR.G; maxGScoreNodeR = currentR; } // Loop through all walkable neighbours of the node and add them to the open list. currentR.node.Open(this, currentR, pathHandler); // Any nodes left to search? if (pathHandler.heap.isEmpty) { if (chosenNodeR != null) { CompleteState = PathCompleteState.Complete; } else if (maxGScoreNodeR != null) { chosenNodeR = maxGScoreNodeR; CompleteState = PathCompleteState.Complete; } else { LogError("Not a single node found to search"); Error(); } break; } // Select the node with the lowest F score and remove it from the open list currentR = pathHandler.heap.Remove(); // Check for time every 500 nodes, roughly every 0.5 ms usually if (counter > 500) { // Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag if (System.DateTime.UtcNow.Ticks >= targetTick) { // Return instead of yield'ing, a separate function handles the yield (CalculatePaths) return; } counter = 0; if (searchedNodes > 1000000) { throw new System.Exception("Probable infinite loop. Over 1,000,000 nodes searched"); } } counter++; } if (CompleteState == PathCompleteState.Complete) { Trace(chosenNodeR); } }
public float GetRandomNumber(float minimum, float maximum) { return((float)rnd.NextDouble() * (maximum - minimum) + minimum); }
/// <summary> /// returns a float between 0 and 1 from a layerd perlin texture, the sacle at witch the values extend on x and y is dictated by base noise scale, alows for jitter /// </summary> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="layerInfo">each Layers info.</param> /// <param name="baseNoiseScale">amount x and y will walk along the perlin teture.</param> /// <param name="jitter">Jitter.</param> public static float perlinNoise(int x, int y, NoiseOctaveInfo[] layerInfo, float baseNoiseScale,float jitter) { noisePrng = new System.Random(Mathf.Abs(x)^Mathf.Abs(y)); float maxPersistance =0; for(int i=0; i < layerInfo.Length; i++) { if(layerInfo[i].Persistance < 0) Debug.LogError("invalid Persistance" + ". Persistance = "+layerInfo[i]); if(layerInfo[i].Lacunarity < 0) Debug.LogError("invalid Lacunarity" + ". Lacunarity = "+layerInfo[i]); maxPersistance += layerInfo[i].Persistance; } float heightValue = 0; for(int i=0; i < layerInfo.Length; i++) { heightValue += Mathf.PerlinNoise((x + (((float)noisePrng.NextDouble() * 2 * jitter)- jitter)) * baseNoiseScale *layerInfo[i].Lacunarity, (y+ (((float)noisePrng.NextDouble() * 2 * jitter)- jitter)) * baseNoiseScale * layerInfo[i].Lacunarity) * layerInfo[i].Persistance; } heightValue = heightValue / maxPersistance; //re normalize the value return heightValue; }
public static double NextDouble() { return(_random.NextDouble()); }
public ExpressionParser() { var rnd = new System.Random(); m_Consts.Add("PI", () => System.Math.PI); m_Consts.Add("e", () => System.Math.E); m_Funcs.Add("sqrt", (p) => System.Math.Sqrt(p.FirstOrDefault())); m_Funcs.Add("abs", (p) => System.Math.Abs(p.FirstOrDefault())); m_Funcs.Add("ln", (p) => System.Math.Log(p.FirstOrDefault())); m_Funcs.Add("floor", (p) => System.Math.Floor(p.FirstOrDefault())); m_Funcs.Add("ceiling", (p) => System.Math.Ceiling(p.FirstOrDefault())); m_Funcs.Add("round", (p) => System.Math.Round(p.FirstOrDefault())); m_Funcs.Add("sin", (p) => System.Math.Sin(p.FirstOrDefault())); m_Funcs.Add("cos", (p) => System.Math.Cos(p.FirstOrDefault())); m_Funcs.Add("tan", (p) => System.Math.Tan(p.FirstOrDefault())); m_Funcs.Add("asin", (p) => System.Math.Asin(p.FirstOrDefault())); m_Funcs.Add("acos", (p) => System.Math.Acos(p.FirstOrDefault())); m_Funcs.Add("atan", (p) => System.Math.Atan(p.FirstOrDefault())); m_Funcs.Add("atan2", (p) => System.Math.Atan2(p.FirstOrDefault(),p.ElementAtOrDefault(1))); //System.Math.Floor m_Funcs.Add("min", (p) => System.Math.Min(p.FirstOrDefault(), p.ElementAtOrDefault(1))); m_Funcs.Add("max", (p) => System.Math.Max(p.FirstOrDefault(), p.ElementAtOrDefault(1))); m_Funcs.Add("rnd", (p) => { if (p.Length == 2) return p[0] + rnd.NextDouble() * (p[1] - p[0]); if (p.Length == 1) return rnd.NextDouble() * p[0]; return rnd.NextDouble(); }); }
public void FixedUpdate() { base.OnFixedUpdate(); if (!HighLogic.LoadedSceneIsFlight) { return; } if (engine != null) { // if the engine module is stock, I might mess with it via atmosphericNerf. If it's FSengine, it will only be changed by propeller tweak at the start of flight (or maybe applyDamage), but I need to catch that. if (engine.type == FSengineWrapper.EngineType.FSengine) { maxThrust = engine.maxThrust; } if (TimeWarp.WarpMode == TimeWarp.Modes.HIGH && TimeWarp.CurrentRate > 1.1f) { if (powerAssigned) { powerGroup.audio.volume = 0f; } } else { // power/running sound if (engine.getIgnitionState && !engine.getFlameoutState) { if (powerAssigned) { if (currentPowerDelay > 0f) { currentPowerDelay -= Time.deltaTime; } float adjustedThrustPitch = ((engine.finalThrust / maxThrust) * thrustAddedToPitch) + powerPitchBase; smoothedPowerPitch = Mathf.Lerp(smoothedPowerPitch, adjustedThrustPitch, 0.1f); if (currentPowerDelay <= 0f) { if (currentPowerFadeIn < 1f) { currentPowerFadeIn += powerFadeInSpeed; if (currentPowerFadeIn > 1f) { currentPowerFadeIn = 1f; } } if ((engine.finalThrust / maxThrust) > powerLowerThreshold || powerLowerThreshold <= 0f) { powerGroup.audio.volume = GameSettings.SHIP_VOLUME * currentPowerFadeIn * powerVolume; } else { powerGroup.audio.volume = Mathf.Lerp(powerGroup.audio.volume, 0f, 0.06f); } if (!powerGroup.audio.isPlaying) { powerGroup.audio.Play(); } powerGroup.audio.pitch = smoothedPowerPitch; } } if (runningAssigned) { if (!runningGroup.audio.isPlaying) { runningGroup.audio.volume = GameSettings.SHIP_VOLUME * runningVolume; runningGroup.audio.Play(); } } } else { if (powerAssigned) { if (powerGroup.audio.isPlaying) { powerGroup.audio.Stop(); } if (!engine.getIgnitionState) { currentPowerFadeIn = 0f; currentPowerDelay = powerFadeInDelay + ((float)(rand.NextDouble()) * randomStartDelay); } } if (runningAssigned) { if (runningGroup.audio.isPlaying) { runningGroup.audio.Stop(); } } } // engage sound if (engageAssigned) { if (engine.getIgnitionState && !oldIgnitionState) { if (!engine.getFlameoutState) { engageGroup.audio.volume = GameSettings.SHIP_VOLUME * engageVolume; engageGroup.audio.Play(); if (disengageAssigned) { if (disengageGroup.audio.isPlaying) { disengageGroup.audio.Stop(); } } if (flameoutAssigned) { if (flameoutGroup.audio.isPlaying) { flameoutGroup.audio.Stop(); } } } } } //disangage sound if (disengageAssigned) { if (!engine.getIgnitionState && oldIgnitionState) { if (!engine.getFlameoutState) { disengageGroup.audio.volume = GameSettings.SHIP_VOLUME * disengageVolume; disengageGroup.audio.Play(); if (engageAssigned) { if (engageGroup.audio.isPlaying) { engageGroup.audio.Stop(); } } } } } //flameout if (flameoutAssigned) { if (engine.getFlameoutState && !oldFlameOutState) { flameoutGroup.audio.volume = GameSettings.SHIP_VOLUME * flameoutVolume; flameoutGroup.audio.Play(); if (engageAssigned) { if (engageGroup.audio.isPlaying) { engageGroup.audio.Stop(); } } } } oldIgnitionState = engine.getIgnitionState; oldFlameOutState = engine.getFlameoutState; } //overheat warning if (warningAssigned) { if (warningCountDown > 0f) { warningCountDown -= Time.deltaTime; } if (part.temperature > part.maxTemp * warningSoundThreshold) { if (warningCountDown <= 0) { warningGroup.audio.volume = GameSettings.SHIP_VOLUME * warningVolume; warningGroup.audio.Play(); warningCountDown = warningCooldownTime; } } } } }
private void SetComponents() { this.Camera = new Camera(this, Vector3.UnitZ * 400, -Vector3.UnitZ); this.World = new InfinityWorld(this); this.World.WorldObjects.Add(new Characters.ZombieCharacter(this, new Vector3(-95, 0, 0), Color.Yellow)); var rnd = new System.Random(); for (int i = 0; i < 16; i++) { var z = new Characters.ZombieCharacter(this, new Vector3(rnd.Next(0, 300) * (float)rnd.NextDouble() * (rnd.Next() % 2 == 0 ? -1 : 1), rnd.Next(0, 300) * (float)rnd.NextDouble() * (rnd.Next() % 2 == 0 ? -1 : 1), 0), Color.Red); z.OrientationScalar = rnd.Next(-3, 3) + (float)rnd.NextDouble(); this.World.WorldObjects.Add(z); } this.World.WorldObjects.Add(new Characters.HumanCharacter(this, new Vector3(0, 5, 0))); //this.World.Humans.Add(new Characters.HumanCharacter(this, new Vector3(-66, 45, 0))); }
public void Generate() { System.Random rng = new System.Random(); if (RandomGeneration) { GridSeed = Random.Range(1, int.MaxValue); MaxObstacleHeight = Random.Range(1.5f, 4); ObstacleColorA = new Color((float)rng.NextDouble(), (float)rng.NextDouble(), (float)rng.NextDouble()); } ClearNodes(); allNodeCoords = new List<Coord>(); NavMeshObject.localScale = new Vector3(MaxGridSize.x * NodeSize,MaxGridSize.y * NodeSize,1); for (int x = 0; x < GridSizeX; x++) { for (int y = 0; y < GridSizeY; y++) { Vector3 nodePos = CoordToVector(x, y); Node node = (Node)Instantiate(Node, nodePos, Quaternion.identity); node.transform.parent = transform; node.GridPosition = new Vector2(x, y); Nodes.Add(node); allNodeCoords.Add(new Coord(x,y)); if (GridSizeX/2 == x && GridSizeY/2 == y) CenterNode = node; } } Quaternion teleporterRot = Quaternion.Euler(-90, 0, 0); currentTeleporter = (Teleporter)Instantiate(Teleporter, CenterNode.transform.position, teleporterRot); currentTeleporter.transform.parent = transform; gridCoordCenter = new Coord(GridSizeX/2,GridSizeY/2); shuffledNodeCoords = new Queue<Coord>(Functions.ShuffleArray(allNodeCoords.ToArray(), GridSeed)); bool[,] obstacleMap = new bool[GridSizeX,GridSizeY]; int currentObstacleCount = 0; for (int i = 0; i < Nodes.Count * ObstaclePercent; i++) { Coord randomCoord = GetRandomCoord(); Vector3 coordPos = CoordToVector(randomCoord.X, randomCoord.Y); obstacleMap[randomCoord.X, randomCoord.Y] = true; currentObstacleCount++; if (coordPos != GridCenter && GridIsFullyAccessible(obstacleMap, currentObstacleCount)) { Transform obstacle = (Transform) Instantiate(Obstacle, coordPos, Quaternion.identity); obstacle.parent = transform; float obstacleHeight = Mathf.Lerp(MinObstacleHeight,MaxObstacleHeight , (float)rng.NextDouble()); obstacle.localScale = new Vector3(obstacle.localScale.x, obstacleHeight, obstacle.localScale.z); obstacle.position += new Vector3(0,obstacle.localScale.y/2,0); Renderer obstacleRenderer = obstacle.GetComponent<Renderer>(); Material obstacleMaterial = new Material(obstacleRenderer.sharedMaterial); float colorPercent = randomCoord.Y/(float)GridSizeY; obstacleMaterial.color = Color.Lerp(ObstacleColorA, ObstacleColorB, colorPercent); obstacleRenderer.sharedMaterial = obstacleMaterial; Obstacles.Add(obstacle); } else { obstacleMap[randomCoord.X, randomCoord.Y] = false; currentObstacleCount--; } } for (int i = 0; i < Obstacles.Count; i++) { for (int j = 0; j < Nodes.Count; j++) { Vector3 obstaclePos = new Vector3(Obstacles[i].transform.position.x, 0, Obstacles[i].transform.position.z); if (Nodes[j].transform.position != obstaclePos) continue; Nodes[j].Obstacle = true; break; } } foreach (Node node in Nodes) GridCenter += node.transform.position; GridCenter /= Nodes.Count; NavMeshObject.position = GridCenter; }
IEnumerator MenuGenerate() { yield return new WaitForSeconds(2f); System.Random rng = new System.Random(); if (RandomGeneration) { GridSeed = Random.Range(1, int.MaxValue); MaxObstacleHeight = Random.Range(1.5f, 4); ObstacleColorA = new Color((float)rng.NextDouble(), (float)rng.NextDouble(), (float)rng.NextDouble()); } foreach (Transform obstacle in Obstacles) { DestroyImmediate(obstacle.gameObject); yield return new WaitForSeconds(0.02f); } Obstacles.Clear(); yield return new WaitForSeconds(2f); shuffledNodeCoords = new Queue<Coord>(Functions.ShuffleArray(allNodeCoords.ToArray(), GridSeed)); bool[,] obstacleMap = new bool[GridSizeX, GridSizeY]; int currentObstacleCount = 0; for (int i = 0; i < Nodes.Count * ObstaclePercent; i++) { Coord randomCoord = GetRandomCoord(); Vector3 coordPos = CoordToVector(randomCoord.X, randomCoord.Y); obstacleMap[randomCoord.X, randomCoord.Y] = true; currentObstacleCount++; if (coordPos != GridCenter && GridIsFullyAccessible(obstacleMap, currentObstacleCount)) { Transform obstacle = (Transform)Instantiate(Obstacle, coordPos, Quaternion.identity); obstacle.parent = transform; float obstacleHeight = Mathf.Lerp(MinObstacleHeight,MaxObstacleHeight , (float)rng.NextDouble()); obstacle.localScale = new Vector3(obstacle.localScale.x, obstacleHeight, obstacle.localScale.z); obstacle.position += new Vector3(0, obstacle.localScale.y / 2, 0); Renderer obstacleRenderer = obstacle.GetComponent<Renderer>(); Material obstacleMaterial = new Material(obstacleRenderer.sharedMaterial); float colorPercent = randomCoord.Y / (float)GridSizeY; obstacleMaterial.color = Color.Lerp(ObstacleColorA, ObstacleColorB, colorPercent); obstacleRenderer.sharedMaterial = obstacleMaterial; Obstacles.Add(obstacle); } else { obstacleMap[randomCoord.X, randomCoord.Y] = false; currentObstacleCount--; } yield return new WaitForSeconds(0.02f); } }
void Update() { if (!Global.isMenu) { if (Input.GetMouseButton(0)) // 射击 { if (_activeGun != null && _isReady) { if (_activeGun.Shot()) { Vector2 aimingVector = new Vector2(Screen.width / 2, Screen.height / 2); gameObject.GetComponent <CameraControl>().Translate(new Vector2(_activeGun.GetBaseRecoil() * (float)random.NextDouble(), _activeGun.GetBaseRecoil() * (0.5f - (float)random.NextDouble()))); if (Physics.Raycast(gameObject.GetComponent <CameraControl>().GetActiveCamera().ScreenPointToRay(aimingVector), out var hit)) { if (hit.collider.gameObject.tag == "Character") { hit.collider.gameObject.GetComponent <CharacterControl>().Shot(_activeGun.GetBaseDamage()); } } _isReady = false; StartCoroutine(Recoil()); } } } if (Input.GetKeyDown(KeyCode.R)) // 换弹 { if (_activeGun != null && _isReady) { StartCoroutine(Prepare()); } } } }
/** Returns randomly selected points on the specified nodes with each point being separated by \a clearanceRadius from each other. * Selecting points ON the nodes only works for TriangleMeshNode (used by Recast Graph and Navmesh Graph) and GridNode (used by GridGraph). * For other node types, only the positions of the nodes will be used. * * clearanceRadius will be reduced if no valid points can be found. */ public static List<Vector3> GetPointsOnNodes (List<GraphNode> nodes, int count, float clearanceRadius = 0) { if (nodes == null) throw new System.ArgumentNullException("nodes"); if (nodes.Count == 0) throw new System.ArgumentException("no nodes passed"); var rnd = new System.Random(); List<Vector3> pts = ListPool<Vector3>.Claim(count); // Square clearanceRadius *= clearanceRadius; if (nodes[0] is TriangleMeshNode || nodes[0] is GridNode ) { //Assume all nodes are triangle nodes or grid nodes List<float> accs = ListPool<float>.Claim(nodes.Count); float tot = 0; for (int i = 0; i < nodes.Count; i++) { var tnode = nodes[i] as TriangleMeshNode; if (tnode != null) { /** \bug Doesn't this need to be divided by 2? */ float a = System.Math.Abs(VectorMath.SignedTriangleAreaTimes2XZ(tnode.GetVertex(0), tnode.GetVertex(1), tnode.GetVertex(2))); tot += a; accs.Add(tot); } else { var gnode = nodes[i] as GridNode; if (gnode != null) { GridGraph gg = GridNode.GetGridGraph(gnode.GraphIndex); float a = gg.nodeSize*gg.nodeSize; tot += a; accs.Add(tot); } else { accs.Add(tot); } } } for (int i = 0; i < count; i++) { //Pick point int testCount = 0; int testLimit = 10; bool worked = false; while (!worked) { worked = true; //If no valid points can be found, progressively lower the clearance radius until such a point is found if (testCount >= testLimit) { clearanceRadius *= 0.8f; testLimit += 10; if (testLimit > 100) clearanceRadius = 0; } float tg = (float)rnd.NextDouble()*tot; int v = accs.BinarySearch(tg); if (v < 0) v = ~v; if (v >= nodes.Count) { // This shouldn't happen, due to NextDouble being smaller than 1... but I don't trust floating point arithmetic. worked = false; continue; } var node = nodes[v] as TriangleMeshNode; Vector3 p; if (node != null) { // Find a random point inside the triangle float v1; float v2; do { v1 = (float)rnd.NextDouble(); v2 = (float)rnd.NextDouble(); } while (v1+v2 > 1); p = ((Vector3)(node.GetVertex(1)-node.GetVertex(0)))*v1 + ((Vector3)(node.GetVertex(2)-node.GetVertex(0)))*v2 + (Vector3)node.GetVertex(0); } else { var gnode = nodes[v] as GridNode; if (gnode != null) { GridGraph gg = GridNode.GetGridGraph(gnode.GraphIndex); float v1 = (float)rnd.NextDouble(); float v2 = (float)rnd.NextDouble(); p = (Vector3)gnode.position + new Vector3(v1 - 0.5f, 0, v2 - 0.5f) * gg.nodeSize; } else { //Point nodes have no area, so we break directly instead pts.Add((Vector3)nodes[v].position); break; } } // Test if it is some distance away from the other points if (clearanceRadius > 0) { for (int j = 0; j < pts.Count; j++) { if ((pts[j]-p).sqrMagnitude < clearanceRadius) { worked = false; break; } } } if (worked) { pts.Add(p); break; } testCount++; } } ListPool<float>.Release(accs); } else { for (int i = 0; i < count; i++) { pts.Add((Vector3)nodes[rnd.Next(nodes.Count)].position); } } return pts; }
private Vector2 GetRandomPoint() { var point = new Vector2(( float )_randomizer.NextDouble(), ( float )_randomizer.NextDouble()); return(point); }
/// <summary> /// Creates random filled matrix /// </summary> /// <param name="rows">int - matrix rows numer</param> /// <param name="cols">int - matrix cols number</param> /// <param name="dispersion">int - randomize range</param> /// <returns>MatrixMB</returns> public static MatrixMB Random(int rows, int cols, int dispersion) { System.Random random = new System.Random(); MatrixMB matrix = new MatrixMB(rows, cols); int max = dispersion; int min = -dispersion; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix.Data[i][j] = random.NextDouble() * (max - min) + min; } } return matrix; }
public override bool Update(System.Random RND) { Status = stage.ToString().Replace("_", " "); switch (stage) { case Stage.LOAD: level_loaded = false; ScenarioTester.LoadGame(Save); stage = Stage.WAIT_FOR_LEVEL; delay.Reset(); break; case Stage.WAIT_FOR_LEVEL: if (level_loaded && FlightGlobals.ready && FlightGlobals.ActiveVessel != null && !FlightGlobals.ActiveVessel.packed) { if (!delay.TimePassed) { break; } if (!GetTCA()) { Utils.Message("TCA is not installed/enabled on the ship"); return(false); } if (!GetModule()) { Utils.Message("{0} module is not installed on the ship", typeof(ToOrbitAutopilot).Name); return(false); } VSL.SetTarget(null); Debug.ClearDeveloperConsole(); orbit_set_up = false; stage = Stage.SETUP; } break; case Stage.SETUP: if (!orbit_set_up) { ResetFlightCamera(); TCAGui.ShowInstance(true); TCAGui.Instance.ActiveTab = TCAGui.Instance.ORB; ORB.TargetOrbit.RetrogradeOrbit = RND.NextDouble() > 0.5? true : false; ORB.TargetOrbit.DescendingNode = RND.NextDouble() > 0.5? true : false; ORB.TargetOrbit.UpdateValues(); ORB.TargetOrbit.Inclination.Value = (float)RND.NextDouble() * 90; ORB.TargetOrbit.Inclination.ClampValue(); inclination = ORB.TargetOrbit.Inclination; abs_inclination = (float)ORB.TargetOrbit.TargetInclination; ORB.TargetOrbit.ApA.Value = (float)(ORB.MinR + 1000 + RND.NextDouble() * 500000 - VSL.Body.Radius) / 1000; ORB.TargetOrbit.ApA.ClampValue(); ApA = ORB.TargetOrbit.ApA * 1000; ORB.ShowOptions = true; VSL.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); CFG.AP2.XOn(Autopilot2.ToOrbit); orbit_set_up = true; Log("TargetOrbit: {}", ORB.TargetOrbit); Log("TargetInclination: {}", ORB.TargetOrbit.TargetInclination); break; } if (CFG.AP2[Autopilot2.ToOrbit]) { delay.Reset(); stage = Stage.TO_ORBIT; } break; case Stage.TO_ORBIT: CFG.WarpToNode = true; if (VSL == null || VSL.vessel == null || VSL.vessel.state == Vessel.State.DEAD) { LogFlightLog("Vessel was destroyed:"); stage = Stage.FINISH; delay.Reset(); break; } if (CFG.AP2[Autopilot2.ToOrbit]) { if (ORB.stage >= ToOrbitAutopilot.Stage.ChangeApA) { if (!MapView.MapIsEnabled) { MapView.EnterMapView(); } RotateMapView(); } else { FlightCameraOverride.AnchorForSeconds(FlightCameraOverride.Mode.OrbitAround, VSL.vessel.transform, 1); } break; } Log("Achived Orbit: {}", VSL.vessel.orbit); var dApA = VSL.vessel.orbit.ApA - ApA; Log("ApA Error: {} m {} %", dApA, dApA / ApA * 100); var dInc = VSL.vessel.orbit.inclination - abs_inclination; Log("Inclination Error: {} deg {} %", dInc, dInc / inclination * 100); CFG.AP2.XOff(); stage = Stage.FINISH; delay.Reset(); break; case Stage.FINISH: if (!delay.TimePassed) { break; } Log("Done."); Cleanup(); Setup(); break; } return(true); }