16 Commits

16 changed files with 594 additions and 73 deletions

View File

@@ -1,11 +1,31 @@
local getInstance = Class.getInstance
---@class BaseUI ---@class BaseUI
---Context for transferring data between displaying ---Context for transferring data between displaying
---the form spec to the player and handling callbacks. ---the form spec to the player and handling callbacks.
---@field contex table<string, table> ---@field name string
---@field getFormSpecString fun(self:BaseUI,playerName:string,...):string
---@field contex table<string, table>
local BaseUI = { local BaseUI = {
contex = {} contex = {}
} }
---@param name string
---@param getFormSpecString fun(self:BaseUI,playerName:string,...):string
function BaseUI:new(name, getFormSpecString)
---@type BaseUI
local instance = getInstance(self, {})
instance.name = name
instance.getFormSpecString = getFormSpecString
-- Ensure that when the form is closed, the context is cleared.
instance:registerOnFormQuit(function(player)
instance:clearContex(player)
end)
return instance
end
---Set a value for a specific key. ---Set a value for a specific key.
---Recommended for use where `core.show_formspec` is used. ---Recommended for use where `core.show_formspec` is used.
--- ---
@@ -14,7 +34,7 @@ local BaseUI = {
---@param key string ---@param key string
---@param value any ---@param value any
function BaseUI:setContex(player, key, value) function BaseUI:setContex(player, key, value)
if type(player) == 'table' then if type(player) ~= 'string' then
player = player:get_player_name() player = player:get_player_name()
end end
@@ -33,7 +53,7 @@ end
---@param key string ---@param key string
---@return any? ---@return any?
function BaseUI:getContex(player, key) function BaseUI:getContex(player, key)
if type(player) == 'table' then if type(player) ~= 'string' then
player = player:get_player_name() player = player:get_player_name()
end end
@@ -45,11 +65,58 @@ end
---Recommended for use when closing formspec. ---Recommended for use when closing formspec.
---@param player string|Player Player as an object (entity) or his name ---@param player string|Player Player as an object (entity) or his name
function BaseUI:clearContex(player) function BaseUI:clearContex(player)
if type(player) == 'table' then if type(player) ~= 'string' then
player = player:get_player_name() player = player:get_player_name()
end end
self.contex[player] = {} self.contex[player] = {}
end end
---Register a callback for a specific player action in FormSpec.
---
---The callback is guaranteed to be called only for the specified field.
---@param fieldName string the name of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called.
--- * `fieldValue` - the field value that is passed in the `fields` table.
function BaseUI:registerOnFormFieldAction(fieldName, callback)
Smc.registerOnFormFieldAction(self.name, fieldName, callback)
end
---Register a callback function to close the FormSpec.
---
---The callback is guaranteed to be called only for the specified form.
---@param callback fun(player:Player) Callback to handle the close. Parameters:
--- * `player` - the player who closed the form.
function BaseUI:registerOnFormQuit(callback)
Smc.registerOnFormQuit(self.name, callback)
end
---Register a callback for a specific player action in FormSpec.
---
---The callback function is guaranteed to be called only for the specified form and
---for the field whose name matches the pattern.
---@param fieldNamePattern string the name pattern of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called (will match the pattern).
--- * `fieldValue` - the field value that is passed in the `fields` table.
function BaseUI:registerOnFormFieldActionMatch( fieldNamePattern, callback)
Smc.registerOnFormFieldActionMatch(self.name, fieldNamePattern, callback)
end
---Shows the player the FormSpec registered by the instance of this UI.
---@param playerName string
function BaseUI:showForm(playerName, ...)
core.show_formspec(playerName, self.name, self:getFormSpecString(playerName, ...))
end
---Close the player the FormSpec registered by the instance of this UI.
---@param playerName string
function BaseUI:closeForm(playerName)
core.close_formspec(playerName, self.name)
end
return BaseUI return BaseUI

View File

@@ -5,6 +5,8 @@ local require = modInfo.require
---@type CraftSystem.BaseCraft ---@type CraftSystem.BaseCraft
local BaseCraft = require('CraftSystem.BaseCraft') local BaseCraft = require('CraftSystem.BaseCraft')
---@type CraftSystem.ImmersiveCraftCounter
local ImmersiveCraftCounter = require('CraftSystem.ImmersiveCraftCounter')
---Types of immersive stages. ---Types of immersive stages.
---@class CraftSystem.StagesTypes : table<CraftSystem.ImmersiveCraftStage.Type, CraftSystem.ImmersiveCraftStage> ---@class CraftSystem.StagesTypes : table<CraftSystem.ImmersiveCraftStage.Type, CraftSystem.ImmersiveCraftStage>
@@ -95,10 +97,44 @@ function ImmersiveCraft:new(name, def)
end end
---Initialize the start of the immersive crafting process. ---Initialize the start of the immersive crafting process.
---
---Returns `true` if the crafting process was running.
---@param pos MapPosition ---@param pos MapPosition
---@param Player Player ---@param player Player
function ImmersiveCraft:startCraft(pos, Player) ---@param amount integer
-- TODO: забирать из инвентаря игрока материалы для крафта ---@return boolean
function ImmersiveCraft:startCraft(pos, player, amount)
-- Adding craft to the counter.
-- If crafting has not been added...
if not ImmersiveCraftCounter:addCraft(pos, player) then
-- ...then we don't let the player start a new craft.
core.chat_send_player(player:get_player_name(),
'The limit of simultaneously active crafts has been reached:'..
'complete or cancel active crafts to start a new one')
return false
end
-- We get the material as an ItemStack.
---@type ItemStack
local stack = ItemStack(self.triggerItem)
-- We edit the amount of materials in accordance with the number of crafts being performed.
stack:set_count(stack:get_count() * amount)
-- We get the player's inventory, from where we must take the materials for crafting.
local playerInventory = player:get_inventory()
-- If the player does not have the necessary materials for crafting...
if not playerInventory:contains_item('main', stack) then
-- ...we inform him about this.
core.chat_send_player(player:get_player_name(),
'Not enough materials for crafting')
return false
end
-- If we have the materials, we take them and start initializing the craft.
playerInventory:remove_item('main', stack)
-- We get the first stage of crafting. -- We get the first stage of crafting.
local stage = self.stagesByName[self.startStageName] local stage = self.stagesByName[self.startStageName]
@@ -108,24 +144,94 @@ function ImmersiveCraft:startCraft(pos, Player)
local craftData = { local craftData = {
craftName = self.name, craftName = self.name,
stageName = stage.name, stageName = stage.name,
amount = amount,
} }
-- We save it to the workstation metadata. -- We save it to the workstation metadata.
Smc.setCraftDataByPos(pos, craftData) Smc.setCraftDataByPos(pos, craftData)
-- We are starting the first stage of crafting. -- We are starting the first stage of crafting.
stage:startHandler(pos, Player) stage:startHandler(pos, player)
return true
end end
---Complete the immersive crafting process. ---Complete the immersive crafting process.
---@param pos MapPosition ---@param pos MapPosition
---@param Player Player ---@param Player Player
function ImmersiveCraft:endCraft(pos, Player) function ImmersiveCraft:endCraft(pos, Player)
-- We get current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- We drop the result of crafting.
local dropPos = vector.new(pos) + vector.new(0, 0.9,0)
for i=1, craftData.amount do
core.item_drop(ItemStack(self.output), nil, dropPos)
end
-- Clearing the temporary data table for crafting, freeing up the work station for new crafts. -- Clearing the temporary data table for crafting, freeing up the work station for new crafts.
Smc.setCraftDataByPos(pos) Smc.setCraftDataByPos(pos)
-- We drop away the result of crafting. -- Remove craft from the counter.
-- TODO: переписать определение этого метода в хелпере: itemstack не может быть строкой, а dropper опционален ImmersiveCraftCounter:removeCraft(pos, Player)
core.item_drop(ItemStack(self.output), nil, vector.new(pos)+vector.new(0, 0.9,0)) end
---Stop the crafting process and free up the workbench.
---@param pos MapPosition
---@param Player Player
function ImmersiveCraft:abortCraft(pos, Player)
-- We get current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- We get the current stage and start the abort process.
local stage = self.stagesByName[craftData.stageName]
stage:abortHandler(pos, Player)
-- Clearing the temporary data table for crafting, freeing up the work station for new crafts.
Smc.setCraftDataByPos(pos)
-- Remove craft from the counter.
ImmersiveCraftCounter:removeCraft(pos, Player)
end
---Returns a human-readable description of the crafting process.
---@return string
function ImmersiveCraft:toString()
-- We get the material as an ItemStack.
---@type ItemStack
local stack = ItemStack(self.triggerItem)
-- We obtain a table of item parameters.
---@type ItemDefinition
local itemDef = stack:get_definition()
-- Let's start writing a description of the craft.
local craftDesc = ('Material: %s x%s\n\n'):format(itemDef._title, stack:get_count())..
'Crafting process:\n'
-- Let's start with the first crafting stage.
---@type string?
local stageName = self.startStageName
local stages = self.stagesByName
-- While we have a stage name...
local count = 1
while stageName ~= nil do
-- We get a crafting stage...
local stage = stages[stageName]
-- ...and we add its description to the list of actions for crafting.
craftDesc = craftDesc..tostring(count)..'. '..stage:toString()..'\n'
-- We also get the name of the next stage.
stageName = stage.nextStage
end
-- If the cycle is interrupted, it means we have processed all the stages.
-- Return the craft description.
return craftDesc
end end
return ImmersiveCraft return ImmersiveCraft

View File

@@ -0,0 +1,62 @@
local posToString, getSize = core.pos_to_string, table.get_size
local CRAFT_LIMIT_PER_PLAYER = 2
local CRAFT_LIMIT_PER_SERVER = 10
---Designed to keep track of active immersive
---crafts so as not to overload the server.
---
---The counter is individual for each player,
---but the total number of active crafts is also tracked.
---@class CraftSystem.ImmersiveCraftCounter
---@field craftsCountForPlayers table<string, table<string, boolean>>
---@field craftsCountForServer table<string, boolean>
local ImmersiveCraftCounter = {
craftsCountForPlayers = {},
craftsCountForServer = {}
}
---Add craft to the counter.
---
---Returns `false` if the counter is already full.
---@param pos MapPosition
---@param Player Player
---@return boolean
function ImmersiveCraftCounter:addCraft(pos, Player)
local playerName = Player:get_player_name()
if self.craftsCountForPlayers[playerName] == nil then
self.craftsCountForPlayers[playerName] = {}
end
if getSize(self.craftsCountForPlayers[playerName]) >= CRAFT_LIMIT_PER_PLAYER then
return false
end
if getSize(self.craftsCountForServer) >= CRAFT_LIMIT_PER_SERVER then
return false
end
local posString = posToString(pos)
self.craftsCountForPlayers[playerName][posString] = true
self.craftsCountForServer[posString] = true
return true
end
---Remove craft from the counter.
---@param pos MapPosition
---@param Player Player
function ImmersiveCraftCounter:removeCraft(pos, Player)
local playerCrafts = self.craftsCountForPlayers[Player:get_player_name()]
if playerCrafts == nil then
return
end
local posString = posToString(pos)
playerCrafts[posString] = nil
self.craftsCountForServer[posString] = nil
end
-- TODO: сделать сохранение данных во время перезагрузки сервера
return ImmersiveCraftCounter

View File

@@ -25,7 +25,7 @@ local tappingNode = ImmersiveCraftNode:new({
initial_properties = { initial_properties = {
visual = 'wielditem', visual = 'wielditem',
visual_size = {x=0.4, y=0.4, z=0.4}, visual_size = {x=0.4, y=0.4, z=0.4},
static_save = false, --static_save = false,
}, },
_item_name = '', _item_name = '',
@@ -58,11 +58,24 @@ local tappingNode = ImmersiveCraftNode:new({
on_punch = function(luaEntity, puncher, time_from_last_punch, tool_capabilities, dir, damage) on_punch = function(luaEntity, puncher, time_from_last_punch, tool_capabilities, dir, damage)
-- We simply trigger the event that the player hits the crafting node, bound to the work station with coordinates. -- We simply trigger the event that the player hits the crafting node, bound to the work station with coordinates.
Events.call(('craft_system:punch_tapping_node:%s:%s'):format( Events.call(('craft_system:punch_tapping_node:%s:%s'):format(
luaEntity._craft_name, luaEntity._stage_name), luaEntity._work_station_pos, puncher) luaEntity._craft_name, luaEntity._stage_name), luaEntity._work_station_pos, puncher, luaEntity)
return false return false
end, end,
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
get_staticdata = function(luaEntity)
---@type CraftSystem.ImmersiveCraftStage.TappingNode.InitParams?
local params = {
targetItem = luaEntity._item_name,
craftName = luaEntity._craft_name,
stageName = luaEntity._stage_name,
WorkStationPos = luaEntity._work_station_pos
}
return core.serialize(params)
end,
---Sets the entity display of the item. If the item stack was not transferred, `self._item_name` is used. ---Sets the entity display of the item. If the item stack was not transferred, `self._item_name` is used.
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode ---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
---@param itemName ItemStackString? ---@param itemName ItemStackString?

View File

@@ -10,8 +10,10 @@ local getInstance = Class.getInstance
---@field startHandler fun(self, pos:Position, Player:Player) ---@field startHandler fun(self, pos:Position, Player:Player)
---@field processHandler fun(self, pos:Position, Player:Player) ---@field processHandler fun(self, pos:Position, Player:Player)
---@field endHandler fun(self, pos:Position, Player:Player) ---@field endHandler fun(self, pos:Position, Player:Player)
---@field abortHandler fun(self, pos:Position, Player:Player)
---@field toString fun(self):string
---@field nextStage string? ---@field nextStage string?
---@field returnItems table? TODO: доделать тут тип ---@field returnItems ItemStackString[]?
local ImmersiveCraftStage = {} local ImmersiveCraftStage = {}
---Definition table for the `CraftSystem.ImmersiveCraft`. ---Definition table for the `CraftSystem.ImmersiveCraft`.
@@ -22,7 +24,7 @@ local ImmersiveCraftStage = {}
---@field type CraftSystem.ImmersiveCraftStage.Type ---@field type CraftSystem.ImmersiveCraftStage.Type
---@field craftName string? ---@field craftName string?
---@field nextStage string? ---@field nextStage string?
---@field returnItems table? TODO: доделать тут тип ---@field returnItems ItemStackString[]?
---@param def CraftSystem.ImmersiveCraftStageDef ---@param def CraftSystem.ImmersiveCraftStageDef
---@return CraftSystem.ImmersiveCraftStage ---@return CraftSystem.ImmersiveCraftStage

View File

@@ -14,6 +14,7 @@ local ImmersiveCraftStage = require('CraftSystem.ImmersiveCraftStage')
---@field startHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player) ---@field startHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field processHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player) ---@field processHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field endHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player) ---@field endHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field toString fun(self:CraftSystem.ImmersiveCraftStage.TappingStage):string
local TappingStage = extend(ImmersiveCraftStage, {}) local TappingStage = extend(ImmersiveCraftStage, {})
---Definition table for the `CraftSystem.ImmersiveCraftStage.TappingStage`. ---Definition table for the `CraftSystem.ImmersiveCraftStage.TappingStage`.
@@ -42,7 +43,7 @@ function TappingStage:new(def)
-- Registering the crafting stage start handler. -- Registering the crafting stage start handler.
instance.startHandler = function(tappingStage , pos, Player) instance.startHandler = function(tappingStage , pos, Player)
-- We determine the coordinate where we will create the crafting node (entity). -- We determine the coordinate where we will create the crafting node (entity).
local entityPos = vector.new(pos) + vector.new(0,0.9,0) local entityPos = vector.new(pos) + vector.new(0,0.8,0)
-- We create a table of initial parameters that we will pass to the entity. -- We create a table of initial parameters that we will pass to the entity.
---@class CraftSystem.ImmersiveCraftStage.TappingNode.InitParams ---@class CraftSystem.ImmersiveCraftStage.TappingNode.InitParams
@@ -70,7 +71,6 @@ function TappingStage:new(def)
-- Saving temporary data in work station metadata. -- Saving temporary data in work station metadata.
setStageDataByPos(pos, stageData) setStageDataByPos(pos, stageData)
print(pos, dump(Smc.getCraftDataByPos(pos)), 'ONE')
end end
-- Registering the crafting stage process handler. -- Registering the crafting stage process handler.
@@ -79,7 +79,6 @@ function TappingStage:new(def)
-- Obtaining stage time data from work station metadata. -- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData? ---@type ImmersiveStageData.TappingStageData?
local stageData = getStageDataByPos(pos) local stageData = getStageDataByPos(pos)
print(dump(pos), dump(Smc.getCraftDataByPos(pos)), 'TWO')
assert(stageData ~= nil, 'Immersive stage data is empty.') assert(stageData ~= nil, 'Immersive stage data is empty.')
-- Increasing the click counter -- Increasing the click counter
@@ -115,9 +114,64 @@ function TappingStage:new(def)
Events.call('craft_system:next_immersive_stage:'..tappingStage.craftName, tappingStage, pos, Player) Events.call('craft_system:next_immersive_stage:'..tappingStage.craftName, tappingStage, pos, Player)
end end
-- Registering the aborting the crafting process handler.
---@param tappingStage CraftSystem.ImmersiveCraftStage.TappingStage
instance.abortHandler = function(tappingStage, pos, Player)
-- We receive current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData?
local stageData = craftData.stageData
assert(stageData ~= nil, 'Immersive stage data is empty.')
-- We get the entity object.
local entity = Smc.getObjectByGUID(stageData.entityGUID)
assert(entity ~= nil, 'The entity for immersive crafting is nil.')
-- Removing an entity from the world.
entity:remove()
-- We drop the item as it was before processing.
local dropPos = vector.new(pos)+vector.new(0, 0.9,0)
for i=1, craftData.amount do
core.item_drop(ItemStack(tappingStage.targetItem), nil, dropPos)
end
end
-- Returns a human-readable description of the crafting stage.
instance.toString = function(tappingStage)
local stageDesc = ('Tapping x%s'):format(tappingStage.clicksNeed)
return stageDesc
end
-- Subscribe to an event that means the player hit the entity. -- Subscribe to an event that means the player hit the entity.
Events.subscribe(('craft_system:punch_tapping_node:%s:%s'):format(instance.craftName, instance.name), Events.subscribe(('craft_system:punch_tapping_node:%s:%s'):format(instance.craftName, instance.name),
function(eventName, pos, Player) ---@param craftNode LuaEntity
function(eventName, pos, Player, craftNode)
-- DRAFT START:
-- Creating particles
for i=0, 10 do
core.add_particle({
pos = vector.new(pos)+vector.new(0,0.5,0),
velocity = {x=math.random(-1,1), y=4, z=math.random(-1,1)},
acceleration = {x=0, y=-9.8, z=0},
expirationtime = 2,
collision_removal = true,
node = {name=instance.targetItem}
})
end
-- Making the entity shake (silly method :P).
craftNode.object:set_rotation(vector.new(0.01,0.1,0.01))
core.after(0.1, function() craftNode.object:set_rotation(vector.new(-0.01,-0.1,-0.01))end)
core.after(0.2, function() craftNode.object:set_rotation(vector.new(0,0,0))end)
-- DRAFT END
-- Calling the crafting stage process handler.
instance:processHandler(pos, Player) instance:processHandler(pos, Player)
end) end)

View File

@@ -7,18 +7,18 @@ local require = modInfo.require
local BaseCraft = require('CraftSystem.BaseCraft') local BaseCraft = require('CraftSystem.BaseCraft')
---@class CraftSystem.PrimitiveCraft : CraftSystem.BaseCraft ---@class CraftSystem.PrimitiveCraft : CraftSystem.BaseCraft
---@field output string ---@field output string
---@field recipe CraftSystem.CraftRecipe ---@field recipe CraftSystem.CraftRecipe
---@field returnItems table? TODO: доделать тут тип ---@field returnItems ItemStackString[]
local PrimitiveCraft = extend(BaseCraft, {}) local PrimitiveCraft = extend(BaseCraft, {})
---Definition table for the `CraftSystem.PrimitiveCraft`. ---Definition table for the `CraftSystem.PrimitiveCraft`.
--- ---
---**Only for EmmyLua.** ---**Only for EmmyLua.**
---@class CraftSystem.PrimitiveCraftDef : CraftSystem.BaseCraftDef ---@class CraftSystem.PrimitiveCraftDef : CraftSystem.BaseCraftDef
---@field output string ---@field output string
---@field recipe CraftSystem.CraftRecipe ---@field recipe CraftSystem.CraftRecipe
---@field returnItems table? TODO: доделать тут тип ---@field returnItems ItemStackString[]
---@param name string ---@param name string
---@param def CraftSystem.PrimitiveCraftDef ---@param def CraftSystem.PrimitiveCraftDef

View File

@@ -103,17 +103,19 @@ local function itemDefToLuantiDef(itemDef)
end end
if s._title_color ~= nil and s._description_color ~= nil then if s._title_color ~= nil and s._description_color ~= nil then
description = colorize(s._title_color ,S(title))..'\n'.. title = colorize(s._title_color ,S(title))
colorize(s._description_color, S(description)) description = colorize(s._description_color, S(description))
else else
error('Item description color parameters cannot be empty.') error('Item description color parameters cannot be empty.')
end end
assert(s._rarity ~= nil, 'The rarity of an item cannot be empty.') assert(s._rarity ~= nil, 'The rarity of an item cannot be empty.')
description = addRarityToDesc(s._rarity, description) local luantiDescription = addRarityToDesc(s._rarity, title..'\n'..description)
s.description = description..core.get_background_escape_sequence('#110F13') s._title = title
s._description = description
s.description = luantiDescription..core.get_background_escape_sequence('#110F13')
local luantiDef = defMerge(s, c) local luantiDef = defMerge(s, c)

View File

@@ -9,15 +9,18 @@ local WorkStationUI = Mod.getInfo('smc__ui__work_station').require('WorkStationU
---@type Node ---@type Node
local Node = Mod.getInfo('smc__core__node').require('Node') local Node = Mod.getInfo('smc__core__node').require('Node')
-- Default settings that a work station node should have.
local WorkStationNode = Node:getExtended({ local WorkStationNode = Node:getExtended({
settings = { settings = {
name = 'work_station', name = 'work_station',
drawtype = 'normal', drawtype = 'normal',
paramtype = 'light', paramtype = 'light',
groups = {work_station = 1} groups = {work_station = 1, dig_immediate = 2,}
} }
}) })
---A work station (node) that enables player interaction
---with the immersive crafting mechanics.
---@class WorkStation ---@class WorkStation
---@field name string ---@field name string
---@field group CraftSystem.CraftGroup ---@field group CraftSystem.CraftGroup
@@ -36,53 +39,135 @@ local WorkStation = {}
function WorkStation:new(name, def) function WorkStation:new(name, def)
local nodeDef = def.nodeDef local nodeDef = def.nodeDef
if nodeDef.callbacks == nil then if nodeDef.callbacks == nil then
---@type Node.Callbacks
nodeDef.callbacks = {} nodeDef.callbacks = {}
end end
local settings = nodeDef.settings local settings = nodeDef.settings
local callbacks = nodeDef.callbacks local callbacks = nodeDef.callbacks
-- Callback when the work station block is installed in the world
-- Ensures initialization of necessary parameters
callbacks.on_construct = function(pos) callbacks.on_construct = function(pos)
-- Getting node metadata
local meta = core.get_meta(pos) local meta = core.get_meta(pos)
--meta:set_string('work_station_name', name) -- Initializing the table of temporary parameters for crafting.
--meta:set_string('craft_group', def.group) Smc.setCraftDataByMeta(meta)
end end
-- Callback for interaction with a work station (start of crafting)
callbacks.on_rightclick = function(pos, node, clicker, itemstack, pointed_thing) callbacks.on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
Logger.warningLog('Punch') -- If the workstation is occupied by another craft...
local crafts = ImmersiveCraftHandler:getCraftsByTriggerItem(itemstack:get_name()) if not Smc.workStationIsFree(pos) then
-- ...we inform the player about this...
if crafts == nil then core.chat_send_player(clicker:get_player_name(), 'The workbench is occupied by another craft.')
-- ...and do nothing.
return return
end end
self:showSelectionCraftForm(clicker, crafts) -- We get a list of crafts that can be produced using the item that the player was holding in his hand.
local crafts = ImmersiveCraftHandler:getCraftsByTriggerItem(itemstack:get_name())
-- If the list is empty...
if crafts == nil then
-- ..this means there are no crafts for this item,
-- so we don't do anything.
return
else
-- ...else we show the player the formspec for choosing a craft.
self:showSelectionCraftForm(clicker, crafts, pos)
end
end end
local instance = getInstance(self, { callbacks.on_dig = function(pos, node, digger)
name = name, if Smc.workStationIsFree(pos) then
group = def.group, return core.node_dig(pos, node, digger)
nodeDef = nodeDef else
}) return false
print('NODEDEF: ',dump(nodeDef.callbacks)) end
end
---@type WorkStation
local instance = getInstance(self, {})
instance.name = name
instance.group = def.group
instance.nodeDef = nodeDef
-- Registering a node for Luanti.
WorkStationNode:new(nodeDef) WorkStationNode:new(nodeDef)
return instance return instance
end end
---@param player Player ---Show the player the initial workstation interface for choosing a craft.
---@param crafts CraftSystem.ImmersiveCraft[] ---@param player Player
function WorkStation:showSelectionCraftForm(player, crafts) ---@param crafts CraftSystem.ImmersiveCraft[]
---@param pos Position
function WorkStation:showSelectionCraftForm(player, crafts, pos)
-- Create a table in the format craft result - craft name.
local outputs = {} local outputs = {}
for _, craft in ipairs(crafts) do
for i, craft in ipairs(crafts) do outputs[craft.output] = craft.name
outputs[i] = craft.output
end end
core.show_formspec(player:get_player_name(), 'work_station:selection_craft', WorkStationUI:selectionCraftForm(outputs)) -- We get the name of the player who wants to start crafting.
local playerName = player:get_player_name()
-- We set the context for transferring data about the workstation coordinates and the list of crafts.
WorkStationUI:setContex(playerName, 'pos', pos)
WorkStationUI:setContex(playerName, 'outputs', outputs)
-- Showing the desktop interface to the player.
WorkStationUI:showForm(playerName,false)
end end
-- Registering a callback for player choice of craft (this does not start crafting).
WorkStationUI:registerOnFormFieldActionMatch('%S+::item_button',function(player, fieldName, fieldValue)
-- We get the name of the craft from the name of the button the player pressed.
local craftName = string.match(fieldName, '(%S+)::item_button')
assert(craftName ~= nil, 'Craft name cannot be empty')
-- We get a craft object.
local craft = ImmersiveCraftHandler:getCraftByName(craftName)
-- We get the name of the player who wants to start crafting.
local playerName = player:get_player_name()
-- We enter into the context the craft that the player has chosen.
WorkStationUI:setContex(playerName, 'craft', craft)
-- We show the player a new interface with a crafting description tab.
WorkStationUI:showForm(playerName, true)
end)
-- We register a callback when the player starts crafting.
WorkStationUI:registerOnFormFieldAction('work_station:start_craft', function(player, fieldName, fieldValue)
-- We get the name of the player who wants to start crafting.
local playerName = player:get_player_name()
-- We get the workstation position and craft from the context.
local pos = WorkStationUI:getContex(playerName, 'pos')
---@type CraftSystem.ImmersiveCraft
local craft = WorkStationUI:getContex(playerName, 'craft')
-- We process the amount of crafting.
local isCraftStart = false
if fieldValue == 'x1' then
-- Single craft
isCraftStart = craft:startCraft(pos, player, 1)
elseif fieldValue == 'x10' then
-- Ten crafts at a time.
isCraftStart = craft:startCraft(pos, player, 10)
end
-- If the craft was started...
if isCraftStart then
-- ...we are closing the formspec.
WorkStationUI:closeForm(playerName)
end
end)
-- --- DEBUG ---
WorkStation:new('test_station', { WorkStation:new('test_station', {
group = 'test', group = 'test',
nodeDef = { nodeDef = {
@@ -93,20 +178,52 @@ WorkStation:new('test_station', {
} }
}) })
ImmersiveCraftHandler:addCraft('bricks', { ImmersiveCraftHandler:registerCraft('bricks', {
triggerItem = 'rocks:sylite', triggerItem = 'rocks:sylite',
output = 'rocks:sylite_bricks', output = 'rocks:sylite_bricks',
startStageName = 'ab', startStageName = 'tapping',
group = 'test', group = 'test',
stages = {}, stages = {
---@type CraftSystem.ImmersiveCraftStage.TappingStageDef
{
name = 'tapping',
targetItem = 'rocks:sylite',
type = 'tapping',
clicksNeed = 3,
}
},
}) })
ImmersiveCraftHandler:addCraft('block', { ImmersiveCraftHandler:registerCraft('block', {
triggerItem = 'rocks:sylite', triggerItem = 'rocks:sylite',
output = 'rocks:sylite_block', output = 'rocks:sylite_block',
startStageName = 'ab', startStageName = 'tapping',
group = 'test', group = 'test',
stages = {}, stages = {
---@type CraftSystem.ImmersiveCraftStage.TappingStageDef
{
name = 'tapping',
targetItem = 'rocks:sylite',
type = 'tapping',
clicksNeed = 5,
}
},
})
ImmersiveCraftHandler:registerCraft('marentine_planks', {
triggerItem = 'wood:marentine_log',
output = 'wood:marentine_planks',
startStageName = 'tapping',
group = 'test',
stages = {
---@type CraftSystem.ImmersiveCraftStage.TappingStageDef
{
name = 'tapping',
targetItem = 'wood:marentine_log',
type = 'tapping',
clicksNeed = 5,
}
},
}) })
return WorkStation return WorkStation

View File

@@ -7,8 +7,7 @@ local Node = Mod.getInfo('smc__core__node').require('Node')
---@type Node.NodeDefinition ---@type Node.NodeDefinition
local defaultRockDef = { local defaultRockDef = {
settings = { settings = {
name = "", name = '',
_description = "A rocks",
tiles = {}, tiles = {},
groups = { groups = {
dig_immediate = 2, dig_immediate = 2,

View File

@@ -0,0 +1,6 @@
# textdomain: rocks
sylite_block-title=Силитовый блок
sylite_block-desc=Массивный блок из цельного куска силита.
sylite_bricks-title=Силитовые кирпичи
sylite_bricks-desc=Кладка из силитовых кирпичей.

View File

@@ -6,4 +6,5 @@ local require = modInfo.require
require('Lib.globalStep') require('Lib.globalStep')
require('Lib.color') require('Lib.color')
require('Lib.immersiveCraftData') require('Lib.immersiveCraftData')
require('Lib.getObjectByGUID') require('Lib.getObjectByGUID')
require('Lib.receiveFields')

View File

@@ -3,8 +3,9 @@ local EMPTY_FLAG = 'EMPTY_FLAG'
---@class ImmersiveStageData ---@class ImmersiveStageData
---@class ImmersiveCraftData ---@class ImmersiveCraftData
---@field craftName string, ---@field craftName string
---@field stageName string, ---@field stageName string
---@field amount integer
---@field stageData ImmersiveStageData? ---@field stageData ImmersiveStageData?
---Returns craft data for immersive crafting, which is stored in the desktop metadata. ---Returns craft data for immersive crafting, which is stored in the desktop metadata.

View File

@@ -0,0 +1,67 @@
---Register a callback for a specific player action in FormSpec.
---
---The callback is guaranteed to be called only for the specified form and the specified field.
---@param formName string the name of the formspec for which the callback will be called.
---@param fieldName string the name of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called.
--- * `fieldValue` - the field value that is passed in the `fields` table.
function Smc.registerOnFormFieldAction(formName, fieldName, callback)
core.register_on_player_receive_fields(function(player, formname, fields)
-- If the form name does not match the given...
if formName ~= formname then
-- ...we do nothing.
return
end
local fieldValue = fields[fieldName]
-- If the field value is not nil (the player called this field)...
if fieldValue ~= nil then
-- ...calling a callback.
callback(player, fieldName, fieldValue)
end
end)
end
---Register a callback function to close the FormSpec.
---
---The callback is guaranteed to be called only for the specified form.
---@param formName string the name of the form that is being closed.
---@param callback fun(player:Player) Callback to handle the close. Parameters:
--- * `player` - the player who closed the form.
function Smc.registerOnFormQuit(formName, callback)
Smc.registerOnFormFieldAction(formName, 'quit', callback)
end
---Register a callback for a specific player action in FormSpec.
---
---The callback function is guaranteed to be called only for the specified form and
---for the field whose name matches the pattern.
---@param formName string the name of the formspec for which the callback will be called.
---@param fieldNamePattern string the name pattern of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called (will match the pattern).
--- * `fieldValue` - the field value that is passed in the `fields` table.
function Smc.registerOnFormFieldActionMatch(formName, fieldNamePattern, callback)
core.register_on_player_receive_fields(function(player, formname, fields)
-- If the form name does not match the given...
if formName ~= formname then
-- ...we do nothing.
return
end
-- We go through each field in the list of fields.
for fieldName, fieldValue in pairs(fields) do
-- We check the field name pattern compliance.
local capturedName = string.match(fieldName, fieldNamePattern)
-- If the captured name is not nil...
if capturedName ~= nil then
-- ...calling a callback.
callback(player, fieldName, fieldValue)
end
end
end)
end

View File

@@ -4,23 +4,28 @@ local require = modInfo.require
---@type Formspec ---@type Formspec
local Formspec = require('Formspec') local Formspec = require('Formspec')
---@class WorkStationUI ---@type BaseUI
local WorkStationUI = {} local BaseUI = Mod.getInfo('smc__core__base_ui').require('BaseUI')
---@param self BaseUI
---@param playerName string
---@param isSelect boolean
---@return string
local function getFormSpecString(self, playerName, isSelect)
local outputs = self:getContex(playerName, 'outputs')
---@type CraftSystem.ImmersiveCraft
local craft = self:getContex(playerName, 'craft')
---@param items string[]
---@return string
function WorkStationUI:selectionCraftForm(items)
local listForm = Formspec:new({ local listForm = Formspec:new({
size = {x=10, y=8}, size = {x=16, y=8},
}) })
local listFormItems = Formspec:new() local listFormItems = Formspec:new()
table.sort(items) table.sort(outputs)
local w, h = 0, 0 local w, h = 0, 0
---@param name string for result, craftName in pairs(outputs) do
for _, name in ipairs(items) do listFormItems:itemImageButton(w, h, 2, 2, result, craftName..'::item_button')
listFormItems:itemImageButton(w, h, 2, 2, name, name..'::item_button')
w = w + 2 w = w + 2
@@ -34,7 +39,26 @@ function WorkStationUI:selectionCraftForm(items)
scrollContainer(listFormItems, 0.5, 0.5, 8, 6, 'work_station:list_items', 'vertical'): scrollContainer(listFormItems, 0.5, 0.5, 8, 6, 'work_station:list_items', 'vertical'):
scrollbar(8, 0.5, 0.25, 7, 'vertical', 'work_station:list_items') scrollbar(8, 0.5, 0.25, 7, 'vertical', 'work_station:list_items')
if isSelect then
local stage = craft.stagesByName[craft.startStageName]
local outputDef = core.registered_nodes[craft.output]
listForm:
itemImage(9, 0.5, 2, 2, craft.output):
areaLabel(9, 6, 2, 1, 'Start crafting:'):
button(9, 6.5, 3, 1, 'work_station:start_craft', 'x1'):
button(12, 6.5,3, 1, 'work_station:start_craft', 'x10'):
areaLabel(11.5, 0.5, 4, 4,
outputDef._title..'\n'..
outputDef._description):
areaLabel(9, 2.5, 6, 4, 'Craft description:'..'\n'..craft:toString())
end
return listForm:toString() return listForm:toString()
end end
return WorkStationUI ---@class WorkStationUI : BaseUI
---@field getFormSpecString fun(self:BaseUI,playerName:string,isSelect:boolean):string
---@field showForm fun(self:BaseUI,playerName:string,isSelect:boolean):string
local WorkStationUI = BaseUI:new('work_station:selection_craft', getFormSpecString)
return WorkStationUI