diff --git a/.emmyrc.json b/.emmyrc.json index c53433d..fa2d5da 100644 --- a/.emmyrc.json +++ b/.emmyrc.json @@ -1,50 +1,80 @@ { - "codeAction": { - "insertSpace": false - }, - "codeLens": { - "enable": true - }, "completion": { + "enable": true, "autoRequire": false, "autoRequireFunction": "require", "autoRequireNamingConvention": "keep", "autoRequireSeparator": ".", "callSnippet": false, - "enable": true, "postfix": "@" }, "diagnostics": { - "diagnosticInterval": 1, "disable": [ - "unnecessary-if", - "redefined-local" + "unnecessary-if" ], "enable": true, - "enables": [], "globals": [ "core", "table", "VoxelArea", - "VoxelManip", + "VoxelManip", "vector", "Ensure", "string", "string_utf8" ], - "globalsRegex": [] + "globalsRegex": [], + "severity": {}, + "enables": [], + "diagnosticInterval": 1 }, - "documentColor": { - "enable": true + "signature": { + "detailSignatureHelper": true }, "hint": { "enable": true, + "paramHint": true, "indexHint": true, "localHint": true, - "overrideHint": true, - "paramHint": true + "overrideHint": true }, - "hover": { + "runtime": { + "version": "LuaJIT", + "requireLikeFunction": [], + "frameworkVersions": [], + "extensions": [], + "requirePattern": [], + "classDefaultCall": { + "functionName": "", + "forceNonColon": false, + "forceReturnSelf": false + } + }, + "workspace": { + "ignoreDir": [], + "ignoreGlobs": [], + "library": [], + "workspaceRoots": [], + "preloadFileSize": 0, + "encoding": "utf-8", + "moduleMap": [], + "reindexDuration": 5000, + "enableReindex": false + }, + "resource": { + "paths": [] + }, + "codeLens": { + "enable": true + }, + "strict": { + "requirePath": false, + "typeCall": false, + "arrayIndex": true, + "metaOverrideFileDefine": true, + "docBaseConstMatchBaseType": true + }, + "semanticTokens": { "enable": true }, "references": { @@ -52,45 +82,16 @@ "fuzzySearch": true, "shortStringSearch": false }, - "resource": { - "paths": [] - }, - "runtime": { - "classDefaultCall": { - "forceNonColon": false, - "forceReturnSelf": false, - "functionName": "" - }, - "extensions": [], - "frameworkVersions": [], - "requireLikeFunction": [], - "requirePattern": [], - "version": "LuaJIT" - }, - "semanticTokens": { + "hover": { "enable": true }, - "signature": { - "detailSignatureHelper": true + "documentColor": { + "enable": true }, - "strict": { - "arrayIndex": true, - "docBaseConstMatchBaseType": true, - "metaOverrideFileDefine": true, - "requirePath": false, - "typeCall": false + "codeAction": { + "insertSpace": false }, - "workspace": { - "enableReindex": false, - "encoding": "utf-8", - "ignoreDir": [], - "ignoreGlobs": [], - "library": [ - "util/ide-helper" - ], - "moduleMap": [], - "preloadFileSize": 0, - "reindexDuration": 5000, - "workspaceRoots": [] - } + "workspace.library": [ + "util/ide-helper" + ] } \ No newline at end of file diff --git a/mods/API/Mod/init.lua b/mods/API/Mod/init.lua index f51cebd..998707f 100644 --- a/mods/API/Mod/init.lua +++ b/mods/API/Mod/init.lua @@ -3,7 +3,7 @@ ---@field name string Technical name of the mod. ---@field shortName string ---@field path string Path to the mod folder. ----@field Class any A public class that provides a mod. +---@field Class table A public class that provides a mod. ---@field require fun(FileName:string):table Mod = {} @@ -17,10 +17,9 @@ local function getShortModName(name) end ---Return table with mod name, path and require function. ----@param modname? string Specify a name of mod to get its info ---@return {name: string, shortName: string, path: string, require: fun(FileName : string): table} -function Mod.getInfo(modname) - local name = modname or core.get_current_modname() +function Mod.getInfo() + local name = core.get_current_modname() local shortName = getShortModName(name) local path = core.get_modpath(name) local require = Require.getModRequire(name, path) diff --git a/mods/CORE/Item/src/Item.lua b/mods/CORE/Item/src/Item.lua index 34e9872..5413e9e 100644 --- a/mods/CORE/Item/src/Item.lua +++ b/mods/CORE/Item/src/Item.lua @@ -1,5 +1,5 @@ -local modInfo = Mod.getInfo() -local require = modInfo.require +local modInfo = Mod.getInfo() +local require = modInfo.require local VisualEnum = require('Item.VisualEnum') diff --git a/mods/CORE/MapGen/init.lua b/mods/CORE/MapGen/init.lua index 847ec48..1d4e918 100644 --- a/mods/CORE/MapGen/init.lua +++ b/mods/CORE/MapGen/init.lua @@ -3,3 +3,4 @@ local MapGen = Mod:new() MapGen.Class = MapGen.require('MapGen') Api.addModToGlobalSpace(MapGen, 'Core.MapGen') + diff --git a/mods/CORE/MapGen/mod.conf b/mods/CORE/MapGen/mod.conf index d8f5259..3767411 100644 --- a/mods/CORE/MapGen/mod.conf +++ b/mods/CORE/MapGen/mod.conf @@ -1,2 +1,2 @@ name = smc__core__map_gen -depends = smc__api__api_loader, smc__core__polyhedron, smc__game__items__rocks, smc__game__items__liquids \ No newline at end of file +depends = smc__api__api_loader, smc__game__items__rocks, smc__game__items__liquids \ No newline at end of file diff --git a/mods/CORE/MapGen/src/MapGen.lua b/mods/CORE/MapGen/src/MapGen.lua index fafeeba..e2c561d 100644 --- a/mods/CORE/MapGen/src/MapGen.lua +++ b/mods/CORE/MapGen/src/MapGen.lua @@ -1,15 +1,7 @@ -local modInfo = Mod.getInfo() -local require = modInfo.require +local mathCeil, mathAbs, mathRound, mathMin + = math.ceil, math.abs, math.round, math.min -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 --- +-- --- MapGen default moises --- ---@type ValueNoise local oceanNoise @@ -68,8 +60,20 @@ 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 @@ -83,7 +87,7 @@ local MapGen = { layersByName = {}, layersList = {}, biomesList = {}, - biomesDiagram = {}, + biomesDiagram = {}, multinoiseInitialized = false, isRunning = false, } @@ -145,24 +149,35 @@ 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 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" +---@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 local layer = self.layersByName[layerName] - if not layer then error("Invalid layer: " .. layerName) end - -- 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 + if not layer then + error("Invalid layer: " .. layerName) end - local region = Region:new(polyhedron, multinoiseParams, bufferZone) + 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) + layer:addRegion(region) end @@ -199,7 +214,7 @@ function MapGen:initBiomesDiagram() diagram[temp] = {} for humidity = 0, 100 do - local minDistance = mathHuge + local minDistance = math.huge local closestBiome = nil ---@param biome MapGen.Biome @@ -217,6 +232,34 @@ 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 @@ -264,55 +307,68 @@ local function generateNode(mapGenerator, hight, temp, humidity, data, index, x, end ---@param mapGenerator MapGen -local function generatorHandler3D(mapGenerator, data, index, x, y, z) +local function generatorHandler(mapGenerator, data, index, x, y, z) + -- If generation occurs outside the layers, then a void is generated local layer = mapGenerator:getLayerByHeight(y) if layer == nil then data[index] = mapGenerator.nodeIDs.air + return 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 + -- The ocean floor height is used as the default value. + if oceanNoise == nil then + oceanNoise = core.get_value_noise(oceanNoiseParams) + end - -- 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}) + -- Default noise's values. + local noiseHeightValue = oceanNoise:get_2d({x = x, y = z}) + local noiseTempValue = 0.0 + local noiseHumidityValue = 0.0 - local finalHeight = baseHeight - local finalTemp = baseTemp - local finalHumidity = baseHumidity + local tempValuesCount = 0 + local humidityValuesCount = 0 - 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 + 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 ) end - - if regionNoises.tempNoise then - local regionTemp = regionNoises.tempNoise:get_3d({x = x, y = y, z = z}) - finalTemp = baseTemp + (regionTemp - baseTemp) * blendFactor + + if tempNoise ~= nil then + noiseTempValue = noiseTempValue + tempNoise:get_2d({x = x, y = z}) + + tempValuesCount = tempValuesCount + 1 end - - if regionNoises.humidityNoise then - local regionHumidity = regionNoises.humidityNoise:get_3d({x = x, y = y, z = z}) - finalHumidity = baseHumidity + (regionHumidity - baseHumidity) * blendFactor + + if humidityNoise ~= nil then + noiseHumidityValue = noiseHumidityValue + humidityNoise:get_2d({x = x, y = z}) + + humidityValuesCount = humidityValuesCount + 1 end end - generateNode(mapGenerator, mathRound(finalHeight), mathRound(finalTemp), - mathRound(finalHumidity), data, index, x, y, z) + 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) end ---@param minPos table @@ -336,7 +392,7 @@ function MapGen:onMapGenerated(minPos, maxPos, blockseed) local index = area:index(minPos.x, y, z) for x = minPos.x, maxPos.x do - generatorHandler3D(self, data, index, x, y, z) + generatorHandler(self, data, index, x, y, z) index = index + 1 end diff --git a/mods/CORE/MapGen/src/MapGen/Biome.lua b/mods/CORE/MapGen/src/MapGen/Biome.lua index 8b9d816..7f729c4 100644 --- a/mods/CORE/MapGen/src/MapGen/Biome.lua +++ b/mods/CORE/MapGen/src/MapGen/Biome.lua @@ -25,4 +25,4 @@ function Biome:new(name, tempPoint, humidityPoint, groundNodes, soilHeight) return instance end -return Biome +return Biome \ No newline at end of file diff --git a/mods/CORE/MapGen/src/MapGen/InterpolationPresets.lua b/mods/CORE/MapGen/src/MapGen/InterpolationPresets.lua deleted file mode 100644 index d1beddf..0000000 --- a/mods/CORE/MapGen/src/MapGen/InterpolationPresets.lua +++ /dev/null @@ -1,25 +0,0 @@ ----@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 diff --git a/mods/CORE/MapGen/src/MapGen/Layer.lua b/mods/CORE/MapGen/src/MapGen/Layer.lua index 6622ccf..720d433 100644 --- a/mods/CORE/MapGen/src/MapGen/Layer.lua +++ b/mods/CORE/MapGen/src/MapGen/Layer.lua @@ -1,157 +1,63 @@ ---@class MapGen.Layer ----@field name string ----@field minY number ----@field maxY number ----@field regionsList table ----@field defaultRegion MapGen.Region +---@field name string +---@field minY number +---@field maxY number +---@field regionsList table local Layer = { regionsList = {} } -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 +---@param name string +---@param minY number +---@param maxY number +---@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 ----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 +---@param region MapGen.Region function Layer:addRegion(region) table.insert(self.regionsList, region) end ----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) +---@param xPos number +---@param yPos number +---@param zPos number +---@return MapGen.Region[] +function Layer:getRegionsByPos(xPos, yPos, zPos) + -- TODO: возможно здесь получится сделать более оптимизированный алгоритм + -- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated + -- и может быть даже не один раз + -- Можно подумать над тем, чтобы использовать сортированный список - 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 + ---@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) end + end - -- 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 + return regions end return Layer diff --git a/mods/CORE/MapGen/src/MapGen/Region.lua b/mods/CORE/MapGen/src/MapGen/Region.lua index f8cb85f..0c98e16 100644 --- a/mods/CORE/MapGen/src/MapGen/Region.lua +++ b/mods/CORE/MapGen/src/MapGen/Region.lua @@ -1,9 +1,10 @@ ---@class MapGen.Region ----@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 +---@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 local Region = {} ---@param multinoiseParams MapGen.Region.MultinoiseParams @@ -19,30 +20,57 @@ local function multinoiseParamsToMultinoise(multinoiseParams) return multinoise end ----@param polyhedron Polyhedron +---@param minPos vector +---@param maxPos vector ---@param multinoiseParams MapGen.Region.MultinoiseParams ----@param bufferZone MapGen.Region.BufferZone +---@param weightFactor number ---@return MapGen.Region -function Region:new(polyhedron, multinoiseParams, bufferZone) - local _polyhedron = polyhedron - local _multinoiseParams = multinoiseParams - local _bufferZone = bufferZone - local _interpolationPreset = bufferZone.preset or "linear" - local _multinoise = {} +function Region:new(minPos, maxPos, multinoiseParams, weightFactor) - local instance = setmetatable({}, {__index = self}) + ---@type vector + local _minPos = minPos + ---@type vector + local _maxPos = maxPos + ---@type MapGen.Region.MultinoiseParams + local _multinoiseParams = multinoiseParams - 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 + if weightFactor < 0 then + weightFactor = 1 + end - return instance + ---@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 end return Region diff --git a/mods/CORE/MapGen/src/MapGen/Region/BufferZone.lua b/mods/CORE/MapGen/src/MapGen/Region/BufferZone.lua deleted file mode 100644 index 8d49a4d..0000000 --- a/mods/CORE/MapGen/src/MapGen/Region/BufferZone.lua +++ /dev/null @@ -1,16 +0,0 @@ ----@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 diff --git a/mods/CORE/OBJLoader/init.lua b/mods/CORE/OBJLoader/init.lua deleted file mode 100644 index 58c7e70..0000000 --- a/mods/CORE/OBJLoader/init.lua +++ /dev/null @@ -1,5 +0,0 @@ -local OBJLoader = Mod:new() - -OBJLoader.Class = OBJLoader.require('OBJLoader') - -Api.addModToGlobalSpace(OBJLoader, 'Core.OBJLoader') diff --git a/mods/CORE/OBJLoader/mod.conf b/mods/CORE/OBJLoader/mod.conf deleted file mode 100644 index d4eda56..0000000 --- a/mods/CORE/OBJLoader/mod.conf +++ /dev/null @@ -1,2 +0,0 @@ -name = smc__core__obj_loader -depends = smc__api__api_loader, smc__core__polyhedron \ No newline at end of file diff --git a/mods/CORE/OBJLoader/src/OBJLoader.lua b/mods/CORE/OBJLoader/src/OBJLoader.lua deleted file mode 100644 index 2c78544..0000000 --- a/mods/CORE/OBJLoader/src/OBJLoader.lua +++ /dev/null @@ -1,37 +0,0 @@ -local OBJLoader = {} - -function OBJLoader:load(filename) - local file = io.open(filename, "r") - if not file then error("Cannot open OBJ file: " .. filename) end - - local vertices = {} - local faces = {} - - for line in file:lines() do - line = tostring(line) -- to make EmmyLua shut up - - if line:sub(1, 2) == "v " then - local x, y, z = line:match("v (%S+) (%S+) (%S+)") - ---@diagnostic disable-next-line: param-type-not-match -- TODO: tell alek to fix his ide-helper's vector.new annotation - table.insert(vertices, vector.new(tonumber(x), tonumber(y), tonumber(z))) - elseif line:sub(1, 2) == "f " then - local faceVertices = {} - for vertex in line:gmatch("%S+") do - if vertex ~= "f" then - local index = tonumber(vertex:match("(%d+)")) - table.insert(faceVertices, index) - end - end - table.insert(faces, faceVertices) - end - end - - file:close() - - ---@diagnostic disable-next-line: need-check-nil -- TODO: idk wtf to do but something has to be done - local polyhedron = Core.Polyhedron.Class:new(vertices, faces) - - return polyhedron -end - -return OBJLoader diff --git a/mods/CORE/Polyhedron/init.lua b/mods/CORE/Polyhedron/init.lua deleted file mode 100644 index 133ed82..0000000 --- a/mods/CORE/Polyhedron/init.lua +++ /dev/null @@ -1,5 +0,0 @@ -local Polyhedron = Mod:new() - -Polyhedron.Class = Polyhedron.require('Polyhedron') - -Api.addModToGlobalSpace(Polyhedron, 'Core.Polyhedron') diff --git a/mods/CORE/Polyhedron/mod.conf b/mods/CORE/Polyhedron/mod.conf deleted file mode 100644 index 7751de8..0000000 --- a/mods/CORE/Polyhedron/mod.conf +++ /dev/null @@ -1,2 +0,0 @@ -name = smc__core__polyhedron -depends = smc__api__api_loader, \ No newline at end of file diff --git a/mods/CORE/Polyhedron/src/Polyhedron.lua b/mods/CORE/Polyhedron/src/Polyhedron.lua deleted file mode 100644 index f81b5e6..0000000 --- a/mods/CORE/Polyhedron/src/Polyhedron.lua +++ /dev/null @@ -1,392 +0,0 @@ ----@class Polyhedron ----@field vertices vector[] ----@field faces integer[][] ----@field boundingBox {min: vector, max: vector} -local Polyhedron = {} - -local mathMin, mathMax, mathHuge, mathSqrt, mathAbs - = math.min, math.max, math.huge, math.sqrt, math.abs - ----Creates a new Polyhedron instance ----@param vertices vector[] Array of 3D vertices that define the polyhedron ----@param faces integer[][] Array of faces, where each face is an array of vertex indices ----@return Polyhedron -function Polyhedron:new(vertices, faces) - local instance = setmetatable({ - vertices = vertices, - faces = faces, - boundingBox = self:calculateBoundingBox(vertices) - }, {__index = self}) - return instance -end - ----Calculates the axis-aligned bounding box for the polyhedron ----@param vertices vector[] Array of vertices to compute bounds for ----@return {min: vector, max: vector} Bounding box with min and max corners -function Polyhedron:calculateBoundingBox(vertices) - local min = vector.new(mathHuge, mathHuge, mathHuge) - local max = vector.new(-mathHuge, -mathHuge, -mathHuge) - - for _, vertex in ipairs(vertices) do - min.x = mathMin(min.x, vertex.x) - min.y = mathMin(min.y, vertex.y) - min.z = mathMin(min.z, vertex.z) - max.x = mathMax(max.x, vertex.x) - max.y = mathMax(max.y, vertex.y) - max.z = mathMax(max.z, vertex.z) - end - - return {min = min, max = max} -end - ----Computes the normal vector for a face using Newell's method ----@param face integer[] Array of vertex indices forming the face ----@return vector Normalized normal vector for the face -function Polyhedron:computeFaceNormal(face) - if #face < 3 then - error("Face must have at least 3 vertices") - end - - -- Use Newell's method for more robust normal calculation with non-convex polygons - local normal = vector.new(0, 0, 0) - - for i = 1, #face do - local j = (i % #face) + 1 - local current = self.vertices[face[i]] - local next = self.vertices[face[j]] - - normal.x = normal.x + (current.y - next.y) * (current.z + next.z) - normal.y = normal.y + (current.z - next.z) * (current.x + next.x) - normal.z = normal.z + (current.x - next.x) * (current.y + next.y) - end - - return normal:normalize() -end - ----Computes the plane equation for a face ----@param face integer[] Array of vertex indices forming the face ----@return {normal: vector, point: vector, d: number} Plane equation in form: normal·x + d = 0 -function Polyhedron:computePlane(face) - local normal = self:computeFaceNormal(face) - local point = self.vertices[face[1]] - local d = -normal:dot(point) - return {normal = normal, point = point, d = d} -end - ----Finds the intersection point between a ray and a plane ----@param rayOrigin vector Starting point of the ray ----@param rayDir vector Direction vector of the ray (should be normalized) ----@param plane {normal: vector, point: vector, d: number} Plane equation ----@return vector|nil Intersection point, or nil if no intersection -function Polyhedron:rayPlaneIntersection(rayOrigin, rayDir, plane) - local denom = plane.normal:dot(rayDir) - - -- Ray is parallel to plane - if mathAbs(denom) < 1e-6 then - return nil - end - - local t = (-plane.normal:dot(rayOrigin) - plane.d) / denom - - -- Intersection is behind ray origin - if t < 0 then - return nil - end - - return rayOrigin + rayDir * t -end - ----Checks if a 3D point lies within a face (convex or non-convex) ----@param point vector The point to test ----@param face integer[] Array of vertex indices forming the face ----@return boolean True if point is inside the face, false otherwise -function Polyhedron:pointInFace(point, face) - if #face < 3 then - return false - end - - -- Project the face and point to 2D using the face's plane - local plane = self:computePlane(face) - - -- Create a 2D coordinate system on the plane - local uAxis, vAxis = self:createPlaneBasis(plane.normal) - - -- Project all vertices to 2D - local vertices2D = {} - for _, vertexIndex in ipairs(face) do - local vertex = self.vertices[vertexIndex] - local vecToVertex = vertex - plane.point - local u = vecToVertex:dot(uAxis) - local v = vecToVertex:dot(vAxis) - table.insert(vertices2D, {u, v}) - end - - -- Project the point to 2D - local vecToPoint = point - plane.point - local pointU = vecToPoint:dot(uAxis) - local pointV = vecToPoint:dot(vAxis) - local point2D = {pointU, pointV} - - -- Use winding number algorithm for point-in-polygon test (works with non-convex polygons) - return self:pointInPolygon2D(point2D, vertices2D) -end - ----Creates an orthonormal basis for a plane defined by its normal ----@param normal vector Normal vector of the plane ----@return vector uAxis First basis vector ----@return vector vAxis Second basis vector -function Polyhedron:createPlaneBasis(normal) - -- Choose an arbitrary vector not parallel to normal - local temp - if mathAbs(normal.x) > mathAbs(normal.y) then - temp = vector.new(0, 1, 0) - else - temp = vector.new(1, 0, 0) - end - - local uAxis = normal:cross(temp):normalize() - local vAxis = normal:cross(uAxis):normalize() - - return uAxis, vAxis -end - ----Winding number algorithm for 2D point-in-polygon test ----@param point number[] 2D point as {u, v} coordinates ----@param polygon number[][] Array of 2D polygon vertices as {{u,v}, ...} ----@return boolean True if point is inside polygon, false otherwise -function Polyhedron:pointInPolygon2D(point, polygon) - local wn = 0 -- Winding number counter - - for i = 1, #polygon do - local j = (i % #polygon) + 1 - local vi = polygon[i] - local vj = polygon[j] - - if vi[2] <= point[2] then - if vj[2] > point[2] then - -- Upward crossing - if self:isLeft(vi, vj, point) > 0 then - wn = wn + 1 - end - end - else - if vj[2] <= point[2] then - -- Downward crossing - if self:isLeft(vi, vj, point) < 0 then - wn = wn - 1 - end - end - end - end - - return wn ~= 0 -- Non-zero means inside -end - ----Helper function for winding number algorithm - determines if point is left of edge ----@param a number[] First vertex of edge {u, v} ----@param b number[] Second vertex of edge {u, v} ----@param p number[] Point to test {u, v} ----@return number Positive if left, negative if right, zero if collinear -function Polyhedron:isLeft(a, b, p) - return (b[1] - a[1]) * (p[2] - a[2]) - (p[1] - a[1]) * (b[2] - a[2]) -end - ----Checks if a ray intersects with a face ----@param rayOrigin vector Starting point of the ray ----@param rayDir vector Direction vector of the ray ----@param face integer[] Array of vertex indices forming the face ----@return boolean True if ray intersects the face, false otherwise -function Polyhedron:rayIntersectsFace(rayOrigin, rayDir, face) - local plane = self:computePlane(face) - local intersection = self:rayPlaneIntersection(rayOrigin, rayDir, plane) - - if not intersection then - return false - end - - return self:pointInFace(intersection, face) -end - ----Calculates the minimum distance from a point to a face ----@param point vector The point to measure distance from ----@param face integer[] Array of vertex indices forming the face ----@return number Minimum distance to the face (0 if point is on the face) -function Polyhedron:distanceToFace(point, face) - local plane = self:computePlane(face) - - -- First check if projection is inside the face - local projection = point - plane.normal * (plane.normal:dot(point) + plane.d) - - if self:pointInFace(projection, face) then - -- Point projects inside face, return distance to plane - return mathAbs(plane.normal:dot(point) + plane.d) - end - - -- Point projects outside face, find minimum distance to edges or vertices - local minDistance = mathHuge - - -- Check distance to each edge - for i = 1, #face do - local j = (i % #face) + 1 - local v1 = self.vertices[face[i]] - local v2 = self.vertices[face[j]] - - local edgeDistance = self:pointToLineSegmentDistance(point, v1, v2) - minDistance = mathMin(minDistance, edgeDistance) - end - - -- Also check distance to vertices (in case the closest point is a vertex) - for _, vertexIndex in ipairs(face) do - local vertex = self.vertices[vertexIndex] - local vertexDistance = (point - vertex):length() - minDistance = mathMin(minDistance, vertexDistance) - end - - return minDistance -end - ----Calculates the distance from a point to a line segment ----@param point vector The point to measure distance from ----@param lineStart vector Start point of the line segment ----@param lineEnd vector End point of the line segment ----@return number Minimum distance from point to the line segment -function Polyhedron:pointToLineSegmentDistance(point, lineStart, lineEnd) - local lineVec = lineEnd - lineStart - local lineLengthSq = lineVec:dot(lineVec) - - if lineLengthSq == 0 then - return (point - lineStart):length() - end - - local t = (point - lineStart):dot(lineVec) / lineLengthSq - t = mathMax(0, mathMin(1, t)) - - local projection = lineStart + lineVec * t - return (point - projection):length() -end - ----Checks if this polyhedron's bounding box intersects with another's ----@param otherPolyhedron Polyhedron The other polyhedron to test against ----@return boolean True if bounding boxes intersect, false otherwise -function Polyhedron:boundingBoxIntersects(otherPolyhedron) - local box1 = self.boundingBox - local box2 = otherPolyhedron.boundingBox - - return box1.min.x <= box2.max.x and box1.max.x >= box2.min.x and - box1.min.y <= box2.max.y and box1.max.y >= box2.min.y and - box1.min.z <= box2.max.z and box1.max.z >= box2.min.z -end - ----Checks if any edge of this polyhedron intersects with any face of another polyhedron ----@param otherPolyhedron Polyhedron The other polyhedron to test against ----@return boolean True if any edge intersects any face, false otherwise -function Polyhedron:edgesIntersect(otherPolyhedron) - -- Check each edge of this polyhedron against each face of the other - for _, face in ipairs(self.faces) do - for i = 1, #face do - local j = (i % #face) + 1 - local edgeStart = self.vertices[face[i]] - local edgeEnd = self.vertices[face[j]] - - if self:edgeIntersectsPolyhedron(edgeStart, edgeEnd, otherPolyhedron) then - return true - end - end - end - - -- Check each edge of the other polyhedron against each face of this - for _, face in ipairs(otherPolyhedron.faces) do - for i = 1, #face do - local j = (i % #face) + 1 - local edgeStart = otherPolyhedron.vertices[face[i]] - local edgeEnd = otherPolyhedron.vertices[face[j]] - - if self:edgeIntersectsPolyhedron(edgeStart, edgeEnd, otherPolyhedron) then - return true - end - end - end - - return false -end - ----Checks if an edge intersects with any face of a polyhedron ----@param edgeStart vector Start point of the edge ----@param edgeEnd vector End point of the edge ----@param polyhedron Polyhedron The polyhedron to test against ----@return boolean True if edge intersects the polyhedron, false otherwise -function Polyhedron:edgeIntersectsPolyhedron(edgeStart, edgeEnd, polyhedron) - local edgeDir = (edgeEnd - edgeStart):normalize() - local edgeLength = (edgeEnd - edgeStart):length() - - for _, face in ipairs(polyhedron.faces) do - local plane = polyhedron:computePlane(face) - local intersection = self:rayPlaneIntersection(edgeStart, edgeDir, plane) - - if intersection then - local t = (intersection - edgeStart):length() - - -- Check if intersection is within edge bounds and inside face - if t >= 0 and t <= edgeLength and polyhedron:pointInFace(intersection, face) then - return true - end - end - end - - return false -end - ----Determines if a point is inside the polyhedron using ray-casting ----@param point vector The point to test ----@return boolean True if point is inside the polyhedron, false otherwise -function Polyhedron:containsPoint(point) - -- Ray-casting algorithm for point-in-polyhedron test - local rayDir = vector.new(1, 0, 0) -- Simple X-direction ray - local intersections = 0 - - for _, face in ipairs(self.faces) do - if self:rayIntersectsFace(point, rayDir, face) then - intersections = intersections + 1 - end - end - - return intersections % 2 == 1 -- Odd number of intersections = inside -end - ----Calculates the minimum distance from a point to the surface of the polyhedron ----@param point vector The point to measure distance from ----@return number Minimum distance to the polyhedron surface -function Polyhedron:distanceToSurface(point) - local minDistance = mathHuge - - for _, face in ipairs(self.faces) do - local distance = self:distanceToFace(point, face) - minDistance = mathMin(minDistance, distance) - end - - return minDistance -end - ----Checks if this polyhedron intersects with another polyhedron ----@param otherPolyhedron Polyhedron The other polyhedron to test against ----@return boolean True if polyhedrons intersect, false otherwise -function Polyhedron:intersects(otherPolyhedron) - -- Check if bounding boxes intersect first (optimization) - if not self:boundingBoxIntersects(otherPolyhedron) then - return false - end - - -- Check if any vertex of one is inside the other - for _, vertex in ipairs(self.vertices) do - if otherPolyhedron:containsPoint(vertex) then return true end - end - - for _, vertex in ipairs(otherPolyhedron.vertices) do - if self:containsPoint(vertex) then return true end - end - - -- Check for edge-face intersections - return self:edgesIntersect(otherPolyhedron) -end - -return Polyhedron \ No newline at end of file diff --git a/mods/ENVIRONMENT/MapGenerator/init.lua b/mods/ENVIRONMENT/MapGenerator/init.lua index 83ea8a6..cc2ef35 100644 --- a/mods/ENVIRONMENT/MapGenerator/init.lua +++ b/mods/ENVIRONMENT/MapGenerator/init.lua @@ -1,14 +1,7 @@ -local require = Mod.getInfo("smc__core__polyhedron").require -local Polyhedron = require("Polyhedron") - -require = Mod.getInfo("smc__core__map_gen").require -local Mapgen = require("MapGen") -local BufferZone = require("MapGen.Region.BufferZone") - local id = core.get_content_id ---@type MapGen -local mapGenerator = Mapgen:new({ +local mapGenerator = Core.MapGen.Class:new({ -- Special nodes air = id("air"), @@ -28,75 +21,55 @@ local mapGenerator = Mapgen:new({ mapGenerator:RegisterLayer("world", -1000, 500) --- Create a polyhedron for the region (cube from -150 to 150 in XZ, full layer height in Y) -local regionVertices = { - vector.new(-150, -1000, -150), -- Bottom southwest - vector.new( 150, -1000, -150), -- Bottom southeast - vector.new( 150, -1000, 150), -- Bottom northeast - vector.new(-150, -1000, 150), -- Bottom northwest - vector.new(-150, 500, -150), -- Top southwest - vector.new( 150, 500, -150), -- Top southeast - vector.new( 150, 500, 150), -- Top northeast - vector.new(-150, 500, 150) -- Top northwest -} - -local regionFaces = { - {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 -} - -local regionPolyhedron = Polyhedron:new(regionVertices, regionFaces) - --- Define buffer zone with 50 node thickness and smoothstep interpolation -local regionBufferZone = BufferZone:new(50, "smoothstep") - --- Register the region with the new system -mapGenerator:RegisterRegion("Region Alpha", "world", regionPolyhedron, { - landscapeNoise = { - offset = 50, - scale = 10, - spread = {x = 100, y = 100, z = 100}, - seed = 47, - octaves = 8, - persistence = 0.4, - lacunarity = 2, +mapGenerator:RegisterRegion("world", + vector.new(-150,0,-150), + vector.new(150,0,150), + { + landscapeNoise = { + offset = 50, + scale = 10, + spread = {x = 100, y = 100, z = 100}, + seed = 47, + octaves = 8, + persistence = 0.4, + lacunarity = 2, + }, + tempNoise = { + offset = 50, + scale = 25, + spread = {x = 10, y = 10, z = 10}, + seed = 12, + octaves = 2, + persistence = 0.6, + lacunarity = 2, + }, + humidityNoise = { + offset = 50, + scale = 25, + spread = {x = 10, y = 10, z = 10}, + seed = 12, + octaves = 2, + persistence = 0.6, + lacunarity = 2, + } }, - tempNoise = { - offset = 50, - scale = 25, - spread = {x = 10, y = 10, z = 10}, - seed = 12, - octaves = 2, - persistence = 0.6, - lacunarity = 2, + true, 1.5) +--[[ +mapGenerator:RegisterRegion("world", + vector.new(-50, 0, -50), + vector.new(50, 0, 50), + { + landscapeNoise = { + offset = -60, + scale = 10, + spread = {x = 100, y = 100, z = 100}, + seed = 41, + octaves = 3, + persistence = 0.4, + lacunarity = 2, + } }, - humidityNoise = { - offset = 50, - scale = 25, - spread = {x = 10, y = 10, z = 10}, - seed = 12, - octaves = 2, - persistence = 0.6, - lacunarity = 2, - } -}, regionBufferZone) - --- Alternative: Register region from OBJ file (uncomment if you have an OBJ file) --- mapGenerator:RegisterRegionFromOBJ("world", "regions/mountain_range.obj", { --- landscapeNoise = { --- offset = -60, --- scale = 10, --- spread = {x = 100, y = 100, z = 100}, --- seed = 41, --- octaves = 3, --- persistence = 0.4, --- lacunarity = 2, --- } --- }, BufferZone:new(30, "linear"), "linear") + true, 1.5) --]] mapGenerator:RegisterBiome("biome1", 0, 0, { soil = "soils:clay_soil_baren", @@ -108,4 +81,4 @@ mapGenerator:RegisterBiome("biome2", 100, 100, { turf = "soils:rocky_soil_baren", }, 1) -mapGenerator:run() \ No newline at end of file +mapGenerator:run() diff --git a/mods/ENVIRONMENT/MapGenerator/mod.conf b/mods/ENVIRONMENT/MapGenerator/mod.conf index 6a9eafa..614a05a 100644 --- a/mods/ENVIRONMENT/MapGenerator/mod.conf +++ b/mods/ENVIRONMENT/MapGenerator/mod.conf @@ -1,2 +1,2 @@ name = smc__core__map_generator -depends = smc__core__map_gen, smc__core__polyhedron, smc__game__items__rocks, smc__game__items__liquids \ No newline at end of file +depends = smc__core__map_gen, smc__game__items__rocks, smc__game__items__liquids \ No newline at end of file