MapGenV: create mapgen

This commit is contained in:
Van
2025-09-25 14:42:40 +00:00
parent c0eb6b5920
commit e17b2d522f
7 changed files with 347 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
local MapGen = Mod:new()
MapGen.Class = MapGen.require('MapGen')
Api.addModToGlobalSpace(MapGen, 'Core.MapGen')
-- DEBUG MAPGEN
---@type MapGenV
local MapGen = MapGen.Class:new()
MapGen:RegisterLayer("world", -1000, 500)
MapGen:RegisterRegion("world",
{x = -1000, y = 0, z = -1000},
{x = 1000, y = 0, z = 1000},
{
landscapeNoise = {
offset = 0,
scale = 10,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 4,
persistence = 0.3,
lacunarity = 3,
}
},
true)
MapGen:enable()

View File

@@ -0,0 +1,2 @@
name = smc__core__map_gen
depends = smc__api__system

View File

@@ -0,0 +1,210 @@
local mathCeil, id
= math.ceil, core.get_content_id
-- --- Node's IDs for generation ---
-- Specials
local id_air = id("air")
-- Stones
-- Liquids
-- --- End Node's IDs
local modInfo = Mod.getInfo()
local require = modInfo.require
-- -@type MapGen.Utils
---local MapGenUtils = require("MapGen.Utils")
---@type MapGenV.Layer
local Layer = require("MapGen.Layer")
---@type MapGenV.Region
local Region= require("MapGen.Region")
---@class MapGenV
---@field layersByName table
---@field layersList table
---@field isEnable boolean A static field that guarantees that only one instance of the `MapGen` class will work.
local MapGen = {
isEnable = false,
}
---@return MapGen
function MapGen:new()
local instance = setmetatable({
layersByName = {},
layersList = {},
--registeredRegions = {},
}, {__index = self})
return instance
end
---@param yPos number
---@return MapGenV.Layer?
function MapGen:getLayerByHeight(yPos)
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз
--- Можно подумать над тем, чтобы использовать сортированный список
---@param layer MapGenV.Layer
for _, layer in ipairs(self.layersList) do
if yPos >= layer.minY and yPos <= layer.maxY then
return layer
end
end
end
---@param name string
---@param minY number
---@param maxY number
function MapGen:RegisterLayer(name, minY, maxY)
---Checking if layers overlap
if self:getLayerByHeight(minY) ~= nil and self:getLayerByHeight(maxY) ~= nil then
error('Registered layers must not overlap!')
end
---@type MapGenV.Layer
local layer = Layer:new(name, minY, maxY)
self.layersByName[name] = layer
table.insert(self.layersList, layer)
-- Sort layers by maxY descending for processing priority
table.sort(self.layersList, function(a, b)
return a.maxY > b.maxY
end)
end
---@param layerName string
---@param minPos table
---@param maxPos table
---@param noises table
---@param regionIs2D boolean?
function MapGen:RegisterRegion(layerName, minPos, maxPos, noises, regionIs2D)
---@type MapGenV.Layer
local layer = self.layersByName[layerName]
if not layer then
error("Invalid layer: " .. layerName)
end
if regionIs2D then
minPos.y = layer.minY
maxPos.y = layer.maxY
end
---@type MapGenV.Region
local region = Region:new(minPos, maxPos, noises)
--TODO: реализовать регистрацию допольнительных регионов для сглаживания шумов
layer:addRegion(region)
end
function MapGen:landscapeGeneration(data, area, x, y, z)
local index = area:index(x, y, z)
-- If generation occurs outside the layers, then a void is generated
local layer = self:getLayerByHeight(y)
if layer == nil then
data[index] = id_air
return
end
-- If generation occurs outside the regions, then a ocean is generated
local regions = layer:getRegionsByPos(x, y, z)
if table.is_empty(regions) then
-- TODO: прописать генерацию океана
return
end
local noiseHeightValue = 0
-- The height noise values ​​of all regions that a node is part of are added together...
---@param region MapGenV.Region
for _, region in ipairs(regions) do
if region.noises.landscapeNoise ~= nil then
local noise = core.get_value_noise(region.noises.landscapeNoise)
noiseHeightValue = noiseHeightValue + noise:get_2d({x = x, y = z})
end
end
-- ...And the average height is found: this provides smoothing
noiseHeightValue = mathCeil(noiseHeightValue / #regions)
if y > noiseHeightValue then
data[index] = id_air
else
data[index] = core.get_content_id("rocks:tauitite") -- TODO: прописать заполнение камнем
end
end
function MapGen:postprocessGeneration(data, area, x, y, z)
local index = area:index(x, y, z)
-- TODO: генерация покрытия
-- TODO: генерация растительности
end
---@param minPos table
---@param maxPos table
---@param blockseed number
function MapGen:onMapGenerated(minPos, maxPos, blockseed)
-- We obtain a generation area for further manipulations
local voxelManip, eMin, eMax = core.get_mapgen_object("voxelmanip")
local data = voxelManip:get_data()
local area = VoxelArea:new({MinEdge = eMin, MaxEdge = eMax})
-- local param2_data = voxelManip:get_param2_data()
-- Initial generation: landscape
for z = minPos.z, maxPos.z do
for y = minPos.y, maxPos.y do
for x = minPos.x, maxPos.x do
self:landscapeGeneration(data, area, x, y, z)
--core.handle_async(self.landscapeGeneration, callback, self, data, area, x, y, z)
-- вероятно благодаря 2D шуму высоты генерацию ландшафта можно оптимизировать
-- до генерации столбами (т. к. по x, z можно найти требуемый y)
end
end
end
-- Post-processing: adding cover and vegetation
--[[for z = minPos.z, maxPos.z do
for y = minPos.y, maxPos.y do
for x = minPos.x, maxPos.x do
MapGen:postprocessGeneration(data, area, x, y, z)
end
end
end --]]
-- We make changes back to LVM and recalculate light & liquids
voxelManip:set_data(data)
-- voxelManip:set_param2_data(param2_data)
voxelManip:update_liquids()
voxelManip:calc_lighting()
voxelManip:write_to_map()
end
function MapGen:enable()
if MapGen.isEnable then
error('Only one instance of a `MapGen` class can be used.')
end
core.register_on_generated(function(...)
self:onMapGenerated(...)
end)
MapGen.isEnable = true
end
return MapGen

View File

@@ -0,0 +1,61 @@
---@class MapGenV.Layer
---@field name string
---@field minY number
---@field maxY number
---@field regionsList table
local Layer = {
regionsList = {}
}
---@param name string
---@param minY number
---@param maxY number
---@return MapGenV.Layer
function Layer:new(name, minY, maxY)
---@type MapGenV.Layer
local instance = setmetatable({
name = name,
minY = minY,
maxY = maxY,
}, {__index = self})
return instance
end
---@param region MapGenV.Region
function Layer:addRegion(region)
table.insert(self.regionsList, region)
end
---@param xPos number
---@param yPos number
---@param zPos number
---@return table
function Layer:getRegionsByPos(xPos, yPos, zPos)
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз
--- Можно подумать над тем, чтобы использовать сортированный список
local regions = {}
---@param region MapGenV.Region
for _, region in ipairs(self.regionsList) do
if (
xPos >= region.minPos.x and
yPos >= region.minPos.y and
zPos >= region.minPos.z) and
(
xPos <= region.maxPos.x and
yPos <= region.maxPos.y and
zPos <= region.maxPos.z
) then
table.insert(regions, region)
end
end
return regions
end
return Layer

View File

@@ -0,0 +1,35 @@
---@class MapGenV.Region
---@field minPos table
---@field maxPos table
---@field noises MapGenV.Region.Noises
local Region = {}
---@param noisesParams MapGenV.Region.Noises
---@return MapGenV.Region.Noises
local function paramsToNoises(noisesParams)
---@type MapGenV.Region.Noises
local noises = {}
for noiseName, noiseParams in pairs(noisesParams) do
noises[noiseName] = core.get_value_noise(noiseParams)
end
return noises
end
---@param minPos table
---@param maxPos table
---@param noisesParams MapGenV.Region.Noises
---@return MapGenV.Region
function Region:new(minPos, maxPos, noisesParams)
---@type MapGenV.Region
local instance = setmetatable({
minPos = minPos,
maxPos = maxPos,
noises = noisesParams --paramsToNoises(noisesParams)
}, {__index = self})
return instance
end
return Region

View File

@@ -0,0 +1,8 @@
---Only for EmmyLua
---@class MapGenV.Region.Noises
---@field landscapeNoise table?
---@field tempNoise table?
---@field humidityNoise table?
local Noises = {}
return Noises