Files
LonaRPG-Online-Games/ModScripts/_Mods/LonaCraft/Scripts/55_Recipes.rb
T
2026-10-29 21:59:06 +04:00

1299 lines
45 KiB
Ruby

#==============================================================================
# LonaCraft - 55_Recipes.rb
# What it does:
# * One recipe list for the crafting screen (every station, the hand list of
# the main menu included).
# * Gear recipes are derived from each craftable base item's pot tags
# (Tiers::CRAFTABLE), so no hand-written list is needed:
# Wood w -> ceil(w/2) Plank (min 1)
# Metal m -> ceil(m/3) Iron Ingot (min 1)
# Cloth c -> ceil(c/2) Cloth Bolt (min 1)
# Leather l -> ceil(l/2) Leather (min 1)
# + 1 Nails if Wood and Metal, + 1 Rope if Cloth and Leather
# + Rope for a bow (a weapon whose item_name or display name says Bow,
# not Crossbow or Bowie Knife): 1 Rope, 2 when its Wood tag is 6 or
# more (BOW_ROPE, BOW_BIG_WOOD; `"rules": {"bow_rope": n}` in
# Config/Recipes.json changes n, 0 = off)
# then, if the inputs' value (count x material base price) is below
# price / 4, more of the material of the largest tag (Metal -> Iron
# Ingot, Wood -> Plank, Cloth -> Cloth Bolt, Leather -> Leather) is
# added until it is not, never above 12 of any one input
# skill requirement = round(sqrt(price / 50)), 0..20
# Overrides (below) are taken as written, no padding.
# * Recipes/*.json overrides replace the derived recipe for their output:
# {"output":"ItemX","inputs":{"ItemLonaCraftPlank":2},"skill_req":3}
# (one object or an array of them per file; "skill_req" optional;
# optional "category": "furniture" / "decoration" / "ammo" / "building",
# "fixed_tier": 1..5, "amount" (outputs per craft, default 1),
# "max_tier" (1..5, best tier it can give), "requires": ["ModId"]
# (skipped without a console line unless those mods are loaded) and
# "id" (default the output; a second recipe for the same output needs its
# own id, e.g. "hand:ItemX"). Recipes/Furniture_*.json are the furniture
# recipes of Scripts/90_Furniture.rb, Recipes/Arrows_*.json RolePlayS's
# arrows.
# Furniture recipes craft like gear (1 STA per input, gear exp) but are
# always made at their fixed tier. Ammo crafts like gear (1 STA per input,
# never a tier) but gives the processing exp.
# * The Process recipes (30_Process.rb PROCESS_RECIPES) are in the same list
# with fixed_tier 1 and category :process (id "process:<Key>").
# * Config/Recipes.json (RecipeConfig below) is merged on top, field by
# field, per recipe id; Config/Recipes_defaults.json is written at boot
# (only when it changed) with every recipe before that merge.
# Precedence: Config/Recipes.json > Recipes/*.json > derived / PROCESS.
# * craft: takes the inputs from the inventory (equipped items never count),
# costs stamina, rolls the tier with Skill.roll_tier, gives the variant,
# grants crafting exp (60_Skill.rb).
# * Stations: every recipe has a list of stations it can be made at
# (Recipe#stations, symbols of Stations::LIST). Rules (Stations below):
# process - Stations::PROCESS by text key (planks and fibre rope are
# by hand AND at their home station)
# gear - by the base item's dominant tag (largest of Wood / Metal /
# Cloth / Leather, ties Metal > Wood > Cloth > Leather):
# Wood -> carpentry, Metal -> anvil, Cloth/Leather -> tailor;
# no tag -> carpentry
# furniture and decoration - carpentry (the Carpentry Bench recipe
# file adds "hand", so the first bench can be built)
# A JSON override may set "station": "anvil" or ["hand", "carpentry"].
# :hand is the main menu's crafting (by hand); only recipes that name it
# are listed there, and it never gives more than Common
# (MAX_TIER, applied to the roll and to the shown chances). The old
# "pot" station is read as "hand" (ALIASES); the dark pot itself only
# cooks (20_Station.rb).
# * Station cost (owner 2026-10-06): a station may multiply the inputs of
# every recipe made there (Stations::COST, "stations": {"<id>": {"cost": x}}
# in Config/Recipes.json; by hand 1.25, every other station 1.0). Effective
# input = ceil(count x cost), "*plant" included. Recipes.inputs_at(recipe,
# station) is the one place that works it out; affordability, the missing
# list, the craft's deduction, the crafting screen and the defaults file
# all use it. Processing recipes with amount > 1 are scaled too: by hand
# 1 Wooden Club (2 Plank) becomes 2 Wooden Clubs for the 2 Planks. The
# stamina cost still counts the recipe's own inputs. Building a base piece
# on the spot (110_Bases.rb) pays the bench amounts.
#==============================================================================
module LonaCraft
#--------------------------------------------------------------------------
# Crafting stations
#--------------------------------------------------------------------------
module Stations
# every station, in display order
LIST = [:hand, :carpentry, :furnace, :anvil, :tailor]
# old names still accepted in recipe files and Config/Recipes.json
ALIASES = {:pot => :hand}
# best tier a station can give (nil = no cap); Config/Recipes.json
# "stations": {"<id>": {"max_tier": n}} changes it
MAX_TIER = {:hand => 1}
# input cost multiplier per station (1.0 when not listed); Config/Recipes.json
# "stations": {"<id>": {"cost": x}} changes it. By hand costs a little more.
COST = {:hand => 1.25}
# PROCESS_RECIPES text key (30_Process.rb) => stations
PROCESS = {
"Plank" => [:hand, :carpentry], # club -> planks (bootstrap by hand)
"CutStone" => [:carpentry], # masonry
"Smelt" => [:furnace],
"Glass" => [:furnace],
"Nails" => [:anvil],
"ClothFibre" => [:tailor],
"RopeFibre" => [:hand, :tailor], # fibre -> rope (bootstrap by hand)
"RopeCloth" => [:tailor],
"Leather" => [:tailor]
}
PROCESS_DEFAULT = [:carpentry]
# dominant tag => station; TAG_ORDER breaks ties (earlier wins)
TAG_ORDER = ["Metal", "Wood", "Cloth", "Leather"]
TAG_STATION = {"Metal" => :anvil, "Wood" => :carpentry, "Cloth" => :tailor, "Leather" => :tailor}
NO_TAG_STATION = :carpentry
FURNITURE_STATION = :carpentry
@max_tier = MAX_TIER.dup
@cost = COST.dup
def self.valid?(station)
LIST.include?(station)
end
# "Hand" / :hand / "pot" => :hand; nil when it is no station
def self.normalize(value)
return nil if value.nil?
sym = value.to_s.strip.downcase.to_sym
sym = ALIASES[sym] || sym
valid?(sym) ? sym : nil
end
# "anvil" / :anvil / ["pot", "carpentry"] => [:anvil] / [:hand, :carpentry]; nil if none valid
def self.parse(value)
list = value.is_a?(Array) ? value : [value]
out = []
list.each{|v|
sym = normalize(v)
out << sym if sym && !out.include?(sym)
}
out.empty? ? nil : out
end
# best tier +station+ can give, nil = no cap
def self.max_tier(station)
@max_tier[normalize(station)]
end
def self.set_max_tier(station, tier)
sym = normalize(station)
@max_tier[sym] = tier if sym
end
# back to MAX_TIER (before Config/Recipes.json is applied)
def self.reset_max_tier
@max_tier = MAX_TIER.dup
end
# input multiplier of +station+ (default COST, else 1.0); nil station = 1.0
def self.cost(station)
sym = normalize(station)
sym ? (@cost[sym] || 1.0).to_f : 1.0
end
def self.set_cost(station, value)
sym = normalize(station)
return unless sym
@cost[sym] = value.nil? ? nil : value.to_f
end
# back to COST (before Config/Recipes.json is applied)
def self.reset_cost
@cost = COST.dup
end
def self.for_process(key)
(PROCESS[key.to_s] || PROCESS_DEFAULT).dup
end
# "Metal", "Wood", "Cloth", "Leather" or nil, from the item's pot tags
def self.dominant_tag(item)
item = $data_ItemName[item.to_s] if item.is_a?(String)
return nil if item.nil? || !item.respond_to?(:pot_data)
pot = item.pot_data
return nil unless pot.is_a?(Hash)
best = nil
TAG_ORDER.each{|tag|
v = pot[tag].to_f
next if v <= 0
best = tag if best.nil? || v > pot[best].to_f
}
best
end
def self.for_item(item)
tag = dominant_tag(item)
tag ? TAG_STATION[tag] : NO_TAG_STATION
end
def self.text(station)
$game_text["LonaCraft:Craft:Station/#{station}"].to_s
end
end
module Recipes
# output : base item_name (gear) or material item_name (process)
# inputs : {item_name => count}; LonaCraft::FIBRE = any plant/herb
# skill_req : 0..20
# fixed_tier : nil (rolled) or 1..5 (always that tier)
# category : :gear, :furniture, :decoration, :ammo, :building (base pieces, 110_Bases.rb) or :process
# amount : how many are made
# key : process text key under LonaCraft:Station:Process/ (nil for gear)
# stations : [station symbol, ...] where it can be made (Stations above);
# nil until build fills it in
# id : the recipe's name in Config/Recipes.json: the output's
# item_name, "process:<key>", or a recipe file's own "id";
# nil until build fills it in
# max_tier : nil or 1..5, best tier this recipe can give
# requires : nil or [mod id, ...] it was loaded for (shown in the defaults file)
Recipe = Struct.new(:output, :inputs, :skill_req, :fixed_tier, :category, :amount, :key, :stations, :id, :max_tier, :requires)
MAX_SKILL_REQ = 20
SKILL_PRICE_DIV = 50 # skill_req = round(sqrt(price / 50)), 0..20
MIN_VALUE_SHARE = 0.25 # derived inputs must be worth >= price / 4 (material base prices)
MAX_INPUT = 12 # no single derived input above 12
# Largest tag first decides which material pads a recipe up to MIN_VALUE_SHARE
# (ties: the earlier row wins).
TAG_MATERIAL = [["Metal", "IronIngot"], ["Wood", "Plank"], ["Cloth", "ClothBolt"], ["Leather", "Leather"]]
GEAR_STA_PER_INPUT = 1 # like the dark pot: 1 STA per item used
OVERRIDE_DIR = "Recipes"
# "category" values an override may give (anything else is :gear)
OVERRIDE_CATEGORIES = {"gear" => :gear, "furniture" => :furniture, "decoration" => :decoration, "ammo" => :ammo, "building" => :building}
MAX_TIER = 5
# Bow rule (owner 2026-10-06): a derived bow recipe also takes Rope
BOW_ROPE = 1 # Rope for a bow; Config/Recipes.json "rules": {"bow_rope": n}
BOW_BIG_WOOD = 6 # a bow with this Wood tag or more takes twice that
@list = []
@last_fibre_used = []
@process_keys = []
#----------------------------------------------------------------------
# Build (called from LonaCraft.load_database after Tiers.generate_variants)
#----------------------------------------------------------------------
# Also the debug reload (95_Debug.rb): recipes are not saved, so
# building again at any time is safe.
def self.build
list = []
# the user file is read once; its "rules" shape the derived recipes below
LonaCraft::RecipeConfig.load_user
begin
overrides = load_overrides # keyed by recipe id
LonaCraft::Tiers::CRAFTABLE.each{|base_name|
recipe = overrides.delete(base_name) || derive(base_name)
list << recipe if recipe
}
overrides.each_value{|recipe| list << recipe } # outputs that are not craftable bases, extra recipes
list.concat(process_recipes_from_table)
list.each{|recipe|
recipe.stations ||= default_stations(recipe)
recipe.id ||= default_id(recipe)
}
rescue => e
p "LonaCraft Recipes build error #{e.message}"
msgbox("#{LonaCraft::TextFallback.get("Info", "Err/build_recipes", "LonaCraft failed to build its recipes.")}\n#{e.message}\n#{e.backtrace.join("\n")}")
end
list = sort_list(list)
@process_keys = list.select{|r| r.category == :process && r.key }.map{|r| r.key.to_s }
# the defaults file shows every recipe before the user config
LonaCraft::RecipeConfig.write_defaults(list)
LonaCraft::Stations.reset_max_tier
LonaCraft::Stations.reset_cost
begin
list = sort_list(LonaCraft::RecipeConfig.apply(list))
rescue => e
p "LonaCraft Config: #{e.class} #{e.message}, Config/Recipes.json not applied"
end
@list = list
p "LonaCraft Recipes: #{@list.length} recipes"
@list
end
#----------------------------------------------------------------------
# Rules (Config/Recipes.json "rules")
#----------------------------------------------------------------------
def self.bow_rope
@bow_rope.nil? ? BOW_ROPE : @bow_rope
end
def self.set_bow_rope(value)
@bow_rope = value.to_i
end
def self.reset_rules
@bow_rope = nil
end
# true for a bow weapon: its item_name or display name says Bow
# ("Long Bow", Item2MhBowJaeger, LongBow); Crossbows and "Bowie Knife" do not count
def self.bow?(item)
return false unless item.is_a?(RPG::Weapon)
names = [item.item_name.to_s]
names << LonaCraft::RecipeConfig.item_text(item).to_s
names.any?{|name| bow_name?(name) }
end
def self.bow_name?(name)
return false if name =~ /cross\s*bow/i
return true if name =~ /\bbow\b/i
return true if name =~ /(long|short)bow\b/i
name =~ /Bow(?![a-z])/ ? true : false
end
# Rope a derived recipe of +item+ (Wood tag +wood+) takes for the bow rule
def self.bow_rope_for(item, wood)
n = bow_rope
return 0 if n < 1 || !bow?(item)
wood.to_f >= BOW_BIG_WOOD ? n * 2 : n
end
def self.sort_list(list)
list.sort_by{|r| [r.skill_req.to_i, r.category == :process ? 0 : 1, r.output.to_s, r.id.to_s] }
end
def self.default_id(recipe)
recipe.key ? "process:#{recipe.key}" : recipe.output.to_s
end
# true when PROCESS_RECIPES row +key+ was built into the list (the
# crafting screen then leaves it to this list, config changes included)
def self.process_key_known?(key)
(@process_keys || []).include?(key.to_s)
end
# true when every mod id in +value+ (a string or a list) is enabled
def self.requires_met?(value)
requires_list(value).all?{|id| mod_loaded?(id) }
end
def self.requires_list(value)
return [] if value.nil?
list = value.is_a?(Array) ? value : [value]
list.map{|id| id.to_s.strip }.reject{|id| id.empty? }
end
def self.mod_loaded?(id)
return false if $mod_manager.nil? || !$mod_manager.respond_to?(:mods) || $mod_manager.mods.nil?
mod = $mod_manager.mods[id.to_s]
return false if mod.nil?
mod.respond_to?(:enabled) ? (mod.enabled ? true : false) : true
end
def self.mat(id)
LonaCraft::MATERIAL[id]
end
def self.units(value, per)
n = (value.to_f / per).ceil
n < 1 ? 1 : n
end
def self.skill_req_for(item)
price = item.price.to_f
price = 0.0 if price < 0
clamp_req(Math.sqrt(price / SKILL_PRICE_DIV).round)
end
# Sum of count x base price of the inputs (the "any plant" input counts 0)
def self.material_value(inputs)
total = 0.0
inputs.each{|name, qty|
obj = $data_ItemName[name]
next if obj.nil?
total += qty.to_i * obj.price.to_f
}
total
end
# Add +name+ one at a time until the inputs are worth +target+ or it hits MAX_INPUT.
def self.pad_to_value(inputs, name, target)
obj = $data_ItemName[name]
return if obj.nil? || obj.price.to_f <= 0
guard = 0
while material_value(inputs) < target && inputs[name].to_i < MAX_INPUT && (guard += 1) <= MAX_INPUT
inputs[name] = inputs[name].to_i + 1
end
end
def self.clamp_req(value)
v = value.to_i
v = 0 if v < 0
v = MAX_SKILL_REQ if v > MAX_SKILL_REQ
v
end
def self.derive(base_name)
item = $data_ItemName[base_name]
return nil if item.nil? || !item.pot_data.is_a?(Hash)
pot = item.pot_data
wood = pot["Wood"].to_f
metal = pot["Metal"].to_f
cloth = pot["Cloth"].to_f
leather = pot["Leather"].to_f
inputs = {}
inputs[mat("Plank")] = units(wood, 2) if wood > 0
inputs[mat("IronIngot")] = units(metal, 3) if metal > 0
inputs[mat("ClothBolt")] = units(cloth, 2) if cloth > 0
inputs[mat("Leather")] = units(leather, 2) if leather > 0
inputs[mat("Nails")] = 1 if metal > 0 && wood > 0
inputs[mat("Rope")] = 1 if cloth > 0 && leather > 0
rope = bow_rope_for(item, wood)
inputs[mat("Rope")] = rope if rope > inputs[mat("Rope")].to_i
return nil if inputs.empty?
inputs.keys.each{|name| inputs[name] = MAX_INPUT if inputs[name] > MAX_INPUT }
top = TAG_MATERIAL.first
TAG_MATERIAL.each{|row| top = row if pot[row[0]].to_f > pot[top[0]].to_f }
pad_to_value(inputs, mat(top[1]), item.price.to_f * MIN_VALUE_SHARE)
Recipe.new(base_name, inputs, skill_req_for(item), nil, :gear, 1, nil)
end
def self.load_overrides
out = {}
Dir.glob(File.join(LonaCraft.resource(OVERRIDE_DIR), "*.json")).sort.each{|path|
begin
# Strict reader (ConfigJSON below), not the game's JSON.decode:
# that one loops for ever on an unclosed [ or a stray character
# inside a [...] list (101_jsonEnDecoder.rb parse_array), which
# would freeze the boot. A broken file is skipped with a line.
raw = ConfigJSON.parse(File.open(path, "rb"){|f| f.read })
entries = raw.is_a?(Array) ? raw : [raw]
entries.each{|entry|
recipe = parse_override(entry, path)
out[recipe.id] = recipe if recipe
}
rescue => e
p "LonaCraft Recipes: cannot read #{path} #{e.message}"
end
}
out
end
def self.parse_override(entry, path)
return nil unless entry.is_a?(Hash)
# a mod the recipe needs is missing: skipped without a console line
return nil if entry.has_key?("requires") && !requires_met?(entry["requires"])
output = entry["output"].to_s
item = $data_ItemName[output]
if item.nil?
p "LonaCraft Recipes: #{path} output #{output} not found, skipped"
return nil
end
inputs = {}
(entry["inputs"].is_a?(Hash) ? entry["inputs"] : {}).each{|name, qty|
count = qty.to_i
next if count < 1
if name != LonaCraft::FIBRE && $data_ItemName[name].nil?
p "LonaCraft Recipes: #{path} input #{name} not found, recipe skipped"
return nil
end
inputs[name] = count
}
return nil if inputs.empty?
req = entry.has_key?("skill_req") ? clamp_req(entry["skill_req"]) : skill_req_for(item)
fixed = LonaCraft::Tiers.craftable?(output) ? nil : 1
if entry.has_key?("fixed_tier") && !entry["fixed_tier"].nil?
fixed = entry["fixed_tier"].to_i
fixed = 1 if fixed < 1 || fixed > 5
end
category = OVERRIDE_CATEGORIES[entry["category"].to_s] || :gear
stations = entry.has_key?("station") ? LonaCraft::Stations.parse(entry["station"]) : nil
amount = entry["amount"].to_i
amount = 1 if amount < 1
cap = nil
if !entry["max_tier"].nil?
cap = entry["max_tier"].to_i
cap = nil if cap < 1 || cap > MAX_TIER
end
id = entry["id"].to_s.strip
id = output if id.empty?
requires = requires_list(entry["requires"])
requires = nil if requires.empty?
Recipe.new(output, inputs, req, fixed, category, amount, nil, stations, id, cap, requires)
end
# Stations of a recipe without a "station" of its own (rules in the header)
def self.default_stations(recipe)
case recipe.category
when :process
LonaCraft::Stations.for_process(recipe.key)
when :furniture, :decoration, :building
[LonaCraft::Stations::FURNITURE_STATION]
else
[LonaCraft::Stations.for_item(recipe.output)]
end
end
# PROCESS_RECIPES rows: [text key, {input => qty}, {output => qty}]
def self.process_recipes_from_table
out = []
LonaCraft::PROCESS_RECIPES.each{|key, ins, outs|
out_name, qty = outs.first
next if out_name.nil? || $data_ItemName[out_name].nil?
next if ins.keys.any?{|name| name != LonaCraft::FIBRE && $data_ItemName[name].nil? }
out << Recipe.new(out_name, ins.dup, 0, 1, :process, qty.to_i, key, nil, "process:#{key}")
}
out
end
#----------------------------------------------------------------------
# Queries
#----------------------------------------------------------------------
# All recipes, sorted by skill_req, then process before gear, then output item_name
def self.all
@list || []
end
def self.gear_recipes
all.select{|r| r.category == :gear }
end
def self.process_recipes
all.select{|r| r.category == :process }
end
def self.furniture_recipes
all.select{|r| r.category == :furniture || r.category == :decoration }
end
# Recipes that can be made at +station+ (:hand, :carpentry, ...)
def self.for_station(station)
all.select{|r| at_station?(r, station) }
end
def self.at_station?(recipe, station)
list = recipe.stations || default_stations(recipe)
list.include?(station)
end
def self.find(output)
all.find{|r| r.output == output }
end
def self.find_id(id)
all.find{|r| r.id == id }
end
# Best tier +recipe+ can give at +station+: the lower of the recipe's
# max_tier and the station's (Stations.max_tier); nil = no cap.
def self.tier_cap(recipe, station = nil)
caps = []
caps << recipe.max_tier.to_i if recipe && recipe.respond_to?(:max_tier) && recipe.max_tier
cap = station ? LonaCraft::Stations.max_tier(station) : nil
caps << cap.to_i if cap
caps.empty? ? nil : caps.min
end
# How many of an input the party holds (inventory only, not equipped)
def self.input_count(name)
return 0 if $game_party.nil?
return LonaCraft.fibre_total if name == LonaCraft::FIBRE
obj = $data_ItemName[name]
return 0 if obj.nil?
$game_party.item_number(obj)
end
# Display name of an input (handles the "any plant" pseudo input)
def self.input_label(name)
return LonaCraft::Tiers.text("Input/fibre") if name == LonaCraft::FIBRE
obj = $data_ItemName[name]
obj ? $game_text[obj.name].to_s : name.to_s
end
# +inputs+ ({name => count}) as paid at +station+: ceil(count x the
# station's cost) each, "*plant" too, never below the count itself.
# The cost is rounded to 4 places and a hair is taken off before the
# ceil, so 1.25 x 4 stays 5 and 1.1 x 10 stays 11 (no float noise).
def self.scale_inputs(inputs, station = nil)
mult = LonaCraft::Stations.cost(station)
out = {}
(inputs || {}).each{|name, qty|
n = qty.to_i
if mult > 1.0
n = (n * mult.round(4) - 1.0e-9).ceil
n = qty.to_i if n < qty.to_i
end
out[name] = n
}
out
end
# What +recipe+ really takes when made at +station+ (nil = its own
# inputs). The one place the station cost is applied.
def self.inputs_at(recipe, station = nil)
return {} if recipe.nil?
scale_inputs(recipe.inputs, station)
end
def self.affordable?(recipe, station = nil)
return false if recipe.nil?
return true if LonaCraft::Debug.free? # D2 god mode
inputs_at(recipe, station).each{|name, qty| return false if input_count(name) < qty }
true
end
# {input item_name => how many are missing}; empty when affordable
def self.missing(recipe, station = nil)
out = {}
return out if recipe.nil? || LonaCraft::Debug.free? # D2 god mode: nothing missing
inputs_at(recipe, station).each{|name, qty|
short = qty - input_count(name)
out[name] = short if short > 0
}
out
end
def self.skill_ok?(recipe)
LonaCraft::Skill.effective >= recipe.skill_req.to_i
end
def self.sta_cost(recipe)
return LonaCraft::PROCESS_STA_COST if recipe.category == :process
total = 0
recipe.inputs.each_value{|qty| total += qty.to_i }
total *= GEAR_STA_PER_INPUT
total < 1 ? 1 : total
end
# nil when craft would succeed, else :actor (not Lona), :inputs or :sta.
# The skill requirement is not checked here; the crafting screen blocks
# a recipe above the player's effective skill (80_CraftScene.rb try_craft).
def self.why_not(recipe, station = nil)
return :inputs if recipe.nil?
actor = $game_player ? $game_player.actor : nil
return :actor if LonaCraft.vanilla_only_actor?(actor)
return :inputs unless affordable?(recipe, station)
return :sta if actor.sta <= 0 # same rule as cooking (Command_DarkPot.rb:58-62)
nil
end
def self.can_craft?(recipe, station = nil)
why_not(recipe, station).nil?
end
# Plants used by the last craft: [[RPG::Item, amount], ...]
def self.last_fibre_used
@last_fibre_used || []
end
#----------------------------------------------------------------------
# Craft
# interpreter: pass the Game_Interpreter on the map to get the game's
# item gain/loss popups (optain_item / optain_lose_item); leave nil in a
# scene (popups need the map spriteset).
# station: where it is made (:hand, ...); its tier cap and its input
# cost (inputs_at) apply.
# Returns [RPG item made, tier] or nil when why_not(recipe) is not nil.
#----------------------------------------------------------------------
def self.craft(recipe, interpreter = nil, station = nil)
@last_fibre_used = []
return nil unless can_craft?(recipe, station)
actor = $game_player.actor
picked = []
# D2 god mode: no inputs taken, no stamina (the crafting screen has no map top-up)
free = LonaCraft::Debug.free?
paid = free ? {} : inputs_at(recipe, station)
paid.each{|name, qty|
next unless name == LonaCraft::FIBRE
got = LonaCraft.pick_fibre(qty)
return nil if got.empty?
picked.concat(got)
}
actor.sta -= sta_cost(recipe) unless LonaCraft::Debug.god?
picked.each{|obj, amount| lose(obj, amount, interpreter) }
paid.each{|name, qty| lose(name, qty, interpreter) unless name == LonaCraft::FIBRE }
if recipe.category == :process
out_name = recipe.output
tier = 1
else
tier = recipe.fixed_tier ? recipe.fixed_tier.to_i : LonaCraft::Skill.roll_tier(recipe.skill_req)
cap = tier_cap(recipe, station)
tier = cap if cap && tier > cap
out_name = LonaCraft::Tiers.variant(recipe.output, tier)
tier = LonaCraft::Tiers.tier_of(out_name) # 1 if the output has no variants
end
obj = $data_ItemName[out_name]
gain(obj, recipe.amount.to_i < 1 ? 1 : recipe.amount.to_i, interpreter)
@last_fibre_used = picked
LonaCraft::Skill.on_craft(recipe)
[obj, tier]
end
def self.lose(item, qty, interpreter)
if interpreter && interpreter.respond_to?(:optain_lose_item)
interpreter.optain_lose_item(item, qty)
else
$game_party.lose_item(item, qty)
end
end
def self.gain(item, qty, interpreter)
return if item.nil?
if interpreter && interpreter.respond_to?(:optain_item)
interpreter.optain_item(item, qty)
else
$game_party.gain_item(item, qty)
end
end
end
#--------------------------------------------------------------------------
# Small strict JSON reader for the hand-edited Config/Recipes.json and
# the Recipes/*.json files. The game's JSON.decode (101_jsonEnDecoder.rb)
# reports no errors and loops for ever on an unclosed [ ... list, so a
# typo would freeze the boot. This one takes // line comments, \r, a
# UTF-8 BOM, backslash escapes and a comma before ] or }, and raises
# ConfigJSON::Error with the line number. Strings come back as UTF-8.
# Every loop moves forward through the text; a step cap (tick) turns any
# case that would not into an Error instead of a hang.
#--------------------------------------------------------------------------
module ConfigJSON
class Error < StandardError
end
def self.parse(text)
s = text.to_s.dup
s.force_encoding("ASCII-8BIT") if s.respond_to?(:force_encoding)
if s.length >= 3 && s.getbyte(0) == 0xEF && s.getbyte(1) == 0xBB && s.getbyte(2) == 0xBF
s = s[3..-1]
end
@s = s
@i = 0
@steps = 0
@max_steps = s.length * 4 + 1000
@depth = 0
value = read_value
skip_space
fail_at("text after the end") if @i < @s.length
value
end
def self.fail_at(what)
line = @s[0, @i].count("\n") + 1
raise Error, "#{what} (line #{line})"
end
def self.tick
@steps += 1
fail_at("text too long or broken") if @steps > @max_steps
end
# [ and { nest by recursion: a cap keeps a broken file from running
# out of stack (SystemStackError is not caught by "rescue => e").
MAX_DEPTH = 64
def self.nest(delta)
@depth += delta
fail_at("lists nested too deep") if @depth > MAX_DEPTH
end
def self.skip_space
while @i < @s.length
tick
c = @s[@i, 1]
if c == " " || c == "\t" || c == "\n" || c == "\r"
@i += 1
elsif c == "/" && @s[@i + 1, 1] == "/"
nl = @s.index("\n", @i)
@i = nl ? nl : @s.length
else
break
end
end
end
def self.read_value
skip_space
c = @s[@i, 1].to_s
fail_at("unexpected end of file") if c.empty?
case c
when "{" then return read_object
when "[" then return read_array
when "\x22" then return read_string
when "t" then return read_word("true", true)
when "f" then return read_word("false", false)
when "n" then return read_word("null", nil)
end
return read_number if "-0123456789".include?(c)
fail_at("unexpected character #{c}")
end
def self.read_word(word, value)
fail_at("unexpected word (only true, false and null go without quotes)") unless @s[@i, word.length] == word
@i += word.length
value
end
def self.read_number
m = @s[@i, 40].match(/\A-?\d+(\.\d+)?([eE][-+]?\d+)?/)
fail_at("bad number") if m.nil?
@i += m[0].length
(m[1] || m[2]) ? m[0].to_f : m[0].to_i
end
def self.read_string
@i += 1
out = ""
out.force_encoding("ASCII-8BIT") if out.respond_to?(:force_encoding)
while true
tick
fail_at("unclosed string") if @i >= @s.length
c = @s[@i, 1]
@i += 1
if c == "\x22"
break
elsif c == "\n"
fail_at("unclosed string")
elsif c == "\x5C"
e = @s[@i, 1].to_s
@i += 1
case e
when "n" then out << "\n"
when "t" then out << "\t"
when "r" then out << "\r"
when "u" then out << "\x5Cu" # kept as written
else out << e
end
else
out << c
end
end
out.force_encoding("UTF-8") if out.respond_to?(:force_encoding)
out
end
def self.read_array
@i += 1
nest(1)
out = []
skip_space
if @s[@i, 1] == "]"
@i += 1
nest(-1)
return out
end
while true
tick
out << read_value
skip_space
c = @s[@i, 1]
@i += 1
break if c == "]"
fail_at("expected , or ] in a [...] list") unless c == ","
skip_space
if @s[@i, 1] == "]" # a comma before ] is forgiven
@i += 1
break
end
end
nest(-1)
out
end
def self.read_object
@i += 1
nest(1)
out = {}
skip_space
if @s[@i, 1] == "}"
@i += 1
nest(-1)
return out
end
while true
tick
skip_space
fail_at("expected a quoted name in {...}") unless @s[@i, 1] == "\x22"
key = read_string
skip_space
fail_at("expected : after #{key}") unless @s[@i, 1] == ":"
@i += 1
out[key] = read_value
skip_space
c = @s[@i, 1]
@i += 1
break if c == "}"
fail_at("expected , or } after #{key}") unless c == ","
skip_space
if @s[@i, 1] == "}" # a comma before } is forgiven
@i += 1
break
end
end
nest(-1)
out
end
end
#--------------------------------------------------------------------------
# Recipe config (README "Config").
# * Config/Recipes.json: the player's changes, never written by the mod.
# {"stations": {"hand": {"max_tier": 1, "cost": 1.25}, ...},
# "rules": {"bow_rope": 1}, (Rope in derived bow recipes, 0 = off)
# "recipes": [{"id": "...", <only the fields that change>}, ...]}
# Entries merge field by field onto the recipe with that id (output
# item_name, "process:<Key>" or a recipe file's own "id"); an id with no
# recipe makes a new one (then "station" and "inputs" are needed).
# A bad entry is skipped with a console line, never a message box.
# * Config/Recipes_defaults.json: every recipe as built before that merge,
# one entry per line with the display name as a // comment above it;
# written at boot only when its text changed.
#--------------------------------------------------------------------------
module RecipeConfig
USER_FILE = "Config/Recipes.json"
DEFAULTS_FILE = "Config/Recipes_defaults.json"
MAX_STATION_COST = 10 # a station may multiply its inputs by 1 to 10
MAX_BOW_ROPE = 5 # "rules": {"bow_rope": 0..5}
ENTRY_KEYS = ["id", "enabled", "station", "skill", "skill_req", "inputs", "amount", "max_tier", "category", "requires", "output"]
CATEGORIES = {"gear" => :gear, "furniture" => :furniture, "decoration" => :decoration, "ammo" => :ammo, "building" => :building, "process" => :process}
def self.say(text)
p "LonaCraft Config: #{text}"
end
def self.user_path
LonaCraft.resource(USER_FILE)
end
def self.defaults_path
LonaCraft.resource(DEFAULTS_FILE)
end
def self.utf8(text)
s = text.to_s.dup
s.force_encoding("UTF-8") if s.respond_to?(:force_encoding)
s
end
#----------------------------------------------------------------------
# Reading and merging the user file
#----------------------------------------------------------------------
# The user file as Ruby data; nil when missing or unreadable (console line)
def self.read_user
path = user_path
return nil unless File.exist?(path)
text = File.open(path, "rb"){|f| f.read }
ConfigJSON.parse(text)
rescue ConfigJSON::Error => e
say("#{USER_FILE} not used, #{e.message}")
nil
rescue => e
say("#{USER_FILE} not used, #{e.class} #{e.message}")
nil
end
# Recipes.build reads the user file once up front: its "rules" shape the
# derived recipes, and apply merges the same data afterwards.
def self.load_user
@user_data = read_user
@user_loaded = true
apply_rules(@user_data)
end
# "rules": {"bow_rope": 0..5}
def self.apply_rules(data)
LonaCraft::Recipes.reset_rules
return unless data.is_a?(Hash) && data.has_key?("rules")
rules = data["rules"]
unless rules.is_a?(Hash)
say("rules must be {\x22bow_rope\x22: 1}, not used")
return
end
rules.each_key{|k| say("rules: unknown key #{k} ignored") unless k == "bow_rope" }
return unless rules.has_key?("bow_rope")
v = rules["bow_rope"]
if v.is_a?(Numeric) && v.to_i >= 0 && v.to_i <= MAX_BOW_ROPE
LonaCraft::Recipes.set_bow_rope(v.to_i)
else
say("rules.bow_rope must be 0 to #{MAX_BOW_ROPE}, ignored")
end
end
# Merges the user file onto +list+ (from Recipes.build); returns the new list.
def self.apply(list)
data = @user_loaded ? @user_data : read_user
@user_loaded = false
@user_data = nil
return list if data.nil?
unless data.is_a?(Hash)
say("#{USER_FILE} must be one {...} object, not used")
return list
end
data.each_key{|k| say("unknown key #{k} ignored") unless k == "stations" || k == "recipes" || k == "rules" }
apply_stations(data["stations"])
entries = data["recipes"]
return list if entries.nil?
unless entries.is_a?(Array)
say("recipes must be a [...] list, not used")
return list
end
out = list.dup
by_id = {}
out.each{|r| by_id[r.id.to_s] = r }
used = 0
entries.each_with_index{|entry, i|
begin
used += 1 if apply_entry(entry, i + 1, by_id, out)
rescue => e
say("entry #{i + 1} skipped, #{e.class} #{e.message}")
end
}
say("#{used} of #{entries.length} recipe entries used") unless entries.empty?
out
end
def self.apply_stations(value)
return if value.nil?
unless value.is_a?(Hash)
say("stations must be {\x22hand\x22: {\x22max_tier\x22: 1, \x22cost\x22: 1.25}, ...}, not used")
return
end
value.each{|name, opts|
station = LonaCraft::Stations.normalize(name)
if station.nil?
say("stations: unknown station #{name} ignored")
next
end
unless opts.is_a?(Hash)
say("stations.#{name} must be {\x22max_tier\x22: n, \x22cost\x22: x}, ignored")
next
end
opts.each_key{|k| say("stations.#{name}: unknown key #{k} ignored") unless k == "max_tier" || k == "cost" }
if opts.has_key?("max_tier")
tier = opts["max_tier"]
if tier.nil?
LonaCraft::Stations.set_max_tier(station, nil)
elsif tier.is_a?(Numeric) && tier.to_i >= 1 && tier.to_i <= LonaCraft::Recipes::MAX_TIER
LonaCraft::Stations.set_max_tier(station, tier.to_i)
else
say("stations.#{name}.max_tier must be 1 to 5 (or null), ignored")
end
end
next unless opts.has_key?("cost")
cost = opts["cost"]
if cost.is_a?(Numeric) && cost.to_f >= 1.0 && cost.to_f <= MAX_STATION_COST
LonaCraft::Stations.set_cost(station, cost)
else
say("stations.#{name}.cost must be 1 to #{MAX_STATION_COST}, ignored")
end
}
end
# One "recipes" entry; true when it changed something.
def self.apply_entry(entry, n, by_id, out)
unless entry.is_a?(Hash)
say("entry #{n} is not a {...} object, skipped")
return false
end
id = entry["id"].to_s.strip
if id.empty?
say("entry #{n} has no id, skipped")
return false
end
where = "entry #{n} (#{id})"
entry.each_key{|k| say("#{where}: unknown key #{k} ignored") unless ENTRY_KEYS.include?(k) }
# a mod it needs is missing: skipped without a console line
return false if entry.has_key?("requires") && !LonaCraft::Recipes.requires_met?(entry["requires"])
base = by_id[id]
if entry.has_key?("enabled") && entry["enabled"] == false
if base.nil?
say("#{where}: no recipe with this id to switch off, skipped")
return false
end
out.delete_if{|r| r.equal?(base) }
by_id.delete(id)
return true
end
fields = read_fields(entry, where)
return false if fields.nil?
if base
if entry.has_key?("output") && entry["output"].to_s.strip != base.output.to_s
say("#{where}: output only counts for a new recipe, ignored")
end
recipe = base.dup
else
recipe = new_recipe(entry, id, fields, where)
return false if recipe.nil?
end
fields.each{|field, value| recipe[field] = (value == :none ? nil : value) }
if base
at = out.index{|r| r.equal?(base) }
out[at] = recipe if at
else
out << recipe
end
by_id[id] = recipe
true
end
# {Recipe field => value} from an entry; nil (console line) when a field is wrong
def self.read_fields(entry, where)
fields = {}
if entry.has_key?("station")
stations = strict_stations(entry["station"])
if stations.nil?
say("#{where}: unknown station (hand, carpentry, furnace, anvil, tailor), skipped")
return nil
end
fields[:stations] = stations
end
skill_key = entry.has_key?("skill") ? "skill" : (entry.has_key?("skill_req") ? "skill_req" : nil)
if skill_key
v = entry[skill_key]
unless v.is_a?(Numeric)
say("#{where}: skill must be a number 0 to 20, skipped")
return nil
end
fields[:skill_req] = LonaCraft::Recipes.clamp_req(v)
end
if entry.has_key?("inputs")
inputs = read_inputs(entry["inputs"], where)
return nil if inputs.nil?
fields[:inputs] = inputs
end
if entry.has_key?("amount")
v = entry["amount"]
unless v.is_a?(Numeric) && v.to_i >= 1
say("#{where}: amount must be 1 or more, skipped")
return nil
end
fields[:amount] = v.to_i
end
if entry.has_key?("max_tier")
v = entry["max_tier"]
if v.nil?
fields[:max_tier] = :none
elsif v.is_a?(Numeric) && v.to_i >= 1 && v.to_i <= LonaCraft::Recipes::MAX_TIER
fields[:max_tier] = v.to_i
else
say("#{where}: max_tier must be 1 to 5 (or null), skipped")
return nil
end
end
if entry.has_key?("category")
cat = CATEGORIES[entry["category"].to_s.strip.downcase]
if cat.nil?
say("#{where}: category must be gear, furniture, decoration, ammo or building, skipped")
return nil
end
fields[:category] = cat
end
fields
end
# every name must be a station (or "pot"); nil otherwise
def self.strict_stations(value)
list = value.is_a?(Array) ? value : [value]
out = []
list.each{|v|
station = LonaCraft::Stations.normalize(v)
return nil if station.nil?
out << station unless out.include?(station)
}
out.empty? ? nil : out
end
def self.read_inputs(value, where)
unless value.is_a?(Hash) && !value.empty?
say("#{where}: inputs must be {\x22ItemName\x22: count, ...}, skipped")
return nil
end
out = {}
value.each{|name, qty|
unless qty.is_a?(Numeric) && qty.to_i >= 1
say("#{where}: input #{name} needs a count of 1 or more, skipped")
return nil
end
if name != LonaCraft::FIBRE && $data_ItemName[name].nil?
say("#{where}: input #{name} not found, skipped")
return nil
end
out[name] = qty.to_i
}
out
end
# A recipe for an id that has none yet ("output" or the id names the item)
def self.new_recipe(entry, id, fields, where)
output = entry.has_key?("output") ? entry["output"].to_s.strip : id
item = output.start_with?("process:") ? nil : $data_ItemName[output]
if item.nil?
say("#{where}: no recipe with this id and no item #{output}, skipped")
return nil
end
unless fields[:stations] && fields[:inputs]
say("#{where}: a new recipe needs station and inputs, skipped")
return nil
end
fixed = LonaCraft::Tiers.craftable?(output) ? nil : 1
requires = LonaCraft::Recipes.requires_list(entry["requires"])
requires = nil if requires.empty?
LonaCraft::Recipes::Recipe.new(output, nil, LonaCraft::Recipes.skill_req_for(item), fixed, :gear, 1, nil, nil, id, nil, requires)
end
#----------------------------------------------------------------------
# The defaults file
#----------------------------------------------------------------------
# Writes Config/Recipes_defaults.json when its text changed.
def self.write_defaults(list)
text = defaults_text(list)
text.force_encoding("ASCII-8BIT") if text.respond_to?(:force_encoding)
path = defaults_path
old = File.exist?(path) ? File.open(path, "rb"){|f| f.read } : nil
return if old == text
dir = File.dirname(path)
Dir.mkdir(dir) unless File.directory?(dir)
File.open(path, "wb"){|f| f.write(text) }
say("wrote #{DEFAULTS_FILE} (#{list.length} recipes)")
rescue => e
say("cannot write #{DEFAULTS_FILE}, #{e.class} #{e.message}")
end
def self.defaults_text(list)
lines = []
lines << "// LonaCraft recipe defaults: every recipe loaded at the last start (the mod's own,"
lines << "// Recipes/*.json, and recipes worked out from the game's and other mods' gear),"
lines << "// BEFORE Config/Recipes.json is applied. Written by the game at start: edits here are lost."
lines << "// To change a recipe, copy its line into the recipes list of Config/Recipes.json and"
lines << "// keep only the fields you change. Stations: hand (main menu), carpentry, furnace, anvil,"
lines << "// tailor. max_tier 5 = no cap. The comment above each line is the item's display name."
lines << "// Stations cost: the multiplier on a recipe's inputs at that station, rounded up per input"
lines << "// (by hand x#{LonaCraft::Stations::COST[:hand]}). The inputs below are the bench amounts."
lines << "// Derived bows include #{LonaCraft::Recipes.bow_rope} Rope (rules.bow_rope in Config/Recipes.json; it shapes this file)."
lines << "{"
lines << " \x22stations\x22: {"
names = LonaCraft::Stations::LIST
names.each_with_index{|st, i|
cap = LonaCraft::Stations::MAX_TIER[st] || LonaCraft::Recipes::MAX_TIER
sep = i < names.length - 1 ? "," : ""
cost = (LonaCraft::Stations::COST[st] || 1.0).to_f
lines << " #{dump(st.to_s)}: {\x22max_tier\x22: #{cap}, \x22cost\x22: #{cost}}#{sep}"
}
lines << " },"
lines << " \x22recipes\x22: ["
list.each_with_index{|recipe, i|
sep = i < list.length - 1 ? "," : ""
lines << " // #{comment_for(recipe)}"
lines << " #{dump(entry_for(recipe))}#{sep}"
}
lines << " ]"
lines << "}"
lines.map{|line| utf8(line) }.join("\n") + "\n"
end
# The entry of +recipe+ in the Config/Recipes.json schema
def self.entry_for(recipe)
h = {}
h["id"] = recipe.id.to_s
h["output"] = recipe.output.to_s if recipe.category != :process && recipe.output.to_s != recipe.id.to_s
h["station"] = (recipe.stations || []).map{|s| s.to_s }
h["skill"] = recipe.skill_req.to_i
h["inputs"] = recipe.inputs || {}
h["amount"] = recipe.amount.to_i < 1 ? 1 : recipe.amount.to_i
h["max_tier"] = recipe.max_tier.to_i if recipe.max_tier
h["category"] = recipe.category.to_s
h["requires"] = recipe.requires if recipe.requires && !recipe.requires.empty?
h
end
# "Plank x2 - hand, carpentry" ("- by hand x1.25" added when it can be made by hand)
def self.comment_for(recipe)
obj = $data_ItemName[recipe.output.to_s]
name = obj ? item_text(obj) : recipe.output.to_s
name = "#{name} x#{recipe.amount.to_i}" if recipe.amount.to_i > 1
text = "#{name} - #{(recipe.stations || []).map{|s| s.to_s }.join(", ")}"
mult = LonaCraft::Stations::COST[:hand]
text += " - by hand x#{mult}" if mult && mult > 1.0 && (recipe.stations || []).include?(:hand)
text
end
# Display name of an item in the current language, one line, no
# message codes; the item_name when there is none
def self.item_text(obj)
text = $game_text ? utf8($game_text[obj.name]) : ""
text = text.gsub(/[\r\n]+/, " ").gsub(/\x5C[A-Za-z{}]+(\[[^\]]*\])?/, "").strip
text.empty? ? obj.item_name.to_s : text
rescue
obj.item_name.to_s
end
# Small pretty-printer: one line per value, ", " and ": " separators,
# quotes and backslashes escaped (the game's JSON.encode does neither).
def self.dump(value)
case value
when Hash
"{" + value.map{|k, v| "#{dump(k.to_s)}: #{dump(v)}" }.join(", ") + "}"
when Array
"[" + value.map{|v| dump(v) }.join(", ") + "]"
when String
"\x22" + value.gsub(/[\x22\x5C]/){|c| "\x5C" + c } + "\x22"
when Symbol
dump(value.to_s)
when nil
"null"
else
value.to_s
end
end
end
end