Files
LonaRPG-Online-Games/ModScripts/_Mods/LonaCraft/Scripts/90_Furniture.rb
T

1280 lines
51 KiB
Ruby
Raw Normal View History

2026-10-29 21:59:06 +04:00
#==============================================================================
# LonaCraft - 90_Furniture.rb
# What it does:
# * Furniture and decoration items, one KINDS row each (Item/Furniture_<Key>
# .json, Recipes/Furniture_<Key>.json, texts <Key>/... in
# Text/<lang>/Furniture.txt). Registered from LonaCraft.load_database
# (0_Core.rb) before Recipes.build, so their recipes are found. Each also
# gets a ground-drop event (same clone as the materials).
# Adding a piece = one KINDS row + an item JSON + a recipe JSON + texts.
# * Four crafting stations are furniture too: Carpentry Bench, Furnace,
# Anvil, Tailor's Table (row option :station). Their "Craft" opens the
# crafting screen for that station; Carpentry/Anvil/Tailor also have
# "Salvage" (20_Station.rb lonacraft_salvage_menu).
# * Fixed town stations (TOWN_STATIONS) are injected into existing maps in
# Game_Map#setup_event_hack with the same event builder, without Pick up.
# * Owner sprites (CUSTOM_SPRITES): if ModScripts/_Mods/LonaCraft/Graphics/
# Characters/<name>.png exists, that kind uses it instead of its shipped
# placeholder. The file is ONE cell (the whole PNG): the event's init block
# sets @manual_cw = @manual_ch = 1 (44_Sprite_Character.rb:145-147) and
# the graphic is index 0, direction 2, pattern 0, so the source rect is the
# whole bitmap (update_src_rect, 44_Sprite_Character.rb:171-177). The path
# is "../../<mod path>/Graphics/Characters/<name>"; Cache.character
# prepends "Graphics/Characters/" (4_Cache.rb:41).
# * Using a piece from the inventory menu: the item is consumable, so the
# game takes 1 (Game_Battler#use_item) and then evals its
# player_item_usage_eval in Game_Actor#use_item (25_Game_Actor.rb:1369),
# which calls Furniture.use_item(self, item). That gives the item back at
# once and reserves the game's Load_Eval common event
# ($game_temp.loadEval, 10_Game_Temp.rb:44), which makes the menu close
# to the map (191_menu_07items.rb:651) and runs
# Game_Interpreter#lonacraft_furniture_place on the map interpreter.
# * Placement: a see-through copy of the piece (the "ghost") appears on the
# tile in front of Lona; arrow keys move it up to REACH tiles from her,
# OK places it, Cancel stops. The item is taken only when it is placed.
# * A spot is fine when every tile of the piece's footprint (see
# "Footprints" below) is on the map, not Lona's tile, has no event on it,
# is not water or bush and is passable from all four sides. The map must
# not be the overmap, not in combat ($game_map.threat) and allowed by
# Furniture.map_allowed?: a home the player owns
# (LonaCraft::Homes.furniture_allowed?, Scripts/100_Homes.rb; false when
# that is not loaded), a map name in the extra allow-list, or a field map
# where a base may be built (LonaCraft::Bases.furniture_map_ok?,
# Scripts/110_Bases.rb; board R7 B5). On a base map a piece counts as a
# building: placing one makes (or keeps) the base and pins the map, its
# record is keyed by the base's map number, and picking up the last thing
# on the base ends it (Bases.after_furniture_removed).
# * A placed piece is a runtime RPG::Event (graphic from KINDS; same
# priority as characters and not passable, or below characters and
# passable for :walk pieces; action button) whose command is
# lonacraft_furniture_interact(<uid>), plus one invisible blocker event
# on every other footprint tile (summon_data :LonaCraftBlocker => uid;
# their action key opens the same menu). Recorded as
# {"uid","map_id","x","y","item_name"(,"box")} in
# $game_system.lonacraft_data["furniture"] (plain types, no save hook).
# * Game_Map#setup is aliased (after the original): every record of the new
# map that has no live event yet is spawned again. A record whose item no
# longer exists is skipped with a console note and kept.
# * Actions: :sleep (the bed events' Command_AreaNap.rb), :open (a storage
# box per piece, id from BOX_BASE up), :craft / :salvage (stations),
# :bathe (the game's Command_bath.rb, what water spots run), :cook (the
# dark pot's cooking script, Stove and Cooking Fire), :pickup. :light pieces carry a game
# light (give_light in the init block, as the player pot), :anim pieces
# use step animation.
#==============================================================================
module LonaCraft
module Furniture
# [key, item_name, character sheet, index, direction, pattern, options]
# options: :actions (in \optB order), :station, :storage, :anim, :walk, :light,
# :foot_w / :foot_h (footprint in tiles, instead of the formula),
# :occupy (a :walk piece whose tile still takes no other piece),
# :wall (hung on an owned back-wall tile, Homes.wall_allowed_at?;
# 1x1, no blockers, drawn above characters, never on floor)
# Generated from the scratchpad spec gen_furn4.py (kinds4.py) together with the
# item, recipe and text files; keep them in step when editing by hand.
KINDS = [
["Bed", "ItemLonaCraftFurnitureBed", "grimdark64_01", 4, 8, 1, {:actions => [:sleep, :pickup, :cancel], :foot_w => 1, :foot_h => 2}],
["BedDark", "ItemLonaCraftFurnitureBedDark", "grimdark64_01", 4, 8, 0, {:actions => [:sleep, :pickup, :cancel], :foot_w => 2, :foot_h => 2}],
["BedBlue", "ItemLonaCraftFurnitureBedBlue", "grimdark64_01", 4, 8, 2, {:actions => [:sleep, :pickup, :cancel], :foot_w => 1, :foot_h => 2}],
["Chest", "ItemLonaCraftFurnitureChest", "!$_chest_4", 0, 2, 1, {:actions => [:open, :pickup, :cancel], :storage => true}],
["Wardrobe", "ItemLonaCraftFurnitureWardrobe", "!_clutter2", 3, 2, 1, {:actions => [:open, :pickup, :cancel], :storage => true, :foot_w => 1, :foot_h => 2}],
["Cabinet", "ItemLonaCraftFurnitureCabinet", "grimdark64_01", 2, 8, 2, {:actions => [:pickup, :cancel]}],
["CarpentryBench", "ItemLonaCraftFurnitureCarpentryBench", "grimdark64_03", 1, 6, 0, {:actions => [:craft, :salvage, :pickup, :cancel], :station => :carpentry}],
["Furnace", "ItemLonaCraftFurnitureFurnace", "grimdark128_01", 3, 2, 1, {:actions => [:craft, :pickup, :cancel], :station => :furnace, :anim => true, :light => "torch_weak"}],
["Anvil", "ItemLonaCraftFurnitureAnvil", "grimdark64_02", 3, 4, 0, {:actions => [:craft, :salvage, :pickup, :cancel], :station => :anvil, :foot_w => 1, :foot_h => 1}],
["TailorTable", "ItemLonaCraftFurnitureTailorTable", "grimdark96_01", 2, 2, 1, {:actions => [:craft, :salvage, :pickup, :cancel], :station => :tailor}],
["Stove", "ItemLonaCraftFurnitureStove", "grimdark64_04", 1, 2, 0, {:actions => [:cook, :pickup, :cancel], :anim => true, :light => "torch_weak"}],
["WashTub", "ItemLonaCraftFurnitureWashTub", "grimdark32_02", 0, 4, 1, {:actions => [:bathe, :pickup, :cancel]}],
["WaterTrough", "ItemLonaCraftFurnitureWaterTrough", "grimdark64_02", 7, 6, 2, {:actions => [:bathe, :pickup, :cancel]}],
["Table", "ItemLonaCraftFurnitureTable", "grimdark64_02", 4, 4, 0, {:actions => [:pickup, :cancel]}],
["DiningTable", "ItemLonaCraftFurnitureDiningTable", "grimdark64_04", 4, 2, 1, {:actions => [:pickup, :cancel]}],
["Bench", "ItemLonaCraftFurnitureBench", "grimdark64_03", 4, 8, 0, {:actions => [:pickup, :cancel]}],
["Chair", "ItemLonaCraftFurnitureChair", "!_clutter2", 1, 2, 0, {:actions => [:pickup, :cancel]}],
["Armchair", "ItemLonaCraftFurnitureArmchair", "!_clutter2", 2, 2, 0, {:actions => [:pickup, :cancel]}],
["Shelf", "ItemLonaCraftFurnitureShelf", "grimdark64_03", 0, 2, 1, {:actions => [:pickup, :cancel]}],
["Barrel", "ItemLonaCraftFurnitureBarrel", "grimdark32_01", 3, 2, 2, {:actions => [:pickup, :cancel]}],
["Sack", "ItemLonaCraftFurnitureSack", "grimdark32_01", 3, 2, 0, {:actions => [:pickup, :cancel]}],
["Bucket", "ItemLonaCraftFurnitureBucket", "grimdark32_01", 3, 8, 1, {:actions => [:pickup, :cancel]}],
["Campfire", "ItemLonaCraftFurnitureCampfire", "!_fire", 4, 2, 0, {:actions => [:cook, :pickup, :cancel], :anim => true, :light => "torch_weak"}],
["Lamp", "ItemLonaCraftFurnitureLamp", "grimdark96_01", 4, 4, 0, {:actions => [:pickup, :cancel], :light => "lanternSM_item", :foot_w => 1, :foot_h => 1}],
["Candelabra", "ItemLonaCraftFurnitureCandelabra", "!_clutter", 4, 8, 0, {:actions => [:pickup, :cancel], :light => "lanternSM_item"}],
["WallTorch", "ItemLonaCraftFurnitureWallTorch", "!_fire", 0, 6, 1, {:actions => [:pickup, :cancel], :anim => true, :light => "torch_weak", :wall => true}],
["WallCandles", "ItemLonaCraftFurnitureWallCandles", "grimdark64_02", 2, 2, 0, {:actions => [:pickup, :cancel], :light => "torch_weak", :wall => true}],
["HangingLantern", "ItemLonaCraftFurnitureHangingLantern", "grimdark96_01", 5, 4, 0, {:actions => [:pickup, :cancel], :light => "lanternSM_item", :foot_w => 1, :foot_h => 1}],
["TorchStand", "ItemLonaCraftFurnitureTorchStand", "!_fire", 0, 2, 1, {:actions => [:pickup, :cancel], :anim => true, :light => "torch_weak"}],
["RugRed", "ItemLonaCraftFurnitureRugRed", "grimdark32_02", 7, 2, 0, {:actions => [:pickup, :cancel], :walk => true}],
["RugPattern", "ItemLonaCraftFurnitureRugPattern", "grimdark64_02", 2, 2, 1, {:actions => [:pickup, :cancel], :walk => true}],
["FurRug", "ItemLonaCraftFurnitureFurRug", "grimdark64_01", 7, 2, 0, {:actions => [:pickup, :cancel]}],
["PottedPlant", "ItemLonaCraftFurniturePottedPlant", "grimdark64_01", 6, 2, 1, {:actions => [:sleep, :pickup, :cancel], :walk => true, :occupy => true}],
["FlowerPot", "ItemLonaCraftFurnitureFlowerPot", "!_clutter", 7, 2, 0, {:actions => [:pickup, :cancel]}],
["Banner", "ItemLonaCraftFurnitureBanner", "grimdark64_01", 2, 4, 0, {:actions => [:pickup, :cancel]}],
["BannerTall", "ItemLonaCraftFurnitureBannerTall", "grimdark96_01", 0, 4, 0, {:actions => [:pickup, :cancel], :wall => true}],
["Painting", "ItemLonaCraftFurniturePainting", "grimdark64_02", 3, 2, 1, {:actions => [:pickup, :cancel], :wall => true}],
["DeerTrophy", "ItemLonaCraftFurnitureDeerTrophy", "grimdark64_01", 6, 4, 0, {:actions => [:pickup, :cancel], :wall => true}],
["WeaponRack", "ItemLonaCraftFurnitureWeaponRack", "!_clutter", 6, 6, 0, {:actions => [:pickup, :cancel]}],
["SpearRack", "ItemLonaCraftFurnitureSpearRack", "!_clutter", 6, 6, 1, {:actions => [:pickup, :cancel]}],
["ShieldDisplay", "ItemLonaCraftFurnitureShieldDisplay", "grimdark64_02", 0, 4, 2, {:actions => [:pickup, :cancel], :wall => true}],
["WineShelf", "ItemLonaCraftFurnitureWineShelf", "grimdark64_01", 5, 4, 0, {:actions => [:pickup, :cancel]}],
["Shrine", "ItemLonaCraftFurnitureShrine", "!_clutter", 4, 8, 1, {:actions => [:pickup, :cancel], :wall => true}],
["Throne", "ItemLonaCraftFurnitureThrone", "grimdark64_04", 4, 4, 1, {:actions => [:pickup, :cancel]}],
["StoneStatue", "ItemLonaCraftFurnitureStoneStatue", "grimdark64_03", 5, 4, 0, {:actions => [:pickup, :cancel]}],
["SkullBanner", "ItemLonaCraftFurnitureSkullBanner", "grimdark64_03", 2, 4, 0, {:actions => [:pickup, :cancel], :wall => true}],
["IronCage", "ItemLonaCraftFurnitureIronCage", "grimdark64_04", 4, 8, 1, {:actions => [:pickup, :cancel]}],
["HayBale", "ItemLonaCraftFurnitureHayBale", "grimdark64_02", 7, 8, 0, {:actions => [:pickup, :cancel]}],
["Fence", "ItemLonaCraftFurnitureFence", "grimdark64_02", 7, 8, 1, {:actions => [:pickup, :cancel]}],
["LogPile", "ItemLonaCraftFurnitureLogPile", "grimdark64_03", 7, 8, 1, {:actions => [:pickup, :cancel]}],
["ClothesRack", "ItemLonaCraftFurnitureClothesRack", "grimdark96_01", 2, 2, 1, {:actions => [:pickup, :cancel]}],
["Still", "ItemLonaCraftFurnitureStill", "grimdark128_01", 2, 2, 0, {:actions => [:pickup, :cancel], :anim => true}],
["MarketStall", "ItemLonaCraftFurnitureMarketStall", "grimdark128_01", 6, 2, 1, {:actions => [:pickup, :cancel]}],
["Tent", "ItemLonaCraftFurnitureTent", "grimdark128_01", 2, 4, 0, {:actions => [:pickup, :cancel]}]
]
ITEM_NAMES = KINDS.map{|row| row[1] }
DEFAULT_ACTIONS = [:pickup, :cancel]
# Owner sprites: kind key => PNG name in <mod>/Graphics/Characters.
# Used only when the file exists; otherwise the KINDS placeholder stays.
# A name whose kind does not exist (yet) is ignored.
CUSTOM_SPRITES = {
"Anvil" => "LonaCraft_Anvil",
"CarpentryBench" => "LonaCraft_CarpentryBench",
"TailorTable" => "LonaCraft_TailorTable",
"Loom" => "LonaCraft_Loom"
}
# Fixed stations in town maps: [map name, x, y, kind key, mode].
# mode nil: a new station is added on (x, y) (with blockers on the
# rest of its footprint); skipped when a footprint tile has a map event,
# a placed piece or is not passable.
# mode :existing: the map's own event standing on (x, y) becomes the
# station (its action opens our menu); skipped if there is none.
# Move them by editing the coordinates (x, y are map tiles).
TOWN_STATIONS = [
["NoerBlackSmithShop", 20, 31, "Furnace", :existing], # the smithy's own back-room forge (EV002, grimdark128_01 [3])
["NoerBlackSmithShop", 19, 32, "Anvil"], # back room, left of the forge's work spot (20,32)
["NoerMarket", 50, 37, "TailorTable"] # beside the Noer market dress trader (52,37); 2x2 covers 50-51 x 36-37
# No town Carpentry Bench: it is the piece the player builds first (by
# hand, main-menu Craft). Owner, 2026-10-06.
]
# Extra allow-list of map names for other mods (nil = none). Placement
# is otherwise allowed only where LonaCraft::Homes.furniture_allowed?
# says so (Scripts/100_Homes.rb, a home the player owns).
ALLOWED_MAPS = nil
TILE = 32 # map tile size in pixels (footprints)
REACH = 3 # the ghost stays within 3 tiles of Lona
BOX_BASE = 66000 # storage box ids; the game uses map ids and 65533-65537
GHOST_OK = 200 # ghost opacity on a good tile
GHOST_BAD = 70 # ghost opacity on a tile it cannot go on
NAP_SCRIPT = "Data/HCGframes/Command_AreaNap.rb" # what bed events run
BATH_SCRIPT = "Data/HCGframes/Command_bath.rb" # what water spots run for "Bathe"
TEXT = "LonaCraft:Furniture:"
@allowed_maps = nil
@warned = {}
@custom = {}
@cell_sizes = {}
def self.text_key(key)
"#{TEXT}#{key}"
end
#----------------------------------------------------------------------
# Kinds
#----------------------------------------------------------------------
def self.row_to_kind(row)
opts = row[6] || {}
kind = {:key => row[0], :item_name => row[1], :sprite => row[2], :index => row[3],
:dir => row[4], :pattern => row[5], :custom => false,
:actions => opts[:actions] || DEFAULT_ACTIONS, :station => opts[:station],
:storage => opts[:storage] ? true : false, :anim => opts[:anim] ? true : false,
:walk => opts[:walk] ? true : false, :light => opts[:light],
:foot_w => opts[:foot_w], :foot_h => opts[:foot_h],
:occupy => opts[:occupy] ? true : false, :wall => opts[:wall] ? true : false}
path = @custom[row[0]]
if path
kind[:sprite] = path
kind[:index] = 0
kind[:dir] = 2
kind[:pattern] = 0
kind[:custom] = true
kind[:anim] = false
end
kind
end
# Kind hash for an item_name, or nil
def self.kind_for(item_name)
row = KINDS.find{|r| r[1] == item_name.to_s }
row ? row_to_kind(row) : nil
end
def self.kind_by_key(key)
row = KINDS.find{|r| r[0] == key.to_s }
row ? row_to_kind(row) : nil
end
# town: the fixed town stations have no Pick up
def self.actions_for(kind, town = false)
list = kind[:actions] || DEFAULT_ACTIONS
town ? list.reject{|a| a == :pickup } : list
end
def self.custom_sprite_path(name)
"../../#{LonaCraft.path}/Graphics/Characters/#{name}"
end
def self.load_custom_sprites
@custom = {}
CUSTOM_SPRITES.each{|key, name|
next unless KINDS.any?{|r| r[0] == key }
file = LonaCraft.resource("Graphics/Characters/#{name}.png")
next unless File.exist?(file)
@custom[key] = custom_sprite_path(name)
p "LonaCraft Furniture: #{key} uses #{file}"
}
rescue => e
p "LonaCraft Furniture custom sprite error #{e.class} #{e.message}"
end
#----------------------------------------------------------------------
# Items (called from LonaCraft.load_database, 0_Core.rb)
#----------------------------------------------------------------------
def self.load_items
load_custom_sprites
KINDS.each{|row|
key = row[0]
item_name = row[1]
path = LonaCraft.resource("Item/Furniture_#{key}.json")
unless File.exist?(path)
p "LonaCraft Furniture: missing item file #{path}"
next
end
existing = $data_items.find{|item| item && item.item_name == item_name }
if existing
existing.load_additional_data(path)
else
obj = RPG::Item.new
obj.load_additional_data(path)
obj.id = $data_items.length
$data_items << obj
end
}
LonaCraft.register_drop_events(ITEM_NAMES)
rescue => e
p "LonaCraft Furniture load_items error #{e.class} #{e.message}"
end
# Game_Actor#use_item evals the item's player_item_usage_eval with
# self = the actor; the JSON passes (self, item).
def self.use_item(actor, item)
return if item.nil?
# the game already took one (consumable); placing takes it for real
$game_party.gain_item(item, 1) if item.consumable && !item.key_item?
return if kind_for(item.item_name).nil?
if $game_player.nil? || !actor.equal?($game_player.actor) || LonaCraft.vanilla_only_actor?(actor)
SndLib.sys_buzzer
return
end
$game_temp.loadEval("lonacraft_furniture_place(#{item.item_name.to_s.inspect})")
rescue => e
p "LonaCraft Furniture use_item error #{e.class} #{e.message}"
end
#----------------------------------------------------------------------
# Where furniture may go
#----------------------------------------------------------------------
def self.allowed_maps
@allowed_maps || ALLOWED_MAPS
end
# extra allow-list of map names (or nil) for other mods
def self.allowed_maps=(list)
@allowed_maps = list
end
# true on a field map where a base may stand (Scripts/110_Bases.rb);
# never on a home (homes keep their own rules)
def self.base_map?(map)
return false if map.nil? || !defined?(LonaCraft::Bases)
return false if defined?(LonaCraft::Homes) && LonaCraft::Homes.respond_to?(:home_at_map?) && LonaCraft::Homes.home_at_map?(map)
LonaCraft::Bases.furniture_map_ok?(map) ? true : false
rescue => e
p "LonaCraft Furniture base check error #{e.class} #{e.message}"
false
end
# true on a home the player owns (LonaCraft::Homes, 100_Homes.rb) or on
# a map in the extra allow-list; false when Homes is not loaded
def self.map_allowed?(map = $game_map)
return false if map.nil?
list = allowed_maps
return true if list.is_a?(Array) && list.include?(map.name.to_s)
return true if base_map?(map)
return false unless defined?(LonaCraft::Homes) && LonaCraft::Homes.respond_to?(:furniture_allowed?)
LonaCraft::Homes.furniture_allowed?(map) ? true : false
rescue => e
p "LonaCraft Furniture map check error #{e.class} #{e.message}"
false
end
# true when (x, y) on +map+ is inside an owned area
# (LonaCraft::Homes.furniture_allowed_at?: an owned room rectangle or
# an owned interior map) or the map is in the extra allow-list;
# false when Homes or that method is missing
def self.tile_allowed?(map, x, y)
return false if map.nil?
list = allowed_maps
return true if list.is_a?(Array) && list.include?(map.name.to_s)
if base_map?(map)
return LonaCraft::Bases.furniture_tile_ok?(map, x, y) ? true : false
end
return false unless defined?(LonaCraft::Homes) && LonaCraft::Homes.respond_to?(:furniture_allowed_at?)
LonaCraft::Homes.furniture_allowed_at?(map, x, y) ? true : false
rescue => e
p "LonaCraft Furniture tile check error #{e.class} #{e.message}"
false
end
# nil when furniture may be placed somewhere on +map+ (early exit:
# no owned area on this map at all), else :overmap, :threat, :map or
# :enemy_near (R9: the Deep Sewer, a hostile NPC close to Lona,
# Bases.hostile_near?)
def self.block_reason(map = $game_map)
return :map if map.nil?
return :overmap if map.isOverMap
return :threat if map.threat
return :map unless map_allowed?(map)
if defined?(LonaCraft::Bases) && LonaCraft::Bases.respond_to?(:sewer_map?) && LonaCraft::Bases.sewer_map?(map)
return :enemy_near if LonaCraft::Bases.hostile_near?(map)
end
nil
end
#----------------------------------------------------------------------
# Footprints. A sprite cell of cw x ch pixels is drawn bottom-anchored
# and centred on its tile, so it blocks w = max(1, ceil((cw-16)/32)) tiles
# across and h = max(1, ceil(ch/64)) tiles up (32 and 64 px -> 1 row,
# 96 and 128 px -> 2 rows; KINDS options :foot_w / :foot_h override
# w / h for one kind). Odd w: x-(w-1)/2 ..
# x+(w-1)/2. Even w: the sprite is shifted right by half a tile
# (@forced_x = 16, a screen offset; @real_x cannot be used because a
# real_x different from x counts as moving), so it covers
# x-w/2+1 .. x+w/2 (x .. x+1 for w = 2). Rows y-h+1 .. y.
# Walkable pieces cover only their own tile and get no blockers.
#----------------------------------------------------------------------
def self.cell_size(kind)
name = kind[:sprite].to_s
return @cell_sizes[name] if @cell_sizes[name]
size = [TILE, TILE]
begin
bmp = Cache.character(name)
if kind[:custom]
size = [bmp.width, bmp.height] # one PNG = one cell
else
sign = name[/^[\!\$]./]
if sign && sign.include?("$")
size = [bmp.width / 3, bmp.height / 4]
else
size = [bmp.width / 12, bmp.height / 8]
end
end
rescue => e
p "LonaCraft Furniture: cannot read #{name} (#{e.message}), footprint 1x1"
end
@cell_sizes[name] = size
end
# Width of the drawn picture in tiles, rounding half down
# (ceil((cw - 16) / 32): 32 -> 1, 48 -> 1, 64 -> 2, 96 -> 3, 128 -> 4).
# Decides both the footprint width and the half-tile shift.
def self.picture_width(kind)
cw = cell_size(kind)[0]
w = ((cw.to_f - TILE / 2) / TILE).ceil
w < 1 ? 1 : w
end
# [w_tiles, h_tiles]: w = ceil((cw-16)/32), h = ceil(ch/64) (the top half
# of a picture is drawn "up the wall", not on the floor), both at
# least 1; a KINDS row may set :foot_w / :foot_h instead.
def self.footprint_size(kind)
return [1, 1] if kind[:walk] || kind[:wall]
ch = cell_size(kind)[1]
w = kind[:foot_w] ? kind[:foot_w].to_i : picture_width(kind)
h = kind[:foot_h] ? kind[:foot_h].to_i : (ch.to_f / (TILE * 2)).ceil
w = 1 if w < 1
h = 1 if h < 1
[w, h]
end
# Half-tile shift (@forced_x) when the footprint is an even number of
# tiles wide: an explicit :foot_w decides the parity, otherwise the
# picture width does. Walkable and wall pieces are 1 wide, never shifted.
def self.even_width?(kind)
return false if kind[:walk] || kind[:wall]
w = kind[:foot_w] ? kind[:foot_w].to_i : picture_width(kind)
w.even?
end
# [[tx, ty], ...] covered by +kind+ standing on (x, y), anchor included
def self.footprint(kind, x, y)
w, h = footprint_size(kind)
x0 = w.odd? ? x - (w - 1) / 2 : x - w / 2 + 1
tiles = []
(y - h + 1).upto(y){|ty|
x0.upto(x0 + w - 1){|tx| tiles << [tx, ty] }
}
tiles
end
def self.front_tile
x = $game_player.x
y = $game_player.y
case $game_player.direction
when 2 then y += 1
when 8 then y -= 1
when 4 then x -= 1
when 6 then x += 1
end
[x, y]
end
def self.in_reach?(x, y)
(x - $game_player.x).abs <= REACH && (y - $game_player.y).abs <= REACH
end
# true on a back-wall tile of an owned area
# (LonaCraft::Homes.wall_allowed_at?, window tiles excluded); false
# when Homes or that method is missing
def self.wall_tile_allowed?(map, x, y)
return false if map.nil?
if base_map?(map)
return LonaCraft::Bases.wall_decoration_ok?(map, x, y) ? true : false
end
return false unless defined?(LonaCraft::Homes) && LonaCraft::Homes.respond_to?(:wall_allowed_at?)
LonaCraft::Homes.wall_allowed_at?(map, x, y) ? true : false
rescue => e
p "LonaCraft Furniture wall check error #{e.class} #{e.message}"
false
end
# true when +ev+ does not stop a piece from being placed on its tile:
# the ghost, or a walkable piece (rug) without :occupy
def self.placement_ignores?(ev, ghost)
return true if ev.equal?(ghost)
uid = event_uid(ev)
return false if uid.nil?
rec = record(uid)
kind = rec ? kind_for(rec["item_name"]) : nil
!kind.nil? && kind[:walk] && !kind[:occupy]
end
# nil when +kind+ can stand on (x, y), else the popup key saying why.
# Floor pieces, every footprint tile: inside the map, inside an owned
# area (tile_allowed?) and not an owned wall tile, not Lona's tile, no
# event (rugs without :occupy do not count), not water or bush,
# passable from all four sides. Wall pieces (1x1): inside the map, an
# owned back-wall tile (wall_tile_allowed?), no event; no passability
# check, the wall is meant to be impassable.
# +ignore+: the ghost, which stands on the anchor tile.
def self.tile_problem(kind, x, y, ignore = nil)
map = $game_map
blocked = "QuickMsg:Lona/CannotPlaceHere#{rand(2)}"
if kind[:wall]
return blocked unless map.valid?(x, y)
return text_key("Place/not_wall") unless wall_tile_allowed?(map, x, y)
return blocked if map.events_xy(x, y).any?{|ev| !placement_ignores?(ev, ignore) }
return nil
end
footprint(kind, x, y).each{|tx, ty|
return blocked unless map.valid?(tx, ty)
return text_key("Place/not_home") unless tile_allowed?(map, tx, ty)
return text_key("Place/not_home") if wall_tile_allowed?(map, tx, ty)
return blocked if $game_player.x == tx && $game_player.y == ty
return blocked if map.events_xy(tx, ty).any?{|ev| !placement_ignores?(ev, ignore) }
return "QuickMsg:Lona/WrongPlace#{rand(2)}" if map.water_floor?(tx, ty) || map.bush?(tx, ty)
return blocked unless [2, 4, 6, 8].all?{|d| map.passable?(tx, ty, d) }
}
nil
end
#----------------------------------------------------------------------
# Records ($game_system.lonacraft_data, 60_Skill.rb)
#----------------------------------------------------------------------
def self.data
return nil if $game_system.nil? || !$game_system.respond_to?(:lonacraft_data)
$game_system.lonacraft_data
end
def self.records
d = data
return [] if d.nil?
d["furniture"] = [] unless d["furniture"].is_a?(Array)
d["furniture"]
end
def self.record(uid)
records.find{|rec| rec.is_a?(Hash) && rec["uid"].to_i == uid.to_i }
end
# true when a placed piece on +map_id+ covers (x, y) with its footprint
def self.record_covers?(map_id, x, y)
records.any?{|rec|
next false unless rec.is_a?(Hash) && rec["map_id"] == map_id
kind = kind_for(rec["item_name"])
next false if kind.nil?
footprint(kind, rec["x"].to_i, rec["y"].to_i).include?([x, y])
}
end
def self.next_uid
d = data
n = d["furniture_next_uid"].to_i
n = 1 if n < 1
used = records.map{|rec| rec["uid"].to_i }
n += 1 while used.include?(n)
d["furniture_next_uid"] = n + 1
n
end
def self.box_contents(box_id)
return nil if $game_boxes.nil? || box_id.to_i < BOX_BASE
$game_boxes.get_box(box_id.to_i)
end
def self.box_empty?(box_id)
box = box_contents(box_id)
return true if box.nil?
box.values.all?{|count| count.to_i <= 0 }
end
# Online ownership of a placed piece: lc_net_id is "playerId.uid".
# Offline / untagged local pieces count as the local player's.
def self.owner_player_id(rec)
return "" unless rec.is_a?(Hash)
net_id = rec["lc_net_id"].to_s
return "" if net_id.empty?
net_id.split(".", 2)[0].to_s
rescue
""
end
def self.local_owner?(rec)
return true if rec.nil?
return true unless defined?(LonaCraft::OnlineSync)
begin
online = defined?(::WebSocket) && ::WebSocket.respond_to?(:connected?) && ::WebSocket.connected?
return true unless online
rescue
return true
end
owner = owner_player_id(rec)
return true if owner.empty?
# Current durable identity, or any previous identity we used
# (cloud restore used to regenerate lc_online_identity each login).
if LonaCraft::OnlineSync.respond_to?(:known_identity?)
return true if LonaCraft::OnlineSync.known_identity?(owner)
end
pid = LonaCraft::OnlineSync.player_id.to_s rescue ""
return true if pid.empty? || owner == pid
# Durable chest snapshot for this piece => we owned it before.
begin
if defined?(LonaCraft::ChestCloud)
net_id = rec["lc_net_id"].to_s
row = LonaCraft::ChestCloud.cached_row(net_id) if net_id != ""
if row.is_a?(Hash)
LonaCraft::OnlineSync.reclaim_identity!(owner) if LonaCraft::OnlineSync.respond_to?(:reclaim_identity!)
return true
end
end
rescue
end
# Soft reclaim: this prefix dominates our placed furniture (old id
# after a wipe that already minted a new random identity).
begin
if LonaCraft::OnlineSync.respond_to?(:adopt_identity_from_owned_furniture)
claimed = LonaCraft::OnlineSync.adopt_identity_from_owned_furniture
if claimed.to_s == owner.to_s && LonaCraft::OnlineSync.respond_to?(:reclaim_identity!)
LonaCraft::OnlineSync.reclaim_identity!(owner)
return true
end
end
rescue
end
false
rescue
true
end
def self.owner_restricted_action?(action)
action == :open || action == :pickup || action == :salvage
end
# A box id from BOX_BASE up that no record and no filled box uses.
def self.next_box_id
d = data
n = d["furniture_next_box"].to_i
n = BOX_BASE if n < BOX_BASE
used = records.map{|rec| rec["box"].to_i }
n += 1 while used.include?(n) || !box_empty?(n)
d["furniture_next_box"] = n + 1
n
end
#----------------------------------------------------------------------
# Events
#----------------------------------------------------------------------
def self.label(name)
RPG::EventCommand.new(118, 0, [name])
end
# Runtime RPG::Event. mode: :piece (placed, uid), :ghost, :town (fixed
# town station, arg = kind key)
def self.build_event(kind, mode, arg, x, y)
ghost = mode == :ghost
ev = RPG::Event.new(x, y)
ev.name = case mode
when :ghost then "LonaCraftFurnitureGhost"
when :town then "LonaCraftTown#{arg}"
else "LonaCraftFurniture#{arg}"
end
page = RPG::Event::Page.new
page.graphic.tile_id = 0
page.graphic.character_name = kind[:sprite]
page.graphic.character_index = kind[:index]
page.graphic.direction = kind[:dir]
page.graphic.pattern = kind[:pattern]
page.move_type = 0
page.walk_anime = false
page.step_anime = kind[:anim] ? true : false
page.direction_fix = true
if ghost
page.through = true
page.priority_type = 2
elsif kind[:wall]
# The wall itself blocks. Priority stays "same as characters"
# because the action key only starts normal-priority events on
# the tile in front (35_Game_Player.rb:331-332, 388-391); the init
# block adds @forced_z = 10, which draws it like "above
# characters" (Game_Event#screen_z, 39_Game_Event.rb:2272-2285).
page.through = true
page.priority_type = 1
elsif kind[:walk]
page.through = true
page.priority_type = 0 # below characters: walk over it, action key while standing on it
else
page.through = false
page.priority_type = 1
end
page.trigger = 0
init = []
init << "@manual_cw = 1" << "@manual_ch = 1" if kind[:custom] # the PNG is one cell
init << "@forced_x = #{TILE / 2}" if even_width?(kind) # even footprint: half a tile right
init << "@forced_z = 10" if kind[:wall] && !ghost # drawn like "above characters"
init << "give_light(#{kind[:light].inspect})" if kind[:light] && !ghost
list = []
unless init.empty?
# the game's init block (PreLaunchConfig), as the player pot uses it
list << label("init")
list << label("common")
init.each{|line| list << EvLib.NewEventCMD(line) }
list << label("end_common")
end
case mode
when :piece
list << EvLib.NewEventCMD("lonacraft_furniture_interact(#{arg.to_i}) if respond_to?(:lonacraft_furniture_interact)")
when :town
list << EvLib.NewEventCMD("lonacraft_town_station_interact(#{arg.to_s.inspect}) if respond_to?(:lonacraft_town_station_interact)")
end
list << RPG::EventCommand.new(0, 0, [])
page.list = list
ev.pages = [page]
ev
end
# Invisible event on one non-anchor footprint tile: no graphic, not
# passable, same priority as characters. Its action key forwards to
# the piece's menu, so a big piece can be used from any side.
# mode :piece (arg = uid) or :town (arg = kind key); n = blocker number
def self.build_blocker(mode, arg, n, x, y)
ev = RPG::Event.new(x, y)
ev.name = mode == :town ? "LonaCraftTownBlock#{arg}_#{n}" : "LonaCraftBlock#{arg}_#{n}"
page = RPG::Event::Page.new
page.graphic.tile_id = 0
page.graphic.character_name = ""
page.move_type = 0
page.walk_anime = false
page.step_anime = false
page.direction_fix = true
page.through = false
page.priority_type = 1
page.trigger = 0
list = []
if mode == :town
list << EvLib.NewEventCMD("lonacraft_town_station_interact(#{arg.to_s.inspect}) if respond_to?(:lonacraft_town_station_interact)")
else
list << EvLib.NewEventCMD("lonacraft_furniture_interact(#{arg.to_i}) if respond_to?(:lonacraft_furniture_interact)")
end
list << RPG::EventCommand.new(0, 0, [])
page.list = list
ev.pages = [page]
ev
end
# footprint tiles other than the anchor
def self.blocker_tiles(kind, x, y)
return [] if kind[:walk] || kind[:wall]
footprint(kind, x, y).reject{|t| t[0] == x && t[1] == y }
end
def self.event_uid(ev)
return nil if ev.nil? || ev.deleted?
data = ev.summon_data
return nil unless data.is_a?(Hash)
data[:LonaCraftFurniture]
end
def self.blocker_uid(ev)
return nil if ev.nil? || ev.deleted?
data = ev.summon_data
return nil unless data.is_a?(Hash)
data[:LonaCraftBlocker]
end
def self.ghost?(ev)
!ev.nil? && ev.summon_data.is_a?(Hash) && ev.summon_data[:LonaCraftGhost] ? true : false
end
# the piece's own event(s)
def self.events_of(map, uid)
map.events.values.select{|ev| !ev.nil? && event_uid(ev) == uid.to_i }
end
# the piece's blocker events (found by uid; their event ids change on
# every map load, so they are not stored in the record)
def self.blockers_of(map, uid)
map.events.values.select{|ev| !ev.nil? && blocker_uid(ev) == uid.to_i }
end
def self.spawn(map, rec, kind)
uid = rec["uid"].to_i
x = rec["x"].to_i
y = rec["y"].to_i
ev = build_event(kind, :piece, uid, x, y)
piece = map.lonacraft_spawn_event(ev, {:LonaCraftFurniture => uid})
spawn_blockers(map, rec, kind)
piece
end
# true when the piece's live blockers stand exactly on its current
# footprint (minus its own tile)
def self.blockers_match?(map, rec, kind)
want = blocker_tiles(kind, rec["x"].to_i, rec["y"].to_i).select{|t| map.valid?(t[0], t[1]) }
have = blockers_of(map, rec["uid"]).map{|b| [b.x, b.y] }
want.sort == have.sort
end
# (Re)creates the piece's blockers on every footprint tile but its own
def self.spawn_blockers(map, rec, kind)
uid = rec["uid"].to_i
blockers_of(map, uid).each{|b| b.nappable = false; b.delete }
blocker_tiles(kind, rec["x"].to_i, rec["y"].to_i).each_with_index{|t, i|
next unless map.valid?(t[0], t[1])
map.lonacraft_spawn_event(build_blocker(:piece, uid, i, t[0], t[1]), {:LonaCraftBlocker => uid})
}
end
def self.spawn_ghost(map, kind, x, y)
ev = build_event(kind, :ghost, 0, x, y)
ghost = map.lonacraft_spawn_event(ev, {:LonaCraftGhost => true})
ghost.nappable = false
ghost.opacity = GHOST_OK
ghost
rescue => e
p "LonaCraft Furniture ghost error #{e.class} #{e.message}"
nil
end
def self.shade_ghost(ghost, kind, x, y)
return if ghost.nil?
ghost.opacity = tile_problem(kind, x, y, ghost).nil? ? GHOST_OK : GHOST_BAD
end
def self.remove_ghost(ghost)
return if ghost.nil? || ghost.deleted?
ghost.nappable = false
ghost.delete
rescue => e
p "LonaCraft Furniture ghost remove error #{e.message}"
end
# New piece at (x, y) on +map+: record + event. Returns the record.
def self.place(map, item_name, x, y)
kind = kind_for(item_name)
return nil if kind.nil?
# on a base map the base is made first (it re-keys the live map to
# the base's map number, 110_Bases.rb Bases.rekey)
if base_map?(map)
return nil if LonaCraft::Bases.ensure_base(map).nil?
end
rec = {"uid" => next_uid, "map_id" => map.map_id, "x" => x, "y" => y, "item_name" => item_name.to_s}
rec["box"] = next_box_id if kind[:storage]
records << rec
spawn(map, rec, kind)
rec
end
# Deletes the piece's events on +map+ and its record; frees an empty box.
def self.remove(map, uid)
(events_of(map, uid) + blockers_of(map, uid)).each{|ev|
ev.nappable = false # a deleted event would come back on a nap otherwise
ev.delete
}
rec = record(uid)
return if rec.nil?
box_id = rec["box"].to_i
$game_boxes.write_box(box_id, nil) if box_id >= BOX_BASE && box_empty?(box_id)
records.delete(rec)
end
# After Game_Map#setup: spawn every piece of this map that is not there.
def self.respawn_map(map)
map.events.values.each{|ev| remove_ghost(ev) if ghost?(ev) }
map_id = map.map_id
records.each{|rec|
next unless rec.is_a?(Hash)
next unless rec["map_id"] == map_id
uid = rec["uid"].to_i
kind = kind_for(rec["item_name"])
unless events_of(map, uid).empty?
# already there (nap, or a save made under another footprint
# rule): rebuild the blockers when they do not match
spawn_blockers(map, rec, kind) if kind && !blockers_match?(map, rec, kind)
next
end
if kind.nil? || $data_ItemName[rec["item_name"].to_s].nil?
unless @warned[uid]
@warned[uid] = true
p "LonaCraft Furniture: #{rec["item_name"]} no longer exists, piece #{uid} on map #{map_id} not placed (record kept)"
end
next
end
spawn(map, rec, kind)
}
end
# [[x, y, kind key, mode], ...] of the town stations of map +name+
def self.town_stations_for(name)
TOWN_STATIONS.select{|row| row[0] == name.to_s }.map{|row| [row[1].to_i, row[2].to_i, row[3], row[4]] }
end
def self.town_command(key)
"lonacraft_town_station_interact(#{key.to_s.inspect}) if respond_to?(:lonacraft_town_station_interact)"
end
end
end
#==============================================================================
# Game_Map: spawn a runtime event (as ask_summon_event, 31_Game_Map.rb:1204,
# but from an RPG::Event instead of an EventLib name), re-spawn pieces after
# setup, inject the town stations before the map's events are built.
#==============================================================================
class Game_Map
def lonacraft_spawn_event(rpg_event, data)
new_id = @events.keys.max
new_id = new_id.nil? ? 1 : new_id + 1
rpg_event.id = new_id
@added_ev_ids.push(new_id) # the spriteset adds a sprite for it
ev = Game_Event.new(@map_id, rpg_event, data) # moveto puts it in the position hash
ev.summoner_id = -1
ev.foreign_event = true
@events[new_id] = ev
ev
end
# check_passage (31_Game_Map.rb:734) on the map layers only: tile events
# are not built yet when setup_event_hack runs.
def lonacraft_layer_pass?(x, y, bit)
b = @lonacraft_wall_block # 110_Bases.rb: the A4 wall tops of a base
return false if b && b[y * width + x]
flags = tileset.flags
layered_tiles(x, y).each{|tile_id|
flag = flags[tile_id]
next if flag & 0x10 != 0
return true if flag & bit == 0
return false if flag & bit == bit
}
false
end
def lonacraft_town_tile_free?(x, y)
return false unless valid?(x, y)
return false if @map.events.values.any?{|e| e && e.x == x && e.y == y }
return false if LonaCraft::Furniture.record_covers?(@map_id, x, y)
[1, 2, 4, 8].all?{|bit| lonacraft_layer_pass?(x, y, bit) }
end
def lonacraft_add_map_event(ev)
new_id = @map.events.keys.max
new_id = new_id.nil? ? 1 : new_id + 1
ev.id = new_id
@map.events[new_id] = ev
@preload_EventHash[ev.name] = ev if @preload_EventHash.is_a?(Hash)
ev
end
# Adds the town stations of this map to @map.events, so setup_events
# builds them like map events (and a nap rebuilds them the same way).
def lonacraft_inject_town_stations
fur = LonaCraft::Furniture
fur.town_stations_for(@name).each{|x, y, key, mode|
kind = fur.kind_by_key(key)
next if kind.nil?
if mode == :existing
lonacraft_hook_town_station(x, y, key)
next
end
name = "LonaCraftTown#{key}"
next if @map.events.values.any?{|e| e && e.name == name } # already there
tiles = fur.footprint(kind, x, y)
bad = tiles.find{|t| !lonacraft_town_tile_free?(t[0], t[1]) }
if bad
p "LonaCraft Furniture: town #{key} on #{@name} (#{x},#{y}) skipped, tile #{bad[0]},#{bad[1]} taken"
next
end
lonacraft_add_map_event(fur.build_event(kind, :town, key, x, y))
fur.blocker_tiles(kind, x, y).each_with_index{|t, i|
lonacraft_add_map_event(fur.build_blocker(:town, key, i, t[0], t[1]))
}
}
end
# The map's own event on (x, y) becomes the station: its "no trigger"
# line (@manual_trigger=-1) is lifted and our menu command is added
# before the end of its page (the _DEMO_6_EventHack pattern).
def lonacraft_hook_town_station(x, y, key)
fur = LonaCraft::Furniture
target = nil
@map.events.keys.sort.each{|id|
e = @map.events[id]
next if e.nil? || e.x != x || e.y != y
next if e.name.to_s =~ /\A-point-|\ALonaCraft/
next if e.pages.nil? || e.pages.empty?
target = e
break
}
if target.nil?
p "LonaCraft Furniture: town #{key} on #{@name} (#{x},#{y}) skipped, no map event to hook"
return
end
page = target.pages[0]
command = fur.town_command(key)
return if page.list.any?{|c| c.code == 355 && c.parameters[0] == command } # already hooked
page.list.each{|c|
next unless c.code == 355 || c.code == 655
next unless c.parameters[0].is_a?(String)
c.parameters[0] = c.parameters[0].gsub(/@manual_trigger\s*=\s*-1/, "@manual_trigger = nil")
}
page.trigger = 0
last = page.list.rindex{|c| c.code == 0 && c.indent == 0 } || page.list.length
page.list.insert(last, EvLib.NewEventCMD(command))
p "LonaCraft Furniture: #{@name} event #{target.id} (#{x},#{y}) is the town #{key}"
end
unless method_defined?(:setup_event_hack_lonacraft_furniture)
alias_method :setup_event_hack_lonacraft_furniture, :setup_event_hack
def setup_event_hack
setup_event_hack_lonacraft_furniture
begin
lonacraft_inject_town_stations
rescue => e
p "LonaCraft Furniture town station error #{e.class} #{e.message}"
end
end
end
# A nap keeps the live events and rebuilds the "strong" ones from the
# fresh map data (reset_events, 31_Game_Map.rb:359-367, called from
# setup:205). A live event whose data is gone, e.g. a town station
# removed from TOWN_STATIONS after a save was made on that map (the game
# saves $game_map with its live events), would crash Game_Event.new on
# nil. Such events are marked non-nappable so reset_events deletes them.
unless method_defined?(:reset_events_lonacraft_stale)
alias_method :reset_events_lonacraft_stale, :reset_events
def reset_events
begin
if @events.is_a?(Hash) && @map && @map.events.is_a?(Hash)
@events.each{|i, ev|
next if ev.nil?
next if ev.respond_to?(:foreign_event) && ev.foreign_event
next unless @map.events[i].nil?
name = ev.respond_to?(:name) ? ev.name.to_s : "?"
p "LonaCraft: live event #{i} (#{name}) has no map data any more, dropped before the nap"
ev.nappable = false if ev.respond_to?(:nappable=)
}
end
rescue => e
p "LonaCraft stale event check error #{e.class} #{e.message}"
end
reset_events_lonacraft_stale
end
end
unless method_defined?(:setup_lonacraft_furniture)
alias_method :setup_lonacraft_furniture, :setup
def setup(map_id)
setup_lonacraft_furniture(map_id)
begin
LonaCraft::Furniture.respawn_map(self)
rescue => e
p "LonaCraft Furniture respawn error #{e.class} #{e.message}"
end
begin
LonaCraft::ChestCloud.apply_all_cached! if defined?(LonaCraft::ChestCloud)
rescue
end
end
end
end
#==============================================================================
# Game_Interpreter: placement and the per-piece menus
#==============================================================================
class Game_Interpreter
# Run by the Load_Eval common event after the item was used.
def lonacraft_furniture_place(item_name)
fur = LonaCraft::Furniture
item = $data_ItemName[item_name.to_s]
kind = fur.kind_for(item_name)
return if item.nil? || kind.nil?
return unless $game_party.has_item?(item)
if LonaCraft.vanilla_only_actor?($game_player.actor)
SndLib.sys_buzzer
return
end
reason = fur.block_reason($game_map)
if reason
lonacraft_furniture_refuse(reason)
return
end
x, y = fur.front_tile
# facing the map edge: start on Lona's tile (moveto would wrap around)
unless $game_map.valid?(x, y)
x = $game_player.x
y = $game_player.y
end
ghost = fur.spawn_ghost($game_map, kind, x, y)
fur.shade_ghost(ghost, kind, x, y)
$game_map.popup(0, fur.text_key("Place/hint"), 0, 0)
placed = false
begin
wait(2)
loop do
wait(1)
if Input.trigger?(:B) || WolfPad.trigger?(:X_LINK)
SndLib.play_cursor
break
end
if Input.trigger?(:C) || WolfPad.trigger?(:Z_LINK)
reason = fur.block_reason($game_map)
if reason
lonacraft_furniture_refuse(reason)
break
end
problem = fur.tile_problem(kind, x, y, ghost)
if problem.nil?
placed = true
break
end
SndLib.sys_buzzer
$game_map.popup(0, problem, 0, 0)
next
end
dx = 0
dy = 0
if Input.repeat?(:LEFT)
dx = -1
elsif Input.repeat?(:RIGHT)
dx = 1
elsif Input.repeat?(:UP)
dy = -1
elsif Input.repeat?(:DOWN)
dy = 1
end
next if dx == 0 && dy == 0
nx = x + dx
ny = y + dy
next unless $game_map.valid?(nx, ny) && fur.in_reach?(nx, ny)
x = nx
y = ny
ghost.moveto(x, y) if ghost
fur.shade_ghost(ghost, kind, x, y)
SndLib.play_cursor
end
ensure
fur.remove_ghost(ghost)
end
return unless placed
return SndLib.sys_buzzer unless $game_party.has_item?(item)
rec = fur.place($game_map, item_name, x, y)
return SndLib.sys_buzzer if rec.nil?
optain_lose_item(item, 1) unless LonaCraft::Debug.free? # D2 god mode: the item stays in the bag
SndLib.WoodenBuild(80)
end
def lonacraft_furniture_refuse(reason)
SndLib.sys_buzzer
if reason == :threat
$game_map.popup(0, "QuickMsg:Lona/incombat#{rand(2)}", 0, 0)
else
call_msg(LonaCraft::Furniture.text_key("Place/#{reason}"))
eventPlayEnd
end
end
# true when the piece may be used now (no combat, Lona herself)
def lonacraft_furniture_usable?
if $game_map.threat
SndLib.sys_buzzer
$game_map.popup(0, "QuickMsg:Lona/incombat#{rand(2)}", 0, 0)
return false
end
if LonaCraft.vanilla_only_actor?($game_player.actor)
SndLib.sys_buzzer
return false
end
true
end
# Shows the kind's menu; returns the chosen action (:cancel when none)
def lonacraft_furniture_menu(kind, town)
fur = LonaCraft::Furniture
$game_portraits.lprt.hide
call_msg(fur.text_key("#{kind[:key]}/#{town ? "menu_town" : "menu"}"))
pick = $game_temp.choice
$game_temp.choice = -1
return :cancel unless pick.is_a?(Integer) && pick >= 0
fur.actions_for(kind, town)[pick] || :cancel
end
# The command of every placed piece.
def lonacraft_furniture_interact(uid)
fur = LonaCraft::Furniture
rec = fur.record(uid)
if rec.nil?
p "LonaCraft Furniture: piece #{uid} has no record, removed"
fur.remove($game_map, uid)
return
end
kind = fur.kind_for(rec["item_name"])
return if kind.nil?
return unless lonacraft_furniture_usable?
action = lonacraft_furniture_menu(kind, false)
return if lonacraft_furniture_action(action, kind, rec) == :done
eventPlayEnd
end
# The command of the fixed town stations (no Pick up).
def lonacraft_town_station_interact(key)
kind = LonaCraft::Furniture.kind_by_key(key)
return if kind.nil?
return unless lonacraft_furniture_usable?
action = lonacraft_furniture_menu(kind, true)
return if lonacraft_furniture_action(action, kind, nil) == :done
eventPlayEnd
end
def lonacraft_furniture_refuse_owner(fur)
SndLib.sys_buzzer
call_msg(fur.text_key("Storage/not_owner"))
rescue
SndLib.sys_buzzer
end
# Runs one menu action. Returns :done when the called script already
# ended the event itself (sleep, bathe, cook).
def lonacraft_furniture_action(action, kind, rec)
fur = LonaCraft::Furniture
if rec && fur.owner_restricted_action?(action) && !fur.local_owner?(rec)
lonacraft_furniture_refuse_owner(fur)
return nil
end
case action
when :sleep # exactly what the game's bed events run
load_script(LonaCraft::Furniture::NAP_SCRIPT)
return :done
when :bathe # what the game's water spots run for "Bathe"
load_script(LonaCraft::Furniture::BATH_SCRIPT)
return :done
when :cook # the dark pot's cooking (20_Station.rb): Stove, Cooking Fire
lonacraft_run_original_pot
return :done
when :open
lonacraft_furniture_open_box(rec) if rec
when :craft
LonaCraft.open_craft_scene(kind[:station] || :carpentry)
when :salvage
lonacraft_salvage_menu(kind[:station])
when :pickup
lonacraft_furniture_pickup(rec, kind) if rec
end
nil
end
def lonacraft_furniture_open_box(rec)
fur = LonaCraft::Furniture
unless fur.local_owner?(rec)
lonacraft_furniture_refuse_owner(fur)
return
end
box_id = rec["box"].to_i
if box_id < LonaCraft::Furniture::BOX_BASE
box_id = fur.next_box_id
rec["box"] = box_id
end
empty_before = fur.box_empty?(box_id)
begin
LonaCraft::ChestCloud.ensure_net_id(rec) if defined?(LonaCraft::ChestCloud)
if defined?(LonaCraft::ChestCloud) && empty_before
LonaCraft::ChestCloud.apply_to_record(rec)
end
rescue
end
box = $game_boxes.box(box_id)
$game_boxes.setup(box_id, $game_text[fur.text_key("Storage/box_name")], 0)
stacks = box.is_a?(Hash) ? box.values.count{|count| count.to_i > 0 } : 0
p "LonaCraft Storage: chest #{rec["uid"]} box #{box_id} (#{stacks} stacks)"
SceneManager.goto(Scene_ItemStorage)
SceneManager.scene.prepare(box_id)
begin
if defined?(LonaCraft::ChestCloud)
SceneManager.scene.instance_variable_set(:@lc_chest_rec_uid, rec["uid"].to_i)
end
rescue
end
end
def lonacraft_furniture_pickup(rec, kind)
fur = LonaCraft::Furniture
unless fur.local_owner?(rec)
lonacraft_furniture_refuse_owner(fur)
return
end
if kind[:storage] && !fur.box_empty?(rec["box"])
SndLib.sys_buzzer
call_msg(fur.text_key("Storage/not_empty"))
return
end
item = $data_ItemName[rec["item_name"].to_s]
begin
LonaCraft::ChestCloud.forget_record(rec) if defined?(LonaCraft::ChestCloud) && kind[:storage]
rescue
end
fur.remove($game_map, rec["uid"])
SndLib.WoodenBuild
optain_item(item, 1) if item
if fur.base_map?($game_map) && LonaCraft::Bases.after_furniture_removed($game_map)
$game_map.popup(0, LonaCraft::Bases.text_key("Piece/reverted"), 0, 0)
end
end
end