Remake MapGen (based on polyhedrons)

This commit is contained in:
2025-10-12 03:44:37 +07:00
parent 9f4cc443c5
commit ca56b703e3
19 changed files with 842 additions and 322 deletions

View File

@@ -1,7 +1,15 @@
local mathCeil, mathAbs, mathRound, mathMin
= math.ceil, math.abs, math.round, math.min
local modInfo = Mod.getInfo()
local require = modInfo.require
-- --- MapGen default moises ---
local InterpolationPresets = require("MapGen.InterpolationPresets")
local Layer = require("MapGen.Layer")
local Region = require("MapGen.Region")
local Biome = require("MapGen.Biome")
local mathRound, mathHuge
= math.round, math.huge
-- --- MapGen default noises ---
---@type ValueNoise
local oceanNoise
@@ -60,20 +68,8 @@ tempNoiseParams = {
lacunarity = 2,
}
-- --- End of default noises ---
-- --- End default noises ---
local modInfo = Mod.getInfo()
local require = modInfo.require
---@type MapGen.Layer
local Layer = require("MapGen.Layer")
---@type MapGen.Region
local Region = require("MapGen.Region")
---@type MapGen.Biome
local Biome = require("MapGen.Biome")
---@class MapGen
---@field layersByName table
@@ -87,7 +83,7 @@ local MapGen = {
layersByName = {},
layersList = {},
biomesList = {},
biomesDiagram = {},
biomesDiagram = {},
multinoiseInitialized = false,
isRunning = false,
}
@@ -149,35 +145,24 @@ end
---Mark a region of the world as a cubic region by two opposite vertices.
---
---Regions must be included in layers and may overlap each other.
---@param layerName string The name of the layer in which the new region will be included.
---@param minPos vector
---@param maxPos vector
---@param multinoise MapGen.Region.MultinoiseParams Noise that will be assigned to the region and that will influence map generation
---@param regionIs2D boolean? If true, the transmitted Y coordinate will be overwritten by the layer boundaries.
---@param weightFactor number? The coefficient by which the reduction in the impact of regional noise on generation will be calculated. If 0, there will be no reduction.
function MapGen:RegisterRegion(layerName, minPos, maxPos, multinoise, regionIs2D, weightFactor)
---@type MapGen.Layer
---@param regionName string
---@param layerName string Name of the layer in which the new region will be contained.
---@param polyhedron Polyhedron
---@param multinoiseParams MapGen.Region.MultinoiseParams Noise that will be assigned to the region and that will influence map generation
---@param bufferZone MapGen.Region.BufferZone
function MapGen:RegisterRegion(regionName, layerName, polyhedron, multinoiseParams, bufferZone)
local interpolationPreset = bufferZone.preset or "linear"
local layer = self.layersByName[layerName]
if not layer then error("Invalid layer: " .. layerName) end
if not layer then
error("Invalid layer: " .. layerName)
-- Check for intersections with existing regions
for _, existingRegion in ipairs(layer.regionsList) do
if polyhedron:intersects(existingRegion:getPolyhedron()) then
error("Regions cannot intersect! Region '" .. regionName .. "' intersects with existing region.")
end
end
if regionIs2D then
minPos.y = layer.minY
maxPos.y = layer.maxY
end
--TODO: добавить проверку, что координаты вершин региона не совпадают (регион не является линией толщиной в 1 блок)
--TODO: Добавить проверку, что регион не выходит за границы слоя или/и автоматически обрубать регион до слоя
if weightFactor == nil then
weightFactor = 1
end
---@type MapGen.Region
local region = Region:new(minPos, maxPos, multinoise, weightFactor)
local region = Region:new(polyhedron, multinoiseParams, bufferZone)
layer:addRegion(region)
end
@@ -214,7 +199,7 @@ function MapGen:initBiomesDiagram()
diagram[temp] = {}
for humidity = 0, 100 do
local minDistance = math.huge
local minDistance = mathHuge
local closestBiome = nil
---@param biome MapGen.Biome
@@ -232,34 +217,6 @@ function MapGen:initBiomesDiagram()
end
end
---Calculate the weight for noise based on
---the distance of the point from the center of the region.
---
---If the `weightFactor` is `0`, then the region's
---weight is not calculated and is always equal to `1`.
---@param minPos vector
---@param maxPos vector
---@param x number
---@param z number
---@param weightFactor number
---@return number
local function calculateWeight2D(minPos, maxPos, x, z, weightFactor)
if weightFactor == 0 then
return 1
end
local centerX = (minPos.x + maxPos.x) / 2
local centerZ = (minPos.z + maxPos.z) / 2
local distX = 1 - (mathAbs(x - centerX) / (mathAbs((maxPos.x - minPos.x)) / 2))^weightFactor
local distZ = 1 - (mathAbs(z - centerZ) / (mathAbs((maxPos.z - minPos.z)) / 2))^weightFactor
---@type number
local weight = distX * distZ -- mathMin(distX, distZ)
return weight
end
local function generateSoil(biome, data, index, x, y, z)
data[index] = core.get_content_id(biome.groundNodes.turf) -- TODO: убрать тут get_content_id(), переместить его куда-то "выше"
end
@@ -307,68 +264,55 @@ local function generateNode(mapGenerator, hight, temp, humidity, data, index, x,
end
---@param mapGenerator MapGen
local function generatorHandler(mapGenerator, data, index, x, y, z)
-- If generation occurs outside the layers, then a void is generated
local function generatorHandler3D(mapGenerator, data, index, x, y, z)
local layer = mapGenerator:getLayerByHeight(y)
if layer == nil then
data[index] = mapGenerator.nodeIDs.air
return
end
-- The ocean floor height is used as the default value.
if oceanNoise == nil then
oceanNoise = core.get_value_noise(oceanNoiseParams)
end
-- Initialize base noises if needed
if oceanNoise == nil then oceanNoise = core.get_value_noise(oceanNoiseParams) end
if tempNoise == nil then tempNoise = core.get_value_noise(tempNoiseParams) end
if humidityNoise == nil then humidityNoise = core.get_value_noise(humidityNoiseParams) end
-- Default noise's values.
local noiseHeightValue = oceanNoise:get_2d({x = x, y = z})
local noiseTempValue = 0.0
local noiseHumidityValue = 0.0
-- Base values (outside any region)
local baseHeight = oceanNoise:get_3d({x = x, y = y, z = z})
local baseTemp = tempNoise:get_3d({x = x, y = y, z = z})
local baseHumidity = humidityNoise:get_3d({x = x, y = y, z = z})
local tempValuesCount = 0
local humidityValuesCount = 0
local finalHeight = baseHeight
local finalTemp = baseTemp
local finalHumidity = baseHumidity
local regions = layer:getRegionsByPos(x, y, z)
-- The height noise values ​​of all regions that a node is part of are added together.
---@param region MapGen.Region
for _, region in ipairs(regions) do
local heightNoise = region:getMultinoise().landscapeNoise
local tempNoise = region:getMultinoise().tempNoise
local humidityNoise = region:getMultinoise().humidityNoise
if heightNoise ~= nil then
-- The further a point is from the center of a region, the less noise affects it.
local weight = calculateWeight2D(region:getMinPos(), region:getMaxPos(), x, z, region.getWeightFactor())
noiseHeightValue = noiseHeightValue + ( heightNoise:get_2d({x = x, y = z}) * weight )
local region = layer:getRegionByPos(x, y, z)
local polyhedron = region:getPolyhedron()
local distance = polyhedron:distanceToSurface(vector.new(x, y, z))
local bufferZone = region:getBufferZone()
if distance <= bufferZone.thickness then
local regionNoises = region:getMultinoise()
local blendFactor = InterpolationPresets[region:getInterpolationPreset()](distance, bufferZone.thickness)
-- 3D noise interpolation
if regionNoises.landscapeNoise then
local regionHeight = regionNoises.landscapeNoise:get_3d({x = x, y = y, z = z})
finalHeight = baseHeight + (regionHeight - baseHeight) * blendFactor
end
if tempNoise ~= nil then
noiseTempValue = noiseTempValue + tempNoise:get_2d({x = x, y = z})
tempValuesCount = tempValuesCount + 1
if regionNoises.tempNoise then
local regionTemp = regionNoises.tempNoise:get_3d({x = x, y = y, z = z})
finalTemp = baseTemp + (regionTemp - baseTemp) * blendFactor
end
if humidityNoise ~= nil then
noiseHumidityValue = noiseHumidityValue + humidityNoise:get_2d({x = x, y = z})
humidityValuesCount = humidityValuesCount + 1
if regionNoises.humidityNoise then
local regionHumidity = regionNoises.humidityNoise:get_3d({x = x, y = y, z = z})
finalHumidity = baseHumidity + (regionHumidity - baseHumidity) * blendFactor
end
end
noiseHeightValue = mathRound(noiseHeightValue)
if tempValuesCount ~= 0 then
noiseTempValue = mathRound( noiseTempValue / tempValuesCount )
end
if humidityValuesCount ~= 0 then
noiseHumidityValue = mathRound( noiseHumidityValue / humidityValuesCount )
end
generateNode(mapGenerator, noiseHeightValue, noiseTempValue, noiseHumidityValue, data, index, x, y, z)
generateNode(mapGenerator, mathRound(finalHeight), mathRound(finalTemp),
mathRound(finalHumidity), data, index, x, y, z)
end
---@param minPos table
@@ -392,7 +336,7 @@ function MapGen:onMapGenerated(minPos, maxPos, blockseed)
local index = area:index(minPos.x, y, z)
for x = minPos.x, maxPos.x do
generatorHandler(self, data, index, x, y, z)
generatorHandler3D(self, data, index, x, y, z)
index = index + 1
end

View File

@@ -25,4 +25,4 @@ function Biome:new(name, tempPoint, humidityPoint, groundNodes, soilHeight)
return instance
end
return Biome
return Biome

View File

@@ -0,0 +1,25 @@
---@class MapGen.InterpolationPreset
---@field calculate fun(distance: number, thickness: number): number
local InterpolationPresets = {
linear = function(distance, thickness)
return math.max(0, 1 - (distance / thickness))
end,
smoothstep = function(distance, thickness)
local t = math.max(0, 1 - (distance / thickness))
return t * t * (3 - 2 * t)
end,
smootherstep = function(distance, thickness)
local t = math.max(0, 1 - (distance / thickness))
return t * t * t * (t * (t * 6 - 15) + 10)
end,
exponential = function(distance, thickness)
local t = math.max(0, 1 - (distance / thickness))
return t * t -- Quadratic falloff
end
}
return InterpolationPresets

View File

@@ -1,63 +1,157 @@
---@class MapGen.Layer
---@field name string
---@field minY number
---@field maxY number
---@field regionsList table
---@field name string
---@field minY number
---@field maxY number
---@field regionsList table<integer, MapGen.Region>
---@field defaultRegion MapGen.Region
local Layer = {
regionsList = {}
}
---@param name string
---@param minY number
---@param maxY number
---@return MapGen.Layer
local require = Mod.getInfo().require
local BufferZone = require("MapGen.Region.BufferZone")
local Region = require("MapGen.Region")
require = Mod.getInfo("smc__core__polyhedron").require
local Polyhedron = require("Polyhedron")
---Creates a new Layer instance
---@param name string The name of the layer
---@param minY number Minimum Y coordinate of the layer
---@param maxY number Maximum Y coordinate of the layer
---@return MapGen.Layer
function Layer:new(name, minY, maxY)
---@type MapGen.Layer
local instance = setmetatable({
name = name,
minY = minY,
maxY = maxY,
regionsList = {}
}, {__index = self})
-- Create default region that covers the entire layer
instance:createDefaultRegion()
return instance
end
---@param region MapGen.Region
---Creates the default region that covers the entire layer
function Layer:createDefaultRegion()
local polyhedron = self:createLayerPolyhedron()
---@type MapGen.Region.MultinoiseParams
local multinoiseParams = {
landscapeNoise = self:getDefaultLandscapeNoiseParams(),
tempNoise = self:getDefaultTempNoiseParams(),
humidityNoise = self:getDefaultHumidityNoiseParams(),
}
local bufferZone = BufferZone:new(0, "linear") -- No buffer for default region
self.defaultRegion = Region:new(polyhedron, multinoiseParams, bufferZone)
end
---Creates a polyhedron that covers the entire layer
---@return Polyhedron
function Layer:createLayerPolyhedron()
-- Create a very large polyhedron that covers the entire layer in Y and extends far in XZ
local vertices = {
vector.new(-30000, self.minY, -30000),
vector.new( 30000, self.minY, -30000),
vector.new( 30000, self.minY, 30000),
vector.new(-30000, self.minY, 30000),
vector.new(-30000, self.maxY, -30000),
vector.new( 30000, self.maxY, -30000),
vector.new( 30000, self.maxY, 30000),
vector.new(-30000, self.maxY, 30000),
}
local faces = {
{1, 2, 3, 4}, -- Bottom face
{5, 6, 7, 8}, -- Top face
{1, 2, 6, 5}, -- South face
{2, 3, 7, 6}, -- East face
{3, 4, 8, 7}, -- North face
{4, 1, 5, 8}, -- West face
}
return Polyhedron:new(vertices, faces)
end
---Gets default landscape noise parameters
---@return NoiseParams
function Layer:getDefaultLandscapeNoiseParams()
return {
offset = -30,
scale = 10,
spread = {x = 100, y = 100, z = 100},
seed = 47,
octaves = 8,
persistence = 0.4,
lacunarity = 2,
}
end
---Gets default temperature noise parameters
---@return NoiseParams
function Layer:getDefaultTempNoiseParams()
return {
offset = 50,
scale = 25,
spread = {x = 10, y = 10, z = 10},
seed = 12,
octaves = 2,
persistence = 0.6,
lacunarity = 2,
}
end
---Gets default humidity noise parameters
---@return NoiseParams
function Layer:getDefaultHumidityNoiseParams()
return {
offset = 50,
scale = 25,
spread = {x = 10, y = 10, z = 10},
seed = 12,
octaves = 2,
persistence = 0.6,
lacunarity = 2,
}
end
---Adds a region to this layer
---@param region MapGen.Region The region to add
function Layer:addRegion(region)
table.insert(self.regionsList, region)
end
---@param xPos number
---@param yPos number
---@param zPos number
---@return MapGen.Region[]
function Layer:getRegionsByPos(xPos, yPos, zPos)
-- TODO: возможно здесь получится сделать более оптимизированный алгоритм
-- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
-- и может быть даже не один раз
-- Можно подумать над тем, чтобы использовать сортированный список
---Gets the region for a specific position, returns default region if no specific region found
---@param xPos number X coordinate
---@param yPos number Y coordinate
---@param zPos number Z coordinate
---@return MapGen.Region
function Layer:getRegionByPos(xPos, yPos, zPos)
local point = vector.new(xPos, yPos, zPos)
---@type MapGen.Region[]
local regions = {}
---@param region MapGen.Region
for _, region in ipairs(self.regionsList) do
if (
xPos >= region:getMinPos().x and
yPos >= region:getMinPos().y and
zPos >= region:getMinPos().z) and
(
xPos <= region:getMaxPos().x and
yPos <= region:getMaxPos().y and
zPos <= region:getMaxPos().z
) then
table.insert(regions, region)
for _, region in ipairs(self.regionsList) do
local polyhedron = region:getPolyhedron()
local distance = polyhedron:distanceToSurface(point)
local bufferZone = region:getBufferZone()
-- Include region if point is inside OR within buffer zone
if polyhedron:containsPoint(point) or distance <= bufferZone.thickness then
return region
end
end
return regions
-- Fall back to default region
return self.defaultRegion
end
---Returns the default region for this layer
---@return MapGen.Region
function Layer:getDefaultRegion()
return self.defaultRegion
end
return Layer

View File

@@ -1,10 +1,9 @@
---@class MapGen.Region
---@field getMinPos fun():vector
---@field getMaxPos fun():vector
---@field getMultinoiseParams fun():MapGen.Region.MultinoiseParams
---@field getMultinoise fun():MapGen.Region.Multinoise
---@field initMultinoise fun()
---@field getWeightFactor fun():number
---@field getPolyhedron fun():Polyhedron
---@field getMultinoiseParams fun():MapGen.Region.MultinoiseParams
---@field getMultinoise fun():MapGen.Region.Multinoise
---@field getBufferZone fun():MapGen.Region.BufferZone
---@field getInterpolationPreset fun():string
local Region = {}
---@param multinoiseParams MapGen.Region.MultinoiseParams
@@ -20,57 +19,30 @@ local function multinoiseParamsToMultinoise(multinoiseParams)
return multinoise
end
---@param minPos vector
---@param maxPos vector
---@param polyhedron Polyhedron
---@param multinoiseParams MapGen.Region.MultinoiseParams
---@param weightFactor number
---@param bufferZone MapGen.Region.BufferZone
---@return MapGen.Region
function Region:new(minPos, maxPos, multinoiseParams, weightFactor)
function Region:new(polyhedron, multinoiseParams, bufferZone)
local _polyhedron = polyhedron
local _multinoiseParams = multinoiseParams
local _bufferZone = bufferZone
local _interpolationPreset = bufferZone.preset or "linear"
local _multinoise = {}
---@type vector
local _minPos = minPos
---@type vector
local _maxPos = maxPos
---@type MapGen.Region.MultinoiseParams
local _multinoiseParams = multinoiseParams
local instance = setmetatable({}, {__index = self})
if weightFactor < 0 then
weightFactor = 1
end
function instance:getPolyhedron() return _polyhedron end
function instance:getMultinoiseParams() return _multinoiseParams end
function instance:getMultinoise() return _multinoise end
function instance:getBufferZone() return _bufferZone end
function instance:getInterpolationPreset() return _interpolationPreset end
function instance:initMultinoise()
_multinoise = multinoiseParamsToMultinoise(_multinoiseParams)
end
---@type MapGen.Region.Multinoise
local _multinoise = {}
---@type MapGen.Region
local instance = setmetatable({}, {__index = self})
function instance:getMinPos()
return _minPos
end
---@return vector
function instance:getMaxPos()
return _maxPos
end
function instance:getMultinoiseParams()
return _multinoiseParams
end
function instance:getMultinoise()
return _multinoise
end
function instance:initMultinoise()
_multinoise = multinoiseParamsToMultinoise(_multinoiseParams)
print(dump(_multinoise))
end
function instance.getWeightFactor()
return weightFactor
end
return instance
return instance
end
return Region

View File

@@ -0,0 +1,16 @@
---@class MapGen.Region.BufferZone
---@field thickness number
---@field preset string
local BufferZone = {}
function BufferZone:new(thickness, preset)
---@type MapGen.Region.BufferZone
local instance = setmetatable({
thickness = thickness,
preset = preset or "linear"
}, {__index = self})
return instance
end
return BufferZone