@pkmn/engine 0.1.0-dev.d97c6e03 → 0.1.0-dev.f3aaee39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +67 -56
  2. package/build/pkg/addon.d.ts +1 -1
  3. package/build/pkg/addon.js +7 -6
  4. package/build/pkg/addon.js.map +1 -1
  5. package/build/pkg/data/layout.json +25 -3
  6. package/build/pkg/gen1.d.ts +5 -4
  7. package/build/pkg/gen1.js +46 -30
  8. package/build/pkg/gen1.js.map +1 -1
  9. package/build/pkg/index.d.ts +15 -12
  10. package/build/pkg/index.js.map +1 -1
  11. package/build/pkg/protocol.d.ts +4 -2
  12. package/build/pkg/protocol.js +4 -2
  13. package/build/pkg/protocol.js.map +1 -1
  14. package/build/test/display.js +29 -12
  15. package/build/test/display.js.map +1 -1
  16. package/build.zig +89 -65
  17. package/package.json +26 -16
  18. package/src/bin/install-pkmn-engine +11 -6
  19. package/src/lib/binding/node.zig +45 -140
  20. package/src/lib/binding/wasm.zig +5 -3
  21. package/src/lib/common/battle.zig +17 -0
  22. package/src/lib/common/data.zig +11 -11
  23. package/src/lib/common/debug.zig +21 -11
  24. package/src/lib/common/js.zig +118 -0
  25. package/src/lib/common/optional.zig +60 -0
  26. package/src/lib/common/options.zig +12 -3
  27. package/src/lib/common/protocol.zig +242 -178
  28. package/src/lib/common/rational.zig +353 -0
  29. package/src/lib/common/rng.zig +10 -10
  30. package/src/lib/common/util.zig +12 -0
  31. package/src/lib/gen1/README.md +255 -154
  32. package/src/lib/gen1/calc.zig +427 -0
  33. package/src/lib/gen1/chance.zig +1044 -0
  34. package/src/lib/gen1/data/moves.zig +10 -10
  35. package/src/lib/gen1/data/species.zig +2 -2
  36. package/src/lib/gen1/data/types.zig +3 -3
  37. package/src/lib/gen1/data.zig +64 -38
  38. package/src/lib/gen1/helpers.zig +592 -32
  39. package/src/lib/gen1/mechanics.zig +892 -531
  40. package/src/lib/gen2/README.md +12 -13
  41. package/src/lib/gen2/data/items.zig +3 -3
  42. package/src/lib/gen2/data/moves.zig +1 -1
  43. package/src/lib/gen2/data/species.zig +1 -1
  44. package/src/lib/gen2/data/types.zig +3 -3
  45. package/src/lib/gen2/data.zig +33 -22
  46. package/src/lib/gen2/helpers.zig +9 -11
  47. package/src/lib/gen2/mechanics.zig +5 -4
  48. package/src/lib/pkmn.zig +65 -6
@@ -0,0 +1,427 @@
1
+ const std = @import("std");
2
+
3
+ const pkmn = @import("../pkmn.zig");
4
+
5
+ const common = @import("../common/data.zig");
6
+ const DEBUG = @import("../common/debug.zig").print;
7
+ const optional = @import("../common/optional.zig");
8
+ const protocol = @import("../common/protocol.zig");
9
+ const rational = @import("../common/rational.zig");
10
+ const util = @import("../common/util.zig");
11
+
12
+ const chance = @import("chance.zig");
13
+ const data = @import("data.zig");
14
+ const helpers = @import("helpers.zig");
15
+
16
+ const assert = std.debug.assert;
17
+
18
+ const expect = std.testing.expect;
19
+ const expectEqual = std.testing.expectEqual;
20
+
21
+ const enabled = pkmn.options.calc;
22
+
23
+ const Player = common.Player;
24
+ const Result = common.Result;
25
+ const Choice = common.Choice;
26
+
27
+ const Optional = optional.Optional;
28
+
29
+ const Rational = rational.Rational;
30
+
31
+ const PointerType = util.PointerType;
32
+ const FieldType = util.FieldType;
33
+
34
+ const Actions = chance.Actions;
35
+ const Action = chance.Action;
36
+ const Chance = chance.Chance;
37
+ const Durations = chance.Durations;
38
+ const Duration = chance.Duration;
39
+
40
+ const Rolls = helpers.Rolls;
41
+
42
+ /// Information relevant to damage calculation that occured during a Generation I battle `update`.
43
+ pub const Summaries = extern struct {
44
+ /// Relevant information for Player 1.
45
+ p1: Summary = .{},
46
+ /// Relevant information for Player 2.
47
+ p2: Summary = .{},
48
+
49
+ comptime {
50
+ assert(@sizeOf(Summaries) == 12);
51
+ }
52
+
53
+ /// Returns the `Summary` for the given `player`.
54
+ pub inline fn get(self: anytype, player: Player) PointerType(@TypeOf(self), Summary) {
55
+ assert(@typeInfo(@TypeOf(self)).Pointer.child == Summaries);
56
+ return if (player == .P1) &self.p1 else &self.p2;
57
+ }
58
+ };
59
+
60
+ /// Information relevant to damage calculation that occured during a Generation I battle `update`
61
+ /// for a single player.
62
+ pub const Summary = extern struct {
63
+ /// The computed raw damage values.
64
+ damage: Damage = .{},
65
+
66
+ /// Intermediate raw damage values computed during a calculation.
67
+ pub const Damage = extern struct {
68
+ /// The base computed damage before the damage roll is applied.
69
+ base: u16 = 0,
70
+ /// The final computed damage that gets applied to the Pokémon. May exceed the target's HP
71
+ // (to determine the *actual* damage done compare the target's stored HP before and after).
72
+ final: u16 = 0,
73
+ /// Whether higher damage will saturate / result in the same outcome (e.g. additional damage
74
+ /// gets ignored due to it already breaking a Substitute or causing the target to faint).
75
+ capped: bool = false,
76
+
77
+ // NOTE: 15 bits padding
78
+
79
+ comptime {
80
+ assert(@sizeOf(Damage) == 6);
81
+ }
82
+ };
83
+
84
+ comptime {
85
+ assert(@sizeOf(Summary) == 6);
86
+ }
87
+ };
88
+
89
+ /// TODO
90
+ pub const Overrides = extern struct {
91
+ /// TODO
92
+ actions: Actions = .{},
93
+ /// TODO
94
+ durations: Durations = .{},
95
+
96
+ _: u32 = 0,
97
+
98
+ comptime {
99
+ assert(@sizeOf(Overrides) == 24);
100
+ }
101
+ };
102
+
103
+ /// Allows for forcing the value of specific RNG events during a Generation I battle `update` via
104
+ /// `overrides` and tracks `summaries` of information relevant to damage calculation.
105
+ pub const Calc = struct {
106
+ /// Overrides the normal behavior of the RNG during an `update` to force specific outcomes.
107
+ overrides: Overrides = .{},
108
+ /// Information relevant to damage calculation.
109
+ summaries: Summaries = .{},
110
+
111
+ pub fn overridden(
112
+ self: Calc,
113
+ player: Player,
114
+ comptime field: Action.Field,
115
+ ) ?std.meta.FieldType(Action, field) {
116
+ if (!enabled) return null;
117
+
118
+ const overrides =
119
+ if (player == .P1) self.overrides.actions.p1 else self.overrides.actions.p2;
120
+ const val = @field(overrides, @tagName(field));
121
+ return if (switch (@typeInfo(@TypeOf(val))) {
122
+ .Enum => val != .None,
123
+ .Int => val != 0,
124
+ else => unreachable,
125
+ }) val else null;
126
+ }
127
+
128
+ pub fn modify(self: Calc, player: Player, comptime field: Duration.Field) ?bool {
129
+ if (!enabled) return null;
130
+
131
+ const durations = self.overrides.durations;
132
+ const set = @field(if (player == .P1) durations.p1 else durations.p2, @tagName(field));
133
+ if (set == 0) return null;
134
+
135
+ const actions = self.overrides.actions;
136
+ const overrides = if (player == .P1) actions.p1.durations else actions.p2.durations;
137
+ return @field(overrides, @tagName(field)) != 0;
138
+ }
139
+
140
+ pub fn base(self: *Calc, player: Player, val: u16) void {
141
+ if (!enabled) return;
142
+
143
+ self.summaries.get(player).damage.base = val;
144
+ }
145
+
146
+ pub fn final(self: *Calc, player: Player, val: u16) void {
147
+ if (!enabled) return;
148
+
149
+ self.summaries.get(player).damage.final = val;
150
+ }
151
+
152
+ pub fn capped(self: *Calc, player: Player) void {
153
+ if (!enabled) return;
154
+
155
+ self.summaries.get(player).damage.capped = true;
156
+ }
157
+ };
158
+
159
+ /// Null object pattern implementation of Generation I `Calc` which does nothing, though damage
160
+ /// calculator support should additionally be turned off entirely via `options.calc`.
161
+ pub const NULL = Null{};
162
+
163
+ const Null = struct {
164
+ pub fn overridden(
165
+ self: Null,
166
+ player: Player,
167
+ comptime field: Action.Field,
168
+ ) ?std.meta.FieldType(Action, field) {
169
+ _ = .{ self, player };
170
+ return null;
171
+ }
172
+
173
+ pub fn modify(self: Null, player: Player, comptime field: Duration.Field) ?bool {
174
+ _ = .{ self, player, field };
175
+ return null;
176
+ }
177
+
178
+ pub fn base(self: Null, player: Player, val: u16) void {
179
+ _ = .{ self, player, val };
180
+ }
181
+
182
+ pub fn final(self: Null, player: Player, val: u16) void {
183
+ _ = .{ self, player, val };
184
+ }
185
+
186
+ pub fn capped(self: Null, player: Player) void {
187
+ _ = .{ self, player };
188
+ }
189
+ };
190
+
191
+ pub const Stats = struct {
192
+ frontier: usize = 0,
193
+ updates: usize = 0,
194
+ seen: usize = 0,
195
+ saved: usize = 0,
196
+ };
197
+
198
+ pub const Options = struct {
199
+ actions: Actions = .{},
200
+ seed: ?u64 = null,
201
+ cap: bool = false,
202
+ metronome: bool = false,
203
+ };
204
+
205
+ pub fn transitions(
206
+ battle: anytype,
207
+ c1: Choice,
208
+ c2: Choice,
209
+ allocator: std.mem.Allocator,
210
+ writer: anytype,
211
+ options: Options,
212
+ ) !?Stats {
213
+ var stats: Stats = .{};
214
+
215
+ var actions = options.actions;
216
+ var cap = options.cap;
217
+
218
+ var seen = std.AutoHashMap(Actions, void).init(allocator);
219
+ defer seen.deinit();
220
+ var frontier = std.ArrayList(Actions).init(allocator);
221
+ defer frontier.deinit();
222
+
223
+ var opts = pkmn.battle.options(
224
+ protocol.NULL,
225
+ Chance(Rational(u128)){ .probability = .{}, .actions = actions },
226
+ Calc{ .overrides = .{ .actions = actions, .durations = .{
227
+ .p1 = actions.p1.durations,
228
+ .p2 = actions.p2.durations,
229
+ } } },
230
+ );
231
+
232
+ var b = battle;
233
+ _ = try b.update(c1, c2, &opts);
234
+ stats.updates += 1;
235
+
236
+ var p1 = b.side(.P1);
237
+ var p2 = b.side(.P2);
238
+
239
+ var p: Rational(u128) = .{ .p = 0, .q = 1 };
240
+ try frontier.append(opts.chance.actions);
241
+
242
+ // zig fmt: off
243
+ for (Rolls.metronome(frontier.items[0].p1)) |p1_move| {
244
+ for (Rolls.metronome(frontier.items[0].p2)) |p2_move| {
245
+
246
+ if (!options.metronome and (p1_move != .None or p2_move != .None)) return null;
247
+
248
+ var i: usize = 0;
249
+ assert(frontier.items.len == 1);
250
+ while (i < frontier.items.len) : (i += 1) {
251
+ var template = frontier.items[i];
252
+ opts.calc.overrides.durations = .{
253
+ .p1 = template.p1.durations,
254
+ .p2 = template.p2.durations,
255
+ };
256
+
257
+ try debug(writer, template, true, .{ .color = i, .bold = true, .background = true });
258
+
259
+ var a = Actions{ .p1 = .{ .metronome = p1_move }, .p2 = .{ .metronome = p2_move } };
260
+
261
+ for (Rolls.speedTie(template.p1)) |tie| { a.p1.speed_tie = tie; a.p2.speed_tie = tie;
262
+ for (Rolls.sleep(template.p1, actions.p1)) |p1_slp| { a.p1.durations.sleep = p1_slp;
263
+ for (Rolls.sleep(template.p2, actions.p2)) |p2_slp| { a.p2.durations.sleep = p2_slp;
264
+ for (Rolls.disable(template.p1, actions.p1, p1_slp)) |p1_disable| { a.p1.durations.disable = p1_disable;
265
+ for (Rolls.disable(template.p2, actions.p2, p2_slp)) |p2_disable| { a.p2.durations.disable = p2_disable;
266
+ for (Rolls.confusion(template.p1, actions.p1, p1_slp)) |p1_cfz| { a.p1.durations.confusion = p1_cfz;
267
+ for (Rolls.confusion(template.p2, actions.p2, p1_slp)) |p2_cfz| { a.p2.durations.confusion = p2_cfz;
268
+ for (Rolls.confused(template.p1, p1_cfz)) |p1_cfzd| { a.p1.confused = p1_cfzd;
269
+ for (Rolls.confused(template.p2, p2_cfz)) |p2_cfzd| { a.p2.confused = p2_cfzd;
270
+ for (Rolls.paralyzed(template.p1, p1_cfzd)) |p1_par| { a.p1.paralyzed = p1_par;
271
+ for (Rolls.paralyzed(template.p2, p2_cfzd)) |p2_par| { a.p2.paralyzed = p2_par;
272
+ for (Rolls.attacking(template.p1, actions.p1, p1_par)) |p1_atk| { a.p1.durations.attacking = p1_atk;
273
+ for (Rolls.attacking(template.p2, actions.p2, p2_par)) |p2_atk| { a.p2.durations.attacking = p2_atk;
274
+ for (Rolls.binding(template.p1, actions.p1, p1_par)) |p1_bind| { a.p1.durations.binding = p1_bind;
275
+ for (Rolls.binding(template.p2, actions.p2, p2_par)) |p2_bind| { a.p2.durations.binding = p2_bind;
276
+ for (Rolls.duration(template.p1, p1_par)) |p1_dur| { a.p1.duration = p1_dur;
277
+ for (Rolls.duration(template.p2, p2_par)) |p2_dur| { a.p2.duration = p2_dur;
278
+ for (Rolls.hit(template.p1, p1_par)) |p1_hit| { a.p1.hit = p1_hit;
279
+ for (Rolls.hit(template.p2, p2_par)) |p2_hit| { a.p2.hit = p2_hit;
280
+ for (Rolls.psywave(template.p1, p1, p1_hit)) |p1_psywave| { a.p1.psywave = p1_psywave;
281
+ for (Rolls.psywave(template.p2, p2, p2_hit)) |p2_psywave| { a.p2.psywave = p2_psywave;
282
+ for (Rolls.moveSlot(template.p1, p1_hit)) |p1_slot| { a.p1.move_slot = p1_slot;
283
+ for (Rolls.moveSlot(template.p2, p2_hit)) |p2_slot| { a.p2.move_slot = p2_slot;
284
+ for (Rolls.multiHit(template.p1, p1_hit)) |p1_multi| { a.p1.multi_hit = p1_multi;
285
+ for (Rolls.multiHit(template.p2, p1_hit)) |p2_multi| { a.p2.multi_hit = p2_multi;
286
+ for (Rolls.secondaryChance(template.p1, p1_hit)) |p1_sec| { a.p1.secondary_chance = p1_sec;
287
+ for (Rolls.secondaryChance(template.p2, p2_hit)) |p2_sec| { a.p2.secondary_chance = p2_sec;
288
+ for (Rolls.criticalHit(template.p1, p1_hit)) |p1_crit| { a.p1.critical_hit = p1_crit;
289
+ for (Rolls.criticalHit(template.p2, p2_hit)) |p2_crit| { a.p2.critical_hit = p2_crit;
290
+
291
+ var p1_dmg = Rolls.damage(template.p1, p1_hit);
292
+ while (p1_dmg.min < p1_dmg.max) : (p1_dmg.min += 1) {
293
+ a.p1.damage = @intCast(p1_dmg.min);
294
+ var p1_min: u8 = 0;
295
+
296
+ var p2_dmg = Rolls.damage(template.p2, p2_hit);
297
+ while (p2_dmg.min < p2_dmg.max) : (p2_dmg.min += 1) {
298
+ a.p2.damage = @intCast(p2_dmg.min);
299
+
300
+ opts.calc.overrides.actions = a;
301
+ opts.chance = .{ .probability = .{}, .actions = actions };
302
+ const q = &opts.chance.probability;
303
+
304
+ b = battle;
305
+ _ = try b.update(c1, c2, &opts);
306
+ stats.updates += 1;
307
+
308
+ const p1_max: u8 = @intCast(p1_dmg.min);
309
+ const p2_max: u8 = @intCast(p2_dmg.min);
310
+ _ = cap;
311
+
312
+ // var p1_max = if (p1_min != 0) p1_min else
313
+ // try Rolls.coalesce(.P1, @intCast(u8, p1_dmg.min), &opts.calc.summaries, cap);
314
+ // var p2_max =
315
+ // try Rolls.coalesce(.P2, @intCast(u8, p2_dmg.min), &opts.calc.summaries, cap);
316
+
317
+ if (opts.chance.actions.matches(template)) {
318
+ if (!opts.chance.actions.eql(a)) {
319
+ try debug(writer, opts.chance.actions, false, .{ .color = i, .dim = true });
320
+
321
+ p1_min = p1_max;
322
+ p2_dmg.min = p2_max;
323
+ continue;
324
+ }
325
+
326
+ try debug(writer, opts.chance.actions, false, .{ .color = i });
327
+
328
+ for (p1_dmg.min..@as(u9, p1_max) + 1) |p1d| {
329
+ for (p2_dmg.min..@as(u9, p2_max) + 1) |p2d| {
330
+ var acts = opts.chance.actions;
331
+ acts.p1.damage = @intCast(p1d);
332
+ acts.p2.damage = @intCast(p2d);
333
+ if ((try seen.getOrPut(acts)).found_existing) {
334
+ err("already seen {}", .{acts}, options.seed);
335
+ return error.TestUnexpectedResult;
336
+ }
337
+ }
338
+ }
339
+
340
+ if (p1_max != p1_dmg.min) try q.update(p1_max - p1_dmg.min + 1, 1);
341
+ if (p2_max != p2_dmg.min) try q.update(p2_max - p2_dmg.min + 1, 1);
342
+ try p.add(q);
343
+ stats.saved += 1;
344
+
345
+ if (p.q < p.p) {
346
+ err("improper fraction {}", .{p}, options.seed);
347
+ return error.TestUnexpectedResult;
348
+ }
349
+ } else {
350
+ try debug(writer, opts.chance.actions, false, .{ .dim = true });
351
+
352
+ if (!matches(opts.chance.actions, i, frontier.items)) {
353
+ try frontier.append(opts.chance.actions);
354
+
355
+ try debug(writer, opts.chance.actions, true, .{
356
+ .color = frontier.items.len - 1,
357
+ .dim = true,
358
+ .background = true
359
+ });
360
+ }
361
+ }
362
+
363
+ p1_min = p1_max;
364
+ p2_dmg.min = p2_max;
365
+ }
366
+
367
+ assert(p1_min > 0 or p1_dmg.min == 0);
368
+ p1_dmg.min = p1_min;
369
+
370
+ }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
371
+ }
372
+
373
+ assert(frontier.items.len == i);
374
+ stats.frontier = @max(stats.frontier, i);
375
+ frontier.shrinkRetainingCapacity(1);
376
+
377
+ }}
378
+ // zig fmt: on
379
+
380
+ stats.seen = seen.count();
381
+
382
+ p.reduce();
383
+ if (p.p != 1 or p.q != 1) {
384
+ err("expected 1, found {}", .{p}, options.seed);
385
+ return error.TestExpectedEqual;
386
+ }
387
+
388
+ return stats;
389
+ }
390
+
391
+ inline fn matches(actions: Actions, i: usize, frontier: []Actions) bool {
392
+ for (frontier, 0..) |f, j| {
393
+ // TODO: is skipping this redundant check worth it?
394
+ if (i == j) continue;
395
+ if (f.matches(actions)) return true;
396
+ }
397
+ return false;
398
+ }
399
+
400
+ fn err(comptime fmt: []const u8, v: anytype, seed: ?u64) void {
401
+ const w = std.io.getStdErr().writer();
402
+ w.print(fmt, v) catch return;
403
+ if (seed) |s| return w.print("{}\n", .{s}) catch return;
404
+ return w.writeByte('\n') catch return;
405
+ }
406
+
407
+ const Style = struct {
408
+ color: ?usize = null,
409
+ bold: bool = false,
410
+ background: bool = false,
411
+ dim: bool = false,
412
+ };
413
+
414
+ fn debug(writer: anytype, actions: Actions, shape: bool, style: Style) !void {
415
+ _ = .{ writer, actions, shape, style };
416
+ // const mod: usize = if (style.dim) 2 else 1;
417
+ // const background: usize = if (style.background) 4 else 3;
418
+ // const color: usize = if (style.color) |c| (c % 6) + 1 else 7;
419
+ // if (style.dim or style.bold) try writer.print("\x1b[{d}m", .{mod});
420
+ // try writer.print("\x1b[{d}{d}m", .{ background, color });
421
+ // try actions.fmt(writer, shape);
422
+ // try writer.writeAll("\x1b[0m\n");
423
+ // DEBUG
424
+ // if (style.dim) try writer.writeAll(" ");
425
+ // try actions.fmt(writer, shape);
426
+ // try writer.writeByte('\n');
427
+ }