Module: Lich::Gemstone::Combat::Definitions::Supplements

Extended by:
Common::UserDefs
Defined in:
documented/gemstone/combat/defs/supplements.rb

Overview

Reads and compiles player-supplied combat definitions from a YAML file at DATA_DIR/combat/defs.yaml.

Entries are compiled into the same Struct objects the shipped tables use, allowing them to be spliced into the assembly step and included in every derived lookup, detector, and PatternGate rebuild. The supplement file is re-read when its modification time changes, and reset! forces a re-read regardless. Reloads never touch shipped constants; with no file present every reader returns an empty frozen array.

Validation, timeout-bounded regex compilation, reporting, and memoization are shared with Lich::Common::UserDefs. One bad entry never disables the rest; every rejection names the kind, index, value, reason, and consequence.

Constant Summary collapse

MESSAGE_PREFIX =
'[combat.defs]'
ATTACK_SLOTS =

Where the assembly points may place a supplemental attack. Match order is load-bearing (see attacks.rb ALL_ATTACKS), so the player picks a slot rather than a position.

%i[priority generic third_person].freeze
DEFAULT_ATTACK_SLOT =
:generic
TOKENS =

Markup-tolerance tokens a pattern string may carry. Expanded to the same fragments the shipped defs interpolate, so user patterns survive the live XML feed without seeing the fragments themselves.

{
  '{{MK_PRE}}'  => MK_PRE,
  '{{MK_POST}}' => MK_POST
}.freeze
TOKEN_PATTERN =

Matches markup-tolerance tokens in pattern strings, e.g. {MK_PRE} or {MK_POST}.

Examples:

"You attack {{MK_PRE}}target{{MK_POST}}".scan(TOKEN_PATTERN) #=> ["{{MK_PRE}}", "{{MK_POST}}"]

Returns:

  • (Regexp)

See Also:

/\{\{[A-Z_]+\}\}/.freeze
NAME_PATTERN =

Matches valid definition names: lowercase identifier starting with a letter, followed by letters, digits, or underscores.

Examples:

"ice_lance".match?(NAME_PATTERN) #=> true
"IceLance".match?(NAME_PATTERN) #=> false

Returns:

  • (Regexp)
/\A[a-z][a-z0-9_]*\z/.freeze
FLARE_FLAGS =

The three boolean flags that control flare behavior: whether the flare deals damage, affects an area, or spawns minions.

Returns:

See Also:

  • #validate_flare_flags
%w[damaging aoe spawns].freeze
EMPTY =

Frozen empty array returned by readers when a kind is not present in the supplement file or its def module is not loaded.

Returns:

  • (Array)
[].freeze
CAPTURE_TYPES =

Message payload building blocks. A capture maps a payload key to a named capture with a type; a value is a literal scalar. Keys the engine adds itself cannot be set from the file. Deliberately no boolean: game text never carries a literal true/false to capture, it carries one line for the on state and another for the off state. A boolean fact -- including the shipped contracts that want one (haze_703, rebuke_1614, arcane_reflex) -- is therefore written as two entries for the same event, each with the literal under values:. The example file shows the pair, and the rejection for type: boolean points at it.

%w[string integer symbol].freeze
RESERVED_PAYLOAD_KEYS =

Payload keys that Lich sets itself and cannot be overridden in a supplement message definition.

Returns:

See Also:

  • #validate_payload_key
%w[raw].freeze
USER_PREFIX =

New families and events must carry this prefix so a future shipped name can never collide with a player's file on upgrade.

'user_'
DEF_FILE_PATTERN =

Every loaded def file, in load order: what ;hmr combat/defs/ matches, minus this module's own file (re-reading it would reset the memo a second time and re-extend UserDefs for no gain) and minus pattern_gate.rb: it defines the Table struct, and Struct.new yields a fresh class each run, so re-executing it would leave the table of a def file that failed to reload -- the one this method promises stays live -- an instance of a class the Table constant no longer names.

%r{[/\\]gemstone[/\\]combat[/\\]defs[/\\](?!supplements\.rb\z|pattern_gate\.rb\z)[^/\\]+\.rb\z}.freeze

Constants included from Common::UserDefs

Common::UserDefs::REGEX_TIMEOUT_SECONDS

Class Method Summary collapse

Methods included from Common::UserDefs

apply_regexes, extended, reset!

Class Method Details

.assembled!(kind) ⇒ void

This method returns an undefined value.

Records that one def module has just assembled its table from the current file, so stale? answers for the tables the parser matches against rather than for the document cache. Called by each def module at the point it splices the supplements in -- at require time and again on every reload, which are the only two ways a table is built. Inspecting a reader (loaded, summary) deliberately does not call it.

Recorded per kind, because reload_defs! reports a def file that fails to load and carries on with the rest: one shared stamp let the files that did reload answer for the one that did not, so stale? went false while that module's previous table was still live and the login check never retried it.

Parameters:

  • kind (Symbol) —

    the caller's own kind, e.g. :statuses



231
232
233
234
235
236
237
238
# File 'documented/gemstone/combat/defs/supplements.rb', line 231

def assembled!(kind)
  # The stamp is the mtime the DOCUMENT was parsed at, not a fresh
  # stat: the caller's table was built from that document, and an
  # edit landing between its reader call and this line would
  # otherwise be recorded as assembled while the table is still
  # behind the file, and the login check would skip the reload.
  @assembled_mtimes[kind.to_sym] = @loaded_mtime
end

.attacks(slot = DEFAULT_ATTACK_SLOT) ⇒ Array<Attacks::AttackDef>

Supplemental attack defs for one slot.

Parameters:

  • slot (Symbol) (defaults to: DEFAULT_ATTACK_SLOT) —

    one of ATTACK_SLOTS

Returns:

Raises:

  • (ArgumentError)


187
188
189
190
191
# File 'documented/gemstone/combat/defs/supplements.rb', line 187

def attacks(slot = DEFAULT_ATTACK_SLOT)
  raise ArgumentError, "unknown attack slot #{slot.inspect}" unless ATTACK_SLOTS.include?(slot)

  memoize(:attacks)[slot]
end

.flares ⇒ Array<Flares::FlareDef>

Returns frozen.

Returns:



194
# File 'documented/gemstone/combat/defs/supplements.rb', line 194

def flares = memoize(:flares)

.loaded ⇒ Hash{Symbol=>Object}

What the file defined, by kind and name: summary answers "did my file load", this answers "did it load what I meant". A name here that the shipped tables also carry has extended that def; one they do not is a new def of the player's own. Attacks are grouped by slot and messages by family, since those decide where the rows splice and a wrong one is invisible in the counts. Kinds the file does not mention are left out.

Returns:

  • (Hash{Symbol=>Object})


290
291
292
293
294
295
296
297
298
# File 'documented/gemstone/combat/defs/supplements.rb', line 290

def loaded
  {
    attacks: ATTACK_SLOTS.to_h { |s| [s, attacks(s).map(&:name)] }.reject { |_slot, names| names.empty? },
    flares: flares.map(&:name),
    statuses: statuses.map(&:name),
    outcomes: outcomes.map(&:type),
    messages: memoize(:messages).transform_values { |rows| rows.map(&:first) }
  }.reject { |_kind, entries| entries.empty? }
end

.message_families ⇒ Array<Symbol>

Every family name the file declares, shipped or new.

Returns:

  • (Array<Symbol>) —

    frozen



213
# File 'documented/gemstone/combat/defs/supplements.rb', line 213

def message_families = memoize(:messages).keys.freeze

.messages(family) ⇒ Array<Array(Symbol, Regexp, Proc)>

Supplemental message rows for one family, as the [event, pattern, data] triples Definitions::Messages.family takes. Empty for a family the file does not mention.

Parameters:

  • family (Symbol)

Returns:

  • (Array<Array(Symbol, Regexp, Proc)>) —

    frozen



208
# File 'documented/gemstone/combat/defs/supplements.rb', line 208

def messages(family) = memoize(:messages).fetch(family.to_sym, EMPTY)

.notify_reloaded(reloaded) ⇒ void

This method returns an undefined value.

The reload contract's last two steps, after every table has rebound: re-evaluate message subscriptions against the new table (a script may have subscribed to an event the file only now defines), then tell subscribers the definitions changed so any that enumerate event names can re-register. Named subscriptions are idempotent, so re-registering never stacks.



350
351
352
353
354
355
356
# File 'documented/gemstone/combat/defs/supplements.rb', line 350

def notify_reloaded(reloaded)
  combat = Lich::Gemstone::Combat
  combat::Messages.refresh! if combat.const_defined?(:Messages, false)
  Lich::Common::Events.emit('combat.definitions_reloaded',
                            { files: reloaded.map { |f| File.basename(f) }.freeze,
                              supplements: summary.freeze })
end

.outcomes ⇒ Array<Outcomes::OutcomeDef>

Returns frozen.

Returns:



200
# File 'documented/gemstone/combat/defs/supplements.rb', line 200

def outcomes = memoize(:outcomes)

.path ⇒ String

The supplement file. Defaults to DATA_DIR/combat/defs.yaml; assignable for tools and specs.

Returns:



139
140
141
# File 'documented/gemstone/combat/defs/supplements.rb', line 139

def path
  @path ||= File.join(DATA_DIR, 'combat', 'defs.yaml')
end

.path=(new_path) ⇒ Object

Parameters:

  • new_path (String, nil) —

    nil restores the default



144
145
146
147
148
149
150
151
# File 'documented/gemstone/combat/defs/supplements.rb', line 144

def path=(new_path)
  @path = new_path
  @loaded_mtime = nil
  # Every table was assembled from the old path, so none of them
  # answers for the new one.
  @assembled_mtimes = {}
  reset!
end

.present? ⇒ Boolean

True when the file exists on disk.

Returns:

  • (Boolean)


154
# File 'documented/gemstone/combat/defs/supplements.rb', line 154

def present? = File.file?(path)

.reload_defs!(notify: true) ⇒ Array<String>

Re-reads the supplement file and re-executes every loaded def file so each rebinds its TABLE from shipped defs plus the current supplements. Equivalent to ;hmr combat/defs/ with Ruby's constant-redefinition warnings silenced. A file that fails to load is reported and skipped; because each def module binds its table last and in one assignment, its previous complete table stays live.

Parameters:

  • notify (Boolean) (defaults to: true) —

    run notify_reloaded at the end. A caller that holds a lock the subscribers must not run under (the Tracker's ingestion lock) passes false and notifies itself once it has let go.

Returns:

  • (Array<String>) —

    the files that reloaded cleanly



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'documented/gemstone/combat/defs/supplements.rb', line 323

def reload_defs!(notify: true)
  reset!
  @lock.synchronize { @reported_payloads = [] }
  files = $LOADED_FEATURES.grep(DEF_FILE_PATTERN)
  reloaded = []
  verbose = $VERBOSE
  $VERBOSE = nil
  files.each do |file|
    load(file)
    reloaded << file
  rescue ScriptError, StandardError => e
    report("#{File.basename(file)} failed to reload: #{e.class}: #{e.message}. Its previous definitions remain in effect.")
  end
  $VERBOSE = verbose
  report_debug("reloaded #{reloaded.size} def files; supplements: #{summary}")
  notify_reloaded(reloaded) if notify
  reloaded
end

.report_match_timeout(pattern) ⇒ void

This method returns an undefined value.

Reports a pattern that exceeded its evaluation budget while matching, once per pattern source, through UserDefs' own dedup set (cleared by reset!, so a reload reports again). Compile-time timeouts are already reported by the validator; this is the match-time path, where the scanner skips the pattern for that line and carries on with the rest.

Parameters:

  • pattern (Regexp) —

    the pattern that timed out



249
# File 'documented/gemstone/combat/defs/supplements.rb', line 249

def report_match_timeout(pattern) = report_timeout(pattern)

.report_union_failure(label, error) ⇒ void

This method returns an undefined value.

Reports that a set of patterns could not be combined into one detector regex. Only the (unused) compatibility detectors build such a union; matching itself is per pattern, so this costs nothing but the detector.

Parameters:

  • label (String) —

    which table, e.g. 'statuses'

  • error (RegexpError)


259
260
261
262
263
264
# File 'documented/gemstone/combat/defs/supplements.rb', line 259

def report_union_failure(label, error)
  report("the #{label} detector could not be built (#{error.message.split(':').first}). " \
         'Matching is unaffected; only the unused compatibility detector is nil. ' \
         'A pattern with a numbered backreference (\\1) cannot be combined -- use a named ' \
         'capture and \\k<name> instead.')
end

.stale? ⇒ Boolean

True when the file on disk (present or not) differs from what the current def tables were assembled from, so a reload_defs! would change something. Cheap: one stat.

Deliberately NOT the document cache's stamp (@loaded_mtime): reading a supplement re-parses the file, which every reader does, but only a def module rebuilds the table the parser matches against. Sharing one stamp let an inspection call -- loaded or summary, the very things a player runs after an edit -- answer "not stale" while the new definition was still unrecognised, and the login-time reload then skipped it.

True when ANY assembled kind is behind the file, so a reload in which one def file failed still reports stale and gets retried. Only the kinds that have assembled are compared: a kind whose module was never loaded has no table to be out of date, and counting it would report stale forever. Before any def module has loaded there is nothing to answer for, which reads as stale so a reload is not skipped; the one caller (Tracker, at login) runs long after they are required.

Returns:

  • (Boolean)


176
177
178
179
180
181
# File 'documented/gemstone/combat/defs/supplements.rb', line 176

def stale?
  current = present? ? File.mtime(path) : nil
  return true if @assembled_mtimes.empty?

  @assembled_mtimes.each_value.any? { |stamp| stamp != current }
end

.statuses ⇒ Array<Statuses::StatusDef>

Returns frozen.

Returns:



197
# File 'documented/gemstone/combat/defs/supplements.rb', line 197

def statuses = memoize(:statuses)

.summary ⇒ Hash{Symbol=>Integer}

Counts per kind, for debug output and support: the first thing to check when a report may stem from a player's own file.

Returns:

  • (Hash{Symbol=>Integer})


270
271
272
273
274
275
276
277
278
# File 'documented/gemstone/combat/defs/supplements.rb', line 270

def summary
  {
    attacks: ATTACK_SLOTS.sum { |s| attacks(s).size },
    flares: flares.size,
    statuses: statuses.size,
    outcomes: outcomes.size,
    messages: memoize(:messages).values.sum(&:size)
  }
end