@pkmn/engine 0.1.0-dev.5ec64ea5 → 0.1.0-dev.6195e056

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.
@@ -15,10 +15,8 @@ const DEV = ZIG_VERSION.dev ? `-dev.${ZIG_VERSION.dev}` : '';
15
15
  const VERSION = `${ZIG_VERSION.major}.${ZIG_VERSION.minor}.${ZIG_VERSION.patch}${DEV}`;
16
16
  const INDEX = 'https://ziglang.org/download/index.json';
17
17
  const ROOT = path.resolve(__dirname, '..', '..');
18
- let SILENT = false;
19
18
 
20
19
  const sh = (cmd, args) => execFileSync(cmd, args, {encoding: 'utf8', cwd: ROOT});
21
- const log = (...args) => { if (!SILENT) console.log(...args); };
22
20
 
23
21
  // This is hardly the browser fetch API, but it works for our primitive needs
24
22
  const fetch = url => new Promise((resolve, reject) => {
@@ -63,7 +61,7 @@ const unpack7 = (input, output) => new Promise((resolve, reject) => {
63
61
  require.resolve('7zip-min');
64
62
  } catch (err) {
65
63
  if (err.code !== 'MODULE_NOT_FOUND') throw err;
66
- log('Installing 7zip-min package locally to unpack the archive...');
64
+ console.log('Installing 7zip-min package locally to unpack the archive...');
67
65
  sh('npm', ['install', '7zip-min', '--no-audit', '--no-save']);
68
66
  }
69
67
 
@@ -85,7 +83,7 @@ const unpack = async (input, output) => {
85
83
  sh('tar', ['xf', input, '-C', output]);
86
84
  return;
87
85
  } catch {
88
- log('tar command not found, falling back to 7z');
86
+ console.log('tar command not found, falling back to 7z');
89
87
  }
90
88
  }
91
89
  // Try to use a 7z binary if we can, and only install 7zip-min as a last resort
@@ -122,10 +120,10 @@ const find = zig => {
122
120
  (!ZIG_VERSION.dev || (dev && dev >= ZIG_VERSION.dev)));
123
121
 
124
122
  if (compatible) {
125
- log('Found existing compatible Zig executable:', zig_exe);
123
+ console.log('Found existing compatible Zig executable:', zig_exe);
126
124
  return zig_exe;
127
125
  } else {
128
- log(`Existing Zig executable is not compatible (${version} < ${VERSION}):`, zig_exe);
126
+ console.log(`Existing Zig executable is not compatible (${version} < ${VERSION}):`, zig_exe);
129
127
  }
130
128
  } catch (err) {
131
129
  if (err.code !== 'ENOENT') throw err;
@@ -170,11 +168,11 @@ const install = async () => {
170
168
  let base = path.basename(url);
171
169
  const archive = path.join(dir, path.basename(url));
172
170
 
173
- log(`Downloading Zig tarball from ${url} to ${archive}`);
171
+ console.log(`Downloading Zig tarball from ${url} to ${archive}`);
174
172
  try {
175
173
  await download(url, archive, release.shasum);
176
174
 
177
- log(`Extracting tarball and installing to ${dir}`);
175
+ console.log(`Extracting tarball and installing to ${dir}`);
178
176
  await unpack(archive, dir);
179
177
  if (archive.endsWith('.zip')) {
180
178
  base = base.slice(0, -4);
@@ -189,17 +187,17 @@ const install = async () => {
189
187
  } catch (err) {
190
188
  if (err.code !== 'ENOENT') throw err;
191
189
  }
192
- log(`Zig${version === 'master' ? '' : ` v${version}`} executable:`, zig,
190
+ console.log(`Zig${version === 'master' ? '' : ` v${version}`} executable:`, zig,
193
191
  '(this version of Zig will be retained to speed up future updates)');
194
192
  const [pre, post] = tty.isatty(1) ? ['\x1b[1m\x1b[35m', '\x1b[0m'] : ['', ''];
195
- log(
193
+ console.log(
196
194
  `${pre}Consider moving the ${path.dirname(zig)} directory and adding it to your PATH`,
197
195
  `to use Zig on other projects, or delete this if you wish to save space.${post}`
198
196
  );
199
197
 
200
198
  return zig;
201
199
  } finally {
202
- log(`Cleaning up ${archive}`);
200
+ console.log(`Cleaning up ${archive}`);
203
201
  try { fs.rmSync(archive); } catch {}
204
202
  }
205
203
  };
@@ -208,17 +206,17 @@ const install = async () => {
208
206
  const downloadHeaders = async () => {
209
207
  const include = path.resolve(process.execPath, '..', '..', 'include', 'node');
210
208
  if (fs.existsSync(path.join(include, 'node.h'))) {
211
- log('Node headers:', include);
209
+ console.log('Node headers:', include);
212
210
  return include;
213
211
  }
214
212
 
215
213
  const dir = path.join(ROOT, 'build', 'include');
216
- const dest = path.join(dir, 'node');
214
+ const dest = path.join(dir, `node-${process.version}`, 'include', 'node');
217
215
  if (fs.existsSync(path.join(dest, 'node.h'))) {
218
- log('Node headers:', dest);
216
+ console.log('Node headers:', dest);
219
217
  return dest;
220
218
  } else {
221
- log(`Could not find Node headers at ${include}, downloading...`);
219
+ console.log(`Could not find Node headers at ${include}, downloading...`);
222
220
  }
223
221
 
224
222
  try {
@@ -229,28 +227,20 @@ const downloadHeaders = async () => {
229
227
 
230
228
  const url = process.release.headersUrl;
231
229
  const targz = path.join(dir, path.basename(url));
232
- const unpacked = path.join(dir, `node-${process.version}`, 'include');
233
230
 
234
- log(`Downloading Node headers from ${url} to ${targz}`);
231
+ console.log(`Downloading Node headers from ${url} to ${targz}`);
232
+ await download(url, targz);
233
+ await unpack(targz, dir);
235
234
 
236
- try {
237
- await download(url, targz);
238
- await unpack(targz, dir);
239
- fs.renameSync(path.join(unpacked, 'node'), dest);
240
-
241
- log('Node headers:', dest);
235
+ console.log('Node headers:', dest);
242
236
 
243
- return dest;
244
- } finally {
245
- try { fs.rmSync(targz); } catch {}
246
- try { fs.rmSync(unpacked, {recursive: true}); } catch {}
247
- }
237
+ return dest;
248
238
  };
249
239
 
250
240
  const downloadImportLib = async () => {
251
241
  const library = path.resolve(process.execPath, '..', 'node.lib');
252
242
  if (fs.existsSync(path.join(library, 'node.h'))) {
253
- log('Node import library:', library);
243
+ console.log('Node import library:', library);
254
244
  return library;
255
245
  }
256
246
 
@@ -258,10 +248,10 @@ const downloadImportLib = async () => {
258
248
  const url = new URL('./win-x64/node.lib', process.release.headersUrl).href;
259
249
  const dest = path.join(dir, path.basename(url));
260
250
  if (fs.existsSync(path.join(dest))) {
261
- log('Node import library:', dest);
251
+ console.log('Node import library:', dest);
262
252
  return dest;
263
253
  } else {
264
- log(`Could not find Node import library at ${library}, downloading...`);
254
+ console.log(`Could not find Node import library at ${library}, downloading...`);
265
255
  }
266
256
 
267
257
  try {
@@ -270,41 +260,24 @@ const downloadImportLib = async () => {
270
260
  if (err.code !== 'EEXIST') throw err;
271
261
  }
272
262
 
273
- log(`Downloading Node import library from ${url} to ${dest}`);
263
+ console.log(`Downloading Node import library from ${url} to ${dest}`);
274
264
  await download(url, dest);
275
- log('Node import library:', dest);
265
+ console.log('Node import library:', dest);
276
266
 
277
267
  return dest;
278
268
  };
279
269
 
280
270
  (async () => {
281
- let only = false;
282
- let options = undefined;
283
- let error = false;
284
- for (let i = 2; i < process.argv.length; i++) {
285
- switch (process.argv[i]) {
286
- case "--silent": {
287
- SILENT = true;
288
- break;
289
- }
290
- case "--zig": {
291
- if (options || only) error = true;
292
- only = true;
293
- break;
294
- }
295
- default: {
296
- if (options || only || !process.argv[i].startsWith('--options=')) error = true;
297
- options = process.argv[i].slice(10).split(' ');
298
- }
299
- }
300
- }
301
- if (error) {
271
+ const options = (process.argv[2] || '').startsWith('--options=')
272
+ ? process.argv[2].slice(10).split(' ') : undefined;
273
+ if (process.argv.length > 3 ||
274
+ process.argv.length === 3 && !(process.argv[2] === '--zig' || options)) {
302
275
  console.error('Invalid arguments');
303
276
  process.exit(1);
304
277
  }
305
278
 
306
279
  const zig = await install();
307
- if (only) process.exit(0);
280
+ if (process.argv[2] === '--zig') process.exit(0);
308
281
 
309
282
  let tmp;
310
283
  try {
@@ -374,7 +347,7 @@ const downloadImportLib = async () => {
374
347
  opts.includes('-Dshowdown') || opts.includes('-Dshowdown=true') ? '-showdown' : '';
375
348
  const flags = opts.length ? ` (${opts.join(' ')})` : '';
376
349
  const artifact = path.join('build', 'lib', `pkmn${suffix}.${config.type}`);
377
- log(`Building ${artifact}${flags}`);
350
+ console.log(`Building ${artifact}${flags}`);
378
351
  sh(zig, args);
379
352
  // TODO: ziglang/zig#14647 broke emit_to so we get to rename the file ourselves...
380
353
  if (config.type === 'node') {
@@ -382,7 +355,7 @@ const downloadImportLib = async () => {
382
355
  const ext = process.platform === 'darwin'
383
356
  ? 'dylib' : process.platform === 'win32' ? 'dll' : 'so';
384
357
  const actual = path.join('build', 'lib', `${prefix}pkmn${suffix}.node.${ext}`);
385
- fs.renameSync(path.join(ROOT, actual), path.join(ROOT, artifact));
358
+ fs.renameSync(actual, artifact);
386
359
  }
387
360
  }
388
361
  })().catch(e => {
@@ -332,9 +332,7 @@ must be gleaned through the `Battle` state). Useful size and offset information
332
332
  the [`layout.json`](../../data/layout.json) which exists to simplify writing driver code.
333
333
 
334
334
  Documentation of the wire protocol used for logging traces when `-Dtrace` is enabled can be found in
335
- [PROTOCOL.md](../../../docs/PROTOCOL.md). Note that the
336
- [`pkmn-debug`](../../../README.md#pkmn-debug) tool exists to display the binary protocol and battle
337
- data in the browser for ease of debugging.
335
+ [PROTOCOL.md](../../../docs/PROTOCOL.md).
338
336
 
339
337
  ### `Battle`
340
338
 
@@ -469,7 +467,7 @@ data in the browser for ease of debugging.
469
467
 
470
468
  In addition to its alternative [RNG semantics](#rng), Pokémon Showdown's implementation of the first
471
469
  generation of Pokémon contains a number bugs, [many of which are known and have been documented on
472
- Smogon](https://www.smogon.com/forums/posts/5933177/show):
470
+ Smogon](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/#post-5933177):
473
471
 
474
472
  - moves on Pokémon Showdown can do 0 damage instead of failing or causing a [division-by-zero
475
473
  freeze](https://pkmn.cc/bulba-glitch-1#Division_by_0).
@@ -484,21 +482,14 @@ Beyond the general bugs listed above, several move effects are implemented incor
484
482
  Showdown. Some of these moves are [too fundamentally broken to be implemented](#unimplementable) by
485
483
  the pkmn engine, but the following moves have their broken behavior preserved in `-Dshowdown` mode:
486
484
 
487
- - **Bide**: If the opponent faints after Bide inflicts damage on Pokémon Showdown residual damage
488
- incorrectly still gets applied to Bide's user.
489
485
  - **Leech Seed**: Leech Seed fails to heal its source side if a seeded target faints due to
490
- recoil/crash damage on Pokémon Showdown. Pokémon Showdown also updates the battle's last damage
491
- field with the uncapped Leech Seed damage which has consequences for Bide and Counter.
486
+ recoil/crash damage on Pokémon Showdown.
492
487
  - **Pay Day**: Pay Day should still scatter coins if it hits (but doesn't break) and opponent's
493
488
  Substitute but doesn't on Pokémon Showdown.
494
489
  - **Flinch**: Flinching does not get cleared during move selection on Pokémon Showdown and is
495
490
  instead cleared in Pokémon Showdown's "residual" phase, meaning the flinch status gets erroneously
496
491
  preserved across fainting (as fainting triggers Pokémon Showdown's "instaswitch" behavior which
497
492
  skips end-of-turn residuals).
498
- - **Rage**: Rage boosts should still result in burn/paralysis [stat modification
499
- errors](https://pkmn.cc/bulba-glitch-1#Stat_modification_errors) but don't on Pokémon Showdown.
500
- Furthermore, Pokémon Showdown only builds Rage for Disable/Explosion (hit/miss) when attacking
501
- into a Substitute instead of all moves.
502
493
  - **Thrash** / **Petal Dance**: once a Pokémon is locked into a thrashing move they will lose all
503
494
  speed ties on Pokémon Showdown (due to the fact that if they win the speed tie their action will
504
495
  then get "changed" and inserted back into the queue after their opponent's action).
@@ -517,16 +508,14 @@ the pkmn engine, but the following moves have their broken behavior preserved in
517
508
  implement by Pokémon Showdown.
518
509
  - **Roar** / **Whirlwind**: these moves can miss on Pokémon Showdown (and advance the RNG when
519
510
  checking) which is incorrect (these moves should always fail, but do not check accuracy or advance
520
- the RNG). More importantly, these moves should *not* cause the tracked last battle damage to be
521
- zeroed, but on Pokémon Showdown they do.
511
+ the RNG).
522
512
  - **Substitute**: in addition to the [Substitute + Confusion
523
513
  glitch](https://pkmn.cc/bulba-glitch-1#Substitute_.2B_Confusion_glitch) not being implemented
524
514
  correctly (covered above), the [Substitute 1/4
525
515
  glitch](https://glitchcity.wiki/Substitute_%C2%BC_HP_glitch) also fails in many cases due to
526
516
  Pokémon Showdown implementing the health check based on floating point division instead of integer
527
517
  divison like on the cartridge (meaning the Substitute 1/4 glitch will only occur if the Pokémon's
528
- maximum HP is evenly divisible by 4). Finally, Substitute also incorrectly blocks Dream Eater on
529
- Pokémon Showdown.
518
+ maximum HP is evenly divisible by 4).
530
519
 
531
520
  In addition to numerous cases where Pokémon Showdown uses the wrong type of message (e.g. `|-fail`
532
521
  vs. `|-miss|` vs. `|-immune|`, e.g. in the case of Leech Seed) which are not documented here, Pokémon
@@ -560,7 +549,7 @@ called out in the `|rule|` section at the beginning of a battle's log):
560
549
  `|rule|` section** in Generation I (or II) as the actual order of switches here does not have
561
550
  competitive implications like it does in Generation III, but it is still contrary to how the games
562
551
  work where the [host (Player 1)'s Pokemon would switch
563
- first](https://www.smogon.com/forums/posts/5989318/show).
552
+ first](https://www.smogon.com/forums/threads/gen-3-on-ps-final-fixes.3527268/post-5989318).
564
553
 
565
554
  Pokémon Showdown enforces several clauses *before* the battle: **Cleric Clause** (all Pokémon must
566
555
  have full HP and PP, and not have any status conditions prior to the battle), **Stat Tradeback
@@ -581,12 +570,13 @@ left up to a client to support.
581
570
 
582
571
  Numerous moves on Pokémon Showdown are broken not simply due to local issues in the implementation
583
572
  of their effects but instead due to **global issues** related to fundamental mechanics such as
584
- [broken move selection](https://www.smogon.com/forums/posts/8655897/show), using move name instead
585
- of slot to determine move identity, implementing volatile statuses incorrectly or not understanding
586
- how moves which call other moves work means that it isn't possible to completely implement Pokémon
587
- Showdown's behavior for the following moves (the pkmn engine attempts to reproduce as much of the
588
- behavior that can be reproduced without making data structure changes or dramatically deviating from
589
- the correct control flow):
573
+ [broken move
574
+ selection](https://www.smogon.com/forums/threads/rby-fight-button-simulation-improvements-fix-partial-trapping-improve-counter.3673280/#post-8655897),
575
+ using move name instead of slot to determine move identity, implementing volatile statuses
576
+ incorrectly or not understanding how moves which call other moves work means that it isn't possible
577
+ to completely implement Pokémon Showdown's behavior for the following moves (the pkmn engine
578
+ attempts to reproduce as much of the behavior that can be reproduced without making data structure
579
+ changes or dramatically deviating from the correct control flow):
590
580
 
591
581
  - **Wrap**: Binding moves like Wrap are implemented on Pokémon Showdown with an artificial
592
582
  `partialtrappinglock` volatile as opposed to how it works on the cartridge which simply relies on
@@ -675,10 +665,10 @@ compatibility mode, the implications of these differences are outlined below:
675
665
  Finally, the **initial 10-byte seed for link battles on Pokémon Red cannot include bytes larger than
676
666
  the `SERIAL_PREAMBLE_BYTE`**, so must be in the range $\left[0, 252\right]$. This has implications
677
667
  on the first 10 random numbers generated during the battle and has [**non-trivial competitive
678
- implications**](https://www.smogon.com/forums/posts/9068411/show) (at the start of the battle move
679
- effects become more likely, the ["1/256-miss" glitch](https://glitchcity.wiki/1/256_miss_glitch)
680
- cannot happen, Player 1 is more likely to win speed ties, etc) that Pokémon Showdown cannot
681
- replicate due to everything described above.
668
+ implications**](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/page-16#post-9068411)
669
+ (at the start of the battle move effects become more likely, the ["1/256-miss"
670
+ glitch](https://glitchcity.wiki/1/256_miss_glitch) cannot happen, Player 1 is more likely to win
671
+ speed ties, etc) that Pokémon Showdown cannot replicate due to everything described above.
682
672
 
683
673
  All of places in the link battle code where randomness is required are outlined below:
684
674
 
@@ -777,8 +767,11 @@ The pkmn engine attempts to adhere to certain naming conventions:
777
767
  ## Resources
778
768
 
779
769
  - [pret/pokered](https://github.com/pret/pokered/) disassembly
780
- - [Gen I Main Battle Function](https://www.smogon.com/forums/posts/5878612/show) - Crystal_
770
+ - [Gen I Main Battle
771
+ Function](https://www.smogon.com/forums/threads/past-gens-research-thread.3506992/#post-5878612) -
772
+ Crystal_
781
773
  - [Pokemon Showdown!](https://github.com/smogon/pokemon-showdown)
782
774
  - [List of glitches (Generation
783
775
  I)](https://bulbapedia.bulbagarden.net/wiki/List_of_glitches_(Generation_I))
784
- - [Pokémon Showdown RBY Bugs](https://www.smogon.com/forums/posts/5933177/show)
776
+ - [Pokémon Showdown RBY
777
+ Bugs](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/#post-5933177)
@@ -272,7 +272,7 @@ pub const Status = enum(u8) {
272
272
  return num > 0;
273
273
  }
274
274
 
275
- /// Returns a human-readable representation of the status `num`.
275
+ /// Retunrns a human-readable representation of the status `num`.
276
276
  pub fn name(num: u8) []const u8 {
277
277
  if (Status.is(num, .EXT)) return if (num == Status.TOX) "TOX" else "SLF";
278
278
  if (Status.is(num, .SLP)) return "SLP";
@@ -216,7 +216,11 @@ fn blocked(m: Move) bool {
216
216
  if (Move.get(m).effect == .Binding) return true;
217
217
  return switch (m) {
218
218
  .Counter,
219
+ // FIXME: test and see if this can be removed or document
220
+ .Rage,
219
221
  .Mimic,
222
+ // FIXME: test and see if this can be removed or document
223
+ .Bide,
220
224
  .Metronome,
221
225
  .MirrorMove,
222
226
  .Transform,