Module: Lich::Gemstone::Combat::Parser

Defined in:
documented/gemstone/combat/parser.rb

Overview

Core parsing methods for combat events from the XML game feed.

Extracts attacks, damage, outcomes, weapon states, and status effects from hunt log lines with performance-optimized pattern matching.

Constant Summary collapse

/<a exist="(?<id>[^"]+)" noun="(?<noun>[^"]+)">(?<name>[^<]+)<\/a>/i.freeze
/<a exist="(?<id>[^"]+)" noun="(?<noun>[^"]+)">(?<name>[^<]+)\z/i.freeze
BOLD_WRAPPER_PATTERN =

Bold tag pattern - creatures are wrapped in bold tags Non-greedy match to avoid spanning multiple creatures Allow zero or more characters before tag (e.g., "a creature" or just "creature")

/<pushBold\/>([^<]*<a exist="[^"]+"[^>]+>[^<]+<\/a>)<popBold\/>/i.freeze
SELF_TARGET_PATTERN =

A target capture that refers to US rather than a creature. Anchored at the start of the capture: real forms observed in session logs are "you", "your " and tails like "you with its tusk" - but NOT a creature whose name merely contains the word ("a youngling"), hence the \b and the anchor.

/\A(?:you|your)\b/i.freeze
SELF_IN_PATTERN =

Some inbound defs name us in the pattern LITERAL rather than in a target capture (" springs from the shadows and strikes at you!", "... plants ... near you"). They have an attacker capture and no target capture, so without this they too fall through to the line-scan and self-attribute. A def that captures an attacker and addresses "you"/"your" in its own source is aimed at us by construction.

/\b(?:at|towards?|upon|around|near|on)\s+your?\b/i.freeze
SWING_WEAPON_PATTERN =
/You(?: take aim and)? (?:swing|fire) (?:an? |your |some )?(?<weapon>[^<]+?) at (?=<|\S)/.freeze

Class Method Summary collapse

Class Method Details

.extract_attacker_from_match(match) ⇒ Object

Attacker from a third-person def's (?...) capture. Unlike targets, player attackers have NEGATIVE exist ids, so no id sign check; plain text (pre-stripped logs) falls back to name.



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'documented/gemstone/combat/parser.rb', line 208

def extract_attacker_from_match(match)
  return nil unless match.names.include?('attacker')

  text = match[:attacker]
  return nil if text.nil? || text.strip.empty?

  # The LAST link: a flavor prefix can carry the attacker's own
  # pronoun link first ("Froth bubbling on <his> lips, <a tattooed
  # gigas berserker> swings..." - hunt log 2026-09-07 recorded the
  # attacker as "his").
  links = text.to_enum(:scan, TARGET_LINK_PATTERN).map { Regexp.last_match }
  # A possessive INSIDE the link ("<a>flayed gigas disciple's</a>
  # power warps the air") leaves the capture ending mid-link: the
  # def's 's sits inside the <a>. Take the unterminated link too.
  links << Regexp.last_match if links.empty? && OPEN_LINK_TAIL_PATTERN.match(text)
  if (link = links.last)
    { id: link[:id].to_i, noun: link[:noun], name: link_name(link) }
  else
    { name: strip_links(text).strip }
  end
end

.extract_creature_target(line) ⇒ Object

Extract creature target (must be wrapped in bold tags)



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'documented/gemstone/combat/parser.rb', line 369

def extract_creature_target(line)
  # Cheap gate: the wrapper pattern can't match without the bold tag,
  # and the substring check avoids two regexes on most lines
  return nil unless line.include?('<pushBold/>')

  # Check if line contains a bolded link
  bold_match = BOLD_WRAPPER_PATTERN.match(line)
  return nil unless bold_match

  # Extract the link from within the bold tags
  link_text = bold_match[1]
  link_match = TARGET_LINK_PATTERN.match(link_text)
  return nil unless link_match

  id = link_match[:id].to_i
  return nil if id <= 0 # Skip invalid IDs

  {
    id: id,
    noun: link_match[:noun],
    name: link_name(link_match)
  }
end

.extract_target_from_line(line) ⇒ Hash?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Extracts a creature target from an attack line by scanning for bolded links.

Only creatures wrapped in bold tags are accepted as valid targets; non-bolded links (equipment, items, or other non-combatants) are ignored. Returns nil if no bolded creature link is found or the link ID is invalid (zero or negative).

Parameters:

  • line (String) —

    a line from the game feed (may contain XML markup)

Returns:

  • (Hash, nil) —

    a hash with :id (Integer), :noun (String), :name (String), or nil if no valid bolded creature target exists

See Also:

  • #extract_creature_target


432
433
434
435
436
# File 'documented/gemstone/combat/parser.rb', line 432

def extract_target_from_line(line)
  # ONLY accept bolded creatures as targets
  # Non-bolded links are equipment, objects, or other non-combatants
  extract_creature_target(line)
end

.extract_target_from_match(match) ⇒ Object

Try to extract target from regex match first, then from line



394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'documented/gemstone/combat/parser.rb', line 394

def extract_target_from_match(match)
  return nil unless match.names.include?('target')
  target_text = match[:target]
  return nil if target_text.nil? || target_text.strip.empty?

  # Look for creature in target text. A possessive capture ends at
  # the apostrophe INSIDE the link text ("<a ...>human robber" + "'s"
  # outside), so the closing tag falls beyond the capture and
  # TARGET_LINK_PATTERN cannot match - bleed/trickle ticks were
  # resolving to no target and recording as foreign (Rysk logs
  # 2026-09-11: 10 bleed ticks on named creatures, all unattributed).
  # Fall back to the open-tail form, as the attacker path does.
  if (target_match = TARGET_LINK_PATTERN.match(target_text) ||
                     OPEN_LINK_TAIL_PATTERN.match(target_text))
    id = target_match[:id].to_i
    return nil if id < 0

    return {
      id: id,
      noun: target_match[:noun],
      name: link_name(target_match)
    }
  end

  nil
end

.inbound_attack?(line) ⇒ Boolean

True when this line is an attack aimed at US. Used by the processor to keep the attacker's own link out of the target-switcher (see the inbound_line note there).

Returns:

  • (Boolean)


193
194
195
196
197
198
199
200
201
202
203
# File 'documented/gemstone/combat/parser.rb', line 193

def inbound_attack?(line)
  table = Definitions::Attacks.table
  return false if table.rejects?(line)

  table.lookup.each do |pattern, name|
    if (match = Definitions::PatternGate.safe_match(pattern, line))
      return self_target?(match) || Definitions::Attacks::ROOM_TARGETED.include?(name)
    end
  end
  false
end

A creature's display name from its link. The game sometimes puts the possessive INSIDE the link ("grim gigas skald's mastery of music"), which registered a second creature named "grim gigas skald's" (hunt log 2026-09-07). Same id, same creature: strip it. A hidden adjective leaves a doubled space ("halfling cannibal"), squeezed for the same reason.



241
242
243
# File 'documented/gemstone/combat/parser.rb', line 241

def link_name(link)
  link[:name].sub(/'s\z/, '').squeeze(' ').strip
end

.parse_assault_end(line) ⇒ Hash?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Detects the closing line of a single-target multi-round assault bracket.

Matches lines that end sustained attacks on one target: flurry, barrage, pummel, guardant thrusts, and thrash.

Parameters:

  • line (String) —

    a line from the game feed (may contain XML markup)

Returns:

  • (Hash, nil) —

    parsed assault end event or nil if the line does not match

See Also:

  • #parse_assault_start


304
305
306
# File 'documented/gemstone/combat/parser.rb', line 304

def parse_assault_end(line)
  Definitions::Assaults.parse_end(line)
end

.parse_assault_start(line) ⇒ Object

Single-target multi-round assault brackets (flurry, barrage, pummel, guardant thrusts, thrash) - see defs/assaults.rb



291
292
293
# File 'documented/gemstone/combat/parser.rb', line 291

def parse_assault_start(line)
  Definitions::Assaults.parse_start(line)
end

.parse_attack(line) ⇒ Object

Parse attack initiation



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'documented/gemstone/combat/parser.rb', line 51

def parse_attack(line)
  # One table read per call: lookup and gate from the same build
  # even if the defs are hot-reloaded mid-chunk.
  table = Definitions::Attacks.table
  return nil if table.rejects?(line)

  table.lookup.each do |pattern, name|
    if (match = Definitions::PatternGate.safe_match(pattern, line))
      # An inbound attack (creature -> us) names US as its target.
      # Its only creature link is the ATTACKER, so the line-scan
      # fallback below would install the attacker as its own
      # target and apply its damage/crits to itself. Resolve the
      # target as us and stop - never fall through.
      # Environmental / self-inflicted defs (ATTACKERLESS) are
      # damage to us by construction - no attacker, no "you"
      # capture - unless this particular pattern named someone
      # else (a nearby player taking the same tick). They name
      # their source for the ledger: 'environment' (weather) or
      # 'self' (our own gear), so reports can tell them apart.
      attackerless = Definitions::Attacks::ATTACKERLESS.include?(name) &&
                     !(match.names.include?('target') && match[:target])
      if self_target?(match) || attackerless || Definitions::Attacks::ROOM_TARGETED.include?(name)
        attacker = extract_attacker_from_match(match)
        if attackerless
          attacker ||= { name: Definitions::Attacks::ENVIRONMENTAL.include?(name) ? 'environment' : 'self' }
        end
        return {
          name: name,
          target: {},
          inbound: true,
          attacker: attacker,
          damaging: true
        }
      end

      # The fallback is only safe when the def has NO target
      # capture: then the sole creature link on the line really is
      # the target. When a def DID capture a target but it failed
      # to resolve to a creature link, scanning the line would find
      # some other creature (typically the attacker) - so don't.
      attacker = extract_attacker_from_match(match)
      target_info = if match.names.include?('target')
                      extract_target_from_match(match)
                    else
                      extract_target_from_line(line)
                    end
      # Nothing can attack itself. An untargeted def (an AoE like
      # the mastodon's tremors) has no target capture, so the
      # line-scan above returns the only link present - the
      # attacker. Drop it: the event is genuinely untargeted, and
      # the per-target lines that follow bind the real victims.
      target_info = nil if target_info && attacker &&
                           attacker[:id] && target_info[:id] == attacker[:id]
      result = {
        name: name,
        target: target_info || {},
        damaging: true
      }
      # The def NAMED a target but it is not a creature link - a
      # player ("striking Sugiin!"), or a name we cannot resolve.
      # The event is therefore bound to someone who is not a
      # creature, and must never later adopt one: the caster's own
      # bolded props (a summoned ethereal sphere) and room echoes
      # would otherwise fill the empty slot through the
      # target-switcher and take that third party's damage with
      # them (real-feed replay, GSIV-Monstr 2025-09-30).
      if target_info.nil? && match.names.include?('target') &&
         !match[:target].to_s.strip.empty?
        result[:foreign_target] = true
      end
      # Third-person defs capture the attacker (a player link with
      # a negative exist id, or a pushBold-wrapped creature link)
      result[:attacker] = attacker if attacker
      # A NEARBY PLAYER's attack on a creature we can see. When a
      # 3p attack names its actor but that actor is not us and not
      # a creature - a player link (negative id) or a bare name
      # from mid-sentence prose (the paladin weapon_infusion proc
      # names "Heavenscent", not a link) - the whole event belongs
      # to that player. Marked foreign_caster so the processor
      # emits it for observers but never lands its damage on our
      # ledger, the attacker-side mirror of foreign_target
      # (real-feed, GSIV-Nisugi 2026-09-06). Attacks a CREATURE
      # makes on us are :inbound and handled above; those keep
      # their creature-id attacker and are not foreign_caster.
      if attacker && !result[:inbound] &&
         (attacker[:id].to_i < 0 || (attacker[:id].nil? && attacker[:name]))
        result[:foreign_caster] = true
      end
      result[:weapon] = strip_links(match[:weapon]) if match.names.include?('weapon') && match[:weapon]
      # Aimed shots ("You take aim and fire...", "You make a precise
      # attempt to jab...") roll differently from unaimed ones. The
      # defs have captured this all along; it was never surfaced.
      result[:aimed] = true if match.names.include?('aimed') && match[:aimed]
      return result
    end
  end
  nil
end

.parse_damage(line) ⇒ Object

Parse damage amounts using damage definitions



246
247
248
249
# File 'documented/gemstone/combat/parser.rb', line 246

def parse_damage(line)
  result = Definitions::Damage.parse(line)
  result ? result[:damage] : nil
end

.parse_flare(line) ⇒ Object

Parse a flare announce line (weapon scripts, enchants, GEFs, flourishes). Returns name/damaging/aoe/spawns plus the flaring weapon's { id:, name: } when the line links it.



254
255
256
# File 'documented/gemstone/combat/parser.rb', line 254

def parse_flare(line)
  Definitions::Flares.parse(line)
end

.parse_outcome(line) ⇒ Object

Why a swing produced nothing: :evade, :block, :parry, :warded, :miss, :fumble, :hindrance, :confused



260
261
262
# File 'documented/gemstone/combat/parser.rb', line 260

def parse_outcome(line)
  Definitions::Outcomes.parse(line)
end

.parse_resolution(line) ⇒ Object

Roll lines: AS/DS, CS/TD, UAF/UDF, SMR - returns the full breakdown { type:, as:, ds:, avd:, roll:, result: ... }



266
267
268
# File 'documented/gemstone/combat/parser.rb', line 266

def parse_resolution(line)
  Definitions::Resolutions.parse(line)
end

.parse_sequence_end(line) ⇒ Hash?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Detects the closing line of a multi-target action bracket.

Matches lines that end sequences like mstrike volleys, spawned AoE casts, and other damage events that target multiple creatures across consecutive log lines.

Parameters:

  • line (String) —

    a line from the game feed (may contain XML markup)

Returns:

  • (Hash, nil) —

    parsed sequence end event or nil if the line does not match

See Also:

  • #parse_sequence_start


285
286
287
# File 'documented/gemstone/combat/parser.rb', line 285

def parse_sequence_end(line)
  Definitions::Sequences.parse_end(line)
end

.parse_sequence_start(line) ⇒ Object

Multi-TARGET action brackets (mstrike, volley, spawned casts)



271
272
273
# File 'documented/gemstone/combat/parser.rb', line 271

def parse_sequence_start(line)
  Definitions::Sequences.parse_start(line)
end

.parse_spell_loss(line) ⇒ Object

Third-person spell wear-off lines pinned to a spell number (defs/spell_losses.rb). Unlike statuses these apply to players in view as well as creatures, so the subject resolves through ANY link (negative player ids included), falling back to the stripped capture text for plain logs.



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'documented/gemstone/combat/parser.rb', line 345

def parse_spell_loss(line)
  return nil unless Tracker.settings[:track_statuses]

  result = Definitions::SpellLosses.parse(line)
  return nil unless result

  if (link = TARGET_LINK_PATTERN.match(result[:target].to_s))
    result[:id]   = link[:id].to_i
    result[:name] = link[:name]
  else
    result[:id]   = nil
    result[:name] = strip_links(result[:target].to_s).strip
  end
  result
end

.parse_status(line) ⇒ Object

Parse status effects (optional - performance setting)



333
334
335
336
337
338
# File 'documented/gemstone/combat/parser.rb', line 333

def parse_status(line)
  return nil unless Tracker.settings[:track_statuses]

  # Return the full result including action field
  Definitions::Statuses.parse(line)
end

.parse_swing_weapon(line) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Extracts the weapon name from a swing line.

Parses "You swing a [weapon] at..." and "You take aim and fire..." lines to retrieve the weapon in plain text (XML links are stripped). Used to claim pre-swing flares by weapon name.

Examples:

parse_swing_weapon("You swing a sharp kelyn blade at a goblin") #=> "sharp kelyn blade"

Parameters:

  • line (String) —

    a swing line from the game feed

Returns:

  • (String, nil) —

    the weapon name, or nil if the line is not a swing



328
329
330
# File 'documented/gemstone/combat/parser.rb', line 328

def parse_swing_weapon(line)
  SWING_WEAPON_PATTERN.match(line.gsub(%r{</?a\b[^>]*>}, ''))&.[](:weapon)
end

.parse_ucs(line) ⇒ Object

Parse UCS events (position, tierup, smite)



362
363
364
365
366
# File 'documented/gemstone/combat/parser.rb', line 362

def parse_ucs(line)
  return nil unless Tracker.settings[:track_ucs]

  Definitions::UCS.parse(line)
end

.self_target?(match) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Tests whether a regex match captures an attack aimed at the player.

Handles two cases: (1) an explicit target capture matching "you"/"your", and (2) inbound-only defs with no target capture but an attacker capture and literal "you"/"your" in the pattern source itself.

Parameters:

  • match (MatchData) —

    the result of pattern matching an attack line

Returns:

  • (Boolean) —

    true if the attack targets the player

See Also:

  • #parse_attack


176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'documented/gemstone/combat/parser.rb', line 176

def self_target?(match)
  if match.names.include?('target')
    text = match[:target]
    return false if text.nil?

    return SELF_TARGET_PATTERN.match?(strip_links(text).strip)
  end

  # No target capture: inbound only if the def both identifies an
  # attacker and addresses us literally.
  match.names.include?('attacker') &&
    SELF_IN_PATTERN.match?(match.regexp.source)
end

Drop XML link/bold markup from a captured fragment



231
232
233
# File 'documented/gemstone/combat/parser.rb', line 231

def strip_links(text)
  text.gsub(/<[^>]+>/, '')
end