代码拉取完成,页面将自动刷新
#include "map.h"
#include <cmath>
// 初始化地图高度数据
std::vector<std::vector<float>> heightMap(MAP_WIDTH, std::vector<float>(MAP_HEIGHT, 0.0f));
std::vector<std::pair<int, int>> highPoints;
// 随机生成高度值,但限制相邻高度差并限制最大高度
int GenerateRandomHeight(int currentHeight) {
int height = currentHeight + (std::rand() % (MAX_HEIGHT_DIFF + 1) - MAX_HEIGHT_DIFF/2);
return std::max(-5, height); // 确保高度不为负值
}
// 获取给定位置的高度
float GetHeightAtPosition(float x, float z) {
// 将 x 和 z 转换为地图坐标系
int ix = static_cast<int>(x) + 50;
int iz = static_cast<int>(z) + 50;
ix = clamp(ix, 0, MAP_WIDTH - 1);
iz = clamp(iz, 0, MAP_HEIGHT - 1);
return heightMap[ix][iz];
}
// 生成高度数据并保存到文件
void GenerateHeightMap(const std::string& filename, std::vector<std::pair<int, int>>& highPoints) {
std::ofstream file(filename);
if (!file.is_open()) {
std::cerr << "Failed to open file for writing: " << filename << std::endl;
return;
}
std::srand(std::time(nullptr));
std::vector<std::vector<int>> heightMap(MAP_WIDTH, std::vector<int>(MAP_HEIGHT, 1));
// 生成高原区域
for (int x = 0; x < 20; ++x) {
for (int z = 0; z < 20; ++z) {
heightMap[x][z] = HIGHLAND_HEIGHT;
}
}
// 中间区域30-70高度为0,35-65为1
for (int x = 30; x <= 70; ++x) {
for (int z = 30; z <= 70; ++z) {
if (x >= 35 && x <= 65 && z >= 35 && z <= 65) {
heightMap[x][z] = 0;
}
else {
heightMap[x][z] = 1;
}
}
}
// 生成其余随机区域,控制相邻高度差并限制最大高度
for (int x = 0; x < MAP_WIDTH; ++x) {
for (int z = 0; z < MAP_HEIGHT; ++z) {
if ((x < 20 && z < 20) || (x >= 30 && x <= 70 && z >= 30 && z <= 70)) {
continue; // 跳过已生成的高原和中间区域
}
int sumHeight = 0;
int count = 0;
// 考虑周围一圈的内容
for (int dx = -1; dx <= 1; ++dx) {
for (int dz = -1; dz <= 1; ++dz) {
int nx = x + dx;
int nz = z + dz;
if (nx >= 0 && nx < MAP_WIDTH && nz >= 0 && nz < MAP_HEIGHT) {
sumHeight += heightMap[nx][nz];
++count;
}
}
}
int avgHeight = sumHeight / count;
heightMap[x][z] = GenerateRandomHeight(avgHeight);
if (heightMap[x][z] > 2) {
highPoints.push_back({ x - 50, z - 50 });
}
}
}
// 保存到文件
for (int x = 0; x < MAP_WIDTH; ++x) {
for (int z = 0; z < MAP_HEIGHT; ++z) {
file << heightMap[x][z] << " ";
}
file << std::endl;
}
file.close();
std::cout << "Height map generated and saved to " << filename << std::endl;
}
void LoadHeightMapFromFile(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Failed to open height map file: " << filename << std::endl;
return;
}
for (int x = 0; x < MAP_WIDTH; ++x) {
for (int z = 0; z < MAP_HEIGHT; ++z) {
if (!(file >> heightMap[x][z])) {
std::cerr << "Error reading height data at (" << x << ", " << z << ")" << std::endl;
return;
}
}
}
file.close();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。