public void Generate() { // Create the module network ModuleBase moduleBase; switch (noise) { case NoiseType.Billow: moduleBase = new Billow(); break; case NoiseType.RidgedMultifractal: moduleBase = new RidgedMultifractal(); break; case NoiseType.Voronoi: moduleBase = new Voronoi(); break; // case NoiseType.Mix: //Perlin perlin = new Perlin(); //RidgedMultifractal rigged = new RidgedMultifractal(); //moduleBase = new Add(perlin, rigged); //break; default: moduleBase = new Perlin(); break; } // Initialize the noise map this.m_noiseMap = new Noise2D(resolution, resolution, moduleBase); this.m_noiseMap.GeneratePlanar( offset + -1 * 1 / zoom, offset + offset + 1 * 1 / zoom, offset + -1 * 1 / zoom, offset + 1 * 1 / zoom); // Generate the textures this.m_textures[0] = this.m_noiseMap.GetTexture(GradientPresets.Grayscale); this.m_textures[0].Apply(); this.m_textures[1] = this.m_noiseMap.GetTexture(GradientPresets.Terrain); this.m_textures[1].Apply(); this.m_textures[2] = this.m_noiseMap.GetNormalMap(3.0f); this.m_textures[2].Apply(); //display on plane GetComponent <Renderer>().material.mainTexture = m_textures[0]; //write images to disk File.WriteAllBytes(Application.dataPath + "/../Gray.png", m_textures[0].EncodeToPNG()); File.WriteAllBytes(Application.dataPath + "/../Terrain.png", m_textures[1].EncodeToPNG()); File.WriteAllBytes(Application.dataPath + "/../Normal.png", m_textures[2].EncodeToPNG()); Debug.Log("Wrote Textures out to " + Application.dataPath + "/../"); }
public static Mesh MeshFromVoronoi(Voronoi voronoi) { var options = new TriangleNet.Meshing.ConstraintOptions { ConformingDelaunay = true }; var vertices = new List <Vector3>(); var verticesIndex = 0; var triangles = new List <int>(); var colors = new List <Color>(); var regions = voronoi.Regions(); for (var i = 0; i < regions.Count; i++) { var region = regions[i]; var polygon = new TriangleNetGeo.Polygon(); foreach (var corner in region) { polygon.Add(new TriangleNetGeo.Vertex(corner.x, corner.y)); } var cellMesh = (TriangleNet.Mesh)polygon.Triangulate(options); vertices.AddRange( cellMesh.Vertices.Select(v => new Vector3((float)v.x, 0, (float)v.y)) ); triangles.AddRange( cellMesh.Triangles.SelectMany( t => t.vertices.Select(v => v.id + verticesIndex) .Reverse() // Reverse triangles so they're facing the right way ) ); // Update index so the next batch of triangles point to the correct vertices verticesIndex = vertices.Count; // Assign same color to all vertices in region var regionColor = new Color(Random.Range(0, 1f), Random.Range(0, 1f), Random.Range(0, 1f)); colors.AddRange(cellMesh.Vertices.Select(v => regionColor)); } // Just make world-space UVs for now var uvs = vertices.Select(v => new Vector2(v.x, v.y)); var mesh = new Mesh { vertices = vertices.ToArray(), colors = colors.ToArray(), uv = uvs.ToArray(), triangles = triangles.ToArray() }; mesh.RecalculateNormals(); return(mesh); }
internal List<Point> FindAllCenters(Voronoi voronoi, VoronoiSettings settings) { var realCells = voronoi.Cells // filter the "real" cells .Where(c => c.Site.RealPoint).ToList(); var centerOfRealCells = realCells // find center for points .Select(c => { var centerPointOfPoints = GetCenterPointOfPoints(c.Vertices, settings.Width * 2, settings.Height); // account for cells having their center shifted to the other side if (centerPointOfPoints.X > ((double)settings.Width / 2d) * 3d) { centerPointOfPoints = new Point(centerPointOfPoints.X - settings.Width, centerPointOfPoints.Y); } else if (centerPointOfPoints.X < ((double)settings.Width / 2)) { centerPointOfPoints = new Point(centerPointOfPoints.X + settings.Width, centerPointOfPoints.Y); } // fix points to be real again var point = new Point(centerPointOfPoints.X - settings.Width / 2, centerPointOfPoints.Y, c.Site.Name); if (_mapHelper.IsOutOfMap(point, settings.Width * 2, settings.Height)) { return c.Site; } return point; }).ToList(); return centerOfRealCells; }
public void BuildIslandAndInitRenderers() { _tree = RandomTreeBuilder.GetRandomTree(treeNodeCount, treeMaxGrowthLength, treeBounds); var voronoiBounds = new Rectf( 0, 0, size, size ); var points = new List <Vector2>(GetRandomPoints(voronoiPointCount, voronoiBounds)); // Throw the tree points in for fun points.AddRange(_tree.Nodes.Select(n => n.position)); var pointsF = points.Select(v => new Vector2f(v.x, v.y)).ToList(); _voronoi = new Voronoi(pointsF, voronoiBounds, voronoiRelaxation); _map = MapHelper.MapFromVoronoi(_voronoi); MapHelper.CalculateCellTypes(_map, _tree, treeMaxGrowthLength, seaFloorElevation); _map.SetCornerElevations(); if (treeRenderer != null) { treeRenderer.SpawnNodesAndLines(_tree, size, targetTerrain); } UpdateMapTexture(); }
static bool GenVoronoi(MapGenArgs args) { Voronoi voronoi2D = new Voronoi(); voronoi2D.Seed = args.UseSeed ? args.Seed : new Random().Next(); return(Gen2D(args, voronoi2D)); }
public void Result(string mapSeed, Vector2Int mapSize, List <Region> outputMapRegions = null, List <List <Vector2> > outputRegions = null, List <LineSegment> outputSpanningTrees = null) { Rect bounds = new Rect(0, 0, mapSize.x, mapSize.y); List <Vector2> points = CreateRandomPoints(mapSeed, mapSize); //Generates new graph Voronoi voronoi = new Voronoi(points, bounds, VoronoiRelaxationCount); //Results if (outputMapRegions != null) { outputMapRegions.Clear(); List <Vector2> siteCoords = voronoi.SiteCoords(); Dictionary <Vector2, Site> siteDictionary = voronoi.SitesIndexedByLocation; for (int i = 0; i < siteCoords.Count; i++) { Region mapRegion = new Region { RegionSite = siteDictionary[siteCoords[i]] }; outputMapRegions.Add(mapRegion); } } if (outputRegions != null) { outputRegions.Clear(); outputRegions.AddRange(voronoi.Regions()); } if (outputSpanningTrees != null) { outputSpanningTrees.Clear(); outputSpanningTrees.AddRange(voronoi.SpanningTree(KruskalType.MINIMUM)); } }
private void GenerateSections(int numberOfSections) { List <Vector2f> seeds = this.CreateRandomPoints(numberOfSections); this.SectionDiagram = new Voronoi(seeds, this.bounds, 10); foreach (Site site in this.SectionDiagram.Sites) { // Set default elevation to sea floor. Section sectionData = new Section(this.seafloor); this.sectionMetadata.Add(site, sectionData); // Create Voronoi game object corresponding to section. GameObject go = Instantiate(CellPrefab, this.VoronoiTransformPoint(site.Coord), Quaternion.identity).gameObject; go.transform.SetParent(gameObject.transform); Cell cellObject = go.GetComponent(typeof(Cell)) as Cell; cellObject.SetSite(site); sectionData.CellObject = cellObject; // Create new meshes for each cell object. cellObject.GetComponent <MeshFilter>().sharedMesh = new Mesh(); cellObject.GetComponent <MeshCollider>().sharedMesh = new Mesh(); Renderer renderer = cellObject.GetComponent <Renderer>(); renderer.enabled = false; } }
public IEnumerator RedoSame20TimesNoGCAllocsTest() { Voronoi.FlushPools(); Voronoi.InitPools(500, 500, 40, 200); var points = VoronoiTest.CreateRandomPoints(50); yield return(null); Voronoi voronoi = VoronoiTest.TestVoronoi(points); yield return(null); for (int i = 0; i < 20; i++) { Profiler.BeginSample("NoGC Voronoi.Redo same points"); voronoi.Redo(points, VoronoiTest.TestBounds()); Profiler.EndSample(); yield return(null); } Debug.Log(voronoi.DebugCapacities()); yield return(null); }
private void GenerateVoronoi() { voronoiGraph = new Voronoi(minDistance); List <Vector2> sites = new List <Vector2>(); for (int i = 0; i < 50; i++) { bool tooClose = false; Vector2 newSite = new Vector2(Rand.Range(0.0f, size, false), Rand.Range(0.0f, size, false)); foreach (Vector2 site in sites) { if (Vector2.Distance(newSite, site) <= minDistance) { tooClose = true; break; } } if (!tooClose && !(newSite.X == 0 || newSite.X == size || newSite.Y == 0 || newSite.Y == size)) { sites.Add(newSite); } else { i--; } } graphEdges = voronoiGraph.MakeVoronoiGraph(sites, size, size); graphCells = CaveGenerator.GraphEdgesToCells(graphEdges, new Rectangle(0, 0, size, size), (float)size, out graphCellsGrid); sites.Clear(); }
private Voronoi ComputeVoronoi(out double delaunayElapsedMs, out double voronoiElapsedMs) { // Compute Delaunay & Voronoi Voronoi voronoi = null; if (_delaunayMethod == 0) { var points = _points.Select(e => e.Loc).Distinct().ToArray(); voronoi = new VoronoiIncremental(points, _showDiagnostics); } else { var points = _points.Select(e => e.Loc).ToArray(); voronoi = new VoronoiSweepCircle(points, _showDiagnostics); } // Calculate Delaunay triangulation var calcTimeStart = _watch.Elapsed.TotalMilliseconds; voronoi.CalculateDelaunay(); delaunayElapsedMs = _watch.Elapsed.TotalMilliseconds - calcTimeStart; // Calculate Voronoi calcTimeStart = _watch.Elapsed.TotalMilliseconds; if (_showVoronoi) { voronoi.CalculateVoronoi(ViewportWidth(), ViewportHeight()); } voronoiElapsedMs = _watch.Elapsed.TotalMilliseconds - calcTimeStart; return(voronoi); }
public static Voronoi Relax(Voronoi voronoi, Vector2 bounds1, Vector2 bounds2, int amount = 100) { Voronoi newVoronoi; HashSet<Vector2> sites = new HashSet<Vector2>(); Vector2 centroidRemember; foreach (KeyValuePair<Vector2, Polygon> poly in voronoi.Polygons) { centroidRemember = PolygonCentroid(poly.Value); if (centroidRemember.x != -Mathf.Infinity && centroidRemember.y != -Mathf.Infinity && centroidRemember.x != Mathf.Infinity && centroidRemember.y != Mathf.Infinity && centroidRemember.x > bounds1.x && centroidRemember.y > bounds1.y && centroidRemember.x < bounds2.x && centroidRemember.y < bounds2.y) { sites.Add(centroidRemember); } else { sites.Add(poly.Value.MidPoint.Point); } } amount--; newVoronoi = Delaunay.DeriveVoronoi(sites.ToList(), Delaunay.Triangulate(sites.ToList())); if (amount <= 0) { return newVoronoi; } else { return Relax(newVoronoi, bounds1, bounds2, amount); } }
private void menuViewVoronoi_Click(object sender, EventArgs e) { if (mesh == null) { return; } if (menuViewVoronoi.Checked) { renderManager.ShowVoronoi = false; menuViewVoronoi.Checked = false; return; } IVoronoi voronoi; if (mesh.IsPolygon) { voronoi = new BoundedVoronoi(mesh); } else { voronoi = new Voronoi(mesh); } renderData.SetVoronoi(voronoi); renderManager.SetData(renderData); menuViewVoronoi.Checked = true; }
public VoronoiSpawnGenerator(Vector3[] playerSpawns, float minSpacing, float maxDrift, float maxX, float maxZ) { this.minSpacing = minSpacing; this.playerSpawns = playerSpawns; this.maxDrift = maxDrift; this.maxX = maxX; this.maxZ = maxZ; // build site list, translating x,z to x,y var sites = new Vector2[playerSpawns.Length]; for (var i = 0; i < playerSpawns.Length; i++) { sites[i] = new Vector2(playerSpawns[i].x, playerSpawns[i].z); } var size = new Vector3(maxX, maxZ, 0); var bounds = new Bounds(size / 2f, size); this.voronoi = new Voronoi(bounds, sites); voronoi.Compute(); for (var i = 0; i < voronoi.edgeList.Count; i++) { var edge = voronoi.edgeList[i]; Debug.DrawLine( new Vector3(edge.vertices[0].x, 100, edge.vertices[0].y), new Vector3(edge.vertices[1].x, 100, edge.vertices[1].y), Color.red, 300); } }
public static void testPreset(out ModuleBase finalTerrain, out ModuleBase finalTexture) { float f; finalTexture = buildTexture(new Dictionary <Sub, double>(), out f, 1, new System.Random(1)); float scale = 100000f; finalTerrain = new Voronoi(1 / scale, 0, 2623246, true); /*finalTerrain = new Billow(1/scale, * 2, * .5, * 1, * 123414,//Random.Range(int.MinValue, int.MaxValue), * QualityMode.High);*/ /* Curve c = new Curve(finalTerrain); * c.Add(-1, 0); * c.Add(0, 0); * c.Add(.5, 0); * c.Add(1, -1);*/ //finalTerrain = new Min(new Const(-.9), new Invert(finalTerrain)); finalTerrain = new ScaleBias(scale * .5, 0, finalTerrain); //finalTerrain = new Invert(finalTerrain); }
public static void SortSites(List <Site> sites) { sites.Sort(delegate(Site s0, Site s1) { int returnValue = Voronoi.CompareByYThenX(s0, s1); int tempIndex; if (returnValue == -1) { if (s0.siteIndex > s1.SiteIndex) { tempIndex = s0.SiteIndex; s0.SiteIndex = s1.SiteIndex; s1.SiteIndex = tempIndex; } } else if (returnValue == 1) { if (s1.SiteIndex > s0.SiteIndex) { tempIndex = s1.SiteIndex; s1.SiteIndex = s0.SiteIndex; s0.SiteIndex = tempIndex; } } return(returnValue); }); }
public int CompareTo(Site s1) { int returnValue = Voronoi.CompareByYThenX(this, s1); int tempIndex; if (returnValue == -1) { if (this.siteIndex > s1.SiteIndex) { tempIndex = this.SiteIndex; this.SiteIndex = s1.SiteIndex; s1.SiteIndex = tempIndex; } } else if (returnValue == 1) { if (s1.SiteIndex > this.SiteIndex) { tempIndex = s1.SiteIndex; s1.SiteIndex = this.SiteIndex; this.SiteIndex = tempIndex; } } return(returnValue); }
static bool GenVoronoi(Player p, Level lvl, string seed) { Voronoi voronoi2D = new Voronoi(); voronoi2D.Seed = MapGen.MakeInt(seed); return(Gen2D(lvl, voronoi2D)); }
void Triangulate() { List <Vector2> points = new List <Vector2>(); List <uint> colors = new List <uint>(); Vector2 min = Vector2.positiveInfinity; Vector2 max = Vector2.zero; foreach (GeneratorCell c in cells) { if (c.isMainRoom) { colors.Add(0); points.Add(new Vector2(c.posX + (c.width / 2), c.posY + (c.height / 2))); min.x = Mathf.Min(c.posX, min.x); min.y = Mathf.Min(c.posY, min.y); max.x = Mathf.Max(c.posX, max.x); max.y = Mathf.Max(c.posY, max.y); } } Voronoi v = new Voronoi(points, colors, new Rect(min.x, min.y, max.x, max.y)); delaunayLines = v.DelaunayTriangulation(); spanningTree = v.SpanningTree(KruskalType.MINIMUM); }
void Start() { // Scale the quad Vector3 temp = transform.localScale; temp.x = 25.0f; temp.y = 25.0f; transform.localScale = temp; // Modify the position of the model Vector3 pos = transform.localPosition; pos.z = 3; transform.localPosition = pos; // Create your sites (lets call that the center of your polygons) List <Vector2f> points = CreateRandomPoint(); // Create the bounds of the voronoi diagram // Use Rectf instead of Rect; it's a struct just like Rect and does pretty much the same, // but like that it allows you to run the delaunay library outside of unity (which mean also in another tread) Rectf bounds = new Rectf(0, 0, 512, 512); // There is a two ways you can create the voronoi diagram: with or without the lloyd relaxation // Here I used it with 2 iterations of the lloyd relaxation voronoi = new Voronoi(points, bounds); // Now retreive the edges from it, and the new sites position if you used lloyd relaxtion sites = voronoi.SitesIndexedByLocation; edges = voronoi.Edges; DisplayVoronoiDiagram(); }
protected override void DoGenerate() { m_points = new List <Vector2>(); m_regions = new List <VoronoiRegion>(); for (int i = 0; i < NumPoints; ++i) { float x = Random.value; float y = Random.value; m_points.Add(new Vector2(x, y)); } Voronoi voronoi = new Voronoi(m_points, new Rectf(0.0f, 0.0f, 1.0f, 1.0f), 30); m_points = voronoi.SiteCoords(); foreach (var region in voronoi.Regions()) { VoronoiRegion newRegion = new VoronoiRegion(); newRegion.regionPoints = region; newRegion.isWater = Random.Range(0, 2) == 0; m_regions.Add(newRegion); } }
void Start() { // Create your sites center off vornoi cells //these points are used as spawn positions for the trash List <Vector2f> points = CreateRandomPoint(); // Create the bounds of the voronoi diagram Rectf bounds = new Rectf(0, 0, AreaDimensions, AreaDimensions); // There is a two ways you can create the voronoi diagram: with or without the lloyd relaxation // Vornoi with lloyd relaxation Voronoi voronoi = new Voronoi(points, bounds); if (UseLloydRelaxation) { voronoi.LloydRelaxation(LloydFactor); } // Now retreive the edges from it, and the new sites position if you used lloyd relaxtion sites = voronoi.SitesIndexedByLocation; //edge calculation is not needed //edges = voronoi.Edges; Display(); }
public static IModule Voronoi(float frequency) { var module = new Voronoi(); ((Voronoi)module).Frequency = frequency; return(module); }
public void Face_VoronoiFortune() { List <VertexKDTree> listPointsFortune = new List <VertexKDTree>(); string fileNameLong = pathUnitTests + "\\KinectFace_1_15000.obj"; pointCloudSource = IOUtils.ReadObjFile_ToPointCloud(fileNameLong); for (int i = 0; i < pointCloudSource.Count; i++) { VertexKDTree v = new VertexKDTree(new Vector3(pointCloudSource[i].Vector.X, pointCloudSource[i].Vector.Y, pointCloudSource[i].Vector.Z), i); listPointsFortune.Add(v); } List <EdgeFortune> listEdges; Voronoi voronoi = new Voronoi(0.1f); listEdges = voronoi.GenerateVoronoi(listPointsFortune); List <LineD> myLines = new List <LineD>(); for (int i = 0; i < listEdges.Count; i++) { EdgeFortune edge = listEdges[i]; myLines.Add(new LineD(pointCloudSource[edge.PointIndex1].Vector, pointCloudSource[edge.PointIndex2].Vector)); } //------------------- ShowPointCloud(pointCloudSource); }
void Start() { // Create your sites (lets call that the center of your polygons) List <Vector2f> points = CreateRandomPoint(); // Create the bounds of the voronoi diagram // Use Rectf instead of Rect; it's a struct just like Rect and does pretty much the same, // but like that it allows you to run the delaunay library outside of unity (which mean also in another tread) Rectf bounds = new Rectf(0, 0, 512, 512); // There is a two ways you can create the voronoi diagram: with or without the lloyd relaxation // Here I used it with 2 iterations of the lloyd relaxation Voronoi voronoi = new Voronoi(points, bounds, 5); // But you could also create it without lloyd relaxtion and call that function later if you want //Voronoi voronoi = new Voronoi(points,bounds); //voronoi.LloydRelaxation(5); // Now retreive the edges from it, and the new sites position if you used lloyd relaxtion sites = voronoi.SitesIndexedByLocation; edges = voronoi.Edges; //DisplayVoronoiDiagram(); foreach (KeyValuePair <Vector2f, Site> kv in sites) { kv.Value.Region(bounds); } DisplayVoronoiDiagram(); meshifyV(); }
private void DrawSubdivision(Subdivision division) { // generate new random subdivision if desired if (division == null) { PointD offset = new PointD(OutputBox.Width * 0.2, OutputBox.Height * 0.2); SizeD scale = new SizeD(OutputBox.Width * 0.6, OutputBox.Height * 0.6); int count = MersenneTwister.Default.Next(4, 12); PointD[] points = new PointD[count]; for (int i = 0; i < points.Length; i++) { points[i] = new PointD( offset.X + MersenneTwister.Default.NextDouble() * scale.Width, offset.Y + MersenneTwister.Default.NextDouble() * scale.Height); } // outer bounds for Voronoi pseudo-vertices double margin = 3 * FontSize; RectD bounds = new RectD(margin, margin, OutputBox.Width - 2 * margin, OutputBox.Height - 2 * margin); var result = Voronoi.FindAll(points, bounds); division = result.ToVoronoiSubdivision().Source; } _division = division; _division.Validate(); _nearestEdge = -1; _edges = DrawSubdivision(OutputBox, FontSize, division); OutputBox.Children.Add(VertexCircle); }
private void Demo() { GenerateSimplexPlane(); m_points = new List <Vector2>(); m_colors = new List <uint>(); for (int i = 0; i < m_pointCount; i++) { m_colors.Add(RandomUintColor()); m_points.Add(new Vector2( UnityEngine.Random.Range(0, m_mapWidth), UnityEngine.Random.Range(0, m_mapHeight)) ); } //Delaunay.Voronoi v = new Delaunay.Voronoi (m_points, m_colors, new Rect (0, 0, m_mapWidth, m_mapHeight)); m_voronoi = new Delaunay.Voronoi(m_points, m_colors, new Rect(0, 0, m_mapWidth, m_mapHeight)); //m_edges = v.VoronoiDiagram(); m_edges = m_voronoi.VoronoiDiagram(); m_spanningTree = m_voronoi.SpanningTree(KruskalType.MINIMUM); m_delaunayTriangulation = m_voronoi.DelaunayTriangulation(); tmpVBoundary = m_voronoi.VoronoiBoundaryForSite(m_points[0]); //DrawVoronoiPolygon(m_points[0]); AssignSimplexColors(); }
private static Voronoi _calculateVoronoi(Grid grid, List <double[]> points, List <double[]> boundary) { var n = points.Count; var allPoints = new List <double[]>(points); if (boundary != null) { allPoints.AddRange(boundary); } var delauny = fromPoints(allPoints); var voronoi = new Voronoi() { s_triangles_r = delauny.triangles, s_halfedges_s = delauny.halfedges, }; var voronoiCell = new VoronoiCells(voronoi, allPoints, n); grid.cells = voronoiCell.cells; grid.cells.i = D3.range(n); grid.vertices = voronoiCell.vertices; return(voronoi); }
public static float[,] Generate(int width, int height, int seed, int flatness, int voronoi_iterations, int voronoi_start) { // Create the module network ModuleBase moduleBase; moduleBase = new RidgedMultifractal(); Noise2D sound = new Noise2D(width, height, moduleBase); sound.GeneratePlanar( -1, 1, -1, 1, true); for (int i = 0; i <= voronoi_iterations; i++) { seed++; ModuleBase tempBase = new Voronoi(voronoi_start + i, displacement, seed, false); Noise2D temp = new Noise2D(width, height, tempBase); temp.GeneratePlanar( -1, 1, -1, 1, true); LayerNoise(sound, tempBase); ModuleBase pBase = new Perlin() { OctaveCount = perlinOctaves }; LayerNoise(sound, pBase); } Flatten(sound, flatness); return(sound.GetData()); }
public IEnumerator RedoRandom20TimesWith3000PointsTest() { Voronoi.FlushPools(); Voronoi.InitPools(12500, 9000, 40, 11000); var points = VoronoiTest.CreateRandomPoints(3000); Voronoi voronoi = VoronoiTest.TestVoronoi(points); yield return(null); for (int i = 0; i < 20; i++) { points = VoronoiTest.CreateRandomPoints(3000); Profiler.BeginSample("NoGC Voronoi.Redo 20x3000 random points"); voronoi.Redo(points, VoronoiTest.TestBounds()); Profiler.EndSample(); yield return(null); } Debug.Log(voronoi.DebugCapacities()); yield return(null); }
private static void SewBorder(Voronoi graph) { var farSide = (int)(graph.PlotBounds.width + graph.PlotBounds.x); var borderSites = graph.SitesIndexedByLocation.Values.Where(s => s.IsBorderedOnSeamSite); foreach (var s in borderSites) { var p = new Point(farSide, (int)s.y); var distances = new Dictionary <Site, int>(); var sites = graph.SitesIndexedByLocation.Where(st => st.Key.x > farSide - 150); foreach (var site in sites) { distances.Add(site.Value, Mathf.RoundToInt(Boundary.DistanceBetween(new Point(p.x, s.Coord.y), new Point(site.Key.x, site.Key.y)))); } // Get the closest distance pair. var d = distances.OrderBy(kvp => kvp.Value).First(); s.FalseNeighbours.Add(d.Key); d.Key.FalseNeighbours.Add(s); } }
public void Generate(Voronoi voronoi, Generation world, Zone zone) { List <LineSegment> fences = voronoi.VoronoiBoundaryForSite(new Vector2(transform.position.x, transform.position.z)); for (int i = 0; i < fences.Count; i++) { if (world.builtFences.Contains(fences[i])) { fences.RemoveAt(i); } } for (int i = 0; i < fences.Count; i++) { Vector2 left = (Vector2)fences[i].p0; Vector2 right = (Vector2)fences[i].p1; Vector3 startPos = new Vector3(left.x, 100f, left.y); Vector3 endPos = new Vector3(right.x, 100f, right.y); float distance = Vector3.Distance(startPos, endPos); int ammountOfFences = Mathf.RoundToInt(distance / fenceLength); for (int fenceIndex = 0; fenceIndex < ammountOfFences; fenceIndex++) { Vector3 spawnPosition = Vector3.Lerp(startPos, endPos, 1f / ammountOfFences * fenceIndex); Quaternion spawnRotation = Quaternion.LookRotation(endPos - spawnPosition); GameObject fenceInstance = Instantiate(zone.fence, spawnPosition, spawnRotation); } } foreach (var fence in fences) { world.builtFences.Add(fence); } }
private Texture2D texture; // texture created for testing #endregion Fields #region Methods void Generate(bool addToSeed) { Voronoi mySphere = new Voronoi(); mySphere.Seed = seedToModify; // ------------------------------------------------------------------------------------------ // - Compiled Terrain - Debug.LogError ("Not fetching seed data for planets!"); ModuleBase myModule; myModule = mySphere; // ------------------------------------------------------------------------------------------ // - Generate - // this part generates the heightmap to a texture, // and sets the renderer material texture of a sphere to the generated texture Noise2D heightMap; heightMap = new Noise2D( mapSizeX, mapSizeY, myModule ); heightMap.GenerateSpherical( south, north, west, east ); texture = heightMap.GetTexture(GradientPresets.RGBA); sphereRenderer.material.mainTexture = texture; sphereRenderer.material.SetTexture("_Normals",texture); }
private static void GenerateTectonicShifts(Voronoi graph, int iterations) { for (int i = 0; i < iterations; i++) { foreach (var plate in graph.Plates) { foreach (var site in plate.Sites) { foreach (var s in site.GetNeighbouringTectonicPlateSites()) { var p = plate.NeighbourPlates.FirstOrDefault(np => np.Key.Equals(s.TectonicPlate)); s.MapWeight += p.Value; if (s.MapWeight > 255) { s.MapWeight = 255; } if (s.MapWeight < 0) { s.MapWeight = 0; } } } } } // To gamify it a little foreach (var site in graph.SitesIndexedByLocation.Where(s => s.Value.IsNorthPoleSite || s.Value.IsSouthPoleSite)) { site.Value.MapWeight = 255; } }
public void Generate() { // Create the module network ModuleBase moduleBase; switch(noise) { case NoiseType.Billow: moduleBase = new Billow(); break; case NoiseType.RiggedMultifractal: moduleBase = new RiggedMultifractal(); break; case NoiseType.Voronoi: moduleBase = new Voronoi(); break; case NoiseType.Mix: Perlin perlin = new Perlin(); RiggedMultifractal rigged = new RiggedMultifractal(); moduleBase = new Add(perlin, rigged); break; default: moduleBase = new Perlin(); break; } // Initialize the noise map this.m_noiseMap = new Noise2D(resolution, resolution, moduleBase); this.m_noiseMap.GeneratePlanar( offset + -1 * 1/zoom, offset + offset + 1 * 1/zoom, offset + -1 * 1/zoom, offset + 1 * 1/zoom); Debug.Log (moduleBase.GetValue (0, 0, UnityEngine.Random.value)); // Generate the textures this.m_textures[0] = this.m_noiseMap.GetTexture(LibNoise.Unity.Gradient.Grayscale); this.m_textures[0].Apply(); this.m_textures[1] = this.m_noiseMap.GetTexture(LibNoise.Unity.Gradient.Terrain); this.m_textures[1].Apply(); this.m_textures[2] = this.m_noiseMap.GetNormalMap(3.0f); this.m_textures[2].Apply(); //display on plane GetComponent<Renderer>().material.mainTexture = m_textures[0]; //write images to disk File.WriteAllBytes(Application.dataPath + "/../Gray.png", m_textures[0].EncodeToPNG() ); File.WriteAllBytes(Application.dataPath + "/../Terrain.png", m_textures[1].EncodeToPNG() ); File.WriteAllBytes(Application.dataPath + "/../Normal.png", m_textures[2].EncodeToPNG() ); Debug.Log("Wrote Textures out to "+Application.dataPath + "/../"); }
public void Relax(int nIterations) { if (m_voronoi == null) { Gen (); } m_voronoi = m_voronoi.Relax(nIterations); m_edges = m_voronoi.ComputeVoronoiDiagram (); Debug.Log ("Relax done!"); }
protected override ModuleBase CreateAndReadyModule() { Voronoi voronoi = new Voronoi(); voronoi.Seed = seed; voronoi.Frequency = frequency; voronoi.Displacement = displacement; voronoi.UseDistance = enableDistance; return voronoi; }
public Noise(float s, float p, float o, Calculate c, Generator g) { scale = s; power = p; offset = o; calc = c; if (g == Generator.Vonoroi) vonoroi = Generators.Vonoroi(0.1, offset); else if (g == Generator.Perlin) perlin = Generators.Perlin(0.1, offset); else if (g == Generator.Billow) billow = Generators.Billow(0.1, offset); generator = g; }
internal void FixFaultyEdges(Voronoi voronoi, VoronoiSettings settings) { var semiEdges = voronoi.Edges.Where( e => (_mapHelper.IsOutOfMap(e.Start, settings.Width * 2, settings.Height) && !_mapHelper.IsOutOfMap(e.End, settings.Width * 2, settings.Height)) || (!_mapHelper.IsOutOfMap(e.Start, settings.Width * 2, settings.Height) && _mapHelper.IsOutOfMap(e.End, settings.Width * 2, settings.Height))); foreach (var semiEdge in semiEdges) { FixFaultyEdge(semiEdge, settings.Width * 2, settings.Height); } }
// Use this for initialization void Start() { IModule primaryGranite = new Billow(); ((Billow)primaryGranite).Seed = 0; ((Billow)primaryGranite).Frequency = 8.0; ((Billow)primaryGranite).Persistence = 0.625; ((Billow)primaryGranite).Lacunarity = 2.18359375; ((Billow)primaryGranite).OctaveCount = 6; ((Billow)primaryGranite).NoiseQuality = NoiseQuality.Standard; IModule baseGrains = new Voronoi(); ((Voronoi)baseGrains).Seed = 1; ((Voronoi)baseGrains).Frequency = 16.0; ((Voronoi)baseGrains).EnableDistance = true; IModule scaledGrains = new ScaleBias(baseGrains); ((ScaleBias)scaledGrains).Scale = -0.5; ((ScaleBias)scaledGrains).Bias = 0.0; IModule combinedGranite = new Add(primaryGranite, scaledGrains); IModule finalGranite = new Turbulence(combinedGranite); ((Turbulence)finalGranite).Seed = 2; ((Turbulence)finalGranite).Frequency = 4.0; ((Turbulence)finalGranite).Power = 1.0 / 8.0; ((Turbulence)finalGranite).Roughness = 6; NoiseMapBuilderPlane plane = new NoiseMapBuilderPlane(256, 256); plane.SetBounds(-1.0, 1.0, -1.0, 1.0); plane.Build(finalGranite); RendererImage render = new RendererImage(); render.SourceNoiseMap = plane.Map; render.ClearGradient (); render.AddGradientPoint (-1.0000, new Color32( 0, 0, 0, 255)); render.AddGradientPoint (-0.9375, new Color32( 0, 0, 0, 255)); render.AddGradientPoint (-0.8750, new Color32(216, 216, 242, 255)); render.AddGradientPoint ( 0.0000, new Color32(191, 191, 191, 255)); render.AddGradientPoint ( 0.5000, new Color32(210, 116, 125, 255)); render.AddGradientPoint ( 0.7500, new Color32(210, 113, 98, 255)); render.AddGradientPoint ( 1.0000, new Color32(255, 176, 192, 255)); render.IsLightEnabled = true; render.LightAzimuth = 135.0; render.LightElev = 60.0; render.LightContrast = 2.0; render.LightColor = new Color32(255, 255, 255, 0); render.Render(); tex = render.GetTexture(); }
void Start() { List<Vector2> points = GetRandomPoints(); Rect size = new Rect(0, 0, 100, 100); Voronoi voronoi = new Voronoi(points, null, size); foreach (Vector2 point in points) { List<Vector2> region = voronoi.Region(point); for (int i = 0; i < region.Count; i++) { Vector2 next = i < region.Count - 1 ? region[i + 1] : region[0]; Debug.DrawLine(region[i], next, Color.white, 1000); } } }
float CellArea(Voronoi.Cell cell) { float area = 0.0f; Point p1, p2; for (int iHalfEdge = cell.halfEdges.Count - 1; iHalfEdge >= 0; iHalfEdge--) { HalfEdge halfEdge = cell.halfEdges[iHalfEdge]; p1 = halfEdge.GetStartPoint(); p2 = halfEdge.GetEndPoint(); area += p1.x * p2.y; area -= p1.y * p2.x; } area /= 2; return area; }
// === Map methods === public Map(int w_in, int h_in, int regions_in, int dist, int relaxSteps) { width = w_in; height = h_in; regions = regions_in; distanceTwixtSites = dist; colors = new Color[width*height]; ClearColors(Color.black); double[] xVal = new double[regions], yVal = new double[regions]; // used by voronoi below // === Generating === // Generate random points for (int j=0;j<regions;j++) { xVal[j] = Random.Range(0,width-1); yVal[j] = Random.Range(0,height-1); } // Generate voronoi cells graph Voronoi voroObject = new Voronoi ( distanceTwixtSites ); List<GraphEdge> regionBorders = voroObject.generateVoronoi ( xVal, yVal, 0, width-1, 0, height-1 ); for (int i=0; i<relaxSteps; i++) { // Relax voronoi cell centers sites = RelaxVoronoi(regionBorders); foreach (Site s in sites.Values) { xVal[s.id] = s.coordLocation.x; yVal[s.id] = s.coordLocation.y; } // Regenerate cells regionBorders = voroObject.generateVoronoi ( xVal, yVal, 0, width-1, 0, height-1 ); } // Final smoothing regionBorders = voroObject.generateVoronoi ( xVal, yVal, 0, width-1, 0, height-1 ); sites = RelaxVoronoi(regionBorders); GenerateEdgeMap(); // GenerateAdjacencyMap(); }
Point CellCentroid(Voronoi.Cell cell) { float x = 0f; float y = 0f; Point p1, p2; float v; for (int iHalfEdge = cell.halfEdges.Count - 1; iHalfEdge >= 0; iHalfEdge--) { HalfEdge halfEdge = cell.halfEdges[iHalfEdge]; p1 = halfEdge.GetStartPoint(); p2 = halfEdge.GetEndPoint(); v = p1.x * p2.y - p2.x * p1.y; x += (p1.x + p2.x) * v; y += (p1.y + p2.y) * v; } v = CellArea(cell) * 6; return new Point(x / v, y / v); }
public void Gen() { // generate set of random points m_points = new List<Vector2> (); for (int i = 0; i < m_pointCount; i++) { m_points.Add (new Vector2 ( UnityEngine.Random.Range (0, m_mapWidth), UnityEngine.Random.Range (0, m_mapHeight)) ); } // generate voronoi region if (m_voronoi != null) { m_voronoi.Dispose(); } m_voronoi = new Delaunay.Voronoi (m_points, new Rect (0, 0, m_mapWidth, m_mapHeight)); m_edges = m_voronoi.ComputeVoronoiDiagram (); //m_spanningTree = v.SpanningTree (KruskalType.MINIMUM); //m_delaunayTriangulation = v.DelaunayTriangulation (); Debug.Log ("Gen done!"); }
public static Island VoronoiToIsland(Voronoi v, Vector2 bottomLeft, Vector2 topRight) { List<IslandPolygon> islandPoly = new List<IslandPolygon>(); bool isWater = true; foreach (VoronoiEdge edge in v.Edges.OrderBy(x => x.Midpoint.Point.x).ThenBy(x => x.Midpoint.Point.y)) { foreach (Polygon poly in v.Polygons.Values) { isWater = true; if (poly.MidPoint.Point == edge.Midpoint.Point) { if (Mathf.Abs(poly.PerlinNoise - Mathf.Abs(poly.MidPoint.Point.x) - Mathf.Abs(poly.MidPoint.Point.y)) < 25F) { isWater = false; islandPoly.Add(new IslandPolygon(poly, isWater)); break; } else { islandPoly.Add(new IslandPolygon(poly, isWater)); break; } } } } return new Island(islandPoly, bottomLeft, topRight); }
public void GenerateRegions() { List<Vector2> points = new List<Vector2> (); dimensions = new Vector2(Map.terrainSize.tileSize, Map.terrainSize.tileSize); // 1. generate points GeneratePoints (points); if (voronoi != null) { voronoi.Dispose(); } // 2. generate voronoi regions voronoi = new Delaunay.Voronoi (points, new Rect (0, 0, dimensions.x, dimensions.y)); // 3. relax, to make regions a bit more uniform //m_voronoi = m_voronoi.Relax (1); // 4a. get sites defining the island boundary hullSites = voronoi.GetHullSites (); // 4b. get dalaunay boundary //m_delaunayHullSegments = m_voronoi.GetHullLineSegments (); // 4c. get edges for drawing voronoiEdges = voronoi.ComputeVoronoiDiagram (); // 5. Initialize additional structure information InitSiteData (); // force a re-draw debugDraw = null; }
public VoronoiPolygon(Voronoi parentDiagram_, VoronoiPoint original_, Color color_) { parentDiagram = parentDiagram_; originalPoint = original_; color = color_; }
/// <summary> /// Upon every node visited during the traversal, increase boundary distance by 1! /// </summary> void _PreprocessSites(Voronoi.SiteTraversalNode<MapCell> current, Voronoi.SiteTraversalNode<MapCell> previous) { current.data = CreateCell(current.site); // the next node's distance to the boundary is the min of all previous distances + 1 var visitedNeighbors = current.neighbors .Where (neighbor => neighbor.data != null); int distance; if (!visitedNeighbors.Any ()) { // current node is a root distance = 1; } else { // current node is not a root distance = visitedNeighbors .Select (neighbor => neighbor.data.distanceFromBoundary + 1) .Min (); } current.data.distanceFromBoundary = distance; current.data.neighborSites = current.neighbors.Select (neighborNode => neighborNode.site).ToArray(); if (current.site.id < 2) { // Debug.Log(current.site.id + ": " + string.Join (", ", current.site.GetNeighborSites().Select (neighborSite => neighborSite.id.ToString()).ToArray())); } }
private static List<LoadedModule> GetModules(XmlNodeList moduleList) { List<LoadedModule> loadedModules = new List<LoadedModule>(); foreach (XmlNode node in moduleList) { string id = node.Attributes["guid"].Value; Point position = new Point(double.Parse(node.Attributes["position"].Value.Split(',')[0]), double.Parse(node.Attributes["position"].Value.Split(',')[1])); ModuleBase module = null; List<string> links = new List<string>(); switch (node.Attributes["type"].Value) { case "Billow": Billow billow = new Billow(); billow.Frequency = double.Parse(node.SelectSingleNode("Frequency").InnerText); billow.Lacunarity = double.Parse(node.SelectSingleNode("Lacunarity").InnerText); billow.OctaveCount = int.Parse(node.SelectSingleNode("OctaveCount").InnerText); billow.Persistence = double.Parse(node.SelectSingleNode("Persistence").InnerText); billow.Quality = (QualityMode)Enum.Parse(typeof(QualityMode), node.SelectSingleNode("Quality").InnerText); billow.Seed = int.Parse(node.SelectSingleNode("Seed").InnerText); module = billow; break; case "Checker": module = new Checker(); break; case "Const": Const con = new Const(); con.Value = double.Parse(node.SelectSingleNode("Value").InnerText); module = con; break; case "Cylinders": Cylinders cylinder = new Cylinders(); cylinder.Frequency = double.Parse(node.SelectSingleNode("Frequency").InnerText); module = cylinder; break; case "Perlin": Perlin perlin = new Perlin(); perlin.Frequency = double.Parse(node.SelectSingleNode("Frequency").InnerText); perlin.Lacunarity = double.Parse(node.SelectSingleNode("Lacunarity").InnerText); perlin.OctaveCount = int.Parse(node.SelectSingleNode("OctaveCount").InnerText); perlin.Persistence = double.Parse(node.SelectSingleNode("Persistence").InnerText); perlin.Quality = (QualityMode)Enum.Parse(typeof(QualityMode), node.SelectSingleNode("Quality").InnerText); perlin.Seed = int.Parse(node.SelectSingleNode("Seed").InnerText); module = perlin; break; case "RidgedMultifractal": RidgedMultifractal ridgedMF = new RidgedMultifractal(); ridgedMF.Frequency = double.Parse(node.SelectSingleNode("Frequency").InnerText); ridgedMF.Lacunarity = double.Parse(node.SelectSingleNode("Lacunarity").InnerText); ridgedMF.OctaveCount = int.Parse(node.SelectSingleNode("OctaveCount").InnerText); ridgedMF.Quality = (QualityMode)Enum.Parse(typeof(QualityMode), node.SelectSingleNode("Quality").InnerText); ridgedMF.Seed = int.Parse(node.SelectSingleNode("Seed").InnerText); module = ridgedMF; break; case "Spheres": Spheres spheres = new Spheres(); spheres.Frequency = double.Parse(node.SelectSingleNode("Frequency").InnerText); module = spheres; break; case "Voronoi": Voronoi voronoi = new Voronoi(); voronoi.Frequency = double.Parse(node.SelectSingleNode("Frequency").InnerText); voronoi.Displacement = double.Parse(node.SelectSingleNode("Displacement").InnerText); voronoi.UseDistance = bool.Parse(node.SelectSingleNode("UseDistance").InnerText); voronoi.Seed = int.Parse(node.SelectSingleNode("Seed").InnerText); module = voronoi; break; case "Abs": module = new Abs(); XmlNode absInputs = node.SelectSingleNode("ModuleInputs"); links.Add(absInputs.SelectSingleNode("Input").InnerText); break; case "Add": module = new Add(); XmlNode addInputs = node.SelectSingleNode("ModuleInputs"); links.Add(addInputs.SelectSingleNode("Left").InnerText); links.Add(addInputs.SelectSingleNode("Right").InnerText); break; case "Blend": module = new Blend(); XmlNode blendInputs = node.SelectSingleNode("ModuleInputs"); links.Add(blendInputs.SelectSingleNode("Left").InnerText); links.Add(blendInputs.SelectSingleNode("Right").InnerText); links.Add(blendInputs.SelectSingleNode("Operator").InnerText); break; case "Cache": module = new Cache(); XmlNode cacheInputs = node.SelectSingleNode("ModuleInputs"); links.Add(cacheInputs.SelectSingleNode("Input").InnerText); break; case "Clamp": Clamp clamp = new Clamp(); clamp.Maximum = double.Parse(node.SelectSingleNode("Maximum").InnerText); clamp.Minimum = double.Parse(node.SelectSingleNode("Minimum").InnerText); module = clamp; XmlNode clampInputs = node.SelectSingleNode("ModuleInputs"); links.Add(clampInputs.SelectSingleNode("Input").InnerText); break; case "Curve": Curve curve = new Curve(); module = curve; foreach (XmlNode cpNode in node.SelectSingleNode("ControlPoints").ChildNodes) { double x = double.Parse(cpNode.InnerText.Split(',')[0]); double y = double.Parse(cpNode.InnerText.Split(',')[1]); curve.Add(x, y); } XmlNode curveInputs = node.SelectSingleNode("ModuleInputs"); links.Add(curveInputs.SelectSingleNode("Input").InnerText); break; case "Displace": module = new Displace(); XmlNode displaceInputs = node.SelectSingleNode("ModuleInputs"); links.Add(displaceInputs.SelectSingleNode("Primary").InnerText); links.Add(displaceInputs.SelectSingleNode("X").InnerText); links.Add(displaceInputs.SelectSingleNode("Y").InnerText); links.Add(displaceInputs.SelectSingleNode("Z").InnerText); break; case "Exponent": Exponent exponent = new Exponent(); exponent.Value = double.Parse(node.SelectSingleNode("Value").InnerText); module = exponent; XmlNode exponentInputs = node.SelectSingleNode("ModuleInputs"); links.Add(exponentInputs.SelectSingleNode("Input").InnerText); break; case "Invert": module = new Invert(); XmlNode invertInputs = node.SelectSingleNode("ModuleInputs"); links.Add(invertInputs.SelectSingleNode("Input").InnerText); break; case "Max": module = new Max(); XmlNode maxInputs = node.SelectSingleNode("ModuleInputs"); links.Add(maxInputs.SelectSingleNode("Left").InnerText); links.Add(maxInputs.SelectSingleNode("Right").InnerText); break; case "Min": module = new Min(); XmlNode minInputs = node.SelectSingleNode("ModuleInputs"); links.Add(minInputs.SelectSingleNode("Left").InnerText); links.Add(minInputs.SelectSingleNode("Right").InnerText); break; case "Multiply": module = new Multiply(); XmlNode multiplyInputs = node.SelectSingleNode("ModuleInputs"); links.Add(multiplyInputs.SelectSingleNode("Left").InnerText); links.Add(multiplyInputs.SelectSingleNode("Right").InnerText); break; case "Power": module = new Power(); XmlNode powerInputs = node.SelectSingleNode("ModuleInputs"); links.Add(powerInputs.SelectSingleNode("Left").InnerText); links.Add(powerInputs.SelectSingleNode("Right").InnerText); break; case "Rotate": Rotate rotate = new Rotate(); rotate.X = double.Parse(node.SelectSingleNode("X").InnerText); rotate.Y = double.Parse(node.SelectSingleNode("Y").InnerText); rotate.Z = double.Parse(node.SelectSingleNode("Z").InnerText); module = rotate; XmlNode rotateInputs = node.SelectSingleNode("ModuleInputs"); links.Add(rotateInputs.SelectSingleNode("Input").InnerText); break; case "Scale": Scale scale = new Scale(); scale.X = double.Parse(node.SelectSingleNode("X").InnerText); scale.Y = double.Parse(node.SelectSingleNode("Y").InnerText); scale.Z = double.Parse(node.SelectSingleNode("Z").InnerText); module = scale; XmlNode scaleInputs = node.SelectSingleNode("ModuleInputs"); links.Add(scaleInputs.SelectSingleNode("Input").InnerText); break; case "ScaleBias": ScaleBias scaleBias = new ScaleBias(); scaleBias.Scale = double.Parse(node.SelectSingleNode("Scale").InnerText); scaleBias.Bias = double.Parse(node.SelectSingleNode("Bias").InnerText); module = scaleBias; XmlNode scaleBiasInputs = node.SelectSingleNode("ModuleInputs"); links.Add(scaleBiasInputs.SelectSingleNode("Input").InnerText); break; case "Select": Select select = new Select(); select.Minimum = double.Parse(node.SelectSingleNode("Minimum").InnerText); select.Maximum = double.Parse(node.SelectSingleNode("Maximum").InnerText); select.FallOff = double.Parse(node.SelectSingleNode("FallOff").InnerText); module = select; XmlNode selectInputs = node.SelectSingleNode("ModuleInputs"); links.Add(selectInputs.SelectSingleNode("Primary").InnerText); links.Add(selectInputs.SelectSingleNode("Secondary").InnerText); links.Add(selectInputs.SelectSingleNode("Controller").InnerText); break; case "Subtract": module = new Subtract(); XmlNode subtractInputs = node.SelectSingleNode("ModuleInputs"); links.Add(subtractInputs.SelectSingleNode("Left").InnerText); links.Add(subtractInputs.SelectSingleNode("Right").InnerText); break; case "Terrace": Terrace terrace = new Terrace(); module = terrace; foreach (XmlNode cpNode in node.SelectSingleNode("ControlPoints").ChildNodes) { terrace.Add(double.Parse(cpNode.InnerText)); } XmlNode terraceInputs = node.SelectSingleNode("ModuleInputs"); links.Add(terraceInputs.SelectSingleNode("Input").InnerText); break; case "Translate": Translate translate = new Translate(); translate.X = double.Parse(node.SelectSingleNode("X").InnerText); translate.Y = double.Parse(node.SelectSingleNode("Y").InnerText); translate.Z = double.Parse(node.SelectSingleNode("Z").InnerText); module = translate; XmlNode translateInputs = node.SelectSingleNode("ModuleInputs"); links.Add(translateInputs.SelectSingleNode("Input").InnerText); break; case "Turbulence": Turbulence turbulence = new Turbulence(); turbulence.Frequency = double.Parse(node.SelectSingleNode("Frequency").InnerText); turbulence.Power = double.Parse(node.SelectSingleNode("Power").InnerText); turbulence.Roughness = int.Parse(node.SelectSingleNode("Roughness").InnerText); turbulence.Seed = int.Parse(node.SelectSingleNode("Seed").InnerText); module = turbulence; XmlNode turbulenceInputs = node.SelectSingleNode("ModuleInputs"); links.Add(turbulenceInputs.SelectSingleNode("Input").InnerText); break; case "Final": module = new Final(); XmlNode finalInputs = node.SelectSingleNode("ModuleInputs"); links.Add(finalInputs.SelectSingleNode("Input").InnerText); break; default: break; } LoadedModule lm = new LoadedModule(id, module, position, links); loadedModules.Add(lm); } return loadedModules; }
void Start() { // Create your sites (lets call that the center of your polygons) List<Vector2f> points = CreateRandomPoint(); // Create the bounds of the voronoi diagram // Use Rectf instead of Rect; it's a struct just like Rect and does pretty much the same, // but like that it allows you to run the delaunay library outside of unity (which mean also in another tread) Rectf bounds = new Rectf(0,0,512,512); // There is a two ways you can create the voronoi diagram: with or without the lloyd relaxation // Here I used it with 2 iterations of the lloyd relaxation Voronoi voronoi = new Voronoi(points,bounds,5); // But you could also create it without lloyd relaxtion and call that function later if you want //Voronoi voronoi = new Voronoi(points,bounds); //voronoi.LloydRelaxation(5); // Now retreive the edges from it, and the new sites position if you used lloyd relaxtion sites = voronoi.SitesIndexedByLocation; edges = voronoi.Edges; MakeVoronoiCells(); }
// Use this for initialization void Start() { // set seed Random.seed = seed; // pick number of polygons polygonNumber = Random.Range (minPolygons, maxPolygons); // get terrain terrain = (Terrain)gameObject.GetComponent ("Terrain"); // get heightmap heightmap = new float[terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapHeight]; tw = terrain.terrainData.heightmapWidth; th = terrain.terrainData.heightmapHeight; // initialize heightmap array and set values to 0 for(int i=0;i<heightmap.GetLength(0);i++){ for(int j=0;j<heightmap.GetLength(1);j++){ heightmap[i,j] = 1f; // for easy identification } } // Create your sites (lets call that the center of your polygons) List<Vector2f> points = CreateRandomPoint(); islands = new List<List<Vector2f>> (); // Create the bounds of the voronoi diagram // Use Rectf instead of Rect; it's a struct just like Rect and does pretty much the same, // but like that it allows you to run the delaunay library outside of unity (which mean also in another tread) Rectf bounds = new Rectf(0,0,512,512); // There is a two ways you can create the voronoi diagram: with or without the lloyd relaxation // Here I used it with 2 iterations of the lloyd relaxation Voronoi voronoi = new Voronoi(points,bounds,5); // Now retreive the edges from it, and the new sites position if you used lloyd relaxtion sites = voronoi.SitesIndexedByLocation; edges = voronoi.Edges; // apply polygons DisplayVoronoiDiagram(); // discover islands //int k = 0; foreach (KeyValuePair<Vector2f,Site> kv in sites) { // create list List<Vector2f> newIsland = new List<Vector2f>(); // choose modifier float mod = (float)Random.Range(0,islandRange); float targh = ((float)minIslandHeight+mod)/terrain.terrainData.size.y; // floodfill FloodFill(kv.Key,1f,targh,newIsland); // add islands.Add(newIsland); // inc //k++; } // generate maze for (int i=0; i<connectionIts; i++) { RandomConnections (); } // add noise heightmap = PerlinNoise (heightmap); // reattatch array to terrain terrain.terrainData.SetHeights(0,0,heightmap); // move player PlacePlayer (); }
void NoiseSelector() { // Requires LibNoise in your project // https://github.com/ricardojmendez/LibNoise.Unity switch (noiseType) { case NoiseMode.Billow: var billow = new Billow(); billow.Seed = seed; billow.Quality = quality; billow.OctaveCount = _octaveCount; billow.Frequency = _frecuency * 0.1; billow.Lacunarity = _lacunarity; billow.Persistence = _persistence; generate = billow; break; case NoiseMode.Perlin: var perlin = new Perlin(); perlin.Seed = seed; perlin.Quality = quality; perlin.OctaveCount = _octaveCount; perlin.Frequency = _frecuency * 0.1; perlin.Lacunarity = _lacunarity; perlin.Persistence = _persistence; generate = perlin; break; case NoiseMode.RidgedMultifractal: var multiFractal = new RidgedMultifractal(); multiFractal.Seed = seed; multiFractal.Quality = quality; multiFractal.OctaveCount = _octaveCount; multiFractal.Frequency = _frecuency * 0.1; multiFractal.Lacunarity = _lacunarity; generate = multiFractal; break; case NoiseMode.Voronoi: var voroni = new Voronoi(); voroni.Seed = seed; voroni.Frequency = _frecuency; voroni.Displacement = _displacement; generate = voroni; break; default: break; } }
IEnumerator Create() { #region Create Random Size & Pos Rooms int counter = 0; int roomAmount = 25; int widthSum = 0; int heightSum = 0; while (counter < roomAmount) { Room room = CreateRandRoom (); room.name = counter.ToString (); rooms.Add (room); counter++; // sum width/height widthSum += room.Width; heightSum += room.Height; yield return new WaitForSeconds (0.05f); } #endregion #region Remove Small Rooms float widthMean = widthSum / roomAmount; float heightMean = heightSum / roomAmount; yield return new WaitForSeconds (4); for (int i = 0; i < rooms.Count; i++) { //rooms[i].RemovePhysics(); rooms [i].ResetRect (); if (rooms [i].Width < widthMean || rooms [i].Height < heightMean) { Destroy (rooms [i].gameObject); rooms.Remove (rooms [i]); i--; } } yield return new WaitForSeconds (0.5f); #endregion #region Create room connection using DelaunayTriangles _points = new List<Vector2> (); for (int i = 0; i < rooms.Count; i++) _points.Add (rooms [i].Position); Rect rect = GetMinRect (rooms); Voronoi v = new Voronoi (_points, null, rect); _edges = v.VoronoiDiagram (); _spanningTree = v.SpanningTree (KruskalType.MINIMUM); _delaunayTriangulation = v.DelaunayTriangulation (); #endregion #region Extra Loop Connection int maxExtraPathAmt = (int)(_delaunayTriangulation.Count * 0.1f); int rand = Random.Range (1, maxExtraPathAmt); Debug.Log (rand); while (rand > 0) { int randIndex = Random.Range (0, _delaunayTriangulation.Count); if (_spanningTree.Contains (_delaunayTriangulation [randIndex])) continue; else { _spanningTree.Add (_delaunayTriangulation [randIndex]); rand--; } } yield return new WaitForSeconds (0.5f); #endregion #region Create HallWays for (int i = 0; i < _spanningTree.Count; i++) { yield return new WaitForSeconds (0.2f); Room room0 = GetRoomFromPos (_spanningTree [i].p0); Room room1 = GetRoomFromPos (_spanningTree [i].p1); Debug.Log ("Creating Hallway Between " + room0.name + " " + room1.name); float xDistance = Mathf.Abs (room0.Position.x - room1.Position.x); float yDistance = Mathf.Abs (room0.Position.y - room1.Position.y); float xMidPointDistance = xDistance / 2; float yMidPointDistance = yDistance / 2; #region Close in X-Axis // mid x point is inside of both rects if (room0.Position.x + xMidPointDistance < room0.rectMaxX// removed equal sign ==> 避免房间刚好快要重叠,防止做路径时麻烦,因为路径瓦片可能会刚好在网格线上 && room1.Position.x + xMidPointDistance < room1.rectMaxX) { Vector2 startPoint = Vector2.zero; Vector2 endPoint = Vector2.zero; // room0 above room1 if (room0.Position.y >= room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set (room0.Position.x + xMidPointDistance, room0.rectMinY); endPoint.Set (room1.Position.x - xMidPointDistance, room1.rectMaxY); } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set (room0.Position.x - xMidPointDistance, room0.rectMinY); endPoint.Set (room1.Position.x + xMidPointDistance, room1.rectMaxY); } } // room1 above room0 else if (room0.Position.y < room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set (room0.Position.x + xMidPointDistance, room0.rectMaxY); endPoint.Set (room1.Position.x - xMidPointDistance, room1.rectMinY); } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set (room0.Position.x - xMidPointDistance, room0.rectMaxY); endPoint.Set (room1.Position.x + xMidPointDistance, room1.rectMinY); } } #endregion // create vertical line HallWay hallway = new HallWay (startPoint, endPoint, room0, room1); _hallways.Add (hallway); room0.AddHallWay (hallway); Debug.Log ("##CloseXAxis created hallway from " + startPoint + " to " + endPoint + " between " + room0.name + " " + room1.name); } #region Close In Y-Axis // mid y point is inside of both rects else if (room0.Position.y + yMidPointDistance < room0.rectMaxY && room1.Position.y + yMidPointDistance < room1.rectMaxY) { Vector2 startPoint = Vector2.zero; Vector2 endPoint = Vector2.zero; // room0 above room1 if (room0.Position.y >= room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set (room0.rectMaxX, room0.Position.y - yMidPointDistance); endPoint.Set (room1.rectMinX, room1.Position.y + yMidPointDistance); } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set (room0.rectMinX, room0.Position.y - yMidPointDistance); endPoint.Set (room1.rectMaxX, room1.Position.y + yMidPointDistance); } } // room1 above room0 else if (room0.Position.y < room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set (room0.rectMaxX, room0.Position.y + yMidPointDistance); endPoint.Set (room1.rectMinX, room1.Position.y - yMidPointDistance); } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set (room0.rectMinX, room0.Position.y + yMidPointDistance); endPoint.Set (room1.rectMaxX, room1.Position.y - yMidPointDistance); } } // create vertical line HallWay hallway = new HallWay (startPoint, endPoint, room0, room1); _hallways.Add (hallway); room0.AddHallWay (hallway); Debug.Log ("##CloseYAxis created hallway from " + startPoint + " to " + endPoint + " between " + room0.name + " " + room1.name); } #endregion #region Far In Both Axis // create L shape hall way else { Vector2 startPoint = Vector2.zero; Vector2 turnPoint = Vector2.zero; Vector2 endPoint = Vector2.zero; // room0 above room1 if (room0.Position.y >= room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set (room0.rectMaxX, room0.Position.y); turnPoint.Set (room0.Position.x + xDistance, room0.Position.y); endPoint.Set (room1.Position.x, room1.rectMaxY); #region Check If Line Collider With Other Room if (LineHasCollision (startPoint, turnPoint, room0.Collider) || LineHasCollision (turnPoint, endPoint, room1.Collider)) { // go other way startPoint.Set (room0.Position.x, room0.rectMinY); turnPoint.Set (room0.Position.x, room0.Position.y - yDistance); endPoint.Set (room1.rectMinX, room1.Position.y); Debug.Log ("go other way"); } // still has collision, delete this segment from spanning tree if (LineHasCollision (startPoint, turnPoint, room0.Collider) || LineHasCollision (turnPoint, endPoint, room1.Collider)) { Debug.Log ("still collision, remove path"); _spanningTree.RemoveAt (i); i--; continue; } #endregion } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set (room0.rectMinX, room0.Position.y); turnPoint.Set (room0.Position.x - xDistance, room0.Position.y); endPoint.Set (room1.Position.x, room1.rectMaxY); #region Check If Line Collider With Other Room if (LineHasCollision (startPoint, turnPoint, room0.Collider) || LineHasCollision (turnPoint, endPoint, room1.Collider)) { // go other way startPoint.Set (room0.Position.x, room0.rectMinY); turnPoint.Set (room0.Position.x, room0.Position.y - yDistance); endPoint.Set (room1.rectMaxX, room1.Position.y); Debug.Log ("go other way"); } // still has collision, delete this segment from spanning tree if (LineHasCollision (startPoint, turnPoint, room0.Collider) || LineHasCollision (turnPoint, endPoint, room1.Collider)) { Debug.Log ("still collison, delete path"); _spanningTree.RemoveAt (i); i--; continue; } #endregion } } // room1 above room0 else if (room0.Position.y < room1.Position.y) { // room0 left to room1 if (room0.Position.x <= room1.Position.x) { startPoint.Set (room0.Position.x, room0.rectMaxY); turnPoint.Set (room0.Position.x, room0.Position.y + yDistance); endPoint.Set (room1.rectMinX, room1.Position.y); #region Check If Line Collider With Other Room if (LineHasCollision (startPoint, turnPoint, room0.Collider) || LineHasCollision (turnPoint, endPoint, room1.Collider)) { // go other way startPoint.Set (room0.rectMaxX, room0.Position.y); turnPoint.Set (room0.Position.x + xDistance, room0.Position.y); endPoint.Set (room1.Position.x, room1.rectMinY); Debug.Log ("go other way"); } // still has collision, delete this segment from spanning tree if (LineHasCollision (startPoint, turnPoint, room0.Collider) || LineHasCollision (turnPoint, endPoint, room1.Collider)) { Debug.Log ("still collision, delete path"); _spanningTree.RemoveAt (i); i--; continue; } #endregion } // room1 left to room0 else if (room0.Position.x > room1.Position.x) { startPoint.Set (room1.rectMaxX, room1.Position.y); turnPoint.Set (room1.Position.x + xDistance, room1.Position.y); endPoint.Set (room0.Position.x, room0.rectMaxY); #region Check If Line Collider With Other Room if (LineHasCollision (startPoint, turnPoint, room1.Collider) || LineHasCollision (turnPoint, endPoint, room0.Collider)) { // go other way startPoint.Set (room1.Position.x, room1.rectMinY); turnPoint.Set (room1.Position.x, room1.Position.y - yDistance); endPoint.Set (room0.rectMinX, room0.Position.y); Debug.Log ("go other way"); } // still has collision, delete this segment from spanning tree if (LineHasCollision (startPoint, turnPoint, room1.Collider) || LineHasCollision (turnPoint, endPoint, room0.Collider)) { Debug.Log ("still collision, delete path"); _spanningTree.RemoveAt (i); i--; continue; } #endregion } } // create vertical line LHallWay hallway = new LHallWay (startPoint, turnPoint, endPoint, room0, room1); _hallways.Add (hallway); room0.AddHallWay (hallway); Debug.Log ("##Lshape created hallway from " + startPoint + " to " + turnPoint + " to " + endPoint + " between " + room0.name + " " + room1.name); } #endregion } #endregion #region Remove Physics for (int i = 0; i < rooms.Count; i++) rooms [i].RemovePhysics (); #endregion #region Create Tiles for (int i = 0; i < rooms.Count; i++) { rooms [i].Fill (); yield return new WaitForSeconds (0.2f); } //for (int i = 0; i < _hallways.Count; i++) { // _hallways [i].Fill (); // yield return new WaitForSeconds (0.2f); //} #endregion }
public List<Vector2> generateRelaxed(int size,int seed) { int i;Vector2 p;Vector2 q;Voronoi voronoi;List<Vector2> region; for(i=0;i<2;i++){ voronoi =new Voronoi(points,null,new Rect(0,0,size,size)); foreach( Vector2 v in points){ region=voronoi.region(v); v=Vector2.zero; foreach(Vector2 v2 in region){ v.x+=v2.x; v.y+=v2.y; } v.x/=region.Count; v.y/=region.Count; region.Clear(); } voronoi.dispose(); } return points; }
private static GameObject generateVoronoiPiece(GameObject source, List<Vector2> region, Vector2 origVelocity, Vector3 origScale, Quaternion origRotation, Material mat) { //Create Game Object and set transform settings properly GameObject piece = new GameObject(source.name + " piece"); piece.transform.position = source.transform.position; piece.transform.rotation = source.transform.rotation; piece.transform.localScale = source.transform.localScale; //Create and Add Mesh Components MeshFilter meshFilter = (MeshFilter)piece.AddComponent(typeof(MeshFilter)); piece.AddComponent(typeof(MeshRenderer)); Mesh uMesh = piece.GetComponent<MeshFilter>().sharedMesh; if (uMesh == null) { meshFilter.mesh = new Mesh(); uMesh = meshFilter.sharedMesh; } Voronoi voronoi = new Voronoi(region, null, getRect(region)); Vector3[] vertices = calcVerts(voronoi); int[] triangles = calcTriangles(voronoi); uMesh.vertices = vertices; uMesh.triangles = triangles; if (source.GetComponent<SpriteRenderer>() != null) { uMesh.uv = calcUV(vertices, source.GetComponent<SpriteRenderer>(), source.transform); } else { uMesh.uv = calcUV(vertices, source.GetComponent<MeshRenderer>(), source.transform); } //set transform properties before fixing the pivot for easier rotation piece.transform.localScale = origScale; piece.transform.localRotation = origRotation; Vector3 diff = calcPivotCenterDiff(piece); centerMeshPivot(piece, diff); uMesh.RecalculateBounds(); uMesh.RecalculateNormals(); //setFragmentMaterial(piece, source); piece.GetComponent<MeshRenderer>().sharedMaterial = mat; //assign mesh meshFilter.mesh = uMesh; //Create and Add Polygon Collider PolygonCollider2D collider = piece.AddComponent<PolygonCollider2D>(); collider.SetPath(0, calcPolyColliderPoints(region,diff)); //Create and Add Rigidbody Rigidbody2D rigidbody = piece.AddComponent<Rigidbody2D>(); rigidbody.velocity = origVelocity; return piece; }
void GenerateNoise() { mountainTerrain.OctaveCount = Octaves; mountainTerrain.Frequency = 2f; baseFlatTerrain.OctaveCount = Octaves; terrainType.OctaveCount = Octaves; Voronoi vnoise = new Voronoi(); vnoise.Frequency = 5f; Perlin pnoise = new Perlin(); pnoise.Frequency = 2f; Scale scaledvnoise = new Scale(Scalarv, Scalarv, Scalarv, vnoise); Scale scaledpnoise = new Scale(Scalarv, Scalarv, Scalarv, pnoise); baseFlatTerrain.Frequency = 2.0f; ScaleBias flatTerrain = new ScaleBias(0.125, -0.75, baseFlatTerrain); terrainType.Frequency = 0.5f; terrainType.Persistence = 0.25; Select noiseSelect = new Select(scaledpnoise, scaledvnoise, terrainType); Select terrainSelector = new Select(flatTerrain, mountainTerrain, terrainType); terrainSelector.SetBounds(0.0, 1000.0); terrainSelector.FallOff = 0.125; Turbulence finalTerrain = new Turbulence(0.25, terrainSelector); finalTerrain.Frequency = 4.0f; noise = new Scale(Scalarv, Scalarv, Scalarv, finalTerrain); //noise = new Add(new Scale(Scalarv, Scalarv, Scalarv, finalTerrain), noiseSelect); //noise = new Add(noise, scaledvnoise); }
private static int[] calcTriangles(Voronoi region) { //calculate unity triangles int[] triangles = new int[region.Triangles().Count*3]; List<Site> sites = region.Sites()._sites; int idx = 0; foreach (Triangle t in region.Triangles()) { triangles[idx++] = sites.IndexOf(t.sites[0]); triangles[idx++] = sites.IndexOf(t.sites[1]); triangles[idx++] = sites.IndexOf(t.sites[2]); } return triangles; }
private static Vector3[] calcVerts(Voronoi region) { List<Site> sites = region.Sites()._sites; Vector3[] vertices = new Vector3[sites.Count]; int idx = 0; foreach (Site s in sites) { vertices[idx++] = new Vector3(s.x,s.y,0); } return vertices; }
public void DrawLine(Voronoi.Line line, Color c,int thick = 1) { DrawLine(line.Start,line.End,c,thick); }
public void buildGraph_() { Voronoi voronoi=new Voronoi(points,null,new Rect(0,0,SIZE,SIZE)); buildGraph(points,voronoi); improveCorners(); voronoi.dispose(); voronoi=null; points=null; }