public Map(MapInfo info) { this.id = info.id; this.name = info.name; this.CattleyaMapID = info.CattleyaMapID; this.CattleyaX = info.CattleyaX; this.CattleyaY = info.CattleyaY; this.CattleyaZ = info.CattleyaZ; this.actorsByID = new Dictionary<uint, Actor>(); this.actorsByRegion = new Dictionary<uint, List<Actor>>(); this.pcByName = new Dictionary<string, ActorPC>(); this.nextPcId = 1; this.nextNpcId = ID_BORDER + 1; this.nextItemId = ID_BORDER2 + 1; this.gTime = new GameTime(); this.gTime.UpdateTime(1, 12, 0); this.weather = Global.WEATHER_TYPE.SUNNY; this.wTask = new SagaMap.Tasks.SystemTasks.DynamicWeather(this); this.wTask.Activate(); if (info.heightmaps.Count > 0) this.hMap = new HeightMap(info.heightmaps[0]); else this.hMap = null; }
/// <summary> /// Makes the heights of the given coordinates equal by subtracting from the higher and adding to the lower. /// </summary> internal static void BalanceHeightsAtPoints(HeightMap heightMap, int x1, int y1, int x2, int y2) { var heightDif = heightMap[x1, y1] - heightMap[x2, y2]; //Balance this point and the neighboring point in height. heightMap[x1, y1] -= heightDif / 2f; heightMap[x2, y2] += heightDif / 2f; }
void Awake() { _instance = this; seed = Random.Range(0.020f, .032f); texseed = Random.Range(0.001f, .008f); MountainModifier = Random.Range(1.86f, 3.5f); //DontDestroyOnLoad(gameObject); }
/// <summary> /// Multiplies the height at the given point by mul, with bounds checking. /// If the point is out of bounds, the method simply returns. /// </summary> /// <param name="heightMap"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="mul"></param> private static void MultiplyHeightAtPoint(HeightMap heightMap, int x, int y, float mul) { //if point is in bounds if (x > 0 && x < heightMap.Size.X && y > 0 && y < heightMap.Size.Y) { heightMap[x, y] *= mul; } }
public void UpdateTo(HeightMap heightMap) { mHeightMap = heightMap; mWidth = heightMap.Width; mHeight = heightMap.Height; // Release old assets Destroy(); mNumVertices = mWidth * mHeight; mNumLines = (mHeight * (mWidth - 1)); // Create new assets mVertexBuffer = new VertexBuffer( FlatRedBallServices.GraphicsDevice, mNumVertices * VertexPositionColor.SizeInBytes, BufferUsage.None); mIndexBuffer = new IndexBuffer( FlatRedBallServices.GraphicsDevice, 2 * mNumLines * sizeof(int), BufferUsage.None, IndexElementSize.ThirtyTwoBits); // Create data VertexPositionColor[] vertices = new VertexPositionColor[mNumVertices]; int[] indices = new int[2 * mNumLines]; int indicesIndex = 0; // Add data float xstep = 2f / (float)mWidth; float ystep = 2f / (float)mHeight; for (int y = 0; y < mHeight; y++) { for (int x = 0; x < mWidth; x++) { vertices[y * mWidth + x] = new VertexPositionColor(new Vector3( xstep * (float)x - 1f, ystep * (float)y - 1f, heightMap.RawData[x, y]), Color.White); // Set up horizontal lines if (x < mWidth - 1) { // add a horizontal line to the next x vertex indices[indicesIndex] = y * mWidth + x; indices[indicesIndex + 1] = y * mWidth + (x + 1); indicesIndex += 2; } } } // Set buffer data mVertexBuffer.SetData<VertexPositionColor>(vertices); mIndexBuffer.SetData<int>(indices); }
public void GenerateContinents(HeightMap heightMap) { var mapSize = new IntPoint(heightMap.Size.X, heightMap.Size.Y); var startPoints = new List<IntPoint> { new IntPoint(mapSize.X / 2, mapSize.Y / 2) }; foreach (var start in startPoints) { var size = Random.Next(MaximumContinentSize - MinimumContinentSize) + MinimumContinentSize; var scaleStep = -(ScaleAmount - 1f) / size; ScaleSquareAroundPoint(heightMap, start, size, ScaleAmount, scaleStep); } }
/// <summary> /// Returns an 2d Color array with coloring applied based on the given HeightMap /// </summary> public Color[,] Colorize(HeightMap map) { var img = new Color[map.Size.X, map.Size.Y]; for (var y = 0; y < map.Size.Y; y++) { for (var x = 0; x < map.Size.X; x++) { img[x, y] = GetBaseColor(map[x, y], true); } } return img; }
public TreeVertexCollection(Vector3 position, HeightMap heightMap, int scale) { _scale = scale; _topSize = heightMap.Size - 1; _halfSize = _topSize / 2; _position = position; _vertexCount = heightMap.Size * heightMap.Size; //Initialize our array to hold the vertices Vertices = new VertexPositionNormalTexture[_vertexCount]; //Our method to populate the vertex collection this.BuildVertices(heightMap.Heights); //Our method to calculate the normals for all vertices CalculateAllNormals(); }
public HeightMapRenderer(string contentManagerName, int width, int height, Model model, HeightMap heightMap, Matrix transformationMatrix) { mHeightMap = heightMap; // Create camera mCamera = new Camera(contentManagerName, width, height); #if !XNA4 // Set up rendering mode mCamera.RenderOrder.Clear(); mCamera.RenderOrder.Add(FlatRedBall.Graphics.RenderMode.Position); mCamera.DrawsCameraLayer = true; mCamera.DrawsWorld = false; mCamera.DrawToScreen = false; #endif // Get bounds GetMinMax(model, transformationMatrix); // Set up camera orthogonality mCamera.Orthogonal = true; mCamera.OrthogonalWidth = mMax.X - mMin.X; mCamera.OrthogonalHeight = mMax.Y - mMin.Y; mCamera.FarClipPlane = 3f + mMax.Z - mMin.Z; mCamera.NearClipPlane = 1f; // Set up camera position mCamera.Position = new Vector3( (mMax.X + mMin.X) / 2f, (mMax.Y + mMin.Y) / 2f, (mMax.Z + 2f)); // Add post-processing mCamera.PostProcessing.EffectCombineOrder.Clear(); mCamera.PostProcessing.EffectCombineOrder.Add(new HeightMapPostProcessor(heightMap)); // Add the camera to the engine Renderer.Cameras.Add(mCamera); // Add model to camera layer mModel = ModelManager.AddModel(model); ModelManager.AddToLayer(mModel, mCamera.Layer); }
public void generate(HeightMap heightMap){ mapSize = heightMap.mapSize; terrainSize = heightMap.terrainSize; float ratioX = (float)terrainSize.x/mapSize; float ratioY = (float)terrainSize.y/mapSize; for(int i = 0; i < mapSize; i++) { for(int j = 0; j < mapSize; j++) { float worldPosX = (i+mapSize-1)*ratioX; float worldPosY = (j+mapSize-1)*ratioY; float mountains = p_mountainNoise.getNoise(worldPosX, worldPosY); float ground = p_groundNoise.getNoise(worldPosX, worldPosY); //float dist = getRadialDistance(i,j); //float dist = getRadialDistanceClamped(i,j); //dist = dist * Mathf.Pow(2,0.5f); //float dist2=Mathf.Min (dist,0.99f); //float dist = getRadialDistanceClamped2(i,j); float dist = getRadialCoastOnlyDistance(i,j); float height = ground*Mathf.Pow((1.0f - dist),0.5f); height += mountains*Mathf.Pow((1 - dist),0.5f)/2.0f; height -= Mathf.Pow(dist,1.0f)/13 * 10000/terrainSize.x; // float dist = getRadialDistance(i,j) * Mathf.Pow (2,0.5f); // float dist2=Mathf.Min (dist,1.0f); // float height= ground; // height += mountains*Mathf.Pow((1 - dist2),0.3f); // height -= Mathf.Pow(dist,0.7f)/3; heightMap.setHeight(i,j,height); heightMap.setHeight(i,j,height); } } heightMap.scale01 (); }
/// <summary> /// Returns the index of the neighboring height value that most differs from the given height. /// </summary> internal static IntPoint GetHighestSlopedNeighbor(HeightMap heightMap, IReadOnlyList<IntPoint> neighbors, float height, out float slope) { var slopedNeighbor = neighbors[0]; var highestSlope = 0f; foreach (var neighbor in neighbors) { var currentSlope = Math.Abs(height - heightMap[neighbor.X, neighbor.Y]); if (currentSlope > highestSlope) { highestSlope = currentSlope; slopedNeighbor = neighbor; } } slope = highestSlope; return slopedNeighbor; }
public virtual void Erode(HeightMap heightMap) { for (var i = 0; i < Iterations; i++) { for (var y = 0; y < heightMap.Size.Y; y++) { for (var x = 0; x < heightMap.Size.X; x++) { var neighbors = heightMap.GetVonNeumannNeighbors(x, y); float highestSlope; var highestSlopedNeighbor = GetHighestSlopedNeighbor(heightMap, neighbors, heightMap[x, y], out highestSlope); if (highestSlope > TalusAngle) { BalanceHeightsAtPoints(heightMap, x, y, highestSlopedNeighbor.X, highestSlopedNeighbor.Y); } } } } }
public override void Erode(HeightMap heightMap) { for (var i = 0; i < Iterations; i++) { for (var y = 0; y < heightMap.Size.Y; y++) { for (var x = 0; x < heightMap.Size.X; x++) { var neighbors = heightMap.GetVonNeumannNeighbors(x, y); float highestSlope; var highestSlopedNeighbor = GetHighestSlopedNeighbor(heightMap, neighbors, heightMap[x, y], out highestSlope); //This if condition is the only difference between ImprovedThermalErosion and ThermalErosion if (highestSlope <= TalusAngle) { BalanceHeightsAtPoints(heightMap, x, y, highestSlopedNeighbor.X, highestSlopedNeighbor.Y); } } } } }
/// <summary> /// From a start point, scales a box of given size on the HeightMap. The start point will be scaled by the given /// scaleValue. scaleValue will then be incremented by scaleStep as we begin scaling points further from the start. /// </summary> private static void ScaleSquareAroundPoint(HeightMap heightMap, IntPoint start, int size, float scaleValue, float scaleStep) { MultiplyHeightAtPoint(heightMap, start.X, start.Y, scaleValue); for (var d = 1; d < size + 1; d++, scaleValue += scaleStep) { //Corner values MultiplyHeightAtPoint(heightMap, start.X - d, start.Y - d, scaleValue); MultiplyHeightAtPoint(heightMap, start.X + d, start.Y - d, scaleValue); MultiplyHeightAtPoint(heightMap, start.X - d, start.Y + d, scaleValue); MultiplyHeightAtPoint(heightMap, start.X + d, start.Y + d, scaleValue); //Middle Edge values MultiplyHeightAtPoint(heightMap, start.X - d, start.Y, scaleValue); MultiplyHeightAtPoint(heightMap, start.X, start.Y - d, scaleValue); MultiplyHeightAtPoint(heightMap, start.X, start.Y + d, scaleValue); MultiplyHeightAtPoint(heightMap, start.X + d, start.Y, scaleValue); //Left & Right Sides for (var y = 1; y < d; y++) { MultiplyHeightAtPoint(heightMap, start.X - d, start.Y - y, scaleValue); MultiplyHeightAtPoint(heightMap, start.X - d, start.Y + y, scaleValue); MultiplyHeightAtPoint(heightMap, start.X + d, start.Y - y, scaleValue); MultiplyHeightAtPoint(heightMap, start.X + d, start.Y + y, scaleValue); } //Top & Bottom Sides for (var x = 1; x < d; x++) { MultiplyHeightAtPoint(heightMap, start.X - x, start.Y - d, scaleValue); MultiplyHeightAtPoint(heightMap, start.X + x, start.Y - d, scaleValue); MultiplyHeightAtPoint(heightMap, start.X - x, start.Y + d, scaleValue); MultiplyHeightAtPoint(heightMap, start.X + x, start.Y + d, scaleValue); } } }
public void GenerateChunks() { _progressText = "1/3 Generating Heightmap"; _heightMap = new HeightMap(Chunk.SIZE * SIZE); _heightMap.AddPerlinNoise(3f); _heightMap.Perturb(64.0f, 64.0f); for (int i = 0; i < 10; i++) { _heightMap.Erode(256.0f); } _heightMap.Smoothen(); _chunks = new List<Chunk>(); _boxels = new BoxelType[(int)(Math.Pow(Chunk.SIZE, 3) * Math.Pow(SIZE, 3))]; int count = 1; for (int z = 0; z < SIZE; z++) { for (int y = 0; y < SIZE; y++) { for (int x = 0; x < SIZE; x++) { _chunks.Add(new Chunk(new Vector3(x, y, z))); count++; _progress = 0.5f * count / (float)(Math.Pow(SIZE, 3)); _progressText = "2/3 Generating Chunk " + count + " of " + (Math.Pow(SIZE, 3)); } } } }
public void Run() { try { // SF GeoPoint location4326 = new GeoPoint(37.766974, -122.431062); //GeoPoint location4326 = new GeoPoint( 43.542544, 5.445379); DEMDataSet dataset = DEMDataSet.NASADEM; double radius = 5000; GeoPoint location3857 = location4326.ReprojectTo(4326, 3857); BoundingBox bbox3857 = BoundingBox.AroundPoint(location3857, radius); // 5km around point bbox3857.SRID = 3857; BoundingBox bbox4326 = bbox3857.ReprojectTo(Reprojection.SRID_PROJECTED_MERCATOR, Reprojection.SRID_GEODETIC); HeightMap heightMap = _elevationService.GetHeightMap(ref bbox4326, dataset); // Highest point var highest = heightMap.Coordinates.First(pt => pt.Elevation.Value == heightMap.Maximum); _logger.LogInformation($"Highest point: {highest} at {highest.DistanceTo(location4326)} meters"); OsmHighwayProcessor roadsProcessor = new OsmHighwayProcessor(GeoTransformPipeline.Default); // Download buildings and convert them to GeoJson IEnumerable <IFeature> features = _osmService.GetOsmDataAsGeoJson(bbox4326, BasicOsmDataFilter.Create(new string[] { "highway" })); // Create internal building model IEnumerable <HighwayModel> parsed = roadsProcessor.CreateModelsFromGeoJson <HighwayModel>(features, roadsProcessor.ModelFactory); int parallelCount = -1; Parallel.ForEach(parsed, new ParallelOptions { MaxDegreeOfParallelism = parallelCount }, model => //foreach(var model in parsed.Models) { model.LineString = _elevationService.GetLineGeometryElevation(model.LineString, dataset); } ); var osmRoads = parsed.ToDictionary(p => p.Id, p => p); var osmRoadLines = parsed.ToDictionary(p => p.Id, p => p.LineString); (Slope Slope, HighwayModel Road)maxSlope = (Slope.Zero, null); (Slope Slope, HighwayModel Road)maxAvgSlope = (Slope.Zero, null); foreach (var model in osmRoadLines) { var metrics = model.Value.ComputeMetrics(); var slope = GetMaxSlope(model.Value); if (slope > maxSlope.Slope) { maxSlope.Slope = slope; maxSlope.Road = osmRoads[model.Key]; } var slopeAvg = ComputeSlope(model.Value.First(), model.Value.Last()); if (slopeAvg > maxAvgSlope.Slope) { maxAvgSlope.Slope = slopeAvg; maxSlope.Road = osmRoads[model.Key]; } } //int parallelCount = -1; //Parallel.ForEach(parsed.Models, new ParallelOptions { MaxDegreeOfParallelism = parallelCount }, model => ////foreach (var model in parsed.Models) //{ // model.LineString =_elevationService.GetLineGeometryElevation(model.LineString, dataset); //} //); //osmRoadLines = parsed.Models.ToDictionary(p => p.Id, p => p.LineString); //maxSlope = (Slope.Zero, null); //maxAvgSlope = (Slope.Zero, null); //foreach (var model in osmRoadLines) //{ // var metrics = model.Value.ComputeMetrics(); // var slope = GetMaxSlope(model.Value); // if (slope > maxSlope.Slope) // { // maxSlope.Slope = slope; // maxSlope.Road = osmRoads[model.Key]; // } // var slopeAvg = ComputeSlope(model.Value.First(), model.Value.Last()); // if (slopeAvg > maxAvgSlope.Slope) // { // maxAvgSlope.Slope = slopeAvg; // maxSlope.Road = osmRoads[model.Key]; // } //} } catch (Exception ex) { _logger.LogError(ex, $"Error in {nameof(HighestPointFinder)}"); } }
public override void Load() { _rsDefault.CullMode = CullMode.CullCounterClockwiseFace; _rsDefault.FillMode = FillMode.Solid; _rsWire.CullMode = CullMode.CullCounterClockwiseFace; _rsWire.FillMode = FillMode.WireFrame; int size; dynamic map; if (generateHeightMap) { HeightMap heightMap = new HeightMap(513); heightMap.AddPerlinNoise(5.0f); heightMap.Perturb(32.0f, 32.0f); for (int i = 0; i < 10; i++) heightMap.Erode(16.0f); heightMap.Smoothen(); heightMap.Normalize(); size = heightMap.Size; map = heightMap; } else { Texture2D heightMap = Game.Instance.ContentManager.Load<Texture2D>("textures/hmSmall"); size = heightMap.Height; map = heightMap; } this.TopNodeSize = size - 1; this.Vertices = new TreeVertexCollection(this.Position, map, this.Scale); this.Buffers = new BufferManager(this.Vertices.Vertices, this.Device); this.RootNode = new QuadNode(NodeType.FullNode, this.TopNodeSize, 1, null, this, 0); //Construct an array large enough to hold all of the indices we'll need. // SOMETHING IS WRONG HERE this.Indices = new int[((size + 1) * (size + 1)) * 3]; Effect = new BasicEffect(this.Device); Effect.LightingEnabled = true; Effect.AmbientLightColor = new Vector3(0.4f); Effect.DirectionalLight0.Enabled = true; Effect.DirectionalLight0.Direction = new Vector3(-0.5f, -1, -0.5f); Effect.FogEnabled = true; Effect.FogStart = 300f; Effect.FogEnd = 1000f; Effect.FogColor = Color.Black.ToVector3(); Effect.TextureEnabled = true; Effect.Texture = Game.Instance.ContentManager.Load<Texture2D>("textures/grass");//new Texture2D(this.Device, 100, 100); Effect.Projection = this.Projection; Effect.View = this.View; Effect.World = Matrix.Identity; this.RootNode.EnforceMinimumDepth(); }
public void Initialize(int firstSup, string firstState) { heightMap = tileSystem.heightMap; HeightMapUp(SpawnBot(firstSup, firstState).supervisorio.currentState.heightMap); }
public void DrawMapInEditor() { if (tileMapSettings.createOuterWalls) { if (tileMapSettings.isVoxelMap) { /// /// Room Adder //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(Sidewinder.CreateMaze(RandomRoomPlacementMazeAdder.AddRoomsToMaze(MazeGenerator.GenerateMazeGrid(mazeSettings), roomAdder), sidewinder))), tileMapSettings)); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(MazeGenerator.GenerateMazeGrid(mazeSettings))), tileMapSettings)); /// /// Fractal //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(RecursiveDivision.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Eller //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(Eller.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Growing Tree //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(GrowingTree.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(GrowingTree.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings), null, x => x[x.Count-1]))), tileMapSettings)); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(GrowingTree.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings), null, x => Random.value < 0.5f ? x[x.Count-1] : x[Random.Range(0, x.Count)]))), tileMapSettings)); /// /// Prim Weighted Cells //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(PrimWeightedCells.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Prim Same Weight //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(PrimSameWeight.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Kruskal //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(RandomizedKruskal.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Recursive Backtracker //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(RecursiveBacktracker.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Hunt and Kill //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(HuntAndKill.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Wilson //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(Wilson.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Aldous-Broder //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(AldousBroder.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings)))), tileMapSettings)); /// /// Sidewinder //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(Sidewinder.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings), sidewinder))), tileMapSettings)); /// /// Binary Tree //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(BinaryTree.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings), btree))), tileMapSettings)); /// With Distances //DistanceMazeGrid mazeGrid = (DistanceMazeGrid)BinaryTree.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings), btree); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(MazeGenerator.ConvertToEmptyGrid(BinaryTree.CreateMaze(MazeGenerator.GenerateMazeGrid(mazeSettings), btree))), tileMapSettings)); //mazeGrid.distances = mazeGrid.values[0, 0].FindDistanceForAllReachableLinkedCells(); //Debug.Log(mazeGrid.ToString()); /// /// MAZES /// /// /// /// Settling //SettlingRooms.PreprocessMap(tileMapSettings, settling); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(SettlingRooms.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), settling)), tileMapSettings)); /// /// From prefab //GridMapFromPrefabs.PreprocessMap(tileMapSettings, mapFromPrefab); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GridMapFromPrefabs.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), mapFromPrefab)), tileMapSettings)); /// /// Corridor //RandomRoomWithCorridor.PreprocessMap(tileMapSettings, corridor); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(RandomRoomWithCorridor.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), corridor)), tileMapSettings)); /// /// BSP //BinarySpacePartitioning.PreprocessMap(tileMapSettings, bsp); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(BinarySpacePartitioning.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), bsp)), tileMapSettings)); /// /// Random Room Placement //RandomRoomPlacement.PreprocessMap(tileMapSettings, roomPlacement); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(RandomRoomPlacement.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), roomPlacement)), tileMapSettings)); /// /// Diffusion Limited Aggregation //DiffusionLimitedAggregation.PreprocessMap(tileMapSettings, difLimAgr); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(DiffusionLimitedAggregation.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), difLimAgr)), tileMapSettings)); /// /// Random Worms //RandomWorms.PreprocessMap(tileMapSettings, randomWorms); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(RandomWorms.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), randomWorms)), tileMapSettings)); /// /// Random Walkers //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(RandomWalkers.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), randomWalkers)), tileMapSettings)); /// /// GameOfLife //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GameOfLifeCave.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), gameOfLife)), tileMapSettings)); /// /// RandomRoomGrid //RandomRoomSizeGrid.PreprocessMap(tileMapSettings, randomRoomGrid); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(RandomRoomSizeGrid.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), randomRoomGrid)), tileMapSettings)); /// /// RoomGrid //FixedRoomSizeGrid.PreprocessMap(tileMapSettings, roomGrid); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(FixedRoomSizeGrid.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), roomGrid)), tileMapSettings)); /// RoomGrid + GameOfLife //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(FixedRoomSizeGrid.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), roomGrid, gameOfLife)), tileMapSettings)); /// ///FisherYates //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(FisherYatesShuffle.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), fisherYates)), tileMapSettings)); /// /// Without Processing //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GridGenerator.GenerateEmptyGrid(tileMapSettings)), tileMapSettings)); /// PointyHex test //DrawMesh(DiscretePointyHexMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GridGenerator.GenerateEmptyGrid(tileMapSettings)), tileMapSettings)); //DrawMesh(ContiguousPointyHexMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GridGenerator.GenerateEmptyGrid(tileMapSettings)), tileMapSettings)); //DrawMesh(DiscreteSolidPointyHexMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GridGenerator.GenerateEmptyGrid(tileMapSettings)), tileMapSettings)); //DrawMesh(DiscreteSolidPointyHexMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(FisherYatesShuffle.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), fisherYates)), tileMapSettings)); //DrawMesh(DiscreteSolidPointyHexMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GameOfLifeCave.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), gameOfLife)), tileMapSettings)); /// Height maps //DrawMesh(DiscreteSolidPointyHexMeshGenerator.GenerateTerrainMesh(GridGenerator.GenerateEmptyGrid(tileMapSettings).FillWholeGrid(CellType.Wall), tileMapSettings, HeightMapGenerator.GenerateHeightMap(heightMapSettings, new Vector2(0.0f, 0.0f), tileMapSettings.mapWidth, tileMapSettings.mapHeight))); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateTerrainMesh(GridGenerator.GenerateEmptyGrid(tileMapSettings), tileMapSettings, HeightMapGenerator.GenerateHeightMap(heightMapSettings, new Vector2(0.0f, 0.0f), tileMapSettings.mapWidth, tileMapSettings.mapHeight))); /// Layers Height //DrawMesh(DiscreteSolidPointyHexMeshGenerator.GenerateTerrainMesh(GridGenerator.GenerateEmptyGrid(tileMapSettings), tileMapSettings, HeightMapGenerator.GenerateHeightMap(heightMapSettings, new Vector2(0.0f, 0.0f), tileMapSettings.mapWidth, tileMapSettings.mapHeight), heightLayersSettings)); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateTerrainMesh(GridGenerator.GenerateEmptyGrid(tileMapSettings), tileMapSettings, HeightMapGenerator.GenerateHeightMap(heightMapSettings, new Vector2(0.0f, 0.0f), tileMapSettings.mapWidth, tileMapSettings.mapHeight), heightLayersSettings)); //DrawMesh(DiscreteTerrainGenerator.GenerateDiscreteTerrainMesh(discreteTerrainSettings)); //DrawMesh(ContiguousTerrainGenerator.GenerateContiguousTerrainMesh(contiguousTerrainSettings)); HeightMap heightMap = ContiguousTerrainGenerator.GenerateContiguousTerrainHeightMap(contiguousTerrainSettings); textureData.ApplyToMaterial(terrainMaterial); textureData.UpdateMeshHeight(terrainMaterial, heightMap.minValue, heightMap.maxValue); DrawMesh(ContiguousTerrainGenerator.GenerateContiguousTerrainFromHM(heightMap, contiguousTerrainSettings)); /// ///IO Tests /// /// Texture2D //ExportMap.ExportGraphic(OuterWallsGenerator.CreateOuterWalls(FixedRoomSizeGrid.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), roomGrid))); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(ExportMap.ImportGraphic("f", "u", "c"), tileMapSettings)); /// TXT //ExportMap.ExportText(OuterWallsGenerator.CreateOuterWalls(FixedRoomSizeGrid.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), roomGrid))); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(ExportMap.ImportText("f", "u", "c"), tileMapSettings)); /// Binary /// BUG: FAILED TO WRITE\READ ARRAY => Need to make custom loader //ExportMap.SaveDataBinary(OuterWallsGenerator.CreateOuterWalls(FixedRoomSizeGrid.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), roomGrid))); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(ExportMap.LoadDataBinary(), tileMapSettings)); /// JSON //ExportMap.ExportJSON(OuterWallsGenerator.CreateOuterWalls(FixedRoomSizeGrid.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), roomGrid))); //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(ExportMap.ImportJSON("f","u","c"), tileMapSettings)); } else { if (tileMapSettings.isDiscrete) { DrawMesh(DiscreteMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GridGenerator.GenerateEmptyGrid(tileMapSettings)), tileMapSettings)); } else { DrawMesh(ContiguousMeshGenerator.GenerateGridMesh(OuterWallsGenerator.CreateOuterWalls(GridGenerator.GenerateEmptyGrid(tileMapSettings)), tileMapSettings)); } } } else { if (tileMapSettings.isVoxelMap) { ///RoomGrid FixedRoomSizeGrid.PreprocessMap(tileMapSettings, roomGrid); DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(FixedRoomSizeGrid.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), roomGrid), tileMapSettings)); ///FisherYates //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(FisherYatesShuffle.ProcessMap(GridGenerator.GenerateEmptyGrid(tileMapSettings), fisherYates), tileMapSettings)); ///Without Processing //DrawMesh(DiscreteVoxelMeshGenerator.GenerateGridMesh(GridGenerator.GenerateEmptyGrid(tileMapSettings), tileMapSettings)); } else { if (tileMapSettings.isDiscrete) { DrawMesh(DiscreteMeshGenerator.GenerateGridMesh(GridGenerator.GenerateEmptyGrid(tileMapSettings), tileMapSettings)); } else { DrawMesh(ContiguousMeshGenerator.GenerateGridMesh(GridGenerator.GenerateEmptyGrid(tileMapSettings), tileMapSettings)); } } } }
public HeightMapRenderer(string contentManagerName, int width, int height, Model model, HeightMap heightMap) : this(contentManagerName, width, height, model, heightMap, Matrix.Identity) { }
private void PopulateInternal(int Seed, int seed2, int seed3, int seed4, int seed5, Chunk chunk) { #endif if (chunk.OwningRegion.TheWorld.Settings.GeneratorFlat) { if (chunk.WorldPosition.Z == 0) { chunk.SetBlockAt(0, 0, 0, BlockInternal.AIR); for (int i = 0; i < Constants.CHUNK_BLOCK_COUNT; i++) { chunk.BlocksInternal[i] = new BlockInternal((ushort)Material.STONE, 0, 0, 0); } for (int x = 0; x < Chunk.CHUNK_SIZE; x++) { for (int y = 0; y < Chunk.CHUNK_SIZE; y++) { chunk.BlocksInternal[chunk.BlockIndex(x, y, Chunk.CHUNK_SIZE - 1)] = new BlockInternal((ushort)Material.GRASS_PLAINS, 0, 0, 0); chunk.BlocksInternal[chunk.BlockIndex(x, y, Chunk.CHUNK_SIZE - 2)] = new BlockInternal((ushort)Material.DIRT, 0, 0, 0); chunk.BlocksInternal[chunk.BlockIndex(x, y, Chunk.CHUNK_SIZE - 3)] = new BlockInternal((ushort)Material.DIRT, 0, 0, 0); } } } else if (chunk.WorldPosition.Z < 0) { chunk.SetBlockAt(0, 0, 0, BlockInternal.AIR); for (int i = 0; i < Constants.CHUNK_BLOCK_COUNT; i++) { chunk.BlocksInternal[i] = new BlockInternal((ushort)Material.STONE, 0, 0, 0); } } // else: air! return; } if (chunk.WorldPosition.Z > MaxNonAirHeight) { // AIR! return; } Location cpos = chunk.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE; double EstimatedHeight = GetHeight(Seed, seed2, seed3, seed4, seed5, cpos.X + Constants.CHUNK_WIDTH / 2, cpos.Y + Constants.CHUNK_WIDTH / 2, null, false); if (Math.Max(0, EstimatedHeight + MaxSuddenSlope) < cpos.Z) { // TODO: Special case for the chunk being too far down as well? No height map in that case! return; } // About to be populated: ensure chunk has a valid block set. chunk.SetBlockAt(0, 0, 0, BlockInternal.AIR); HeightMap hm = GetHeightMap(chunk.WorldPosition, Seed, seed2, seed3, seed4, seed5); int[] toppers = new int[Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE]; // TODO: Reusable pool? This will generate trash! for (int x = 0; x < Chunk.CHUNK_SIZE; x++) { for (int y = 0; y < Chunk.CHUNK_SIZE; y++) { // Prepare basics int cx = (int)cpos.X + x; int cy = (int)cpos.Y + y; double hheight = hm.Heights[y * Chunk.CHUNK_SIZE + x]; SimpleBiome biome = Biomes.BiomeFor(seed2, seed3, seed4, cx, cy, cpos.Z, hheight) as SimpleBiome; //Biome biomeOrig2; /*double hheight2 = */ /*GetHeight(Seed, seed2, seed3, seed4, seed5, cx + 7, cy + 7, (double)cpos.Z + 7, out biomeOrig2); * SimpleBiome biome2 = (SimpleBiome)biomeOrig2;*/ Material surf = biome.SurfaceBlock(); Material seco = biome.SecondLayerBlock(); Material basb = biome.BaseBlock(); Material water = biome.WaterMaterial(); /*Material surf2 = biome2.SurfaceBlock(); * Material seco2 = biome2.SecondLayerBlock(); * Material basb2 = biome2.BaseBlock();*/ // TODO: Make this possible?: hheight = (hheight + hheight2) / 2f; int hheightint = (int)Math.Round(hheight); double topf = hheight - (double)(chunk.WorldPosition.Z * Chunk.CHUNK_SIZE); int top = (int)Math.Round(topf); // General natural ground for (int z = 0; z < Math.Min(top - 5, Chunk.CHUNK_SIZE); z++) { if (CanBeSolid(seed3, seed4, seed5, cx, cy, (int)cpos.Z + z, biome)) { Material typex = GetMatType(seed2, seed3, seed4, seed5, cx, cy, (int)cpos.Z + z); byte shape = 0; if (typex != Material.AIR) { shape = OreShapes[new MTRandom(39, (ulong)((hheight + cx + cy + cpos.Z + z) * 5)).Next(OreShapes.Length)]; } //bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f; chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)(typex == Material.AIR ? (/*choice ? basb2 : */ basb) : typex), shape, 0, 0); } else if ((CanBeSolid(seed3, seed4, seed5, cx, cy, (int)cpos.Z + z - 1, biome) || (CanBeSolid(seed3, seed4, seed5, cx, cy, (int)cpos.Z + z + 1, biome))) && (CanBeSolid(seed3, seed4, seed5, cx + 1, cy, (int)cpos.Z + z, biome) || CanBeSolid(seed3, seed4, seed5, cx, cy + 1, (int)cpos.Z + z, biome) || CanBeSolid(seed3, seed4, seed5, cx - 1, cy, (int)cpos.Z + z, biome) || CanBeSolid(seed3, seed4, seed5, cx, cy - 1, (int)cpos.Z + z, biome))) { //bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f; chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)(/*choice ? basb2 : */ basb), 3, 0, 0); } } for (int z = Math.Max(top - 5, 0); z < Math.Min(top - 1, Chunk.CHUNK_SIZE); z++) { if (CanBeSolid(seed3, seed4, seed5, cx, cy, (int)cpos.Z + z, biome)) { //bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f; chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)(/*choice ? seco2 :*/ seco), 0, 0, 0); } } for (int z = Math.Max(top - 1, 0); z < Math.Min(top, Chunk.CHUNK_SIZE); z++) { //bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f; chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)(/*choice ? surf2 : */ surf), 0, 0, 0); } // Smooth terrain cap double heightfxp = GetHeightRel(hm, Seed, seed2, seed3, seed4, seed5, cx + 1, cy, (double)cpos.Z, x + 1, y); double heightfxm = GetHeightRel(hm, Seed, seed2, seed3, seed4, seed5, cx - 1, cy, (double)cpos.Z, x - 1, y); double heightfyp = GetHeightRel(hm, Seed, seed2, seed3, seed4, seed5, cx, cy + 1, (double)cpos.Z, x, y + 1); double heightfym = GetHeightRel(hm, Seed, seed2, seed3, seed4, seed5, cx, cy - 1, (double)cpos.Z, x, y - 1); double topfxp = heightfxp - (double)chunk.WorldPosition.Z * Chunk.CHUNK_SIZE; double topfxm = heightfxm - (double)chunk.WorldPosition.Z * Chunk.CHUNK_SIZE; double topfyp = heightfyp - (double)chunk.WorldPosition.Z * Chunk.CHUNK_SIZE; double topfym = heightfym - (double)chunk.WorldPosition.Z * Chunk.CHUNK_SIZE; for (int z = Math.Max(top, 0); z < Math.Min(top + 1, Chunk.CHUNK_SIZE); z++) { //bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f; ushort tsf = (ushort)(/*choice ? surf2 : */ surf); if (topf - top > 0f) { bool xp = topfxp > topf && topfxp - Math.Round(topfxp) <= 0; bool xm = topfxm > topf && topfxm - Math.Round(topfxm) <= 0; bool yp = topfyp > topf && topfyp - Math.Round(topfyp) <= 0; bool ym = topfym > topf && topfym - Math.Round(topfym) <= 0; if (xm && xp) /* Fine as-is */ } {
public static ModelRoot AddTINMesh(ModelRoot model, HeightMap hMap, double precision, SharpGltfService gltf, PBRTexture textures, int srid) { Triangulation triangulation = GenerateTIN(hMap, precision, srid); return(gltf.AddTerrainMesh(model, triangulation, textures, doubleSided: true)); }
/// Creates a map representing convexity of local areas (with @a radius) in another height map. /// Positive heights in the convexity map indicate convex areas and negative heights indicate /// concave areas. /// /// Example: /// @code{.cs} /// var main = HeightMap.Noise(); /// yield HeightMap.ConvexityMap(main, 50) as "ConvexityMap"; /// yield main; /// @endcode /// /// @image html std_2d_convexitymap.png /// /// @param heightMap The height map. /// @param radius The radius. Must be greater than 0. /// @return The convexity map. static HeightMap ConvexityMap(HeightMap heightMap, Number radius);
private Location3DModelResponse Generate3DLocationModel(Location3DModelRequest request, Location3DModelSettings settings) { Location3DModelResponse response = new Location3DModelResponse(); try { bool imageryFailed = false; using (TimeSpanBlock timer = new TimeSpanBlock($"3D model {request.Id}", _logger)) { BoundingBox bbox = GetBoundingBoxAroundLocation(request.Latitude, request.Longitude, settings.SideSizeKm); HeightMap hMap = _elevationService.GetHeightMap(ref bbox, settings.Dataset); var transform = new ModelGenerationTransform(bbox, Reprojection.SRID_PROJECTED_MERCATOR, centerOnOrigin: true, settings.ZScale, centerOnZOrigin: true); response.Attributions.AddRange(settings.Attributions); // will be added to the model response.Attributions.Add(settings.Dataset.Attribution); // will be added to the model PBRTexture pbrTexture = null; if (settings.ImageryProvider != null) { response.Attributions.Add(settings.ImageryProvider.Attribution); // will be added to the model // Imagery TileRange tiles = _imageryService.ComputeBoundingBoxTileRange(bbox, settings.ImageryProvider, settings.MinTilesPerImage); Debug.Assert(tiles.Count < 400); tiles = _imageryService.DownloadTiles(tiles, settings.ImageryProvider); string fileName = Path.Combine(settings.OutputDirectory, $"{request.Id}_Texture.jpg"); TextureInfo texInfo = _imageryService.ConstructTexture(tiles, bbox, fileName, TextureImageFormat.image_jpeg); transform.BoundingBox = bbox; hMap = transform.TransformHeightMap(hMap); //var normalMap = _imageryService.GenerateNormalMap(hMap, settings.OutputDirectory, $"{request.Id}_normalmap.png"); pbrTexture = PBRTexture.Create(texInfo); } // Center on origin //hMap = hMap.CenterOnOrigin(out Matrix4x4 transform).BakeCoordinates(); //response.Origin = new GeoPoint(request.Latitude, request.Longitude).ReprojectTo(Reprojection.SRID_GEODETIC, Reprojection.SRID_PROJECTED_MERCATOR); ModelRoot model = _gltfService.CreateNewModel(); //======================= // Buildings if (settings.OsmBuildings) { model = _sampleOsmProcessor.Run(model, OsmLayer.Buildings, bbox, transform, computeElevations: true, settings.Dataset, settings.DownloadMissingFiles); } if (settings.GenerateTIN) { model = AddTINMesh(model, hMap, 2d, _gltfService, pbrTexture, Reprojection.SRID_PROJECTED_MERCATOR); } else { model = _gltfService.AddTerrainMesh(model, hMap, pbrTexture); } model.Asset.Generator = "DEM Net Elevation API with SharpGLTF"; //model.TryUseExtrasAsList(true).AddRange(response.Attributions); model.SaveGLB(Path.Combine(settings.OutputDirectory, string.Concat(imageryFailed ? "imageryFailed_" : "", settings.ModelFileNameGenerator(settings, request)))); // cleanup //if (pbrTexture != null) //{ // if (pbrTexture.NormalTexture != null) File.Delete(pbrTexture.NormalTexture.FilePath); // File.Delete(pbrTexture.BaseColorTexture.FilePath); //} response.Elapsed = timer.Elapsed; response.NumTiles = pbrTexture.BaseColorTexture.TileCount; } } catch (Exception) { throw; } return(response); }
public static ModelRoot GenerateTIN(HeightMap hMap, double precision, SharpGltfService gltf, PBRTexture textures, int srid) { return(AddTINMesh(gltf.CreateNewModel(), hMap, precision, gltf, textures, srid)); }
private void NewHeightMapDialog_SelectedSizeChanged() { HeightMap.GetPreviewModel(NewHeightMapDialog.Min, NewHeightMapDialog.Max, NewHeightMapDialog.GridSize, ModelHeightMapBoundary, ModelHeightMapPoints); }
public static void addHeightMap(HeightMap h, int x, int z) { heightMaps.Add(f(x, z), h); }
public static Mesh GenerateTerrainMesh(HeightMap map, ContiguousTerrainSettings settings) { Mesh mesh = new Mesh(); Vector2 bottomLeft; if (settings.tileMapSettings.isCentered) { bottomLeft = new Vector2(-map.width, -map.height) * settings.tileMapSettings.cellScale * 0.5f + new Vector2(settings.tileMapSettings.mapOffsetX, -settings.tileMapSettings.mapOffsetZ); } else { bottomLeft = new Vector2(settings.tileMapSettings.mapOffsetX, -settings.tileMapSettings.mapOffsetZ); } Debug.DrawRay(new Vector3(bottomLeft.x, 0.0f, bottomLeft.y), Vector3.up * 5.0f, Color.red, 0.5f); Vector3[] vertices = new Vector3[map.width * map.height]; Vector2[] uv = new Vector2[vertices.Length]; int[] triangles = new int[(map.width - 1) * (map.height - 1) * 6]; //6 = 2 triangles * 3 vertices Color[] colors = new Color[vertices.Length]; float vertexOffset = settings.tileMapSettings.cellScale; int vert = 0; int tri = 0; for (int y = 0; y < map.height; y++) { for (int x = 0; x < map.width; x++) { Vector3 cellOffset = new Vector3(x * settings.tileMapSettings.cellScale, 0.0f, y * settings.tileMapSettings.cellScale) + new Vector3(bottomLeft.x, 0.0f, bottomLeft.y); //cellOffset.y += map.values[x, y] * settings.tileMapSettings.cellScale; cellOffset.y += map.values[x, y]; vertices[vert] = cellOffset; uv[vert] = new Vector2((float)x / map.width, (float)y / map.height); //colors[vert] = map.values[x == 0 ? x : x - 1, y == 0 ? y : y - 1].cellMapColor; colors[vert] = Color.blue; Debug.DrawRay(vertices[vert], Vector3.up * 3.0f, Color.green, 0.5f); vert++; } } vert = 0; for (int y = 0; y < map.height - 1; y++) //careful, <, not <= Because triangles use i and i+1 column inside the loop { for (int x = 0; x < map.width - 1; x++) { triangles[tri] = triangles[tri + 3] = vert; triangles[tri + 1] = vert + (map.width); triangles[tri + 2] = triangles[tri + 4] = vert + (map.width) + 1; triangles[tri + 5] = vert + 1; vert++; tri += 6; } vert++; } mesh.name = "Contiguous Terrain Mesh"; mesh.vertices = vertices; mesh.uv = uv; mesh.triangles = triangles; mesh.colors = colors; mesh.RecalculateNormals(); return(mesh); }
private void LoadObjects( AssetLoadContext loadContext, HeightMap heightMap, MapObject[] mapObjects, NamedCameras namedCameras, List <Team> teams, out WaypointCollection waypointCollection, out RoadCollection roads, out Bridge[] bridges, out CameraCollection cameras) { var waypoints = new List <Waypoint>(); var bridgesList = new List <Bridge>(); var roadTopology = new RoadTopology(); for (var i = 0; i < mapObjects.Length; i++) { var mapObject = mapObjects[i]; switch (mapObject.RoadType & RoadType.PrimaryType) { case RoadType.None: switch (mapObject.TypeName) { case Waypoint.ObjectTypeName: waypoints.Add(new Waypoint(mapObject)); break; default: GameObject.FromMapObject(mapObject, loadContext.AssetStore, GameObjects, heightMap, overwriteAngle: null, teams: teams); break; } break; case RoadType.BridgeStart: case RoadType.BridgeEnd: // Multiple invalid bridges can be found in e.g GLA01. if ((i + 1) >= mapObjects.Length || !mapObjects[i + 1].RoadType.HasFlag(RoadType.BridgeEnd)) { Logger.Warn($"Invalid bridge: {mapObject.ToString()}, skipping..."); continue; } var bridgeEnd = mapObjects[++i]; bridgesList.Add(AddDisposable(new Bridge( loadContext, heightMap, mapObject, mapObject.Position, bridgeEnd.Position, GameObjects))); break; case RoadType.Start: case RoadType.End: var roadEnd = mapObjects[++i]; // Some maps have roads with invalid start- or endpoints. // We'll skip processing them altogether. if (mapObject.TypeName == "" || roadEnd.TypeName == "") { Logger.Warn($"Road {mapObject} has invalid start- or endpoint, skipping..."); continue; } if (!mapObject.RoadType.HasFlag(RoadType.Start) || !roadEnd.RoadType.HasFlag(RoadType.End)) { throw new InvalidDataException(); } // Note that we're searching with the type of either end. // This is because of weirdly corrupted roads with unmatched ends in USA04, which work fine in WB and SAGE. var roadTemplate = loadContext.AssetStore.RoadTemplates.GetByName(mapObject.TypeName) ?? loadContext.AssetStore.RoadTemplates.GetByName(roadEnd.TypeName); if (roadTemplate == null) { throw new InvalidDataException($"Missing road template: {mapObject.TypeName}"); } roadTopology.AddSegment(roadTemplate, mapObject, roadEnd); break; } loadContext.GraphicsDevice.WaitForIdle(); } cameras = new CameraCollection(namedCameras?.Cameras); roads = AddDisposable(new RoadCollection(roadTopology, loadContext, heightMap, Terrain.RadiusCursorDecalsResourceSet)); waypointCollection = new WaypointCollection(waypoints, MapFile.WaypointsList.WaypointPaths); bridges = bridgesList.ToArray(); }
private static List <BeanPoint_internal> GetGeoPointsByHMap(HeightMap p_hMap, int p_srid) { return(p_hMap.Coordinates.Select(c => GetPointInternalFromGeoPoint(c, p_srid)).ToList()); }
/// Creates a deep copy of another height map. /// /// Example: /// @code{.cs} /// var main = HeightMap.RadialGradient([400, 500], 500, 1, 0); /// var copy = HeightMap.Clone(main); /// copy.Move([200, 0]); /// yield main.Unify(copy); /// @endcode /// /// @image html std_2d_clone.png /// /// @param heightMap The map to copy. /// @return The height map. static HeightMap Clone(HeightMap heightMap);
public HeightMapRenderer(string contentManagerName, int width, int height, PositionedModel model, HeightMap heightMap) : this(contentManagerName, width, height, model.XnaModel, heightMap, Matrix.CreateScale(model.ScaleX, model.ScaleY, model.ScaleZ) * model.RotationMatrix) { mModel.ScaleX = model.ScaleX; mModel.ScaleY = model.ScaleY; mModel.ScaleZ = model.ScaleZ; mModel.RotationX = model.RotationX; mModel.RotationY = model.RotationY; mModel.RotationZ = model.RotationZ; }
public HeightMapPostProcessor(HeightMap heightMap) { mHeightMap = heightMap; InitializeEffect(); mEnabled = true; }
/// <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); spriteFont = Content.Load<SpriteFont>("Arial"); ballModel = Content.Load<Model>("Models\\balltest"); groundModel = Content.Load<Model>("Models\\ground"); boxModel = Content.Load<Model>("Models\\cube"); arrowModel = Content.Load<Model>("Models\\arrow"); exitModel = Content.Load<Model>("Models\\exit"); ballTextureBeach = Content.Load<Texture2D>("Textures\\ball"); ballTextureMetal = Content.Load<Texture2D>("Models\\tile"); terrainModel = Content.Load<Model>("Models\\terrain"); rockTexture = Content.Load<Texture2D>("Models\\rocks"); heightMap = terrainModel.Tag as HeightMap; if (heightMap == null) { string message = "The terrain model did not have a HeightMapInfo"; throw new InvalidOperationException(message); } Sound.playSoundLoop("Sound\\background", Content); effect = Content.Load<Effect>("Lighting/Effects"); sky=Content.load<Sky>("Textures\\sky"); }
public DualHeightMap(HeightMap map) : base(map) { m_ByteMap = HeightMapToBytes(); }
void Start() { if(useHeightMap) heightMap = HeightMap.Find(); }
public Wind(Vector3 direction, HeightMap heightmap) : base(direction) { _heightMap = heightmap; }
private IList <InsertPosition> GenerateInsertPositions(HeightMap heightMap) { // computations including the z coordinate // -> only for generating the mesh triangles, not for any angle computations / crossings with z axis / ... ! var startWithZ = Segment.StartPosition.WithZ(heightMap.GetHeight(Segment.StartPosition.X, Segment.StartPosition.Y)); var endWithZ = Segment.EndPosition.WithZ(heightMap.GetHeight(Segment.EndPosition.X, Segment.EndPosition.Y)); var segmentVector = endWithZ - startWithZ; var distanceWithZ = Vector3.Distance(startWithZ, endWithZ); var sectionCount = Math.Max(1, (int)(distanceWithZ / 10)); // generate candidate positions for cutting the road segment var positionCandidates = new List <InsertPosition>(); for (int i = 0; i <= sectionCount; ++i) { var relativeProgress = (float)i / (float)sectionCount; var position = startWithZ + relativeProgress * segmentVector; var newPoint = new InsertPosition() { Position = position, RelativeProgress = relativeProgress }; UpdateHeights(newPoint, heightMap); positionCandidates.Add(newPoint); } // choose which of those to use (don't need additional triangles where the road segment is unbumpy) const float createNewVerticesHeightDeltaThreshold = 0.001f; var usefulPositions = new List <InsertPosition>(); usefulPositions.Add(positionCandidates[0]); for (int i = 1; i < sectionCount; ++i) { var interpolatedHeight = (positionCandidates[i - 1].Position.Z + positionCandidates[i + 1].Position.Z) / 2; if (Math.Abs(interpolatedHeight - positionCandidates[i].Position.Z) > createNewVerticesHeightDeltaThreshold) { usefulPositions.Add(positionCandidates[i]); } } usefulPositions.Add(positionCandidates[sectionCount]); // get vertex normals var count = usefulPositions.Count; for (int i = 0; i < count; ++i) { var prevRoadSection = i > 0 ? Vector3.Normalize(usefulPositions[i].Position - usefulPositions[i - 1].Position) : Vector3.Zero; var nextRoadSection = i < count - 1 ? Vector3.Normalize(usefulPositions[i + 1].Position - usefulPositions[i].Position) : Vector3.Zero; var avgRoadDirection = Vector3.Normalize(prevRoadSection + nextRoadSection); usefulPositions[i].Normal = Vector3.Cross(DirectionNormalNoZ, avgRoadDirection); } // get distance along road usefulPositions[0].DistanceAlongRoad = 0; for (int i = 1; i < count; ++i) { var length = Vector3.Distance(usefulPositions[i].Position, usefulPositions[i - 1].Position); usefulPositions[i].DistanceAlongRoad = usefulPositions[i - 1].DistanceAlongRoad + length; } return(usefulPositions.ToList()); }
public Tile GetTile(Position pos) { if (Tiles.ContainsKey(pos)) { return(Tiles[pos]); } if (terrain == null) { int totalMetal; totalMetal = 0; Tiles.Clear(); terrain = GenerateTerrain(seed); for (int x = 0; x < Game.GameModel.MapWidth; x++) { for (int y = 0; y < Game.GameModel.MapHeight; y++) { Position p = new Position(x, y); Tile t = new Tile(this, p); Tiles.Add(p, t); t.Height = terrain.Data[x, y] / 2; /* * if (t.Height < 0.05) * { * * } * else if (t.Height < 0.1) * { * * } * else if (t.Height < 0.3) * { * t.Metal = Game.Random.Next(2); * } * else if (t.Height <= 0.7) * { * t.Metal = Game.Random.Next(3); * } * else if (t.Height > 0.7) * { * t.Metal = Game.Random.Next(3); * } * else if (t.Height > 0.9) * { * * } * else * { * * } */ if (t.Height >= 0.45 && t.Height <= 0.55) { t.Metal = 0; } else if (t.Height > 0.27 && t.Height < 0.33) { t.Metal = 0; } else { if (Game.Random.Next(80) == 0) { //if (t.Pos.X == 30 && t.Pos.Y == 15) t.Metal = 100; } else { t.Metal = 0; // Game.Random.Next(3); } } totalMetal += t.Metal; } } //checkTotalMetal = GetMapInfo().TotalMetal; } if (Tiles.ContainsKey(pos)) { return(Tiles[pos]); } return(null); /* Dynamically expand. Not now * Tile tile = new Tile(this, pos); * Tiles.Add(pos, tile); * * return tile; */ }
public Terrain(HeightMap map) : this(map, new Colorizer(DefaultColorizer.BaseColorRanges)) { }
public void HeightMapUp(HeightMap hm) { heightMap = HeightMapSynth(heightMap, hm); tileSystem.UpdateMap(heightMap); }
protected override Scene LoadEntry(FileSystemEntry entry, ContentManager contentManager, LoadOptions loadOptions) { contentManager.IniDataContext.LoadIniFile(@"Data\INI\Terrain.ini"); var mapFile = MapFile.FromFileSystemEntry(entry); var result = new Scene(); result.MapFile = mapFile; result.Settings.LightingConfigurations = mapFile.GlobalLighting.LightingConfigurations.ToLightSettingsDictionary(); result.Settings.TimeOfDay = mapFile.GlobalLighting.Time; var heightMap = new HeightMap(mapFile.HeightMapData); result.HeightMap = heightMap; var indexBufferCache = AddDisposable(new TerrainPatchIndexBufferCache(contentManager.GraphicsDevice)); var tileDataTexture = AddDisposable(CreateTileDataTexture( contentManager.GraphicsDevice, mapFile, heightMap)); var cliffDetailsBuffer = AddDisposable(CreateCliffDetails( contentManager.GraphicsDevice, mapFile)); CreateTextures( contentManager, mapFile.BlendTileData, out var textureArray, out var textureDetails); var textureDetailsBuffer = AddDisposable(Buffer <TextureInfo> .CreateStatic( contentManager.GraphicsDevice, textureDetails, BufferBindFlags.ShaderResource)); var terrainMaterial = new TerrainMaterial(contentManager.EffectLibrary.Terrain); terrainMaterial.SetTileData(tileDataTexture); terrainMaterial.SetCliffDetails(cliffDetailsBuffer); terrainMaterial.SetTextureDetails(textureDetailsBuffer); terrainMaterial.SetTextureArray(textureArray); var terrainPatches = CreatePatches( contentManager.GraphicsDevice, heightMap, mapFile.BlendTileData, terrainMaterial, indexBufferCache); var terrain = new Terrain.Terrain(heightMap, terrainPatches); var world = new World(terrain); result.Scene3D = new Scene3D(world); var objectsEntity = new Entity(); result.Entities.Add(objectsEntity); LoadObjects( contentManager, objectsEntity, heightMap, mapFile.ObjectsList.Objects, result.Settings); foreach (var team in mapFile.SidesList.Teams ?? mapFile.Teams.Items) { var name = (string)team.Properties["teamName"].Value; var owner = (string)team.Properties["teamOwner"].Value; var isSingleton = (bool)team.Properties["teamIsSingleton"].Value; // TODO } var waypointPaths = mapFile.WaypointsList.WaypointPaths.Select(path => { var start = result.Settings.Waypoints[path.StartWaypointID]; var end = result.Settings.Waypoints[path.EndWaypointID]; return(new Settings.WaypointPath(start, end)); }).ToList(); result.Settings.WaypointPaths = new WaypointPathCollection(waypointPaths); var scriptsEntity = new Entity(); result.Entities.Add(scriptsEntity); // TODO: Don't hardcode this. // Perhaps add one ScriptComponent for the neutral player, // and one for the active player. var scriptList = (mapFile.SidesList.PlayerScripts ?? mapFile.PlayerScriptsList).ScriptLists[0]; AddScripts(scriptsEntity, scriptList, result.Settings); return(result); }
public void GenerateMesh(RoadTemplate template, HeightMap heightMap, List <RoadShaderResources.RoadVertex> vertices, List <ushort> indices) { const float heightBias = 1f; const float createNewVerticesHeightDeltaThreshold = 0.002f; var rightToPosition = Position - Right.Position; var startPosition = Position + rightToPosition; startPosition.Z = heightMap.GetHeight(startPosition.X, startPosition.Y); var endPosition = new Vector3( Right.Position.X, Right.Position.Y, heightMap.GetHeight(Right.Position.X, Right.Position.Y)); var distance = Vector3.Distance(startPosition, endPosition); var direction = Vector3.Normalize(rightToPosition); var centerToEdgeDirection = Vector3.Cross(Vector3.UnitZ, direction); var up = Vector3.Cross(direction, centerToEdgeDirection); var halfWidth = template.RoadWidth / 2; var initialVertexCount = vertices.Count; void AddVertexPair(in Vector3 position, float distanceAlongRoad) { var u = MathUtility.Lerp(0.71f, 0.96f, distanceAlongRoad / template.RoadWidth); var p0 = position - centerToEdgeDirection * halfWidth; p0.Z += heightBias; vertices.Add(new RoadShaderResources.RoadVertex { Position = p0, Normal = up, UV = new Vector2(u, 0.37f) }); var p1 = position + centerToEdgeDirection * halfWidth; p1.Z += heightBias; vertices.Add(new RoadShaderResources.RoadVertex { Position = p1, Normal = up, UV = new Vector2(u, 0.62f) }); } AddVertexPair(startPosition, 0); var previousPoint = startPosition; var previousPointDistance = 0; for (var currentDistance = 10; currentDistance < distance; currentDistance += 10) { var position = startPosition + direction * currentDistance; var actualHeight = heightMap.GetHeight(position.X, position.Y); var interpolatedHeight = MathUtility.Lerp(previousPoint.Z, endPosition.Z, (currentDistance - previousPointDistance) / distance); if (Math.Abs(actualHeight - interpolatedHeight) > createNewVerticesHeightDeltaThreshold) { AddVertexPair(position, currentDistance); previousPoint = position; previousPointDistance = currentDistance; } } // Add last chunk. AddVertexPair(endPosition, distance); for (var i = initialVertexCount; i < vertices.Count - 2; i += 2) { indices.Add((ushort)(i + 0)); indices.Add((ushort)(i + 1)); indices.Add((ushort)(i + 2)); indices.Add((ushort)(i + 1)); indices.Add((ushort)(i + 2)); indices.Add((ushort)(i + 3)); } }
static void Main(string[] args) { // Launch Debugger Debugger(); Clocker.AddAndStartClock("TotalClock"); Clocker.AddAndStartClock("PipeClock"); if (args.Length != 1) { Console.WriteLine("Pipe requires only one argument"); return; } PipeClient pipeClient = new PipeClient(args[0]); pipeClient.Init(); int ySize; int zSize; int xSize; Differ differ; // Biome, HeightMap, WaterMask and TreeMask arrays/bitmap Biomes[][] biomes; int[][] heightMap; int[][] waterMap; int[][] treeMap; float[][] deltaMap; bool[][] acceptableMap; int[][] villageMap; int[][] houseMap; int[][] roadMap; int[][] mainRoadMap; bool[][] lavaMap; using (BinaryReader reader = pipeClient.ReadMemoryBlock()) { Material[][][] blocks; ySize = reader.ReadInt16(); zSize = reader.ReadInt16(); xSize = reader.ReadInt16(); Console.WriteLine($"Y: {ySize} Z: {zSize} X: {xSize}"); blocks = new Material[ySize][][]; for (int y = 0; y < ySize; y++) { blocks[y] = new Material[zSize][]; for (int z = 0; z < zSize; z++) { blocks[y][z] = new Material[xSize]; for (int x = 0; x < xSize; x++) { blocks[y][z][x] = AlphaMaterials.Set.GetMaterial(reader.ReadInt16(), reader.ReadInt16()); } } } differ = new Differ(blocks); // Biome, HeightMap, WaterMask and TreeMask arrays/bitmap biomes = new Biomes[zSize][]; heightMap = new int[zSize][]; waterMap = new int[zSize][]; treeMap = new int[zSize][]; deltaMap = new float[zSize][]; acceptableMap = new bool[zSize][]; villageMap = new int[zSize][]; houseMap = new int[zSize][]; roadMap = new int[zSize][]; mainRoadMap = new int[zSize][]; lavaMap = new bool[zSize][]; for (int z = 0; z < zSize; z++) { biomes[z] = new Biomes[xSize]; heightMap[z] = new int[xSize]; waterMap[z] = new int[xSize]; treeMap[z] = new int[xSize]; deltaMap[z] = new float[xSize]; acceptableMap[z] = new bool[xSize]; villageMap[z] = new int[xSize]; houseMap[z] = new int[xSize]; roadMap[z] = new int[xSize]; mainRoadMap[z] = new int[xSize]; lavaMap[z] = new bool[xSize]; for (int x = 0; x < xSize; x++) { biomes[z][x] = (Biomes)reader.ReadInt16(); heightMap[z][x] = reader.ReadInt16(); waterMap[z][x] = reader.ReadInt16(); treeMap[z][x] = 0; deltaMap[z][x] = 0; } } } Clocker.PauseClock("PipeClock"); Console.WriteLine("Ora pro nobis"); Clocker.AddAndStartClock("AlgorithmClock"); { Tasker.WorkChunk[] workChunks = { (int zStart, int zEnd, int xStart, int xEnd) => { HeightMap.FixBoxHeights(differ.World,heightMap, treeMap, zStart, xStart, zEnd, xEnd); } }; Tasker.Run2DTasks(zSize, xSize, workChunks, null); } { // Delta Map & Lava Map Tasker.WorkBlock[] workBlocks = { (int z, int x) => { DeltaMap.CalculateDeltaMap(heightMap, waterMap, deltaMap, z, x); TreeMap.ExpandTreeBlock(z, x, treeMap); lavaMap[z][x] = LavaMap.isAcceptableLavaMapBlock(heightMap,differ.World, z, x); } }; Tasker.Run2DTasks(zSize, xSize, null, workBlocks); } { // Acceptable Map Tasker.WorkBlock[] isAcceptable = { (int z, int x) => { acceptableMap[z][x] = DeltaMap.IsAcceptableBlock(deltaMap, z, x) && HeightMap.IsAcceptableTreeMapBlock(treeMap, z, x) && waterMap[z][x] != 1 && !lavaMap[z][x]; } }; Tasker.Run2DTasks(zSize, xSize, null, isAcceptable); } WaterAnalyzer.WaterAnalysis waterAnalysis; { int minWaterSize = 20; waterAnalysis = WaterAnalyzer.AnalyzeWater(waterMap, minWaterSize); Console.WriteLine($"Min Water Body Size {minWaterSize}"); Console.WriteLine($"Found {waterAnalysis.WaterBodies.Count} valid Water Bodies and {waterAnalysis.InvalidWaterBodies.Count} Invalid ones"); Console.WriteLine("Valid Water Bodies Sizes"); foreach (var waterBody in waterAnalysis.WaterBodies) { Console.WriteLine($"\tSize {waterBody.Points.Count}"); } Console.WriteLine("Invalid Water Bodies Sizes"); foreach (var waterBody in waterAnalysis.InvalidWaterBodies) { Console.WriteLine($"\tSize {waterBody.Points.Count}"); } } DataQuadTree <Vector2Int> roadQT = new DataQuadTree <Vector2Int>(new Vector2Int(), new Vector2Int(zSize - 1, xSize - 1)); List <VillageMarker> villages; List <List <Vector2Int> > roads = new List <List <Vector2Int> >(); { int numberOfTries = 1000; int expectedVillageSize = 2500; int radius = 4; int villageCount = 3; int maxVillageCount = 3; villages = VillageDistributor.DistributeVillageMarkers( acceptableMap, villageMap, waterAnalysis, villageCount, maxVillageCount, numberOfTries, radius, expectedVillageSize ); bool mainRoadPlaced = false; int mainRoadVillageStart = -1, mainRoadVillageEnd = -1; if (villages.Count > 1) { for (int i = 0; i < villages.Count - 1; i++) { for (int j = i + 1; j < villages.Count; j++) { List <Vector2Int> road = RoadGenerator.FirstRoad( villages[i].Seed.Z, villages[i].Seed.X, villages[j].Seed.Z, villages[j].Seed.X, acceptableMap, deltaMap, waterMap, roadMap, treeMap, houseMap ); if (road.Count > 0) { mainRoadPlaced = true; mainRoadVillageStart = i; mainRoadVillageEnd = j; Console.WriteLine("Main Road length: " + road.Count); roads.Add(road); foreach (Vector2Int roadPoint in road) { roadQT.Insert(roadPoint, roadPoint); mainRoadMap[roadPoint.Z][roadPoint.X] = 1; } break; } } if (mainRoadPlaced) { break; } } } if (mainRoadPlaced) { for (int i = 0; i < villages.Count; ++i) { if (i != mainRoadVillageStart && i != mainRoadVillageEnd) { Console.WriteLine($"Connecting village: {i} to roads"); List <Vector2Int> road = RoadGenerator.PointToRoad( villages[i].Seed.Z, villages[i].Seed.X, acceptableMap, deltaMap, waterMap, roadMap, treeMap, houseMap, roadQT ); roads.Add(road); foreach (Vector2Int roadPoint in road) { roadQT.Insert(roadPoint, roadPoint); } } } //RoadPlacer.RoadsPlacer(roads, roadMap, heightMap, waterMap, biomes, differ); } else { Console.WriteLine("Failed to Place all the roads"); } } DataQuadTree <RectInt> villagesQT = new DataQuadTree <RectInt>(new Vector2Int(0, 0), new Vector2Int(zSize, xSize)); foreach (VillageMarker village in villages) { HouseDistributor.FillVillage(deltaMap, heightMap, acceptableMap, houseMap, roadMap, villageMap, waterMap, treeMap, biomes, village, differ.World, new Vector2Int(8, 8), differ, villagesQT, roadQT, ref roads); } RoadPlacer.RoadsPlacer(roads, roadMap, heightMap, waterMap, biomes, differ); { // Drawing Mapper.SaveMapInfo[] saveMapInfos = { new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "villagemap", colorWork = (int z, int x) =>{ if (villageMap[z][x] >= 1) { return(Color.Yellow); } else if (acceptableMap[z][x] && villageMap[z][x] <= 0) { return(Color.Orange); } return(Color.Transparent); }, specialColors = (Mapper.ColorApplier colorApplier) => { for (int i = 0; i < villages.Count; i++) { colorApplier.Invoke(villages[i].Seed.Z, villages[i].Seed.X, Color.Blue); } } }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "acceptablemap", colorWork = (int z, int x) =>{ if (acceptableMap[z][x]) { return(Color.Green); } else { return(Color.Red); } }, specialColors = null }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "deltamap", colorWork = (int z, int x) =>{ if (0 <= deltaMap[z][x] && deltaMap[z][x] <= DeltaMap.kMaxDelta) { float tVal = 1.0f - deltaMap[z][x] / DeltaMap.kMaxDelta; return(Color.FromRgba(0, (byte)(255.0f * tVal + 100.0f * (1.0f - tVal)), 0, 255)); } else if (deltaMap[z][x] > DeltaMap.kMaxDelta) { return(Color.Red); } return(Color.Transparent); }, specialColors = null }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "treemap", colorWork = (int z, int x) =>{ if (treeMap[z][x] == 1) { return(Color.Green); } else if (treeMap[z][x] == 2) { return(Color.Brown); } else if (treeMap[z][x] == 3) { return(Color.DarkSeaGreen); } return(Color.Transparent); }, specialColors = null }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "heightmap", colorWork = (int z, int x) =>{ if (heightMap[z][x] >= 0) { return(Color.FromRgba((byte)heightMap[z][x], (byte)heightMap[z][x], (byte)heightMap[z][x], 255)); } else { return(Color.Red); } }, specialColors = null }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "watermap", colorWork = (int z, int x) =>{ if (waterMap[z][x] == 1) { return(Color.Blue); } return(Color.Transparent); }, specialColors = null }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "houseMap", colorWork = (int z, int x) =>{ if (houseMap[z][x] == 1) { return(Color.Brown); } return(Color.Transparent); }, specialColors = null }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "roadMap", colorWork = (int z, int x) =>{ switch (roadMap[z][x]) { case RoadGenerator.MainRoadMarker: return(Color.PaleVioletRed); case RoadGenerator.RoadMarker: return(Color.Purple); case RoadGenerator.BridgeMarker: return(Color.Brown); case RoadGenerator.MainBridgeMarker: return(Color.BurlyWood); default: return(Color.Transparent); } }, specialColors = null }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "mainRoadMap", colorWork = (int z, int x) =>{ if (mainRoadMap[z][x] == 1) { return(Color.Turquoise); } return(Color.Transparent); }, specialColors = null }, new Mapper.SaveMapInfo { zSize = zSize, xSize = xSize, name = "lavaMap", colorWork = (int z, int x) =>{ if (lavaMap[z][x]) { return(Color.DarkRed); } return(Color.Transparent); }, specialColors = null } }; Mapper.SaveMaps(saveMapInfos); } // Write Data Back to Python { using (BinaryWriter writer = new BinaryWriter(new MemoryStream())) { differ.SerializeChanges(writer); // Return data To Python Console.WriteLine(writer.BaseStream.Length); pipeClient.WriteMemoryBlock((MemoryStream)writer.BaseStream); } } // Close Pipe pipeClient.DeInit(); Clocker.PauseClock("AlgorithmClock"); Clocker.PauseClock("TotalClock"); double pipeTime = Clocker.GetTime("PipeClock", true); double algoTime = Clocker.GetTime("AlgorithmClock", true); double totalTime = Clocker.GetTime("TotalClock", true); Clocker.PrintAllTime(true, true, true); Clocker.RemoveClock("PipeClock", true, true, true); Clocker.RemoveClock("AlgorithmClock", true, true, true); Clocker.RemoveClock("TotalClock", true, true, true); Console.WriteLine($"Pipe Percentage of Time: {pipeTime / totalTime * 100.0}% ({pipeTime} secs)"); Console.WriteLine($"Algorithm Percentage of Time: {algoTime / totalTime * 100.0}% ({algoTime} secs)"); }
public CollisionDetector(SharedList particleList, HeightMap heightMap) { _particleList = particleList; _heightMap = heightMap; initCells(); }
/// Creates a height map with a rectangular area of @a pattern repeating infinitely in all /// directions. The repeating pattern will start at point [0, 0]. /// /// Example: /// @code{.cs} /// var pattern = HeightMap.RadialGradient([100, 100], 200, 1, -1); /// yield HeightMap.Pattern(pattern, [0, 0], [200, 200]); /// @endcode /// /// @image html std_2d_pattern.png /// /// @param pattern The height map from which the pattern is copied. /// @param firstRectanglePoint First point defining the pattern rectangle. /// @param secondRectanglePoint Second point defining the pattern rectangle. /// @return The height map. static HeightMap Pattern(HeightMap pattern, Point firstRectanglePoint, Point secondRectanglePoint);
private void LoadObjects( ContentManager contentManager, HeightMap heightMap, MapObject[] mapObjects, Team[] teams, out WaypointCollection waypointCollection, out GameObjectCollection gameObjects, out Road[] roads, out Bridge[] bridges) { var waypoints = new List <Waypoint>(); gameObjects = new GameObjectCollection(contentManager); var roadsList = new List <Road>(); var bridgesList = new List <Bridge>(); var roadTopology = new RoadTopology(); for (var i = 0; i < mapObjects.Length; i++) { var mapObject = mapObjects[i]; var position = mapObject.Position; switch (mapObject.RoadType & RoadType.PrimaryType) { case RoadType.None: switch (mapObject.TypeName) { case "*Waypoints/Waypoint": waypoints.Add(CreateWaypoint(mapObject)); break; default: position.Z += heightMap.GetHeight(position.X, position.Y); var gameObject = CreateGameObject(mapObject, teams, contentManager); if (gameObject != null) { gameObject.Transform.Translation = position; gameObject.Transform.Rotation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, mapObject.Angle); gameObjects.Add(gameObject); if (gameObject.Definition.IsBridge) { // This is a landmark bridge. We need to add towers at the corners. CreateTowers(contentManager, gameObjects, gameObject, mapObject); } } break; } break; case RoadType.BridgeStart: case RoadType.BridgeEnd: // Multiple invalid bridges can be found in e.g GLA01. // TODO: Log a warning. if ((i + 1) >= mapObjects.Length || !mapObjects[i + 1].RoadType.HasFlag(RoadType.BridgeEnd)) { continue; } var bridgeEnd = mapObjects[++i]; var bridgeTemplate = GetBridgeTemplate(contentManager, mapObject); if (Bridge.TryCreateBridge( contentManager, heightMap, bridgeTemplate, mapObject.Position, bridgeEnd.Position, out var bridge)) { bridgesList.Add(AddDisposable(bridge)); } break; case RoadType.Start: case RoadType.End: var roadEnd = mapObjects[++i]; // Some maps have roads with invalid start- or endpoints. // We'll skip processing them altogether. // TODO: Log a warning. if (mapObject.TypeName == "" || roadEnd.TypeName == "") { continue; } if (!mapObject.RoadType.HasFlag(RoadType.Start) || !roadEnd.RoadType.HasFlag(RoadType.End)) { throw new InvalidDataException(); } // Note that we're searching with the type of either end. // This is because of weirdly corrupted roads with unmatched ends in USA04, which work fine in WB and SAGE. var roadTemplate = contentManager.IniDataContext.RoadTemplates.Find(x => x.Name == mapObject.TypeName || x.Name == roadEnd.TypeName); if (roadTemplate == null) { throw new InvalidDataException($"Missing road template: {mapObject.TypeName}"); } roadTopology.AddSegment(roadTemplate, mapObject, roadEnd); break; } contentManager.GraphicsDevice.WaitForIdle(); } // The map stores road segments with no connectivity: // - a segment is from point A to point B // - with a road type name // - and start and end curve types (angled, tight curve, broad curve). // The goal is to create road networks of connected road segments, // where a network has only a single road type. // A road network is composed of 2 or more nodes. // A network is a (potentially) cyclic graph. // A road node has > 1 and <= 4 edges connected to it. // A node can be part of multiple networks. // An edge can only exist in one network. // TODO: If a node stored in the map has > 4 edges, the extra edges // are put into a separate network. var networks = roadTopology.BuildNetworks(); foreach (var network in networks) { foreach (var edge in network.Edges) { var startPosition = edge.Start.TopologyNode.Position; var endPosition = edge.End.TopologyNode.Position; startPosition.Z += heightMap.GetHeight(startPosition.X, startPosition.Y); endPosition.Z += heightMap.GetHeight(endPosition.X, endPosition.Y); roadsList.Add(AddDisposable(new Road( contentManager, heightMap, edge.TopologyEdge.Template, startPosition, endPosition))); } } waypointCollection = new WaypointCollection(waypoints); roads = roadsList.ToArray(); bridges = bridgesList.ToArray(); }
private void Erode(HeightMap heightMap) { var erosion = new _7DaysToDie.Erosion.Erosion(); erosion.Erode(heightMap, heightMap.Size, 1000000, true); }
private void fillHeightMap(){ p_heightMap = new HeightMap (heightMapSize); p_heightMap.terrainSize = p_terrainSize; HeightMapGeneratorIsland heightMapGenerator = new HeightMapGeneratorIsland (); heightMapGenerator.groundNoise = p_groundNoise; heightMapGenerator.mountainNoise = p_mountainNoise; heightMapGenerator.generate (p_heightMap); p_terrain.terrainData.SetHeights (0, 0, p_heightMap.map); }
protected override Scene3D LoadEntry(FileSystemEntry entry, ContentManager contentManager, Game game, LoadOptions loadOptions) { switch (contentManager.SageGame) { case SageGame.Ra3: case SageGame.Ra3Uprising: case SageGame.Cnc4: // TODO break; default: contentManager.IniDataContext.LoadIniFile(@"Data\INI\Terrain.ini"); contentManager.IniDataContext.LoadIniFile(@"Data\INI\Roads.ini"); break; } var mapFile = MapFile.FromFileSystemEntry(entry); var heightMap = new HeightMap(mapFile.HeightMapData); var indexBufferCache = AddDisposable(new TerrainPatchIndexBufferCache(contentManager.GraphicsDevice)); var tileDataTexture = AddDisposable(CreateTileDataTexture( contentManager.GraphicsDevice, mapFile, heightMap)); var cliffDetailsBuffer = AddDisposable(CreateCliffDetails( contentManager.GraphicsDevice, mapFile)); CreateTextures( contentManager, mapFile.BlendTileData, out var textureArray, out var textureDetails); var textureDetailsBuffer = AddDisposable(contentManager.GraphicsDevice.CreateStaticStructuredBuffer(textureDetails)); var terrainPipeline = contentManager.ShaderResources.Terrain.Pipeline; Texture LoadTexture(string name) { var texture = contentManager.Load <Texture>(Path.Combine("Art", "Textures", name), fallbackToPlaceholder: false); if (texture == null) { texture = contentManager.Load <Texture>(Path.Combine("Art", "CompiledTextures", name.Substring(0, 2), name)); } return(texture); } var materialConstantsBuffer = AddDisposable(contentManager.GraphicsDevice.CreateStaticBuffer( new TerrainShaderResources.TerrainMaterialConstants { MapBorderWidth = new Vector2(mapFile.HeightMapData.BorderWidth, mapFile.HeightMapData.BorderWidth) * HeightMap.HorizontalScale, MapSize = new Vector2(mapFile.HeightMapData.Width, mapFile.HeightMapData.Height) * HeightMap.HorizontalScale, IsMacroTextureStretched = false // TODO: This must be one of the EnvironmentData unknown values. }, BufferUsage.UniformBuffer)); var macroTexture = LoadTexture(mapFile.EnvironmentData?.MacroTexture ?? "tsnoiseurb.dds"); var materialResourceSet = AddDisposable(contentManager.ShaderResources.Terrain.CreateMaterialResourceSet( materialConstantsBuffer, tileDataTexture, cliffDetailsBuffer ?? contentManager.GetNullStructuredBuffer(TerrainShaderResources.CliffInfo.Size), textureDetailsBuffer, textureArray, macroTexture)); var terrainPatches = CreatePatches( contentManager.GraphicsDevice, heightMap, mapFile.BlendTileData, indexBufferCache, materialResourceSet); var cloudTexture = LoadTexture(mapFile.EnvironmentData?.CloudTexture ?? "tscloudmed.dds"); var cloudResourceLayout = AddDisposable(contentManager.GraphicsDevice.ResourceFactory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("Global_CloudTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment)))); var cloudResourceSet = AddDisposable(contentManager.GraphicsDevice.ResourceFactory.CreateResourceSet( new ResourceSetDescription( cloudResourceLayout, cloudTexture))); var terrain = new Terrain.Terrain( heightMap, terrainPatches, contentManager.ShaderResources.Terrain.ShaderSet, terrainPipeline, cloudResourceSet); var players = Player.FromMapData(mapFile.SidesList.Players, contentManager).ToArray(); var teams = (mapFile.SidesList.Teams ?? mapFile.Teams.Items) .Select(team => Team.FromMapData(team, players)) .ToArray(); LoadObjects( contentManager, heightMap, mapFile.ObjectsList.Objects, teams, out var waypoints, out var gameObjects, out var roads, out var bridges); var waterAreas = new List <WaterArea>(); if (mapFile.PolygonTriggers != null) { foreach (var polygonTrigger in mapFile.PolygonTriggers.Triggers) { switch (polygonTrigger.TriggerType) { case PolygonTriggerType.Water: case PolygonTriggerType.River: // TODO: Handle this differently. Water texture should be animated "downstream". case PolygonTriggerType.WaterAndRiver: if (WaterArea.TryCreate(contentManager, polygonTrigger, out var waterArea)) { waterAreas.Add(AddDisposable(waterArea)); } break; } } } var lighting = new WorldLighting( mapFile.GlobalLighting.LightingConfigurations.ToLightSettingsDictionary(), mapFile.GlobalLighting.Time); var waypointPaths = new WaypointPathCollection(mapFile.WaypointsList.WaypointPaths .Select(path => { var start = waypoints[path.StartWaypointID]; var end = waypoints[path.EndWaypointID]; return(new Settings.WaypointPath(start, end)); })); // TODO: Don't hardcode this. // Perhaps add one ScriptComponent for the neutral player, // and one for the active player. var scriptList = mapFile.GetPlayerScriptsList().ScriptLists[0]; var mapScripts = CreateScripts(scriptList); var cameraController = new RtsCameraController(contentManager) { TerrainPosition = terrain.HeightMap.GetPosition( terrain.HeightMap.Width / 2, terrain.HeightMap.Height / 2) }; contentManager.GraphicsDevice.WaitForIdle(); return(new Scene3D( game, game.InputMessageBuffer, () => game.Viewport, cameraController, mapFile, terrain, waterAreas.ToArray(), roads, bridges, mapScripts, gameObjects, waypoints, waypointPaths, lighting, players, teams)); }
protected override Scene3D LoadEntry(FileSystemEntry entry, ContentManager contentManager, Game game, LoadOptions loadOptions) { switch (contentManager.SageGame) { case SageGame.Ra3: case SageGame.Ra3Uprising: case SageGame.Cnc4: // TODO break; default: contentManager.IniDataContext.LoadIniFile(@"Data\INI\Terrain.ini"); break; } var mapFile = MapFile.FromFileSystemEntry(entry); var heightMap = new HeightMap(mapFile.HeightMapData); var indexBufferCache = AddDisposable(new TerrainPatchIndexBufferCache(contentManager.GraphicsDevice)); var tileDataTexture = AddDisposable(CreateTileDataTexture( contentManager.GraphicsDevice, mapFile, heightMap)); var cliffDetailsBuffer = AddDisposable(CreateCliffDetails( contentManager.GraphicsDevice, mapFile)); CreateTextures( contentManager, mapFile.BlendTileData, out var textureArray, out var textureDetails); var textureDetailsBuffer = AddDisposable(contentManager.GraphicsDevice.CreateStaticStructuredBuffer(textureDetails)); var terrainMaterial = AddDisposable(new TerrainMaterial(contentManager, contentManager.EffectLibrary.Terrain)); terrainMaterial.SetTileData(tileDataTexture); terrainMaterial.SetCliffDetails(cliffDetailsBuffer); terrainMaterial.SetTextureDetails(textureDetailsBuffer); terrainMaterial.SetTextureArray(textureArray); var terrainPatches = CreatePatches( contentManager.GraphicsDevice, heightMap, mapFile.BlendTileData, terrainMaterial, indexBufferCache); var cloudTextureName = mapFile.EnvironmentData?.CloudTexture ?? "tscloudmed.dds"; var cloudTexture = contentManager.Load <Texture>(Path.Combine("Art", "Textures", cloudTextureName)); var macroTextureName = mapFile.EnvironmentData?.MacroTexture ?? "tsnoiseurb.dds"; var macroTexture = contentManager.Load <Texture>(Path.Combine("Art", "Textures", macroTextureName)); var materialConstantsBuffer = AddDisposable(contentManager.GraphicsDevice.CreateStaticBuffer( new TerrainMaterial.TerrainMaterialConstants { MapBorderWidth = new Vector2(mapFile.HeightMapData.BorderWidth, mapFile.HeightMapData.BorderWidth) * HeightMap.HorizontalScale, MapSize = new Vector2(mapFile.HeightMapData.Width, mapFile.HeightMapData.Height) * HeightMap.HorizontalScale, IsMacroTextureStretched = false // TODO: This must be one of the EnvironmentData unknown values. }, BufferUsage.UniformBuffer)); terrainMaterial.SetMaterialConstants(materialConstantsBuffer); var terrain = new Terrain.Terrain( heightMap, terrainPatches, cloudTexture, macroTexture, contentManager.SolidWhiteTexture); LoadObjects( contentManager, heightMap, mapFile.ObjectsList.Objects, out var waypoints, out var gameObjects); foreach (var team in mapFile.SidesList.Teams ?? mapFile.Teams.Items) { var name = (string)team.Properties["teamName"].Value; var owner = (string)team.Properties["teamOwner"].Value; var isSingleton = (bool)team.Properties["teamIsSingleton"].Value; // TODO } var lighting = new WorldLighting( mapFile.GlobalLighting.LightingConfigurations.ToLightSettingsDictionary(), mapFile.GlobalLighting.Time); var waypointPaths = new WaypointPathCollection(mapFile.WaypointsList.WaypointPaths .Select(path => { var start = waypoints[path.StartWaypointID]; var end = waypoints[path.EndWaypointID]; return(new Settings.WaypointPath(start, end)); })); // TODO: Don't hardcode this. // Perhaps add one ScriptComponent for the neutral player, // and one for the active player. var scriptList = mapFile.GetPlayerScriptsList().ScriptLists[0]; var mapScripts = CreateScripts(scriptList); var cameraController = new RtsCameraController(contentManager) { TerrainPosition = terrain.HeightMap.GetPosition( terrain.HeightMap.Width / 2, terrain.HeightMap.Height / 2) }; contentManager.GraphicsDevice.WaitForIdle(); return(new Scene3D( game, cameraController, mapFile, terrain, mapScripts, gameObjects, waypoints, waypointPaths, lighting)); }
private static DeviceBuffer CreateVertexBuffer( GraphicsDevice graphicsDevice, HeightMap heightMap, Rectangle patchBounds, ushort[] indices, out BoundingBox boundingBox, out Triangle[] triangles) { var numVertices = patchBounds.Width * patchBounds.Height; var vertices = new TerrainVertex[numVertices]; var points = new Vector3[numVertices]; var vertexIndex = 0; for (var y = patchBounds.Y; y < patchBounds.Y + patchBounds.Height; y++) { for (var x = patchBounds.X; x < patchBounds.X + patchBounds.Width; x++) { var position = heightMap.GetPosition(x, y); points[vertexIndex] = position; vertices[vertexIndex++] = new TerrainVertex { Position = position, Normal = heightMap.Normals[x, y], UV = new Vector2(x, y) }; } } boundingBox = BoundingBox.CreateFromPoints(points); triangles = new Triangle[(patchBounds.Width - 1) * (patchBounds.Height) * 2]; var triangleIndex = 0; var indexIndex = 0; for (var y = 0; y < patchBounds.Height - 1; y++) { for (var x = 0; x < patchBounds.Width - 1; x++) { // Triangle 1 triangles[triangleIndex++] = new Triangle { V0 = points[indices[indexIndex++]], V1 = points[indices[indexIndex++]], V2 = points[indices[indexIndex++]] }; // Triangle 2 triangles[triangleIndex++] = new Triangle { V0 = points[indices[indexIndex++]], V1 = points[indices[indexIndex++]], V2 = points[indices[indexIndex++]] }; } } return(graphicsDevice.CreateStaticBuffer(vertices, BufferUsage.VertexBuffer)); }
public Terrain(HeightMap map, IColorizer colorizer) : base(map) { Colorizer = colorizer; Image = new Image(colorizer.Colorize(this)); }
public void RequestMesh(HeightMap heightMap, MeshSettings meshSettings) { hasRequestedMesh = true; ThreadedDataRequester.RequestData(() => MeshGenerator.GenerateTerrainMesh(heightMap.values, meshSettings, lod), OnMeshDataReceived); }
public Environment(HeightMap terrain = null) { Terrain = terrain; }
public ModelRoot AddTerrainMesh(ModelRoot model, HeightMap heightMap, PBRTexture textures) { Triangulation triangulation = _meshService.TriangulateHeightMap(heightMap); return(AddTerrainMesh(model, triangulation, textures)); }