288 lines
10 KiB
Ruby
288 lines
10 KiB
Ruby
#==============================================================================
|
|
# LonaCraft - 05_Config.rb
|
|
# What it does:
|
|
# * LonaCraft::Config: the mod's own switches in Config/LonaCraft.json, read
|
|
# once per game start (Config.load). Keys and defaults (DEFAULTS):
|
|
# "debug" false numpad debug keys (95_Debug.rb Numpad 0-9 + - *,
|
|
# 110_Bases.rb Numpad /, 120_Raids.rb Numpad .) and,
|
|
# with "self_test", the start-up self-test
|
|
# "self_test" true run Scripts/98_SelfTest.rb at start (only with debug)
|
|
# "self_test_log" "UserData/LonaCraft_selftest.log" its report, relative
|
|
# to the game folder
|
|
# "trace" true with "debug": the crash trace (LonaCraft.trace)
|
|
# "trace_log" "UserData/LonaCraft_trace.log" the trace file, relative
|
|
# to the game folder
|
|
# "viewport_guard" true 02_ViewportGuard.rb: no Sprite / Plane / Window /
|
|
# Tilemap outlives its Viewport (on without debug)
|
|
# A missing file means the defaults (no console line). A file that cannot
|
|
# be read, or a value of the wrong type, means the default for it plus one
|
|
# console line "LonaCraft Config: ...". Unknown keys get a console line too.
|
|
# * The file is parsed by the strict reader LonaCraft::ConfigJSON
|
|
# (55_Recipes.rb; the game's JSON.decode can hang on a typo). This file
|
|
# loads before 55_Recipes.rb, so the first Config.get / LonaCraft.debug?
|
|
# after 55_Recipes.rb is loaded reads the file (the first caller is
|
|
# 110_Bases.rb or 98_SelfTest.rb, both before DataManager.load_mod_database
|
|
# and long before the first map frame). A call made before ConfigJSON
|
|
# exists answers from DEFAULTS and does not keep that answer.
|
|
# * LonaCraft.debug? true only when "debug" is exactly true.
|
|
# * LonaCraft::Config.get(key, default) any key; +default+ when absent.
|
|
# * LonaCraft.trace(msg) / LonaCraft.trace{ msg } crash trace (added
|
|
# 2026-10-06 after two RGSS301.dll access violations, fault offset
|
|
# 0x00111a1c, in the crafting screen; a native crash shows no Ruby error
|
|
# box and the console dies with the game). With "debug" and "trace" on it
|
|
# appends one line "HH:MM:SS.mmm msg" to "trace_log", opening, writing,
|
|
# flushing and closing the file on every call, so the last line is the
|
|
# last step reached. The first line of a game run moves the previous file
|
|
# to <name>.prev.log and starts a new one with a header (date, game and
|
|
# mod version). The block form is only run when tracing is on. Never
|
|
# raises; with debug off it costs one cached boolean. trace_mem,
|
|
# trace_bitmap and trace_error build the usual numbers. Callers:
|
|
# 80_CraftScene.rb, 85_MenuCraft.rb.
|
|
#==============================================================================
|
|
module LonaCraft
|
|
module Config
|
|
FILE = "Config/LonaCraft.json"
|
|
DEFAULTS = {
|
|
"debug" => false,
|
|
"self_test" => true,
|
|
"self_test_log" => "UserData/LonaCraft_selftest.log",
|
|
"trace" => true,
|
|
"trace_log" => "UserData/LonaCraft_trace.log",
|
|
"viewport_guard" => true
|
|
}
|
|
|
|
@data = nil # merged settings once read; nil until then
|
|
@status = nil # one line for the self-test log: how the file was read
|
|
|
|
def self.path
|
|
LonaCraft.resource(FILE)
|
|
end
|
|
|
|
def self.say(text)
|
|
p "LonaCraft Config: #{text}"
|
|
end
|
|
|
|
# true for a value that may replace DEFAULTS[key]
|
|
def self.value_ok?(key, value)
|
|
default = DEFAULTS[key]
|
|
case default
|
|
when true, false
|
|
value == true || value == false
|
|
when String
|
|
value.is_a?(String) && !value.strip.empty?
|
|
else
|
|
true
|
|
end
|
|
end
|
|
|
|
# Reads Config/LonaCraft.json once; +force+ reads it again.
|
|
def self.load(force = false)
|
|
return @data if @data && !force
|
|
unless defined?(LonaCraft::ConfigJSON)
|
|
@status = "defaults (55_Recipes.rb not loaded yet)"
|
|
return DEFAULTS.dup # not kept: the next call tries the file again
|
|
end
|
|
data = DEFAULTS.dup
|
|
file = path
|
|
unless File.exist?(file)
|
|
@status = "defaults (#{FILE} not found)"
|
|
return @data = data
|
|
end
|
|
begin
|
|
raw = LonaCraft::ConfigJSON.parse(File.open(file, "rb"){|f| f.read })
|
|
rescue => e
|
|
say("#{FILE} not used, #{e.message}; defaults (debug off)")
|
|
@status = "defaults (#{FILE} unreadable: #{e.message})"
|
|
return @data = data
|
|
end
|
|
unless raw.is_a?(Hash)
|
|
say("#{FILE} not used, it must be one { ... } object; defaults (debug off)")
|
|
@status = "defaults (#{FILE} is not an object)"
|
|
return @data = data
|
|
end
|
|
raw.each{|key, value|
|
|
key = key.to_s
|
|
unless DEFAULTS.has_key?(key)
|
|
say("#{FILE}: unknown key \"#{key}\" ignored")
|
|
next
|
|
end
|
|
unless value_ok?(key, value)
|
|
say("#{FILE}: \"#{key}\" has a wrong value (#{value.inspect}), default #{DEFAULTS[key].inspect} used")
|
|
next
|
|
end
|
|
data[key] = value
|
|
}
|
|
@status = "read #{FILE}"
|
|
@data = data
|
|
rescue => e
|
|
say("#{FILE} not used, #{e.class} #{e.message}")
|
|
@status = "defaults (#{e.class} #{e.message})"
|
|
@data = DEFAULTS.dup
|
|
end
|
|
|
|
def self.data
|
|
@data || load
|
|
end
|
|
|
|
def self.get(key, default = nil)
|
|
d = data
|
|
d.has_key?(key.to_s) ? d[key.to_s] : default
|
|
rescue
|
|
default
|
|
end
|
|
|
|
def self.status
|
|
data
|
|
@status.to_s
|
|
end
|
|
end
|
|
|
|
# The debug switch: numpad debug keys and the start-up self-test.
|
|
def self.debug?
|
|
Config.get("debug", false) == true
|
|
end
|
|
|
|
#--------------------------------------------------------------------------
|
|
# Crash trace (README "Debug and self-test")
|
|
#--------------------------------------------------------------------------
|
|
TRACE_LOG = "UserData/LonaCraft_trace.log"
|
|
|
|
# true when trace lines are written ("debug" and "trace" both true).
|
|
# Cached once the config file can be read (ConfigJSON loaded).
|
|
def self.trace_on?
|
|
return @trace_on unless @trace_on.nil?
|
|
return false unless defined?(LonaCraft::ConfigJSON)
|
|
@trace_on = (debug? && Config.get("trace", true) == true) ? true : false
|
|
rescue StandardError
|
|
false
|
|
end
|
|
|
|
def self.trace_path
|
|
@trace_path ||= Config.get("trace_log", TRACE_LOG).to_s
|
|
end
|
|
|
|
# Appends "HH:MM:SS.mmm msg" and closes the file again. With a block the
|
|
# block gives the text (run only when tracing is on, errors in it caught).
|
|
def self.trace(msg = nil)
|
|
return nil unless trace_on?
|
|
msg = yield if block_given?
|
|
path = trace_path
|
|
trace_begin(path) unless @trace_started
|
|
now = Time.now
|
|
line = now.strftime("%H:%M:%S") + "." + format("%03d", now.usec / 1000) + " "
|
|
line.force_encoding("ASCII-8BIT")
|
|
text = msg.to_s.dup
|
|
text.force_encoding("ASCII-8BIT")
|
|
line << text << "\n"
|
|
File.open(path, "ab"){|f|
|
|
f.write(line)
|
|
f.flush
|
|
}
|
|
nil
|
|
rescue Exception => e
|
|
raise if e.is_a?(SystemExit) || (defined?(RGSSReset) && e.is_a?(RGSSReset))
|
|
nil
|
|
end
|
|
|
|
# First trace line of a game run: the last run's file becomes
|
|
# <name>.prev<ext>, a new file starts with a header.
|
|
def self.trace_begin(path)
|
|
@trace_started = true
|
|
dir = File.dirname(path)
|
|
Dir.mkdir(dir) unless dir == "." || File.directory?(dir)
|
|
ext = File.extname(path)
|
|
prev = File.join(dir, File.basename(path, ext) + ".prev" + ext)
|
|
if File.exist?(path)
|
|
begin
|
|
File.delete(prev) if File.exist?(prev)
|
|
File.rename(path, prev)
|
|
rescue StandardError
|
|
end
|
|
end
|
|
game = (DataManager.export_full_ver_info rescue "?")
|
|
info = (LonaCraft::ConfigJSON.parse(File.open(LonaCraft.resource("_ModInfo.json"), "rb"){|f| f.read }) rescue nil)
|
|
mod = info.is_a?(Hash) ? info["version"].to_s : "?"
|
|
head = []
|
|
head << "LonaCraft crash trace (Scripts/05_Config.rb LonaCraft.trace), game run started #{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"
|
|
head << "Game: #{game} Mod: LonaCraft #{mod} Config: debug #{debug?}, trace #{Config.get("trace", true)}"
|
|
head << "Each line is flushed and the file closed at once: after a crash the last line is the last step reached. Previous run: #{prev}"
|
|
text = ""
|
|
head.each{|l|
|
|
s = l.to_s.dup
|
|
s.force_encoding("ASCII-8BIT")
|
|
text << s << "\n"
|
|
}
|
|
File.open(path, "wb"){|f|
|
|
f.write(text)
|
|
f.flush
|
|
}
|
|
nil
|
|
rescue StandardError
|
|
nil
|
|
end
|
|
|
|
# "mem private 812MB ws 640MB peak private 901MB peak ws 700MB, gc 345"
|
|
# and, with +objects+, ObjectSpace :TOTAL and :FREE (walks the heap).
|
|
def self.trace_mem(objects = false)
|
|
parts = []
|
|
pm = trace_process_memory
|
|
parts << pm if pm
|
|
if objects && ObjectSpace.respond_to?(:count_objects)
|
|
c = ObjectSpace.count_objects
|
|
parts << "objects total #{c[:TOTAL]} free #{c[:FREE]}"
|
|
end
|
|
parts << "gc #{GC.count}" if GC.respond_to?(:count)
|
|
parts.join(", ")
|
|
rescue StandardError => e
|
|
"mem ? (#{e.class})"
|
|
end
|
|
|
|
# This process's memory (GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS:
|
|
# [2] peak working set, [3] working set, [8] private, [9] peak private).
|
|
def self.trace_process_memory
|
|
if @trace_pmi.nil?
|
|
@trace_pmi = false
|
|
[["kernel32", "K32GetProcessMemoryInfo"], ["psapi", "GetProcessMemoryInfo"]].each{|dll, name|
|
|
begin
|
|
@trace_pmi = Win32API.new(dll, name, "ipi", "i")
|
|
break
|
|
rescue StandardError, LoadError
|
|
end
|
|
}
|
|
end
|
|
return nil unless @trace_pmi
|
|
buf = [40].pack("L") + ("\0" * 36)
|
|
return nil if @trace_pmi.call(-1, buf, 40) == 0
|
|
v = buf.unpack("L10")
|
|
mb = 1024 * 1024
|
|
"mem private #{v[8] / mb}MB ws #{v[3] / mb}MB peak private #{v[9] / mb}MB peak ws #{v[2] / mb}MB"
|
|
rescue StandardError, LoadError
|
|
nil
|
|
end
|
|
|
|
# "<label> Bitmap 296x360 obj 0x0A1B2C30 addr_ok": size, Ruby object
|
|
# address, and with +check+ the game's failsafe flag (Bitmap#initialize
|
|
# in 5100_LonaBitmapChanger_hugememmonkeyfix.rb sets @replace_row_address
|
|
# when the bitmap's memory went past the Fixnum range): addr_ok or
|
|
# ADDR_BIGNUM. Bitmaps not made by Bitmap.new (snapshots) are not checked.
|
|
def self.trace_bitmap(label, bmp, check = true)
|
|
return nil unless trace_on?
|
|
trace{
|
|
if bmp.nil?
|
|
"#{label} Bitmap nil"
|
|
elsif bmp.disposed?
|
|
"#{label} Bitmap DISPOSED"
|
|
else
|
|
flag = check ? (bmp.instance_variable_get(:@replace_row_address).nil? ? "addr_ok" : "ADDR_BIGNUM") : "not checked"
|
|
format("%s Bitmap %dx%d obj 0x%08X %s", label, bmp.width, bmp.height, bmp.__id__ * 2, flag)
|
|
end
|
|
}
|
|
end
|
|
|
|
# "ERROR <where>: <class> <message> @ <first backtrace line>"
|
|
def self.trace_error(where, e)
|
|
return nil unless trace_on?
|
|
trace{ "ERROR #{where}: #{e.class} #{e.message} @ #{(e.backtrace || []).first}" }
|
|
end
|
|
end
|