using UnityEngine;
using System.Collections.Generic;
public class AdvancedTerrainGenerator : MonoBehaviour
{
[Header("Basic Settings")]
public int size = 256;
public float baseRoughness = 2.0f;
public float minHeight = -50f;
public float maxHeight = 150f;
[Header("Noise Settings")]
public int octaves = 6;
public float persistence = 0.5f;
public float lacunarity = 2.0f;
public float noiseScale = 50f;
public Vector2 noiseOffset;
[Header("Erosion Settings")]
public int erosionIterations = 50000;
public float erosionStrength = 0.5f;
public float erosionRadius = 3f;
public float sedimentCapacity = 4f;
public float evaporationSpeed = 0.5f;
[Header("Biome Settings")]
public float moistureScale = 20f;
public float temperatureScale = 30f;
private float[,] heightMap;
private float[,] moistureMap;
private float[,] temperatureMap;
private Terrain terrain;
void Start()
{
terrain = GetComponent<Terrain>();
if (terrain == null)
{
Debug.LogError("Terrain component not found!");
return;
}
GenerateTerrain();
}
void GenerateTerrain()
{
// Инициализация карт
heightMap = new float[size, size];
moistureMap = new float[size, size];
temperatureMap = new float[size, size];
// Генерация базового рельефа
GenerateBaseHeightMap();
// Добавление шума Перлина
AddPerlinNoise();
// Применение гидравлической эрозии
ApplyHydraulicErosion();
// Генерация карт влажности и температуры
GenerateBiomeData();
// Применение биомов
ApplyBiomes();
// Сглаживание
SmoothTerrain();
// Применение к террейну
ApplyHeightMap();
}
void GenerateBaseHeightMap()
{
// Diamond-Square алгоритм (из предыдущего примера)
// ... (код из предыдущего примера) ...
}
void AddPerlinNoise()
{
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float amplitude = 1;
float frequency = 1;
float noiseHeight = 0;
// Сложение нескольких октав шума
for (int i = 0; i < octaves; i++)
{
float sampleX = (x + noiseOffset.x) / noiseScale * frequency;
float sampleY = (y + noiseOffset.y) / noiseScale * frequency;
float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
noiseHeight += perlinValue * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
heightMap[x, y] += noiseHeight;
}
}
}
void ApplyHydraulicErosion()
{
for (int iteration = 0; iteration < erosionIterations; iteration++)
{
// Случайная начальная позиция
int x = Random.Range(0, size - 1);
int y = Random.Range(0, size - 1);
float waterVolume = 1;
float sediment = 0;
Vector2 position = new Vector2(x, y);
Vector2 direction = Vector2.zero;
for (int lifetime = 0; lifetime < 30; lifetime++)
{
// Вычисление градиента
Vector2 gradient = CalculateGradient(position);
// Обновление направления
direction = (direction * 0.3f + gradient * 0.7f).normalized;
// Перемещение капли
position += direction;
// Проверка границ
if (position.x < 0 || position.x >= size - 1 || position.y < 0 || position.y >= size - 1)
break;
// Эрозия и отложение
int nodeX = (int)position.x;
int nodeY = (int)position.y;
float oldHeight = heightMap[nodeX, nodeY];
float newHeight = oldHeight;
// Вычисление эрозии
float capacity = Mathf.Max(waterVolume * sedimentCapacity * gradient.magnitude, 0.01f);
if (sediment > capacity)
{
float deposit = (sediment - capacity) * evaporationSpeed;
sediment -= deposit;
newHeight += deposit;
}
else
{
float erosion = Mathf.Min((capacity - sediment) * erosionStrength, oldHeight);
sediment += erosion;
newHeight -= erosion;
}
heightMap[nodeX, nodeY] = newHeight;
// Испарение
waterVolume *= (1 - evaporationSpeed);
}
}
}
Vector2 CalculateGradient(Vector2 pos)
{
int x = (int)pos.x;
int y = (int)pos.y;
float heightL = heightMap[Mathf.Max(x - 1, 0), y];
float heightR = heightMap[Mathf.Min(x + 1, size - 1), y];
float heightD = heightMap[x, Mathf.Max(y - 1, 0)];
float heightU = heightMap[x, Mathf.Min(y + 1, size - 1)];
return new Vector2(heightR - heightL, heightU - heightD) * 0.5f;
}
void GenerateBiomeData()
{
// Генерация карты влажности
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float moisture = Mathf.PerlinNoise(x / moistureScale, y / moistureScale);
moistureMap[x, y] = moisture;
float temperature = Mathf.PerlinNoise(x / temperatureScale + 1000, y / temperatureScale + 1000);
temperatureMap[x, y] = temperature;
}
}
}
void ApplyBiomes()
{
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float height = heightMap[x, y];
float moisture = moistureMap[x, y];
float temperature = temperatureMap[x, y];
// Модификация высоты в зависимости от биома
if (height < 0.2f) // Океан
{
heightMap[x, y] *= 0.3f;
}
else if (height < 0.4f) // Пляж
{
heightMap[x, y] *= 0.7f;
}
else if (temperature > 0.7f && moisture < 0.2f) // Пустыня
{
heightMap[x, y] *= 0.9f;
// Добавляем дюны
heightMap[x, y] += Mathf.PerlinNoise(x * 0.1f, y * 0.1f) * 0.1f;
}
else if (temperature < 0.2f) // Горы
{
heightMap[x, y] *= 1.5f;
// Добавляем острые пики
if (height > 0.7f)
{
heightMap[x, y] *= 1.2f;
}
}
else if (moisture > 0.6f && temperature > 0.3f) // Тропический лес
{
// Добавляем небольшие холмы
heightMap[x, y] += Mathf.PerlinNoise(x * 0.05f, y * 0.05f) * 0.2f;
}
else if (moisture > 0.4f) // Лесистая местность
{
heightMap[x, y] *= 1.1f;
}
}
}
}
void SmoothTerrain()
{
float[,] smoothedHeightMap = new float[size, size];
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float sum = 0;
int count = 0;
// Применяем размытие по Гауссу
for (int offsetY = -2; offsetY <= 2; offsetY++)
{
for (int offsetX = -2; offsetX <= 2; offsetX++)
{
int sampleX = Mathf.Clamp(x + offsetX, 0, size - 1);
int sampleY = Mathf.Clamp(y + offsetY, 0, size - 1);
// Вес по Гауссу
float weight = 1f / (1f + Mathf.Sqrt(offsetX * offsetX + offsetY * offsetY));
sum += heightMap[sampleX, sampleY] * weight;
count++;
}
}
smoothedHeightMap[x, y] = sum / count;
}
}
// Применяем сглаженную карту
heightMap = smoothedHeightMap;
}
void ApplyHeightMap()
{
// Нормализация высот
float[,] normalizedHeightMap = new float[size, size];
float minValue = float.MaxValue;
float maxValue = float.MinValue;
// Находим минимальное и максимальное значения
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
if (heightMap[x, y] < minValue) minValue = heightMap[x, y];
if (heightMap[x, y] > maxValue) maxValue = heightMap[x, y];
}
}
// Нормализуем значения
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
normalizedHeightMap[y, x] = Mathf.InverseLerp(minValue, maxValue, heightMap[x, y]);
}
}
// Настраиваем и применяем к террейну
TerrainData terrainData = terrain.terrainData;
terrainData.heightmapResolution = size;
terrainData.size = new Vector3(size, maxHeight - minHeight, size);
terrainData.SetHeights(0, 0, normalizedHeightMap);
// Добавляем текстуры в зависимости от биома
ApplyTerrainTextures(terrainData);
}
void ApplyTerrainTextures(TerrainData terrainData)
{
// Создаем слои текстур
TerrainLayer[] terrainLayers = new TerrainLayer[6];
// Здесь нужно создать и настроить TerrainLayer для каждого типа местности
// Пример для одного слоя:
terrainLayers[0] = new TerrainLayer
{
diffuseTexture = Resources.Load<Texture2D>("TerrainTextures/Sand"),
tileSize = new Vector2(15, 15)
};
// Установить остальные слои...
terrainData.terrainLayers = terrainLayers;
// Создаем карту смешивания текстур
float[,,] splatmapData = new float[terrainData.alphamapWidth,
terrainData.alphamapHeight,
terrainData.alphamapLayers];
for (int y = 0; y < terrainData.alphamapHeight; y++)
{
for (int x = 0; x < terrainData.alphamapWidth; x++)
{
// Преобразуем координаты
float normX = x * 1.0f / (terrainData.alphamapWidth - 1);
float normY = y * 1.0f / (terrainData.alphamapHeight - 1);
// Получаем высоту и параметры биома
float height = terrainData.GetHeight(
Mathf.RoundToInt(normY * terrainData.heightmapResolution),
Mathf.RoundToInt(normX * terrainData.heightmapResolution)
) / terrainData.size.y;
int mapX = Mathf.RoundToInt(normX * (size - 1));
int mapY = Mathf.RoundToInt(normY * (size - 1));
float moisture = moistureMap[mapX, mapY];
float temperature = temperatureMap[mapX, mapY];
// Распределяем веса текстур
if (height < 0.2f) // Вода
{
splatmapData[y, x, 0] = 1; // Текстура воды
}
else if (height < 0.3f) // Пляж
{
splatmapData[y, x, 1] = 1; // Песок
}
else if (temperature > 0.7f && moisture < 0.2f) // Пустыня
{
splatmapData[y, x, 2] = 1; // Песок пустыни
}
else if (height > 0.7f) // Горы
{
splatmapData[