Annotations changes: clarification of types, addition of missing annotations

This commit is contained in:
Van
2025-10-03 20:50:14 +03:00
parent ab92e372f3
commit 69b8c6469c
13 changed files with 129 additions and 84 deletions

View File

@@ -1,10 +1,10 @@
--- Luanti mod ---Luanti mod
---@class Mod ---@class Mod
---@field public name string Technical name of the mod. ---@field name string Technical name of the mod.
---@field public shortName string ---@field shortName string
---@field public path string Path to the mod folder. ---@field path string Path to the mod folder.
---@field public Class table A public class that provides a mod. ---@field Class table A public class that provides a mod.
---@field public require fun(FileName:string):table ---@field require fun(FileName:string):table
Mod = {} Mod = {}
---Returns the mod name without prefixes ---Returns the mod name without prefixes
@@ -16,7 +16,7 @@ local function getShortModName(name)
return shortName return shortName
end end
--- Return table with mod name, path and require function. ---Return table with mod name, path and require function.
---@return {name: string, shortName: string, path: string, require: fun(FileName : string): table} ---@return {name: string, shortName: string, path: string, require: fun(FileName : string): table}
function Mod.getInfo() function Mod.getInfo()
local name = core.get_current_modname() local name = core.get_current_modname()
@@ -29,40 +29,36 @@ end
function Mod:new() function Mod:new()
---@type Mod ---@type Mod
self = setmetatable(Mod.getInfo(), { __index = self }) local instance = setmetatable(Mod.getInfo(), { __index = self })
return self
end
--- Get an instance of a public class provided by a mod
---@param ... any?
---@return table
-- TODO: возможно стоит создать какой-то абстрактный класс,
-- который будет является алеасом на table и будет обозначать наш класс
function Mod:getModClassInstance(...)
local instance = self.Class:new(...)
return instance return instance
end end
--- Inherits a child class from a parent class ---Get an instance of a public class provided by a mod
---@static ---@param ... any?
---@return table
function Mod:getModClassInstance(...)
local classInstance = self.Class:new(...)
return classInstance
end
---Inherits a child class from a parent class
---@param ParentClass table ---@param ParentClass table
---@param ChildClass table? ---@param ChildClass table?
---@return table ---@return table
function Mod:getClassExtended(ParentClass, ChildClass) function Mod:getClassExtended(ParentClass, ChildClass)
local ChildClass = setmetatable(ChildClass or {}, { __index = ParentClass }) local childClass = setmetatable(ChildClass or {}, { __index = ParentClass })
return ChildClass return childClass
end end
--- Inherits a child class from a parent public class provided by the mod. ---Inherits a child class from a parent public class provided by the mod.
---@static
---@param ChildClass table? ---@param ChildClass table?
---@return table ---@return table
function Mod:getModClassExtended(ChildClass) function Mod:getModClassExtended(ChildClass)
local ChildClass = Mod:getClassExtended(self.Class, ChildClass or {}) local childClass = Mod:getClassExtended(self.Class, ChildClass or {})
return ChildClass return childClass
end end

View File

@@ -19,22 +19,27 @@ local Item = {
} }
} }
---The alias `table.merge` for EmmyLua
---@type fun(...):(NodeDefinition|ItemDefinition)
local defMerge = function(...)
return table.merge(...)
end
---@param itemDef Item.ItemDefinition ---@param itemDef Item.ItemDefinition
---@return NodeDefinition|ItemDefinition
local function itemDefToLuantiDef(itemDef) local function itemDefToLuantiDef(itemDef)
-- TODO: удалить следующую строчку, когда подключим ide-helper от Алека
---@diagnostic disable-next-line: undefined-field
itemDef = table.copy(itemDef) itemDef = table.copy(itemDef)
local s = itemDef.settings local s = itemDef.settings
local c = itemDef.callbacks local c = itemDef.callbacks
local description = s.title .. "\n" .. s.description local description = s.title .. "\n" .. s.description
s.title, s.description = nil, description s.title, s.description = nil, description
local luantiDef = table.merge(s, c) local luantiDef = defMerge(s, c)
return luantiDef return luantiDef
end end
---@param luantiDef table ---@param luantiDef NodeDefinition|ItemDefinition
local function register3dItem(luantiDef) local function register3dItem(luantiDef)
local ld = luantiDef local ld = luantiDef
local name = ld.name local name = ld.name
@@ -42,7 +47,7 @@ local function register3dItem(luantiDef)
core.register_node(':'..name, luantiDef) core.register_node(':'..name, luantiDef)
end end
---@param luantiDef table ---@param luantiDef ItemDefinition
local function registerFlatItem(luantiDef) local function registerFlatItem(luantiDef)
local ld = luantiDef local ld = luantiDef
local name = ld.name local name = ld.name
@@ -50,14 +55,14 @@ local function registerFlatItem(luantiDef)
core.register_craftitem(':'..name, luantiDef) core.register_craftitem(':'..name, luantiDef)
end end
---The aleas `table.merge` for EmmyLua ---The alias `table.merge` for EmmyLua
---@type fun(...):(Item.ItemDefinition) ---@type fun(...):(Item.ItemDefinition)
local defMerge = function(...) local defMerge = function(...)
return table.merge(...) return table.merge(...)
end end
---@param itemDef Item.ItemDefinition ---@param itemDef Item.ItemDefinition
---@return Item ---@return Item
function Item:new(itemDef) function Item:new(itemDef)
---Adding default parameters ---Adding default parameters
itemDef = defMerge(itemDef, self.defaultDef, true) itemDef = defMerge(itemDef, self.defaultDef, true)
@@ -81,13 +86,13 @@ function Item:new(itemDef)
registerFlatItem(luantiDef) registerFlatItem(luantiDef)
end end
---@return string
function instance:getVisual() function instance:getVisual()
return visual return visual
end end
instance.itemDef = itemDef instance.itemDef = itemDef
instance.luantiDef = luantiDef instance.luantiDef = luantiDef
return instance return instance
end end
@@ -95,7 +100,7 @@ end
---default parameters that will be added to the item's parameters ---default parameters that will be added to the item's parameters
---when an instance is received. ---when an instance is received.
---@param defaultDef Item.ItemDefinition ---@param defaultDef Item.ItemDefinition
---@return Item ---@return Item
function Item:getExtended(defaultDef) function Item:getExtended(defaultDef)
---@type Item ---@type Item
local ChildClass = Mod:getClassExtended(self, { local ChildClass = Mod:getClassExtended(self, {
@@ -107,12 +112,13 @@ end
---Returns an instance of the `ItemFactory` class that can be used to mass-register identical items. ---Returns an instance of the `ItemFactory` class that can be used to mass-register identical items.
---@param defaultDef? Item.ItemDefinition ---@param defaultDef? Item.ItemDefinition
---@return ItemFactory ---@return ItemFactory
function Item:getFactory(defaultDef) function Item:getFactory(defaultDef)
if defaultDef == nil then if defaultDef == nil then
defaultDef = self.defaultDef defaultDef = self.defaultDef
end end
---@type ItemFactory
local instance = Core.ItemFactory():new(self, defaultDef) local instance = Core.ItemFactory():new(self, defaultDef)
return instance return instance

View File

@@ -1,7 +1,7 @@
---@class Item.Callbacks ---@class Item.Callbacks
local Callbacks = {} local Callbacks = {}
-- TODO: Вписать вместо `table` более определенные классы: ItemStack, ObjectRef и т.п. -- TODO: Разобраться с дубликатами аннотаций полей. Приоритетно брать аннотации из util/ide-helper
---Called when the 'place' key was pressed with the item in hand ---Called when the 'place' key was pressed with the item in hand
---and pointing at a node. ---and pointing at a node.

View File

@@ -1,6 +1,8 @@
---@class Item.Settings ---@class Item.Settings
local Settings = {} local Settings = {}
-- TODO: Разобраться с дубликатами аннотаций полей. Приоритетно брать аннотации из util/ide-helper
---Technical name of the item. Must be unique and have the format `mod_name:item_name` ---Technical name of the item. Must be unique and have the format `mod_name:item_name`
---@type string ---@type string
Settings.name = "" Settings.name = ""
@@ -70,7 +72,6 @@ Settings.color = nil
---Maximum amount of items that can be in a single stack. ---Maximum amount of items that can be in a single stack.
---The default can be changed by the setting `default_stack_max`. ---The default can be changed by the setting `default_stack_max`.
---TODO: сделать другой стак по умолчанию?
---@type number? ---@type number?
Settings.stack_max = nil Settings.stack_max = nil

View File

@@ -1,11 +1,11 @@
---@class ItemFactory ---@class ItemFactory
---@field defaultDef Item.ItemDefinition | Node.NodeDefinition ---@field defaultDef Item.ItemDefinition|Node.NodeDefinition
---@field itemClass Item | Node ---@field itemClass Item|Node
local ItemFactory = {} local ItemFactory = {}
---@param itemClass Item | Node ---@param itemClass Item|Node
---@param defaultDef Item.ItemDefinition | Node.NodeDefinition Parameters that all nodes registered with this ItemFactory must have. ---@param defaultDef Item.ItemDefinition|Node.NodeDefinition Parameters that all nodes registered with this ItemFactory must have.
---@return ItemFactory ---@return ItemFactory
function ItemFactory:new(itemClass, defaultDef) function ItemFactory:new(itemClass, defaultDef)
---@type ItemFactory ---@type ItemFactory
local instance = setmetatable({ local instance = setmetatable({
@@ -22,7 +22,7 @@ local defMerge = function(...)
return table.merge(...) return table.merge(...)
end end
---@param itemDefs Item.ItemDefinition[] | Node.NodeDefinition[] List of nodes with parameters unique to them. ---@param itemDefs Item.ItemDefinition[]|Node.NodeDefinition[] List of nodes with parameters unique to them.
---@param addModName boolean Whether to add the mod name to the settings.name. Default: `true` ---@param addModName boolean Whether to add the mod name to the settings.name. Default: `true`
function ItemFactory:registerItems(itemDefs, addModName) function ItemFactory:registerItems(itemDefs, addModName)
if addModName == nil then if addModName == nil then
@@ -50,7 +50,6 @@ local defMerge = function(...)
return table.merge(...) return table.merge(...)
end end
---@param shortNodeDefs table Table of the form `{ {name, title, description, tiles}, {name, title, description, tiles}, ...}` ---@param shortNodeDefs table Table of the form `{ {name, title, description, tiles}, {name, title, description, tiles}, ...}`
---@param addModName boolean? Whether to add the mod name to the settings.name. Default: `true` ---@param addModName boolean? Whether to add the mod name to the settings.name. Default: `true`
function ItemFactory:registerNodesByShortDef(shortNodeDefs, addModName) function ItemFactory:registerNodesByShortDef(shortNodeDefs, addModName)
@@ -70,6 +69,7 @@ function ItemFactory:registerNodesByShortDef(shortNodeDefs, addModName)
tiles = shortNodeDef[4] tiles = shortNodeDef[4]
} }
} }
nodeDef = defMerge(nodeDef, self.defaultDef, true) nodeDef = defMerge(nodeDef, self.defaultDef, true)
if addModName then if addModName then

View File

@@ -31,23 +31,24 @@ local Region = require("MapGen.Region")
---@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 nodeIDs table<string, string> ---@field nodeIDs table<string, string>
local MapGen = { local MapGen = {
layersByName = {},
layersList = {},
multinoiseInitialized = false, multinoiseInitialized = false,
isRunning = false, isRunning = false,
} }
---@param nodeIDs table<string, string> ---@param nodeIDs table<string, string>
---@return MapGen ---@return MapGen
function MapGen:new(nodeIDs) function MapGen:new(nodeIDs)
---@type MapGen
local instance = setmetatable({ local instance = setmetatable({
layersByName = {}, nodeIDs = nodeIDs,
layersList = {},
nodeIDs = nodeIDs,
--registeredRegions = {},
}, {__index = self}) }, {__index = self})
return instance return instance
end end
---Determines which layer a node belongs to based on its height coordinate.
---@param yPos number ---@param yPos number
---@return MapGen.Layer? ---@return MapGen.Layer?
function MapGen:getLayerByHeight(yPos) function MapGen:getLayerByHeight(yPos)
@@ -66,6 +67,9 @@ function MapGen:getLayerByHeight(yPos)
end end
end end
---Mark the world area between two heights as a `MapGen.Layer`.
---
---Note: layers must not overlap.
---@param name string ---@param name string
---@param minY number ---@param minY number
---@param maxY number ---@param maxY number
@@ -87,12 +91,15 @@ function MapGen:RegisterLayer(name, minY, maxY)
end) end)
end end
---@param layerName string ---Mark a region of the world as a cubic region by two opposite vertices.
---@param minPos table ---
---@param maxPos table ---Regions must be included in layers and may overlap each other.
---@param multinoise table ---@param layerName string The name of the layer in which the new region will be included.
---@param regionIs2D boolean? ---@param minPos vector
---@param weightFactor number? ---@param maxPos vector
---@param multinoise table 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) function MapGen:RegisterRegion(layerName, minPos, maxPos, multinoise, regionIs2D, weightFactor)
---@type MapGen.Layer ---@type MapGen.Layer
local layer = self.layersByName[layerName] local layer = self.layersByName[layerName]
@@ -106,6 +113,8 @@ function MapGen:RegisterRegion(layerName, minPos, maxPos, multinoise, regionIs2D
maxPos.y = layer.maxY maxPos.y = layer.maxY
end end
--TODO: Добавить проверку, что регион не выходит за границы слоя или/и автоматически обрубать регион до слоя
if weightFactor == nil then if weightFactor == nil then
weightFactor = 1 weightFactor = 1
end end
@@ -131,9 +140,18 @@ function MapGen:initRegionsMultinoise()
self.multinoiseInitialized = true self.multinoiseInitialized = true
end end
---Calculate the weight for noise based on
---@return number ---the distance of the point from the center of the region.
local function calculateWeight(minPos, maxPos, x, z, weightFactor) ---
---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 if weightFactor == 0 then
return 1 return 1
end end
@@ -187,7 +205,7 @@ local function generatorHandler(mapGenerator, data, index, x, y, z)
local noise = region:getMultinoise().landscapeNoise local noise = region:getMultinoise().landscapeNoise
-- The further a point is from the center of a region, the less noise affects it. -- The further a point is from the center of a region, the less noise affects it.
local weight = calculateWeight(region:getMinPos(), region:getMaxPos(), x, z, region.getWeightFactor()) local weight = calculateWeight2D(region:getMinPos(), region:getMaxPos(), x, z, region.getWeightFactor())
noiseHeightValue = noiseHeightValue + ( noise:get_2d({x = x, y = z}) * weight ) noiseHeightValue = noiseHeightValue + ( noise:get_2d({x = x, y = z}) * weight )
end end
@@ -232,9 +250,12 @@ function MapGen:onMapGenerated(minPos, maxPos, blockseed)
voxelManip:write_to_map() voxelManip:write_to_map()
end end
---Run world generation through this mapgen object
---
---Note: only one instance of a `MapGen` class can be running.
function MapGen:run() function MapGen:run()
if MapGen.isRunning then if MapGen.isRunning then
error('Only one instance of a `MapGen` class can be used.') error('Only one instance of a `MapGen` class can be running.')
end end
core.register_on_generated(function(...) core.register_on_generated(function(...)

View File

@@ -2,7 +2,7 @@
---@field name string ---@field name string
---@field minY number ---@field minY number
---@field maxY number ---@field maxY number
---@field regionsList table ---@field regionsList table
local Layer = { local Layer = {
regionsList = {} regionsList = {}
} }
@@ -30,12 +30,14 @@ end
---@param xPos number ---@param xPos number
---@param yPos number ---@param yPos number
---@param zPos number ---@param zPos number
---@return table ---@return MapGen.Region[]
function Layer:getRegionsByPos(xPos, yPos, zPos) function Layer:getRegionsByPos(xPos, yPos, zPos)
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм -- TODO: возможно здесь получится сделать более оптимизированный алгоритм
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated -- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз -- и может быть даже не один раз
--- Можно подумать над тем, чтобы использовать сортированный список -- Можно подумать над тем, чтобы использовать сортированный список
---@type MapGen.Region[]
local regions = {} local regions = {}
---@param region MapGen.Region ---@param region MapGen.Region

View File

@@ -1,8 +1,13 @@
-- TODO: replace `table` with `vector` for minPos and maxPos
---@class MapGen.Region ---@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
local Region = {} local Region = {}
---@param multinoiseParams MapGen.Region.MultinoiseParams -- ??? TODO: should be it's own class in EmmyLua ---@param multinoiseParams MapGen.Region.MultinoiseParams
---@return MapGen.Region.Multinoise ---@return MapGen.Region.Multinoise
local function multinoiseParamsToMultinoise(multinoiseParams) local function multinoiseParamsToMultinoise(multinoiseParams)
---@type MapGen.Region.Multinoise ---@type MapGen.Region.Multinoise
@@ -15,37 +20,43 @@ local function multinoiseParamsToMultinoise(multinoiseParams)
return multinoise return multinoise
end end
---@param minPos table ---@param minPos vector
---@param maxPos table ---@param maxPos vector
---@param multinoiseParams MapGen.Region.MultinoiseParams ---@param multinoiseParams MapGen.Region.MultinoiseParams
---@param weightFactor number ---@param weightFactor number
---@return MapGen.Region ---@return MapGen.Region
function Region:new(minPos, maxPos, multinoiseParams, weightFactor) function Region:new(minPos, maxPos, multinoiseParams, weightFactor)
---@type vector
local _minPos = minPos local _minPos = minPos
---@type vector
local _maxPos = maxPos local _maxPos = maxPos
---@type MapGen.Region.MultinoiseParams
local _multinoiseParams = multinoiseParams local _multinoiseParams = multinoiseParams
if weightFactor < 0 then if weightFactor < 0 then
weightFactor = 1 weightFactor = 1
end end
---@type MapGen.Region.Multinoise
local _multinoise = {} local _multinoise = {}
---@type MapGen.Region
local instance = setmetatable({}, {__index = self}) local instance = setmetatable({}, {__index = self})
---@return {x:number, y:number, z:number}
function instance:getMinPos() function instance:getMinPos()
return _minPos return _minPos
end end
---@return vector
function instance:getMaxPos() function instance:getMaxPos()
return _maxPos return _maxPos
end end
function instance:getMultinoiseParams() function instance:getMultinoiseParams()
return _multinoiseParams return _multinoiseParams
end end
---@return MapGen.Region.Multinoise
function instance:getMultinoise() function instance:getMultinoise()
return _multinoise return _multinoise
end end

View File

@@ -1,9 +1,10 @@
---For EmmyLua only ---For EmmyLua only
-- TODO: Когда в хелпер добавятся аннотации шумов, надо будет удалить этот класс и заменить его на хелперский
---@class MapGen.Region.NoiseParams ---@class MapGen.Region.NoiseParams
---@field offset number ---@field offset number
---@field scale number ---@field scale number
---@field spread vector -- TODO: describe vector class from Luanti (push Alek) ---@field spread vector
---@field seed number ---@field seed number
---@field octaves number ---@field octaves number
---@field persistence number ---@field persistence number

View File

@@ -6,7 +6,7 @@ local VisualEnum = Core.Item.require('Item.VisualEnum')
local Node = Core.Item:getModClassExtended({}) local Node = Core.Item:getModClassExtended({})
---@param nodeDef Node.NodeDefinition ---@param nodeDef Node.NodeDefinition
---@return Node ---@return Node
function Node:new(nodeDef) function Node:new(nodeDef)
nodeDef.settings.visual = VisualEnum.ITEM_3D nodeDef.settings.visual = VisualEnum.ITEM_3D
@@ -20,7 +20,7 @@ end
---default parameters that will be added to the node's parameters ---default parameters that will be added to the node's parameters
---when an instance is received. ---when an instance is received.
---@param defaultDef Node.NodeDefinition ---@param defaultDef Node.NodeDefinition
---@return Node ---@return Node
function Node:getExtended(defaultDef) function Node:getExtended(defaultDef)
---@type Node ---@type Node
local ChildClass = Mod:getClassExtended(self, { local ChildClass = Mod:getClassExtended(self, {
@@ -32,7 +32,7 @@ end
---Returns an instance of the `ItemFactory` class that can be used to mass-register identical items. ---Returns an instance of the `ItemFactory` class that can be used to mass-register identical items.
---@param defaultDef? Node.NodeDefinition ---@param defaultDef? Node.NodeDefinition
---@return ItemFactory ---@return ItemFactory
function Node:getFactory(defaultDef) function Node:getFactory(defaultDef)
if defaultDef == nil then if defaultDef == nil then
defaultDef = self.defaultDef defaultDef = self.defaultDef

View File

@@ -1,6 +1,8 @@
---@type Item.Callbacks ---@type Item.Callbacks
local ItemCallbacks = Core.Item.require('Item.Callbacks') local ItemCallbacks = Core.Item.require('Item.Callbacks')
-- TODO: Разобраться с дубликатами аннотаций полей. Приоритетно брать аннотации из util/ide-helper
---@class Node.Callbacks : Item.Callbacks ---@class Node.Callbacks : Item.Callbacks
local Callbacks = Mod:getClassExtended(ItemCallbacks, {}) local Callbacks = Mod:getClassExtended(ItemCallbacks, {})

View File

@@ -1,6 +1,8 @@
---@type Item.Settings ---@type Item.Settings
local ItemSettings = Core.Item.require('Item.Settings') local ItemSettings = Core.Item.require('Item.Settings')
-- TODO: Разобраться с дубликатами аннотаций полей. Приоритетно брать аннотации из util/ide-helper
---@class Node.Settings : Item.Settings ---@class Node.Settings : Item.Settings
local Settings = Mod:getClassExtended(ItemSettings, {}) local Settings = Mod:getClassExtended(ItemSettings, {})

View File

@@ -1,20 +1,23 @@
---@class TileSheet ---@class TileSheet
---@field image string Name of texture ---@field image string Name of texture
---@field width number Number of tiles in the table horizontally ---@field width number Number of tiles in the table horizontally
---@field height number Number of tiles in the table vertically ---@field height number Number of tiles in the table vertically
local TileSheet = {} local TileSheet = {}
---@param image string Name of texture ---@param image string Name of texture
---@param width number Number of tiles in the table horizontally ---@param width number Number of tiles in the table horizontally
---@param height number Number of tiles in the table vertically ---@param height number Number of tiles in the table vertically
---@return TileSheet ---@return TileSheet
function TileSheet:new(image, width, height) function TileSheet:new(image, width, height)
---@type TileSheet
local instance = setmetatable({ local instance = setmetatable({
image = image, image = image,
width = width, width = width,
height = height, height = height,
}, {__index = self}) }, {__index = self})
-- TODO возможно будет лучше сделать автоматическое определение высоты и ширины по разрешению текстуры
return instance return instance
end end
@@ -28,7 +31,7 @@ function TileSheet:getTextureName(x, y)
return textureName return textureName
end end
---Aleas for `TileSheet:getTextureName`. ---Alias for `TileSheet:getTextureName`.
---@param x number ---@param x number
---@param y number ---@param y number
---@return string ---@return string