4 Commits

Author SHA1 Message Date
ceb35639b8 MapGen: minor refactoring 2026-03-21 21:26:27 +03:00
79df8f2f52 MapGen: a little bit more optimizations 2026-03-21 20:53:02 +03:00
e986a4c538 MapGen: There is now only one triangulation map instead of three. 2026-03-16 20:59:39 +03:00
93bda75727 Profiler: some changes 2026-03-16 20:57:37 +03:00
6 changed files with 182 additions and 231 deletions

View File

@@ -1,21 +1,18 @@
local mathAbs, mathRound, mathMin, mathMax, posToString local mathRound, mathRandom, mathClamp, tableInsert
= math.abs, math.round, math.min, math.max, core.pos_to_string = math.round, math.random, math.clamp, table.insert
local posToString, getUsTime = core.pos_to_string, core.get_us_time
local pairs, ipairs, assert = pairs, ipairs, assert
local v = vector.new local v = vector.new
local id = core.get_content_id local id = core.get_content_id
local AIR_ID = core.CONTENT_AIR
local getInstance = Class.getInstance local getInstance = Class.getInstance
local LOG_PROFILE = true local LOG_PROFILE = true
local PROFILE_CHUNK = true
local function calculateAverage(t)
if #t == 0 then return 0 end -- Защита от деления на ноль
local sum = 0
for i = 1, #t do
sum = sum + t[i]
end
return sum / #t
end
local function mglog(text, ...) local function mglog(text, ...)
core.log((text):format(...)) core.log((text):format(...))
@@ -24,34 +21,30 @@ end
local modInfo = Mod.getInfo('smc__core__map_gen') local modInfo = Mod.getInfo('smc__core__map_gen')
local require = modInfo.require local require = modInfo.require
---Numeric values ​​defining the surface height and climate for the node.
---@alias MapGen.factors {height:number, temp:number, humidity:number} ---@alias MapGen.factors {height:number, temp:number, humidity:number}
---@alias MapGen.PastCalcNoiseValue {triangle:MapGen.Triangle?, x:integer?, z:integer?, noiseValue:number?} ---Table of all past generation factor calculations for nodes.
---
---Contains generation factors by layer name and coordinate.
---@type table<string, table<string, MapGen.factors>>
local pastNoiseValues = {}
---@type table<MapGen.Layer.Category, MapGen.PastCalcNoiseValue> ---The triangle in which generation occurred for the previous node.
local pastNoise2DCalc = { ---@type MapGen.Triangle?
landscape = {}, local pastTriangle
temp = {},
humidity = {}
}
---@type MapGen.Layer ---@type MapGen.Layer
local Layer = require('MapGen.Layer') local Layer = require('MapGen.Layer')
---@type MapGen.StaticLayer ---@type MapGen.StaticLayer
local StaticLayer = require('MapGen.StaticLayer') local StaticLayer = require('MapGen.StaticLayer')
---@type MapGen.Biome ---@type MapGen.Biome
local Biome = require('MapGen.Biome') local Biome = require('MapGen.Biome')
---@type MapGen.Cavern ---@type MapGen.Cavern
local Cavern = require('MapGen.Cavern') local Cavern = require('MapGen.Cavern')
---@type MapGen.Region ---@type MapGen.Region
local Region = require('MapGen.Region') local Region = require('MapGen.Region')
local ff2luat = require('MapGen.ff2luat')
---@class MapGen ---@class MapGen
---@field layersByName table<string, MapGen.Layer> ---@field layersByName table<string, MapGen.Layer>
---@field layersList MapGen.Layer[] ---@field layersList MapGen.Layer[]
@@ -60,6 +53,7 @@ local ff2luat = require('MapGen.ff2luat')
---@field isLayersNoisesInitialized boolean Is the fractal noise of the layer initialized? This is necessary for a one-time noise initialization. ---@field isLayersNoisesInitialized boolean Is the fractal noise of the layer initialized? This is necessary for a one-time noise initialization.
---@field isCavernsNoiseInitialized boolean Is the fractal noise of the caverns initialized? This is necessary for a one-time noise initialization. ---@field isCavernsNoiseInitialized boolean Is the fractal noise of the caverns initialized? This is necessary for a one-time noise initialization.
---@field isRunning boolean A static field that guarantees that only one instance of the `MapGen` class will work. ---@field isRunning boolean A static field that guarantees that only one instance of the `MapGen` class will work.
---@field nodes table<string, string>
---@field nodeIDs table<string, number> ---@field nodeIDs table<string, number>
local MapGen = { local MapGen = {
layersByName = {}, layersByName = {},
@@ -86,11 +80,9 @@ function MapGen:new(def)
nodesIDs[k] = id(v) nodesIDs[k] = id(v)
end end
---@type MapGen local instance = getInstance(self, {})
local instance = getInstance(self, { instance.nodes = def.nodes
nodes = def.nodes, instance.nodeIDs = nodesIDs
nodeIDs = nodesIDs,
})
return instance return instance
end end
@@ -107,18 +99,16 @@ function MapGen:getLayerByName(layerName)
end end
---Determines which layer a node belongs to based on its height coordinate. ---Determines which layer a node belongs to based on its height coordinate.
---@param yPos number ---@param y number
---@return MapGen.Layer? ---@return MapGen.Layer?
function MapGen:getLayerByHeight(yPos) function MapGen:getLayerByHeight(y)
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм --- TODO: возможно здесь получится сделать более оптимизированный алгоритм
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз
--- Можно подумать над тем, чтобы использовать сортированный список --- Можно подумать над тем, чтобы использовать сортированный список
---@param layer MapGen.Layer ---@param layer MapGen.Layer
for _, layer in ipairs(self.layersList) do for _, layer in ipairs(self.layersList) do
if yPos >= layer.minY and yPos <= layer.maxY then if y >= layer.minY and y <= layer.maxY then
return layer return layer
end end
@@ -126,9 +116,9 @@ function MapGen:getLayerByHeight(yPos)
end end
---Determines which statics layer a node belongs to based on its height coordinate. ---Determines which statics layer a node belongs to based on its height coordinate.
---@param yPos number ---@param y number
---@return MapGen.StaticLayer? ---@return MapGen.StaticLayer?
function MapGen:getStaticByHeight(yPos) function MapGen:getStaticByHeight(y)
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм --- TODO: возможно здесь получится сделать более оптимизированный алгоритм
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated --- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз --- и может быть даже не один раз
@@ -137,7 +127,7 @@ function MapGen:getStaticByHeight(yPos)
---@param static MapGen.StaticLayer ---@param static MapGen.StaticLayer
for _, static in ipairs(self.staticsList) do for _, static in ipairs(self.staticsList) do
if yPos >= static.minY and yPos <= static.maxY then if y >= static.minY and y <= static.maxY then
return static return static
end end
@@ -146,16 +136,15 @@ end
---Returns the `MapGen.Peak` at the coordinates. If there is no peak at these coordinates, it returns `nil`. ---Returns the `MapGen.Peak` at the coordinates. If there is no peak at these coordinates, it returns `nil`.
---@param layer string|MapGen.Layer The layer or name of the layer in which the peak is located. ---@param layer string|MapGen.Layer The layer or name of the layer in which the peak is located.
---@param category MapGen.Layer.Category The category in which the peak is located.
---@param pos MapPosition Coordinate of the desired peak. ---@param pos MapPosition Coordinate of the desired peak.
---@return MapGen.Peak? ---@return MapGen.Peak?
function MapGen:getPeakByPos(layer, category, pos) function MapGen:getPeakByPos(layer, pos)
if type(layer) == 'string' then if type(layer) == 'string' then
local layerName = layer local layerName = layer
layer = self:getLayerByName(layerName) layer = self:getLayerByName(layerName)
end end
return layer:getPeakByPos(category, pos) return layer:getPeakByPos(pos)
end end
---Checks if a point is inside a triangle using the vector product method. ---Checks if a point is inside a triangle using the vector product method.
@@ -165,7 +154,7 @@ end
--- ---
---**Note**: works only with coordinates X-Z. ---**Note**: works only with coordinates X-Z.
---@param triangle MapGen.Triangle ---@param triangle MapGen.Triangle
---@param pointPos vector ---@param pointPos IntegerVector
---@return boolean, MapGen.Triangle? ---@return boolean, MapGen.Triangle?
function MapGen:isPointInTriangle(triangle, pointPos) function MapGen:isPointInTriangle(triangle, pointPos)
local e1, e2, e3 = triangle.e1, triangle.e2, triangle.e3 local e1, e2, e3 = triangle.e1, triangle.e2, triangle.e3
@@ -188,18 +177,22 @@ function MapGen:isPointInTriangle(triangle, pointPos)
return true, triangle return true, triangle
end end
---Finds the triangle containing the point specified by coordinates X & Z.
---@param layer MapGen.Layer The layer of the layer the triangle is in. ---@param layer MapGen.Layer The layer of the layer the triangle is in.
---@param category MapGen.Layer.Category The category in which the triangle is in.
---@param x integer ---@param x integer
---@param z integer ---@param z integer
---@param triangle MapGen.Triangle? ---@param triangle MapGen.Triangle? The triangle from which to begin the search.
--- If not specified, the search will be performed
--- from the triangle at `id = 1`
---@return MapGen.Triangle? ---@return MapGen.Triangle?
function MapGen:findTriangle(layer, category, x, z, triangle) function MapGen:findTriangle(layer, x, z, triangle)
if triangle == nil then if triangle == nil then
triangle = layer.trianglesList[category][1] triangle = layer.trianglesList[1]
end end
-- Limit the number of iterations to prevent the loop from going into infinity.
local iterationCount = 1000000 local iterationCount = 1000000
local isFound = false local isFound = false
while not isFound do while not isFound do
if iterationCount < 0 then if iterationCount < 0 then
@@ -209,7 +202,9 @@ function MapGen:findTriangle(layer, category, x, z, triangle)
end end
iterationCount = iterationCount - 1 iterationCount = iterationCount - 1
assert(triangle) if triangle == nil then
return nil
end
isFound, triangle = self:isPointInTriangle(triangle, v(x, 0, z)) isFound, triangle = self:isPointInTriangle(triangle, v(x, 0, z))
end end
@@ -218,6 +213,7 @@ function MapGen:findTriangle(layer, category, x, z, triangle)
end end
---Checks if a point is inside a region. ---Checks if a point is inside a region.
---
---If the point is inside the region, it will also return the distance to the nearest border. ---If the point is inside the region, it will also return the distance to the nearest border.
---@param layer MapGen.Layer The name of the layer in which the region is located. ---@param layer MapGen.Layer The name of the layer in which the region is located.
---@param regionName string The name of the region in which the location of the point is checked. ---@param regionName string The name of the region in which the location of the point is checked.
@@ -267,7 +263,7 @@ local function vertexKey(peak)
end end
---Creates a canonical (sorted) key for an edge. ---Creates a canonical (sorted) key for an edge.
---@param edge MapGen.Triangulation.Edge ---@param edge MapGen.Edge
---@return string ---@return string
local function edgeKey(edge) local function edgeKey(edge)
local k1 = vertexKey(edge.p1) local k1 = vertexKey(edge.p1)
@@ -287,7 +283,7 @@ end
function MapGen:getTriangulateBoundaryVertices(triangles) function MapGen:getTriangulateBoundaryVertices(triangles)
-- Count how many triangles share each edge -- Count how many triangles share each edge
local edgeCount = {} local edgeCount = {}
---@type table<string, MapGen.Triangulation.Edge> ---@type table<string, MapGen.Edge>
local edgeData = {} local edgeData = {}
for _, triangle in ipairs(triangles) do for _, triangle in ipairs(triangles) do
@@ -306,12 +302,12 @@ function MapGen:getTriangulateBoundaryVertices(triangles)
end end
-- Boundary edges belong to exactly ONE triangle -- Boundary edges belong to exactly ONE triangle
---@type MapGen.Triangulation.Edge[] ---@type MapGen.Edge[]
local boundaryEdges = {} local boundaryEdges = {}
for key, count in pairs(edgeCount) do for key, count in pairs(edgeCount) do
if count == 1 then if count == 1 then
table.insert(boundaryEdges, edgeData[key]) tableInsert(boundaryEdges, edgeData[key])
end end
end end
@@ -335,8 +331,8 @@ function MapGen:getTriangulateBoundaryVertices(triangles)
adjacency[k1] = adjacency[k1] or {} adjacency[k1] = adjacency[k1] or {}
adjacency[k2] = adjacency[k2] or {} adjacency[k2] = adjacency[k2] or {}
table.insert(adjacency[k1], k2) tableInsert(adjacency[k1], k2)
table.insert(adjacency[k2], k1) tableInsert(adjacency[k2], k1)
end end
-- Walk along boundary edges to create ordered vertex list -- Walk along boundary edges to create ordered vertex list
@@ -356,7 +352,7 @@ function MapGen:getTriangulateBoundaryVertices(triangles)
visited[currentKey] = true visited[currentKey] = true
local pos = vertexData[currentKey].pos local pos = vertexData[currentKey].pos
table.insert(boundary, { tableInsert(boundary, {
x = pos.x, x = pos.x,
y = 0, y = 0,
z = pos.z z = pos.z
@@ -398,7 +394,9 @@ function MapGen:registerLayer(name, def)
local layer = Layer:new(name, def) local layer = Layer:new(name, def)
self.layersByName[name] = layer self.layersByName[name] = layer
table.insert(self.layersList, layer) tableInsert(self.layersList, layer)
pastNoiseValues[name] = {}
-- Sort layers by maxY descending for processing priority. -- Sort layers by maxY descending for processing priority.
table.sort(self.layersList, function(a, b) table.sort(self.layersList, function(a, b)
@@ -433,7 +431,7 @@ function MapGen:registerStaticLayer(name, def)
local static = StaticLayer:new(name, def) local static = StaticLayer:new(name, def)
self.staticsByName[name] = static self.staticsByName[name] = static
table.insert(self.staticsList, static) tableInsert(self.staticsList, static)
-- Sort srtatics by maxY descending for processing priority. -- Sort srtatics by maxY descending for processing priority.
table.sort(self.staticsList, function(a, b) table.sort(self.staticsList, function(a, b)
@@ -498,12 +496,11 @@ end
---Initialize the boundary region for a layer and category. ---Initialize the boundary region for a layer and category.
---@param layer MapGen.Layer ---@param layer MapGen.Layer
---@param category MapGen.Layer.Category function MapGen:initTriangultaionBoundaryRegion(layer)
function MapGen:initTriangultaionBoundaryRegion(layer, category) local triangles = layer.trianglesList
local triangles = layer.trianglesList[category]
local regionVertices = self:getTriangulateBoundaryVertices(triangles) local regionVertices = self:getTriangulateBoundaryVertices(triangles)
local regionName = category..'_boundary' local regionName = 'triangles_boundary'
local region = Region:new(regionName, {vertices = regionVertices}) local region = Region:new(regionName, {vertices = regionVertices})
@@ -511,12 +508,10 @@ function MapGen:initTriangultaionBoundaryRegion(layer, category)
end end
---Initialize border regions for all layers and all categories. ---Initialize border regions for all layers and all categories.
function MapGen:initLayersBoundaryRegions() function MapGen:initLayersBoundaryRegion()
---@param layer MapGen.Layer ---@param layer MapGen.Layer
for _, layer in ipairs(self.layersList) do for _, layer in ipairs(self.layersList) do
self:initTriangultaionBoundaryRegion(layer, 'landscape') self:initTriangultaionBoundaryRegion(layer)
self:initTriangultaionBoundaryRegion(layer, 'temp')
self:initTriangultaionBoundaryRegion(layer, 'humidity')
end end
end end
@@ -613,17 +608,17 @@ local function generateNode(mapGenerator, layer, factors, data, index, x, y, z)
local scattHeight = y local scattHeight = y
if scatteringGorizontal ~= 0 then if scatteringGorizontal ~= 0 then
scattTemp = scattTemp + math.random(scatteringGorizontal * -1, scatteringGorizontal) scattTemp = scattTemp + mathRandom(scatteringGorizontal * -1, scatteringGorizontal)
scattHumidity = scattHumidity + math.random(scatteringGorizontal * -1, scatteringGorizontal) scattHumidity = scattHumidity + mathRandom(scatteringGorizontal * -1, scatteringGorizontal)
end end
if scatteringVertical ~= 0 then if scatteringVertical ~= 0 then
scattHeight = scattHeight + math.random(scatteringVertical * -1, scatteringVertical) scattHeight = scattHeight + mathRandom(scatteringVertical * -1, scatteringVertical)
end end
scattTemp = math.clamp(scattTemp, layer.minTemp, layer.maxTemp) scattTemp = mathClamp(scattTemp, layer.minTemp, layer.maxTemp)
scattHumidity = math.clamp(scattHumidity, layer.minHumidity, layer.maxHumidity) scattHumidity = mathClamp(scattHumidity, layer.minHumidity, layer.maxHumidity)
scattHeight = math.clamp(scattHeight, layer.minY, layer.maxY) scattHeight = mathClamp(scattHeight, layer.minY, layer.maxY)
scattHeight, scattTemp, scattHumidity = mathRound(scattHeight), mathRound(scattTemp), mathRound(scattHumidity) scattHeight, scattTemp, scattHumidity = mathRound(scattHeight), mathRound(scattTemp), mathRound(scattHumidity)
height, temp, humidity = mathRound(height), mathRound(scattTemp), mathRound(scattHumidity) height, temp, humidity = mathRound(height), mathRound(scattTemp), mathRound(scattHumidity)
@@ -693,13 +688,13 @@ end
---Calculates a weight for a coordinate using the projection onto ---Calculates a weight for a coordinate using the projection onto
---the triangle's height and specifying the distance to the peak ---the triangle's height and specifying the distance to the peak
---for which the weight is calculated. ---for which the weight is calculated.
---@param height MapGen.Triangulation.Edge ---@param height MapGen.Edge
---@param x integer ---@param x integer
---@param y integer ---@param y integer
---@param z integer ---@param z integer
---@return number ---@return number
local function calcWeight(height, x, y, z) local function calcWeight(height, x, y, z)
local pos1 = vector.new(x, y, z) local pos1 = v(x, y, z)
local pos2 = height.p1.pos local pos2 = height.p1.pos
local pos3 = height.p2.pos local pos3 = height.p2.pos
@@ -713,7 +708,7 @@ local function calcWeight(height, x, y, z)
local posP = pos2 + v * t local posP = pos2 + v * t
return 1 - vector.distance(pos2, posP) / height:length() return 1 - pos2:distance(posP) / height:length()
end end
---Returns the weighted values of 2d noise. ---Returns the weighted values of 2d noise.
@@ -766,60 +761,67 @@ end
---Calculates a smoothed 2D noise value based on a preliminary space partitioning. ---Calculates a smoothed 2D noise value based on a preliminary space partitioning.
--- ---
---Returns `nil` if the point is not included in any triangle. ---Returns `nil` if the point is not included in any triangle.
---@param category MapGen.Layer.Category
---@param layer MapGen.Layer ---@param layer MapGen.Layer
---@param x integer ---@param x integer
---@param y integer ---@param y integer
---@param z integer ---@param z integer
---@return number? ---@return number?, number?, number?
function MapGen:getNoises2dValue(category, layer, x, y, z) function MapGen:getFactors(layer, x, y, z)
---@type MapGen.PastCalcNoiseValue local posString = posToString({x=x,y=0,z=z})
local pastCalc = pastNoise2DCalc[category]
if (pastCalc.x ~= nil and pastCalc.z ~= nil) and (x == pastCalc.x and z == pastCalc.z) then local factors = pastNoiseValues[layer.name][posString]
return pastCalc.noiseValue if factors ~= nil then
return factors.height, factors.temp, factors.humidity
end end
if not self:pointInRegion2D(layer, category..'_boundary', {x=x, y=y, z=z}) then -- TODO: это сильно тормозит обычные чанки, но ускоряет те, что находятся за границей
return nil if not self:pointInRegion2D(layer, 'triangles_boundary', {x=x, y=y, z=z}) then
return
end end
if pastCalc.triangle ~= nil then if pastTriangle ~= nil then
---@type number?
local noiseValue
local triangles = { local triangles = {
pastCalc.triangle, pastTriangle,
pastCalc.triangle.neighbours[1], pastTriangle.neighbours[1],
pastCalc.triangle.neighbours[2], pastTriangle.neighbours[2],
pastCalc.triangle.neighbours[3], pastTriangle.neighbours[3],
} }
---@param t MapGen.Triangle ---@param triangle MapGen.Triangle
for _, t in ipairs(triangles) do for _, triangle in ipairs(triangles) do
if self:isPointInTriangle(t, v(x, 0, z)) then if self:isPointInTriangle(triangle, v(x, 0, z)) then
noiseValue = calcNoise2dValue(category, layer, t, x, y, z) local height = calcNoise2dValue('landscape', layer, triangle, x, y, z)
local temp = calcNoise2dValue('temp', layer, triangle, x, y, z)
local humidity = calcNoise2dValue('humidity', layer, triangle, x, y, z)
pastCalc.x = x pastNoiseValues[layer.name][posString] = {
pastCalc.z = z height = height,
pastCalc.noiseValue = noiseValue temp = temp,
humidity = humidity
}
return noiseValue return height, temp, humidity
end end
end end
end end
local triangle = self:findTriangle(layer, category, x, z, pastCalc.triangle) local triangle = self:findTriangle(layer, x, z, pastTriangle)
assert(triangle ~= nil) if triangle == nil then
return
end
local noiseValue = calcNoise2dValue(category, layer, triangle, x, y, z) local height = calcNoise2dValue('landscape', layer, triangle, x, y, z)
local temp = calcNoise2dValue('temp', layer, triangle, x, y, z)
local humidity = calcNoise2dValue('humidity', layer, triangle, x, y, z)
pastCalc.triangle = triangle pastTriangle = triangle
pastCalc.x = x pastNoiseValues[layer.name][posString] = {
pastCalc.z = z height = height,
pastCalc.noiseValue = noiseValue temp = temp,
humidity = humidity
}
return noiseValue return height, temp, humidity
end end
---Generator handler for specific coordinates. ---Generator handler for specific coordinates.
@@ -830,68 +832,45 @@ end
---@param x integer ---@param x integer
---@param y integer ---@param y integer
---@param z integer ---@param z integer
---@return number, number, number
local function generatorHandler(mapGenerator, layer, data, index, x, y, z) local function generatorHandler(mapGenerator, layer, data, index, x, y, z)
local startGetLayerTime = core.get_us_time()
-- If the node belongs to a static layer, then a static node is generated. -- If the node belongs to a static layer, then a static node is generated.
local static = mapGenerator:getStaticByHeight(y) local static = mapGenerator:getStaticByHeight(y)
if static ~= nil then if static ~= nil then
static:generateStaticNode(mapGenerator, data, index, x, y, z) static:generateStaticNode(mapGenerator, data, index, x, y, z)
return core.get_us_time() - startGetLayerTime, 0, 0 return
end end
-- If generation occurs outside the layers, then a void is generated. -- If generation occurs outside the layers, then a void is generated.
if layer == nil then if layer == nil then
data[index] = mapGenerator.nodeIDs.air data[index] = mapGenerator.nodeIDs.air
return core.get_us_time() - startGetLayerTime, 0, 0 return
end end
local endGetLayerTime = core.get_us_time() local endGetLayerTime = getUsTime()
local startNoiseCalcTime = endGetLayerTime local startNoiseCalcTime = endGetLayerTime
-- If the value of the noise is `nil`, -- If the value of the noise is `nil`,
-- then the point does not fall within any of the triangles. -- then the point does not fall within any of the triangles.
local noiseHeightValue = mapGenerator:getNoises2dValue('landscape', layer, x, y, z) local height, temp, humidity = mapGenerator:getFactors(layer, x, y, z)
if noiseHeightValue == nil then if height == nil or temp == nil or humidity == nil then
data[index] = core.CONTENT_IGNORE data[index] = core.CONTENT_IGNORE
return endGetLayerTime - startGetLayerTime, core.get_us_time() - startNoiseCalcTime, 0 return
end
local noiseTempValue = mapGenerator:getNoises2dValue('temp', layer, x, y, z)
if noiseTempValue == nil then
data[index] = core.CONTENT_IGNORE
return endGetLayerTime - startGetLayerTime, core.get_us_time() - startNoiseCalcTime, 0
end
local noiseHumidityValue = mapGenerator:getNoises2dValue('humidity', layer, x, y, z)
if noiseHumidityValue == nil then
data[index] = core.CONTENT_IGNORE
return endGetLayerTime - startGetLayerTime, core.get_us_time() - startNoiseCalcTime, 0
end end
-- We recalculate the climate based on altitude. -- We recalculate the climate based on altitude.
noiseTempValue = layer:calcTemp(noiseTempValue, y) temp = layer:calcTemp(temp, y)
noiseHumidityValue = layer:calcHumidity(noiseHumidityValue, y) humidity = layer:calcHumidity(humidity, y)
---@type MapGen.factors ---@type MapGen.factors
local factors = { local factors = {
height = noiseHeightValue, height = height,
temp = noiseTempValue, temp = temp,
humidity = noiseHumidityValue, humidity = humidity,
} }
local endNoiseCalcTime = core.get_us_time()
local startGenNodeTime = endNoiseCalcTime
generateNode(mapGenerator, layer, factors, data, index, x, y, z) generateNode(mapGenerator, layer, factors, data, index, x, y, z)
local endGenNodeTime = core.get_us_time()
return endGetLayerTime - startGetLayerTime, endNoiseCalcTime - startNoiseCalcTime, endGenNodeTime - startGenNodeTime
end end
---Chunk generation handler. ---Chunk generation handler.
@@ -901,15 +880,15 @@ end
---@param blockseed number ---@param blockseed number
function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed) function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed)
local minPosStr, maxPosStr = posToString(minPos), posToString(maxPos) local minPosStr, maxPosStr = posToString(minPos), posToString(maxPos)
local getLayerTime, NoiseCalcTime, GenNodeTime = {}, {}, {} local startTime, endTime = 0.0, 0.0
if LOG_PROFILE then if LOG_PROFILE then
mglog('Chunk run:\n'.. mglog('Chunk run:\n'..
'min_pos: %s\n'.. 'min_pos: %s\n'..
'max_pos: %s\n', 'max_pos: %s\n',
minPosStr, maxPosStr) minPosStr, maxPosStr)
startTime = getUsTime()
end end
local startTime = core.get_us_time()
local eMin, eMax = voxelManip:get_emerged_area() local eMin, eMax = voxelManip:get_emerged_area()
@@ -937,12 +916,8 @@ function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed)
for y = minPos.y, maxPos.y do for y = minPos.y, maxPos.y do
index = area:index(x, y, z) index = area:index(x, y, z)
if data[index] == core.CONTENT_AIR then if data[index] == AIR_ID then
local t1, t2, t3 = generatorHandler(self, layer, data, index, x, y, z) generatorHandler(self, layer, data, index, x, y, z)
table.insert(getLayerTime, t1)
table.insert(NoiseCalcTime, t2)
table.insert(GenNodeTime, t3)
end end
end end
end end
@@ -975,19 +950,17 @@ function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed)
voxelManip:calc_lighting() voxelManip:calc_lighting()
voxelManip:update_liquids() voxelManip:update_liquids()
local endTime = core.get_us_time() pastTriangle = nil
if LOG_PROFILE then
if PROFILE_CHUNK then
endTime = getUsTime()
mglog('Chunk end:\n'.. mglog('Chunk end:\n'..
'min_pos: %s\n'.. 'min_pos: %s\n'..
'max_pos: %s\n'.. 'max_pos: %s\n'..
'time (sec): %.3f\n'.. 'time (sec): %.3f\n'..
'GenerateHandler time (us): %.3f %.3f %.3f\n'..
'---------------', '---------------',
minPosStr, maxPosStr, minPosStr, maxPosStr,
(endTime - startTime)/1000000, (endTime - startTime)/1000000)
calculateAverage(getLayerTime),
calculateAverage(NoiseCalcTime),
calculateAverage(GenNodeTime))
end end
end end
@@ -1011,7 +984,7 @@ function MapGen:run()
end) end)
self:initBiomesDiagram() self:initBiomesDiagram()
self:initLayersBoundaryRegions() self:initLayersBoundaryRegion()
MapGen.isRunning = true MapGen.isRunning = true
core.log('MapGen run') core.log('MapGen run')

View File

@@ -1,6 +1,6 @@
local getInstance = Class.getInstance local getInstance = Class.getInstance
---@class MapGen.Triangulation.Edge ---@class MapGen.Edge
---@field p1 MapGen.Peak ---@field p1 MapGen.Peak
---@field p2 MapGen.Peak ---@field p2 MapGen.Peak
---@field vec vector ---@field vec vector
@@ -8,9 +8,9 @@ local Edge = {}
---@param p1 MapGen.Peak ---@param p1 MapGen.Peak
---@param p2 MapGen.Peak ---@param p2 MapGen.Peak
---@return MapGen.Triangulation.Edge ---@return MapGen.Edge
function Edge:new( p1, p2 ) function Edge:new( p1, p2 )
---@type MapGen.Triangulation.Edge ---@type MapGen.Edge
local instance = getInstance(self, { local instance = getInstance(self, {
p1 = p1, p1 = p1,
p2 = p2, p2 = p2,
@@ -31,14 +31,14 @@ function Edge:toString()
end end
---Returns true if the edges are equivalent. ---Returns true if the edges are equivalent.
---@param other MapGen.Triangulation.Edge ---@param other MapGen.Edge
---@return boolean ---@return boolean
function Edge:eq(other) function Edge:eq(other)
return self.p1 == other.p1 and self.p2 == other.p2 return self.p1 == other.p1 and self.p2 == other.p2
end end
---Returns true if the edges are similar. ---Returns true if the edges are similar.
---@param other MapGen.Triangulation.Edge ---@param other MapGen.Edge
---@return boolean ---@return boolean
function Edge:same(other) function Edge:same(other)
return (self.p1 == other.p1 and self.p2 == other.p2) return (self.p1 == other.p1 and self.p2 == other.p2)

View File

@@ -7,7 +7,7 @@ local Peak = require('MapGen.Peak')
---Allows you to create a `MapGen.Peak` without specifying a noise parameter. ---Allows you to create a `MapGen.Peak` without specifying a noise parameter.
--- ---
---**WARNING: MUST NOT BE PARTICIPATED IN GENERATION** ---**WARNING: MUST NOT BE PARTICIPATED IN GENERATION**
---@class MapGen.Triangulation.FakePeak : MapGen.Peak ---@class MapGen.FakePeak : MapGen.Peak
---@field id number ---@field id number
---@field getPeakPos fun():vector ---@field getPeakPos fun():vector
local FakePeak = Class.extend(Peak, {}) local FakePeak = Class.extend(Peak, {})

View File

@@ -19,8 +19,8 @@ local Triangle = require('MapGen.Triangle')
---@field waterLevel integer ---@field waterLevel integer
---@field calcTemp fun(self:MapGen.Layer, value:number, height:number):number ---@field calcTemp fun(self:MapGen.Layer, value:number, height:number):number
---@field calcHumidity fun(self:MapGen.Layer, value:number, height:number):number ---@field calcHumidity fun(self:MapGen.Layer, value:number, height:number):number
---@field peaksList table<MapGen.Layer.Category, MapGen.Peak[]> ---@field peaksList MapGen.Peak[]
---@field peaksByPos table<MapGen.Layer.Category, table<string, MapGen.Peak>> ---@field peaksByPos table<string, MapGen.Peak>
---@field noisesByColor table<MapGen.Layer.Category, table<ColorString, ValueNoise>> ---@field noisesByColor table<MapGen.Layer.Category, table<ColorString, ValueNoise>>
---@field noisesParamsByColor table<MapGen.Layer.Category, table<ColorString, NoiseParams>> ---@field noisesParamsByColor table<MapGen.Layer.Category, table<ColorString, NoiseParams>>
---@field biomesByName table<string, MapGen.Biome> ---@field biomesByName table<string, MapGen.Biome>
@@ -31,18 +31,10 @@ local Triangle = require('MapGen.Triangle')
---@field cavernsByName table<string, MapGen.Cavern> ---@field cavernsByName table<string, MapGen.Cavern>
---@field cavernsList MapGen.Cavern[] ---@field cavernsList MapGen.Cavern[]
---@field regionsByName table<string, MapGen.Region> ---@field regionsByName table<string, MapGen.Region>
---@field trianglesList table<MapGen.Layer.Category, MapGen.Triangle[]> ---@field trianglesList MapGen.Triangle[]
local Layer = { local Layer = {
peaksList = { peaksList = {},
landscape = {}, peaksByPos = {},
temp = {},
humidity = {},
},
peaksByPos = {
landscape = {},
temp = {},
humidity = {},
},
noisesByColor = { noisesByColor = {
landscape = {}, landscape = {},
temp = {}, temp = {},
@@ -59,11 +51,7 @@ local Layer = {
cavernsByName = {}, cavernsByName = {},
cavernsList = {}, cavernsList = {},
regionsByName = {}, regionsByName = {},
trianglesList = { trianglesList = {},
landscape = {},
temp = {},
humidity = {},
},
tetrahedronsList = {}, tetrahedronsList = {},
} }
@@ -103,10 +91,9 @@ end
---**Note:** If the colors of the new peak and the existing one at the same coordinates ---**Note:** If the colors of the new peak and the existing one at the same coordinates
---are different, an error will be called. ---are different, an error will be called.
---@param def MapGen.PeakDef ---@param def MapGen.PeakDef
---@param category MapGen.Layer.Category
---@param scale number ---@param scale number
---@return MapGen.Peak ---@return MapGen.Peak
function Layer:registerPeak(def, category, scale) function Layer:registerPeak(def, scale)
assert(def.pos ~= nil) assert(def.pos ~= nil)
assert(def.pos.x ~= nil) assert(def.pos.x ~= nil)
assert(def.pos.z ~= nil) assert(def.pos.z ~= nil)
@@ -119,11 +106,11 @@ function Layer:registerPeak(def, category, scale)
local positionStr = core.pos_to_string(def.pos) local positionStr = core.pos_to_string(def.pos)
local peak = self.peaksByPos[category][positionStr] local peak = self.peaksByPos[positionStr]
if peak == nil then if peak == nil then
peak = Peak:new(def) peak = Peak:new(def)
self.peaksByPos[category][positionStr] = peak self.peaksByPos[positionStr] = peak
elseif peak.color ~= def.color then elseif peak.color ~= def.color then
error('There cannot be two peaks with the same coordinates but different colors.') error('There cannot be two peaks with the same coordinates but different colors.')
end end
@@ -132,13 +119,13 @@ function Layer:registerPeak(def, category, scale)
end end
function Layer:initTrianglesNeighbours() function Layer:initTrianglesNeighbours()
for _, triangles in pairs(self.trianglesList) do local triangles = self.trianglesList
for _, triangle in ipairs(triangles) do
for _, triangle in pairs(triangles) do
for _, id in ipairs(triangle.neighboursIDs) do for _, id in ipairs(triangle.neighboursIDs) do
table.insert(triangle.neighbours, triangles[id]) table.insert(triangle.neighbours, triangles[id])
end end
end end
end
end end
---@param fileName string ---@param fileName string
@@ -155,9 +142,9 @@ function Layer:getTriaglesFromFile(fileName, category, scale)
assert(triangles ~= nil) assert(triangles ~= nil)
for _, tr in ipairs(triangles) do for _, tr in ipairs(triangles) do
local p1 = self:registerPeak( tr.vertices[1], category, scale) local p1 = self:registerPeak( tr.vertices[1], scale)
local p2 = self:registerPeak( tr.vertices[2], category, scale) local p2 = self:registerPeak( tr.vertices[2], scale)
local p3 = self:registerPeak( tr.vertices[3], category, scale) local p3 = self:registerPeak( tr.vertices[3], scale)
local triangle = Triangle:new(tr.id,p1, p2, p3, tr.adjacent_triangle_ids) local triangle = Triangle:new(tr.id,p1, p2, p3, tr.adjacent_triangle_ids)
@@ -219,7 +206,7 @@ end
---@param category MapGen.Layer.Category ---@param category MapGen.Layer.Category
---@param triangle MapGen.Triangle ---@param triangle MapGen.Triangle
function Layer:addTriangle(category, triangle) function Layer:addTriangle(category, triangle)
local triangles = self.trianglesList[category] local triangles = self.trianglesList
if triangles ~= nil then if triangles ~= nil then
triangles[triangle.id] = triangle triangles[triangle.id] = triangle
else else
@@ -231,25 +218,16 @@ end
---@param category MapGen.Layer.Category ---@param category MapGen.Layer.Category
---@param peak MapGen.Peak ---@param peak MapGen.Peak
function Layer:addPeak(category, peak) function Layer:addPeak(category, peak)
if category == 'landscape' then table.insert(self.peaksList, peak)
table.insert(self.peaksList.landscape, peak)
elseif category == 'temp' then
table.insert(self.peaksList.temp, peak)
elseif category == 'humidity' then
table.insert(self.peaksList.humidity, peak)
else
error(('There is no peak category named %s.'):format(category))
end
end end
---Returns the `MapGen.Peak` at the coordinates. If there is no peak at these coordinates, it returns `nil`. ---Returns the `MapGen.Peak` at the coordinates. If there is no peak at these coordinates, it returns `nil`.
---@param category MapGen.Layer.Category The category in which the peak is located.
---@param pos Position Coordinate of the desired peak. ---@param pos Position Coordinate of the desired peak.
---@return MapGen.Peak? ---@return MapGen.Peak?
function Layer:getPeakByPos(category, pos) function Layer:getPeakByPos(pos)
local positionStr = core.pos_to_string(pos) local positionStr = core.pos_to_string(pos)
local peak = self.peaksByPos[category][positionStr] local peak = self.peaksByPos[positionStr]
return peak return peak
end end

View File

@@ -6,10 +6,10 @@ local getInstance = Class.getInstance
local modInfo = Mod.getInfo('smc__core__map_gen') local modInfo = Mod.getInfo('smc__core__map_gen')
local require = modInfo.require local require = modInfo.require
---@type MapGen.Triangulation.Edge ---@type MapGen.Edge
local Edge = require('MapGen.Triangulation.Edge') local Edge = require('MapGen.Edge')
---@type MapGen.Triangulation.FakePeak ---@type MapGen.FakePeak
local FakePeak = require('MapGen.Triangulation.FakePeak') local FakePeak = require('MapGen.FakePeak')
-- --- Helpers functions --- -- --- Helpers functions ---
@@ -67,12 +67,12 @@ end
---@field p1 MapGen.Peak ---@field p1 MapGen.Peak
---@field p2 MapGen.Peak ---@field p2 MapGen.Peak
---@field p3 MapGen.Peak ---@field p3 MapGen.Peak
---@field e1 MapGen.Triangulation.Edge ---@field e1 MapGen.Edge
---@field e2 MapGen.Triangulation.Edge ---@field e2 MapGen.Edge
---@field e3 MapGen.Triangulation.Edge ---@field e3 MapGen.Edge
---@field h1 MapGen.Triangulation.Edge ---@field h1 MapGen.Edge
---@field h2 MapGen.Triangulation.Edge ---@field h2 MapGen.Edge
---@field h3 MapGen.Triangulation.Edge ---@field h3 MapGen.Edge
---@field neighboursIDs integer[] ---@field neighboursIDs integer[]
---@field neighbours MapGen.Triangle[] ---@field neighbours MapGen.Triangle[]
---@field color ColorString? ---@field color ColorString?
@@ -167,7 +167,7 @@ end
---@param p1 MapGen.Peak ---@param p1 MapGen.Peak
---@param p2 MapGen.Peak ---@param p2 MapGen.Peak
---@param p3 MapGen.Peak ---@param p3 MapGen.Peak
---@return MapGen.Triangulation.Edge ---@return MapGen.Edge
function Triangle:getHeight(p1, p2, p3) function Triangle:getHeight(p1, p2, p3)
local pos1 = p1.pos local pos1 = p1.pos
local pos2 = p2.pos local pos2 = p2.pos
@@ -193,7 +193,7 @@ end
---@param p1 MapGen.Peak ---@param p1 MapGen.Peak
---@param p2 MapGen.Peak ---@param p2 MapGen.Peak
---@param p3 MapGen.Peak ---@param p3 MapGen.Peak
---@return MapGen.Triangulation.Edge ---@return MapGen.Edge
function Triangle:getHeight2D(p1, p2, p3) function Triangle:getHeight2D(p1, p2, p3)
local pos1 = p1.pos local pos1 = p1.pos
local pos2 = p2.pos local pos2 = p2.pos

View File

@@ -29,7 +29,7 @@ function Profiler:startTimer()
end end
---Marks the end time of the timer. ---Marks the end time of the timer.
function Profiler:endTimer() function Profiler:stopTimer()
self.endTime = getUsTime() self.endTime = getUsTime()
self.deltaTime = self.endTime - self.startTime self.deltaTime = self.endTime - self.startTime