@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,353 @@
1
+ const builtin = @import("builtin");
2
+ const std = @import("std");
3
+
4
+ const assert = std.debug.assert;
5
+ const expect = std.testing.expect;
6
+ const expectEqual = std.testing.expectEqual;
7
+ const expectError = std.testing.expectError;
8
+
9
+ /// Specialization of a rational number used by the engine to compute probabilties.
10
+ /// For performance reasons the rational is only reduced lazily and thus `reduce` must be
11
+ /// invoked explicitly before reading.
12
+ pub fn Rational(comptime T: type) type {
13
+ return extern struct {
14
+ const Self = @This();
15
+
16
+ /// Numerator. Must always be >= 1. Not guaranteed to be reduced in all cases.
17
+ p: T = 1,
18
+ /// Denominator. Must always be >= 1. Not guaranteed to be reduced in all cases.
19
+ q: T = 1,
20
+
21
+ // With floats we can't rely on an overflow bit to let us know when to reduce, so we instead
22
+ // start reducing when we get sufficiently close to the limit of the mantissa (in our domain
23
+ // we expect updates to involve numbers < 2**10, so we should be safe not reducing before we
24
+ // are 2**10 away from "overflowing" the mantissa)
25
+ const REDUCE = if (@typeInfo(T) == .Float)
26
+ std.math.pow(T, 2, std.math.floatMantissaBits(T) - 10)
27
+ else
28
+ 0;
29
+
30
+ /// Possible error returned by operations on the Rational.
31
+ pub const Error = switch (@typeInfo(T)) {
32
+ .Int => error{Overflow},
33
+ .Float => error{},
34
+ else => unreachable,
35
+ };
36
+
37
+ /// Resets the rational back to 1.
38
+ pub fn reset(r: *Self) void {
39
+ r.p = 1;
40
+ r.q = 1;
41
+ }
42
+
43
+ /// Update the rational by multiplying its numerator by p and its denominator by q.
44
+ /// Both p and q must be >= 1, and if computable at comptime must have no common factors.
45
+ pub fn update(r: *Self, p: anytype, q: anytype) Error!void {
46
+ // FIXME
47
+ // std.debug.print("({d}/{d}) * ", .{p, q});
48
+ assert(p >= 1);
49
+ assert(q >= 1);
50
+
51
+ // If our parameters are not fully reduced they may prematurely
52
+ // cause overflow/loss of precision after the multiplication below
53
+ assert(switch (@typeInfo(@TypeOf(p, q))) {
54
+ .ComptimeInt, .ComptimeFloat => comptime gcd(p, q),
55
+ else => 1,
56
+ } == 1);
57
+
58
+ switch (@typeInfo(T)) {
59
+ .Int => {
60
+ // Greedily attempt to multiply and if it fails, reduce and try again
61
+ r.multiplication(p, q) catch |err| switch (err) {
62
+ error.Overflow => {
63
+ r.reduce();
64
+ try r.multiplication(p, q);
65
+ },
66
+ else => unreachable,
67
+ };
68
+ },
69
+ .Float => {
70
+ // Reduce in situations where we're likely to start losing precision
71
+ if (r.q > REDUCE or r.p > REDUCE) r.reduce();
72
+
73
+ r.p *= switch (@typeInfo(@TypeOf(p))) {
74
+ .Float, .ComptimeFloat => p,
75
+ else => @floatFromInt(p),
76
+ };
77
+ r.q *= switch (@typeInfo(@TypeOf(q))) {
78
+ .Float, .ComptimeFloat => q,
79
+ else => @floatFromInt(q),
80
+ };
81
+
82
+ // We should always be dealing with whole numbers
83
+ assert(std.math.modf(r.p).fpart == 0);
84
+ assert(std.math.modf(r.q).fpart == 0);
85
+ },
86
+ else => unreachable,
87
+ }
88
+ }
89
+
90
+ /// Add two rationals using the identity (a/b) + (c/d) = (ad+bc)/(bd).
91
+ pub fn add(r: *Self, s: *Self) Error!void {
92
+ switch (@typeInfo(T)) {
93
+ .Int => {
94
+ if (r.q == s.q) {
95
+ r.p = std.math.add(T, r.p, s.p) catch |err| switch (err) {
96
+ error.Overflow => val: {
97
+ r.reduce();
98
+ s.reduce();
99
+ break :val try std.math.add(T, r.p, s.p);
100
+ },
101
+ else => unreachable,
102
+ };
103
+ } else {
104
+ r.addition(s.p, s.q) catch |err| switch (err) {
105
+ error.Overflow => {
106
+ r.reduce();
107
+ s.reduce();
108
+ try r.addition(s.p, s.q);
109
+ },
110
+ else => unreachable,
111
+ };
112
+ }
113
+ },
114
+ .Float => {
115
+ if (r.q == s.q) {
116
+ if (r.p > REDUCE) r.reduce();
117
+ if (s.p > REDUCE) s.reduce();
118
+
119
+ r.p += s.p;
120
+ } else {
121
+ // Always reduce to minimize loss of precision from the multiplications
122
+ r.reduce();
123
+ s.reduce();
124
+
125
+ r.p = (r.p * s.q) + (r.q * s.p);
126
+ r.q *= s.q;
127
+ }
128
+
129
+ assert(std.math.modf(r.p).fpart == 0);
130
+ assert(std.math.modf(r.q).fpart == 0);
131
+ },
132
+ else => unreachable,
133
+ }
134
+ }
135
+
136
+ /// Multiplies two rationals.
137
+ pub fn mul(r: *Self, s: *Self) Error!void {
138
+ switch (@typeInfo(T)) {
139
+ .Int => {
140
+ r.multiplication(s.p, s.q) catch |err| switch (err) {
141
+ error.Overflow => {
142
+ r.reduce();
143
+ s.reduce();
144
+ try r.multiplication(s.p, s.q);
145
+ },
146
+ else => unreachable,
147
+ };
148
+ },
149
+ .Float => {
150
+ if (r.q > REDUCE or r.p > REDUCE) r.reduce();
151
+ if (s.q > REDUCE or s.p > REDUCE) s.reduce();
152
+
153
+ r.p *= s.p;
154
+ r.q *= s.q;
155
+
156
+ assert(std.math.modf(r.p).fpart == 0);
157
+ assert(std.math.modf(r.q).fpart == 0);
158
+ },
159
+ else => unreachable,
160
+ }
161
+ }
162
+
163
+ /// Normalize the rational by reducing by the greatest common divisor.
164
+ pub fn reduce(r: *Self) void {
165
+ const d = gcd(r.p, r.q);
166
+ if (d == 1) return;
167
+
168
+ assert(@mod(r.p, d) == 0);
169
+ assert(@mod(r.q, d) == 0);
170
+
171
+ r.p /= d;
172
+ r.q /= d;
173
+
174
+ assert(r.p >= 1);
175
+ assert(r.q >= 1);
176
+ }
177
+
178
+ pub fn format(
179
+ self: Self,
180
+ comptime fmt: []const u8,
181
+ opts: std.fmt.FormatOptions,
182
+ writer: anytype,
183
+ ) !void {
184
+ _ = .{ fmt, opts };
185
+ try writer.print("{d}/{d}", .{ self.p, self.q });
186
+ }
187
+
188
+ inline fn multiplication(r: *Self, p: anytype, q: anytype) !void {
189
+ r.p = try std.math.mul(T, r.p, p);
190
+ r.q = try std.math.mul(T, r.q, q);
191
+ }
192
+
193
+ inline fn addition(r: *Self, p: anytype, q: anytype) !void {
194
+ // (a/b) + (c/d) = (ad+bc)/(bd)
195
+ var d = try std.math.mul(T, r.q, q);
196
+ var n1 = try std.math.mul(T, r.p, q);
197
+ var n2 = try std.math.mul(T, r.q, p);
198
+
199
+ r.p = try std.math.add(T, n1, n2);
200
+ r.q = d;
201
+ }
202
+ };
203
+ }
204
+
205
+ // https://en.wikipedia.org/wiki/Euclidean_algorithm
206
+ inline fn gcd(p: anytype, q: anytype) @TypeOf(p, q) {
207
+ assert(p >= 1);
208
+ assert(q >= 1);
209
+
210
+ var a = p;
211
+ var b = q;
212
+ var c: @TypeOf(p, q) = undefined;
213
+
214
+ while (b != 0) {
215
+ c = b;
216
+ b = @mod(a, b);
217
+ a = c;
218
+ }
219
+
220
+ assert(a > 0);
221
+ return a;
222
+ }
223
+
224
+ fn doTurn(r: anytype) !void {
225
+ try r.update(1, 163); // Metronome
226
+ try r.update(33, 256); // Critical Hit (67 Speed)
227
+ try r.update(1, 39); // Damage roll
228
+ try r.update(89, 128); // Thunder accuracy (178/256)
229
+ try r.update(77, 256); // Thunder secondary proc
230
+ }
231
+
232
+ test Rational {
233
+ inline for (.{ u64, u128, f64 }) |t| {
234
+ var r: Rational(t) = .{};
235
+
236
+ var c: t = 128;
237
+ try r.update(c, 256);
238
+ try doTurn(&r);
239
+
240
+ r.reduce();
241
+ try expectEqual(Rational(t){ .p = 75383, .q = 35550920704 }, r);
242
+
243
+ try r.update(1, 4);
244
+ if (t == u64) {
245
+ try expectError(error.Overflow, doTurn(&r));
246
+ } else {
247
+ try doTurn(&r);
248
+ r.reduce();
249
+ try expectEqual(Rational(t){ .p = 5682596689, .q = 2527735925804191711232 }, r);
250
+ }
251
+
252
+ r.reset();
253
+
254
+ var s = Rational(t){ .p = 10, .q = 13 };
255
+ try r.mul(&s);
256
+ s = Rational(t){ .p = 3, .q = 4 };
257
+ try r.mul(&s);
258
+ try expectEqual(Rational(t){ .p = 30, .q = 52 }, r);
259
+
260
+ s = Rational(t){ .p = 1, .q = 3 };
261
+ try r.add(&s);
262
+ r.reduce();
263
+ try expectEqual(Rational(t){ .p = 71, .q = 78 }, r);
264
+ }
265
+ }
266
+
267
+ /// Adapter of std.math.big.Rational to the engines Rational interface.
268
+ pub const BigRational = struct {
269
+ /// The underlying rational number.
270
+ val: std.math.big.Rational,
271
+
272
+ /// Possible error returned by operations on the rational.
273
+ pub const Error = error{OutOfMemory};
274
+
275
+ /// Create a new BigRational wrapper. A small amount of memory will be allocated on
276
+ /// initialization. Not default initialized to 1 - you must explicitly `reset` first.
277
+ pub fn init(alloc: std.mem.Allocator) !BigRational {
278
+ return BigRational{ .val = try std.math.big.Rational.init(alloc) };
279
+ }
280
+
281
+ /// Frees all memory associated with a rational.
282
+ pub fn deinit(r: *BigRational) void {
283
+ r.val.deinit();
284
+ }
285
+
286
+ /// Resets the rational back to 1.
287
+ pub fn reset(r: *BigRational) !void {
288
+ try r.val.setInt(1);
289
+ }
290
+
291
+ /// Update the rational by multiplying its numerator by p and its denominator by q.
292
+ /// Both p and q must be >= 1.
293
+ pub fn update(r: *BigRational, p: anytype, q: anytype) !void {
294
+ assert(p >= 1);
295
+ assert(q >= 1);
296
+
297
+ var s = try std.math.big.Rational.init(r.val.p.allocator);
298
+ defer s.deinit();
299
+ try s.setRatio(p, q);
300
+ try r.val.mul(r.val, s);
301
+ }
302
+
303
+ /// Adds two rationals.
304
+ pub fn add(r: *BigRational, s: *const BigRational) !void {
305
+ try r.val.add(r.val, s.val);
306
+ }
307
+
308
+ /// Multiplies two rationals.
309
+ pub fn mul(r: *BigRational, s: *const BigRational) !void {
310
+ try r.val.mul(r.val, s.val);
311
+ }
312
+ };
313
+
314
+ test BigRational {
315
+ var r = try BigRational.init(std.testing.allocator);
316
+ defer r.deinit();
317
+ var s = try std.math.big.Rational.init(std.testing.allocator);
318
+ defer s.deinit();
319
+
320
+ try r.reset();
321
+
322
+ var c: u8 = 128;
323
+ try r.update(c, 256);
324
+ try doTurn(&r);
325
+
326
+ try s.setRatio(75383, 35550920704);
327
+ try expect((try s.order(r.val)) == .eq);
328
+
329
+ try r.update(1, 4);
330
+ try doTurn(&r);
331
+
332
+ try s.setRatio(5682596689, 2527735925804191711232);
333
+ try expect((try s.order(r.val)) == .eq);
334
+
335
+ try r.reset();
336
+
337
+ var t = try BigRational.init(std.testing.allocator);
338
+ defer t.deinit();
339
+
340
+ try t.val.setRatio(10, 13);
341
+ try r.mul(&t);
342
+ try t.val.setRatio(3, 4);
343
+ try r.mul(&t);
344
+
345
+ try s.setRatio(15, 26);
346
+ try expect((try s.order(r.val)) == .eq);
347
+
348
+ try t.val.setRatio(1, 3);
349
+ try r.add(&t);
350
+
351
+ try s.setRatio(71, 78);
352
+ try expect((try s.order(r.val)) == .eq);
353
+ }
@@ -47,7 +47,7 @@ pub const PSRNG = extern struct {
47
47
  }
48
48
 
49
49
  pub fn range(self: *PSRNG, comptime T: type, from: T, to: Bound(T)) T {
50
- return @intCast(T, @as(u64, self.src.next()) * (to - from) / divisor + from);
50
+ return @intCast(@as(u64, self.src.next()) * (to - from) / divisor + from);
51
51
  }
52
52
 
53
53
  pub fn chance(self: *PSRNG, comptime T: type, numerator: T, denominator: Bound(T)) bool {
@@ -72,28 +72,28 @@ test PSRNG {
72
72
  // https://pkmn.cc/pokered/engine/battle/core.asm#L6644-L6693
73
73
  // https://pkmn.cc/pokecrystal/engine/battle/core.asm#L6922-L6938
74
74
  pub const Gen12 = extern struct {
75
- seed: [10]u8,
75
+ seed: [9]u8,
76
76
  index: u8 = 0,
77
77
 
78
78
  comptime {
79
- assert(@sizeOf(Gen12) == 11);
79
+ assert(@sizeOf(Gen12) == 10);
80
80
  }
81
81
 
82
82
  pub fn percent(p: u8) u8 {
83
- return @intCast(u8, (@as(u16, p) * 0xFF) / 100);
83
+ return @intCast((@as(u16, p) * 0xFF) / 100);
84
84
  }
85
85
 
86
86
  pub fn next(self: *Gen12) u8 {
87
87
  const val = 5 *% self.seed[self.index] +% 1;
88
88
  self.seed[self.index] = val;
89
- self.index = (self.index + 1) % 10;
89
+ self.index = (self.index + 1) % 9;
90
90
  return val;
91
91
  }
92
92
  };
93
93
 
94
94
  test Gen12 {
95
- const expected = [_]u8{ 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 31, 56, 81 };
96
- var rng = Gen12{ .seed = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } };
95
+ const expected = [_]u8{ 6, 11, 16, 21, 26, 31, 36, 41, 46, 31, 56, 81 };
96
+ var rng = Gen12{ .seed = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } };
97
97
  for (expected) |e| {
98
98
  try expectEqual(e, rng.next());
99
99
  }
@@ -114,7 +114,7 @@ pub const Gen34 = extern struct {
114
114
 
115
115
  pub fn next(self: *Gen34) u16 {
116
116
  self.advance();
117
- return @intCast(u16, self.seed >> 16);
117
+ return @intCast(self.seed >> 16);
118
118
  }
119
119
 
120
120
  pub fn advance(self: *Gen34) void {
@@ -144,7 +144,7 @@ pub const Gen56 = extern struct {
144
144
 
145
145
  pub fn next(self: *Gen56) u32 {
146
146
  self.advance();
147
- return @intCast(u32, self.seed >> 32);
147
+ return @intCast(self.seed >> 32);
148
148
  }
149
149
 
150
150
  pub fn advance(self: *Gen56) void {
@@ -190,7 +190,7 @@ pub fn FixedRNG(comptime gen: comptime_int, comptime len: usize) type {
190
190
 
191
191
  pub fn range(self: *Self, comptime T: type, from: T, to: Bound(T)) T {
192
192
  assert(showdown);
193
- return @intCast(T, @as(u64, self.next()) * (to - from) / divisor + from);
193
+ return @intCast(@as(u64, self.next()) * (to - from) / divisor + from);
194
194
  }
195
195
 
196
196
  pub fn chance(
@@ -0,0 +1,12 @@
1
+ const std = @import("std");
2
+
3
+ const expectEqual = std.testing.expectEqual;
4
+
5
+ pub fn PointerType(comptime P: type, comptime C: type) type {
6
+ return if (@typeInfo(P).Pointer.is_const) *const C else *C;
7
+ }
8
+
9
+ test PointerType {
10
+ try expectEqual(*bool, PointerType(*u8, bool));
11
+ try expectEqual(*const f64, PointerType(*const i32, f64));
12
+ }