@pkmn/engine 0.1.0-dev.02b7f810

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 (52) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +332 -0
  3. package/build/pkg/addon.d.ts +7 -0
  4. package/build/pkg/addon.js +111 -0
  5. package/build/pkg/addon.js.map +1 -0
  6. package/build/pkg/data/ids.json +240 -0
  7. package/build/pkg/data/layout.json +86 -0
  8. package/build/pkg/data/protocol.json +173 -0
  9. package/build/pkg/data.d.ts +91 -0
  10. package/build/pkg/data.js +150 -0
  11. package/build/pkg/data.js.map +1 -0
  12. package/build/pkg/gen1.d.ts +109 -0
  13. package/build/pkg/gen1.js +668 -0
  14. package/build/pkg/gen1.js.map +1 -0
  15. package/build/pkg/index.d.ts +383 -0
  16. package/build/pkg/index.js +122 -0
  17. package/build/pkg/index.js.map +1 -0
  18. package/build/pkg/protocol.d.ts +71 -0
  19. package/build/pkg/protocol.js +452 -0
  20. package/build/pkg/protocol.js.map +1 -0
  21. package/build/test/display.js +382 -0
  22. package/build/test/display.js.map +1 -0
  23. package/build/tools/debug.js +133 -0
  24. package/build/tools/debug.js.map +1 -0
  25. package/build.zig +346 -0
  26. package/package.json +202 -0
  27. package/src/bin/install-pkmn-engine +391 -0
  28. package/src/bin/pkmn-debug +62 -0
  29. package/src/lib/binding/node.zig +229 -0
  30. package/src/lib/binding/wasm.zig +10 -0
  31. package/src/lib/common/data.zig +129 -0
  32. package/src/lib/common/debug.zig +64 -0
  33. package/src/lib/common/options.zig +40 -0
  34. package/src/lib/common/protocol.zig +1297 -0
  35. package/src/lib/common/rng.zig +234 -0
  36. package/src/lib/gen1/README.md +791 -0
  37. package/src/lib/gen1/data/moves.zig +1854 -0
  38. package/src/lib/gen1/data/species.zig +1105 -0
  39. package/src/lib/gen1/data/types.zig +131 -0
  40. package/src/lib/gen1/data.zig +620 -0
  41. package/src/lib/gen1/helpers.zig +234 -0
  42. package/src/lib/gen1/mechanics.zig +2819 -0
  43. package/src/lib/gen2/README.md +309 -0
  44. package/src/lib/gen2/data/items.zig +236 -0
  45. package/src/lib/gen2/data/moves.zig +2784 -0
  46. package/src/lib/gen2/data/species.zig +1798 -0
  47. package/src/lib/gen2/data/types.zig +123 -0
  48. package/src/lib/gen2/data.zig +425 -0
  49. package/src/lib/gen2/helpers.zig +225 -0
  50. package/src/lib/gen2/mechanics.zig +53 -0
  51. package/src/lib/pkmn.zig +54 -0
  52. package/src/test/display/pkmn.html.tmpl +368 -0
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021-2023 pkmn contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,332 @@
1
+ <p align="center">
2
+ <img alt="pkmn/engine" width="192" height="192" src="https://pkmn.cc/engine.svg" />
3
+ <br />
4
+ <br />
5
+ <a href="https://github.com/pkmn/engine/actions/workflows/test.yml">
6
+ <img alt="Test Status" src="https://github.com/pkmn/engine/workflows/Tests/badge.svg" />
7
+ </a>
8
+ <a href="#status">
9
+ <img alt="WIP" src="https://img.shields.io/badge/status-WIP-red.svg" />
10
+ </a>
11
+ <a href="https://github.com/pkmn/engine/blob/master/LICENSE">
12
+ <img alt="License" src="https://img.shields.io/badge/License-MIT-blue.svg" />
13
+ </a>
14
+ </p>
15
+ <hr />
16
+
17
+ A minimal, complete, Pokémon battle simulation engine optimized for performance and
18
+ [designed](docs/DESIGN.md) for tooling, embedded systems, and [artificial
19
+ intelligence](https://github.com/pkmn/0-ERROR) use cases. This engine aims to be a frame-accurate and
20
+ [bug-for-bug compatible](http://www.catb.org/jargon/html/B/bug-for-bug-compatible.html)
21
+ implementation of both Pokémon battles as defined by the original game code, and the [Pokémon
22
+ Showdown](https://pokemonshowdown.com/)[^1] simulator which represents Pokémon battling as practically
23
+ interpreted online.
24
+
25
+ The pkmn engine is [**more than 1000× faster**](docs/TESTING.md#results) than the
26
+ [patched](docs/TESTING.md#patches) [Pokémon Showdown simulator
27
+ code](https://github.com/smogon/pokemon-showdown) when playing out supported formats in
28
+ compatibility mode and is extensively [tested](docs/TESTING.md) and [documented](docs). Note,
29
+ however, that the engine is **not a fully featured simulator** but is instead a low-level library
30
+ which can be used as a building block for more advanced use cases.
31
+
32
+ ## Installation
33
+
34
+ This repository hosts both the engine code (written in [Zig](https://ziglang.org/)) and the
35
+ reference driver code (written in [TypeScript](https://www.typescriptlang.org/)).
36
+
37
+ ### `libpkmn`
38
+
39
+ Binaries of the engine code can be downloaded from the
40
+ [releases](https://github.com/pkmn/engine/releases) tab on GitHub, or you can [download the source
41
+ code](https://github.com/pkmn/engine/archive/refs/heads/main.zip) directly and build it with the
42
+ latest `zig` compiler, see `zig build --help` for build options:
43
+
44
+ ```sh
45
+ $ curl https://github.com/pkmn/engine/archive/refs/heads/main.zip -o engine.zip
46
+ $ unzip engine.zip
47
+ $ cd engine
48
+ $ zig build --prefix /usr/local -Doptimize=ReleaseFast
49
+ ```
50
+
51
+ The Zig website has [installation instructions](https://ziglang.org/learn/getting-started/) which
52
+ walk through how to install Zig on each platform - the engine code should work on Zig v0.11.0 dev
53
+ build 2168 or greater, though tracks Zig's master branch so this may change in the future if
54
+ breaking language changes are introduced:
55
+
56
+ `libpkmn` can be built with `-Dshowdown` to instead produce the Pokémon Showdown compatible
57
+ `libpkmn-showdown` library. Furthermore, trace logging can be enabled through `-Dtrace`. The
58
+ `libpkmn` and `libpkmn-showdown` objects available in the binary release are compiled with and
59
+ without the `-Dtrace` flag respectively.
60
+
61
+ ### `@pkmn/engine`
62
+
63
+ The driver code can be installed from [npm](https://www.npmjs.com/package/@pkmn/engine):
64
+
65
+ ```sh
66
+ $ npm install @pkmn/engine
67
+ ```
68
+
69
+ The driver depends on being able to find compiled Node/WASM addons in
70
+ `node_modules/@pkmn/engine/build/lib` in order to be useful. When you install the package a
71
+ [`postinstall` lifecycle script](https://docs.npmjs.com/cli/v8/using-npm/scripts) will run
72
+ [`install-pkmn-engine`](src/bin/install-pkmn-engine) which will check for a compatible `zig`
73
+ compiler (see above regarding minimum version) and download one to
74
+ `node_module/@pkmn/engine/build/bin` if it can't find one, as well as looking for (and downloading,
75
+ if necessary) the required Node headers needed to successfully build the addons natively.
76
+
77
+ **If you have configured `npm` to `--ignore-scripts` you must either run `npx install-pkmn-engine`
78
+ directly or build the addons manually and place the artifacts in the expected paths.**
79
+
80
+ ### `pkmn`
81
+
82
+ Until the [Zig package manager](https://github.com/ziglang/zig/projects/4) is completed, the
83
+ recommended way of using the `pkmn` package in Zig is by either copying this repository into your
84
+ project or by using [git submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules) and then
85
+ adding the following to your `build.zig`:
86
+
87
+ ```zig
88
+ const std = @import("std");
89
+ const pkmn = @import("lib/pkmn/build.zig");
90
+
91
+ pub fn build(b: *std.build.Builder) void {
92
+ ...
93
+ exe.addModule("pkmn", pkmn.module(b, .{ .showdown = true, .trace = true }));
94
+ ...
95
+ }
96
+ ```
97
+
98
+ The engine's `build.zig` exposes a `module` function that takes an options structure to allow for
99
+ configuring whether or not Pokémon Showdown compatibility mode or trace logs should be enabled.
100
+ Alternatively, you may set options via a `pkmn_options` [root source file
101
+ declaration](https://ziglang.org/documentation/master/#Root-Source-File). There are several
102
+ undocumented internal options that can be tweaked as well via build or root options, though these
103
+ options are not officially supported, affect correctness, and may change meaning or behavior without
104
+ warning. Use at your own risk.
105
+
106
+ ```zig
107
+ pub const pkmn_options = .{ .showdown = true, .trace = true };
108
+ ```
109
+
110
+ ## Usage
111
+
112
+ For each Pokémon generation, the engine provides a battle structure with two functions - a function
113
+ to `update` the battle's state based on both players' choices and a function that defines which
114
+ `choices` are valid at that decision point (at the beginning of a battle both player's must "pass"
115
+ as their first choice in order to switch in the first member of their party). If `-Dtrace` logging
116
+ is enabled each update will produce logs which can be decoded into a buffer (`LOGS_SIZE` constants
117
+ are provided to make it easy to allocate a buffer of the correct size). Each `update` will return a
118
+ result to indicate either that the battle has terminated or which types of choices will be available
119
+ for each player.
120
+
121
+ Unlike [Pokémon Showdown's
122
+ SIM-PROTOCOL](https://github.com/smogon/pokemon-showdown/blob/master/sim/SIM-PROTOCOL.md#choice-requests)
123
+ which provides a rich request object at each decision point, the pkmn engine computes the possible
124
+ choices on demand based on the result of the previous `update` and the battle state (`OPTIONS_SIZE`
125
+ is a good size to initialize the buffer passed to `choices`). **Attempting to update the battle with
126
+ a choice not present in the options returned by `choices` is undefined behavior and may corrupt
127
+ state or cause the engine to crash.**
128
+
129
+ Battles may be played out from any point but to freshly initialize a battle which is yet to start
130
+ the turn count and active Pokémon should be zeroed out (driver code should handle this for you).
131
+ Most driver code should also provide helpers to make initialize a battle convenient - check the
132
+ respective documentation and examples for the bindings being used. The engine's [protocol
133
+ documentation](docs/PROTOCOL.md) goes into greater detail on the specifics of updates and the
134
+ potential logs that may result.
135
+
136
+ *The snippets below are meant to merely illustrate in broad strokes how the pkmn engine can be used
137
+ \- the [`examples`](src/examples) directory contains fully commented and runnable code.*
138
+
139
+ ### C
140
+
141
+ [`pkmn.h`](src/include/pkmn.h) exports the C API for `libpkmn`. Symbols are all prefixed with
142
+ `pkmn_` to avoid name collisions. If `-Dtrace` is enabled and logging throws an error then the error
143
+ will be encoded in the `pkmn_result` and can be checked with `pkmn_error`.
144
+
145
+ ```c
146
+ #include <pkmn.h>
147
+
148
+ pkmn_battle battle = ...;
149
+ uint8_t buf[PKMN_LOGS_SIZE];
150
+ pkmn_result result;
151
+ pkmn_choice c1 = 0, c2 = 0;
152
+ while (!pkmn_result_type(result = pkmn_battle_update(&battle, c1, c2, buf, PKMN_LOGS_SIZE))) {
153
+ c1 = choose(PKMN_PLAYER_P1, pkmn_result_p1(result));
154
+ c2 = choose(PKMN_PLAYER_P2, pkmn_result_p2(result));
155
+ }
156
+ if (pkmn_error(result)) exit(1);
157
+ ```
158
+
159
+ [(full code)](src/examples/c/example.c)
160
+
161
+ The C API does not export any helpers for creating or accessing the opaque battle objects - it is
162
+ instead intended to be used as the foundation for more ergonomic bindings in [other
163
+ languages](#other) (the lack of namespaces and bit fields having an implementation-defined layout in
164
+ C are the main contributing factors to the sparseness of what `libpkmn` chooses to expose).
165
+
166
+ ### JavaScript / TypeScript
167
+
168
+ `@pkmn/engine` depends on the [`@pkmn/data`](https://www.npmjs.com/package/@pkmn/data) which
169
+ requires a `Dex` implementation to be provided as well. The `Battle.create` function can be used to
170
+ initialize a `Battle` from the beginning, or `Battle.restore` can be used to re-instantiate a battle
171
+ which is in already progress. If logging is enabled the output can be turned into Pokémon Showdown
172
+ protocol via `Log.parse`.
173
+
174
+ ```ts
175
+ import {Dex} from '@pkmn/dex';
176
+ import {Generations} from '@pkmn/data';
177
+ import {Battle} from '@pkmn/engine';
178
+
179
+ const gens = new Generations(Dex);
180
+ const battle = Battle.create(...);
181
+
182
+ const choose = (n: number) => Math.random() * n;
183
+
184
+ let result: Result;
185
+ let c1: Choice, c2: Choice;
186
+ while (!(result = battle.update(c1, c2)).type) {
187
+ c1 = battle.choose('p1', result, choose);
188
+ c2 = battle.choose('p2', result, choose);
189
+ }
190
+
191
+ console.log(result);
192
+ ```
193
+
194
+ [(full code)](src/examples/js/example.ts)
195
+
196
+ By default, the `@pkmn/engine` package will compile the engine with `-Dshowdown`, though by running
197
+ `install-pkmn-engine` directly and passing in `--options` you can override this default and build
198
+ different configurations of the extension for the driver to use. The driver can support
199
+ configurations both with and without Pokémon Showdown compatibility simultaneously if present. On
200
+ update, the post-install script will attempt to rebuild whichever extensions it finds with the same
201
+ configuration parameters that were originally used meaning updating to the newest version of the
202
+ library should be seamless.
203
+
204
+ Despite relying on the native engine code, the `@pkmn/engine` code is designed to also work in
205
+ browsers which support [WebAssembly](https://webassembly.org/). Running `npm run start:web` from the
206
+ [`examples`](src/examples/js) directory will start a server that can be used to demonstrate the
207
+ engine running in the browser.
208
+
209
+ ### Zig
210
+
211
+ The `pkmn` Zig package exposes helper methods to simplify state instantiation and any `Writer` can
212
+ be used when logging is enabled to allow for easily printing e.g. to standard out or a buffer.
213
+
214
+ ```zig
215
+ const std = @import("std");
216
+ const pkmn = @import("pkmn");
217
+
218
+ var random = std.rand.DefaultPrng.init(seed).random();
219
+ var options: [pkmn.OPTIONS_SIZE]pkmn.Choice = undefined;
220
+
221
+ var battle = ...
222
+ var log = ...
223
+
224
+ var c1 = pkmn.Choice{};
225
+ var c2 = pkmn.Choice{};
226
+
227
+ var result = try battle.update(c1, c2, log);
228
+ while (result.type == .None) : (result = try battle.update(c1, c2, log)) {
229
+ c1 = options[random.uintLessThan(u8, battle.choices(.P1, result.p1, &options))];
230
+ c2 = options[random.uintLessThan(u8, battle.choices(.P2, result.p2, &options))];
231
+ }
232
+
233
+ std.debug.print("{}\n", .{result.type});
234
+ ```
235
+
236
+ [(full code)](src/examples/zig/example.zig)
237
+
238
+ The Zig package also supports some APIs which are difficult to expose elsewhere such as the
239
+ `FixedRNG` which allows you to fully specify the exact RNG frames (which can be useful for ensuring
240
+ certain outcomes/effects always occur) for a battle, though doing so will change the size of the
241
+ `Battle` object.
242
+
243
+ ### Other
244
+
245
+ Developers who wish to use the engine in other languages should find writing bindings against
246
+ [`libpkmn`](#libpkmn) relatively straightforward based on the existing documentation, though to
247
+ simplify the process even further [`src/data`](src/data) contains JSON dumps of all of the Pokémon
248
+ data, structure sizes and offsets, and protocol information used by the reference driver code. The
249
+ following is a list of known `libpkmn` bindings written by developers outside of the [pkmn
250
+ organization](https://github.com/pkmn) that may be helpful (though note that these projects may not
251
+ necessarily be up-to-date/complete/correct - inclusion in this list does not imply endorsement):
252
+
253
+ | Language | License | URL |
254
+ | ---------- | --------- | --------------------------------------- |
255
+ | **C++** | `BSL-1.0` | https://github.com/pasyg/engine-wrapper |
256
+ | **Python** | `MIT` | https://github.com/AnnikaCodes/PyKMN |
257
+
258
+
259
+ #### `pkmn-debug`
260
+
261
+ The [`@pkmn/engine`](#pkmnengine) package ships with a `pkmn-debug` tool which exists to decode the
262
+ binary data structures and protocols used by the engine and to output a [standalone
263
+ webpage](https://pkmn.cc/debug.html) that can be used for debugging. To use this tool in a folder
264
+ that has the `@pkmn/engine` package installed locally you can use `npx pkmn-debug`, though you may
265
+ also wish to install the package globally to be able to use this tool anywhere without
266
+ [`npx`](https://docs.npmjs.com/cli/v7/commands/npx):
267
+
268
+ ```sh
269
+ $ npm install --global @pkmn/engine
270
+ ```
271
+
272
+ By default, `pkmn-debug` expects to read [binary debug protocol](docs/PROTOCOL.md#debugging) from
273
+ [standard input](https://en.wikipedia.org/wiki/Standard_streams) and output HTML to standard output:
274
+
275
+ ```sh
276
+ $ <cmd> | pkmn-debug > index.html
277
+ ```
278
+
279
+ Alternatively, if a single filename argument is passed to the `pkmn-debug` it will read from that
280
+ instead:
281
+
282
+ ```sh
283
+ $ pkmn-debug <file> > index.html
284
+ ```
285
+
286
+ ## Status
287
+
288
+ The engine is currently expected to be developed over multiple stages:
289
+
290
+ | Stage | Deliverables |
291
+ | ------- | ----------------------------------------------- |
292
+ | **0** | documentation, integration, benchmark, protocol |
293
+ | **1** | RBY & GSC |
294
+ | **2** | ADV & DPP |
295
+ | ***3*** | *modern generations* |
296
+
297
+ Currently, most of the foundational work from stage 0 is done:
298
+
299
+ - [benchmark and integration testing](src/test) infrastructure
300
+ - [documentation](docs) about design, research, methodology, etc
301
+ - definition and implementation of the [protocol](docs/PROTOCOL.md) that will be used by the engine
302
+
303
+ **Stage 1 is currently in progress** and will see the implementation of the actual Generation I & II
304
+ battle engines, followed by Generation III & IV in stage 2. The implementation of further Pokémon
305
+ generations is in scope for the project but should not be considered as part of the immediate
306
+ roadmap (i.e. exploring the options for broadening support for old generation APIs will be given
307
+ higher priority than implementing more modern generations). Furthermore, implementation of modern
308
+ generations is soft-blocked on the [availability of high quality
309
+ decompilations](https://github.com/orgs/pret/repositories) of the original games in question.
310
+
311
+ Certain features will always be deemed **out of scope**:
312
+
313
+ - team/set validation or custom rule ("format") enforcement
314
+ - first-class support for "mods" to core Pokémon data and mechanics
315
+ - [battle variants](https://bulbapedia.bulbagarden.net/wiki/Pok%C3%A9mon_battle#Battle_variants)
316
+ other than single (full) or double battles
317
+ - code for exposing the engine to users (input validation, game socket server, etc)
318
+
319
+ ## License
320
+
321
+ The pkmn engine is distributed under the terms of the [MIT License](LICENSE).
322
+
323
+ [^1]: In the case of Pokémon Showdown, only bugs which stem from a misimplementation of specific
324
+ effects are reproduced in the engine, bugs which are the result of a misunderstanding of the
325
+ fundamental mechanics of Pokémon or which simply arise due to specific Pokémon Showdown
326
+ implementation details that are not replicable without making the same (incorrect) architectural
327
+ choices are not. Furthermore, the "Pokémon Showdown" code referenced by this project includes
328
+ several [patches](docs/TESTING.md#patches) to improve accuracy and smooth over some of the more
329
+ egregious implementation issues. In practical terms, the vast majority of games played out in the
330
+ pkmn engine's compatibility mode and on this patched Pokémon Showdown simulator will be the same,
331
+ it is only in a well defined and documented set of circumstances where the two implementations
332
+ diverge.
@@ -0,0 +1,7 @@
1
+ import { Choice, Player, Result } from '.';
2
+ export declare function check(showdown: boolean): void;
3
+ export declare function supports(showdown: boolean, trace?: boolean): boolean;
4
+ export declare function update(index: number, showdown: boolean, battle: ArrayBuffer, c1?: Choice, c2?: Choice, log?: ArrayBuffer): Result;
5
+ export declare function choices(index: number, showdown: boolean, battle: ArrayBuffer, player: Player, choice: Choice['type'], buf: ArrayBuffer): Choice[];
6
+ export declare function choose(index: number, showdown: boolean, battle: ArrayBuffer, player: Player, choice: Choice['type'], buf: ArrayBuffer, fn: (n: number) => number): Choice;
7
+ export declare function size(index: number, type: 'options' | 'log'): number;
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.size = exports.choose = exports.choices = exports.update = exports.supports = exports.check = void 0;
27
+ const path = __importStar(require("path"));
28
+ const _1 = require(".");
29
+ const ROOT = path.join(__dirname, '..', '..');
30
+ let ADDON = undefined;
31
+ function load() {
32
+ if (ADDON)
33
+ return ADDON;
34
+ let pkmn = undefined;
35
+ let showdown = undefined;
36
+ try {
37
+ pkmn = require(path.join(ROOT, 'build', 'lib', 'pkmn.node'));
38
+ }
39
+ catch { }
40
+ try {
41
+ showdown = require(path.join(ROOT, 'build', 'lib', 'pkmn-showdown.node'));
42
+ }
43
+ catch { }
44
+ if (!pkmn && !showdown) {
45
+ throw new Error('Could not find native addons - did you run `npx install-pkmn-engine`?');
46
+ }
47
+ return (ADDON = [pkmn, showdown]);
48
+ }
49
+ function check(showdown) {
50
+ if (!load()[+showdown]) {
51
+ const opts = ADDON[+!showdown].options.trace ? ['-Dtrace'] : [];
52
+ if (showdown)
53
+ opts.push('-Dshowdown');
54
+ throw new Error(`@pkmn/engine has ${showdown ? 'not' : 'only'} been configured to support Pokémon Showdown.` +
55
+ `\n(running \`npx install-pkmn-engine --options='${opts.join(' ')}'\` can fix this issue).`);
56
+ }
57
+ }
58
+ exports.check = check;
59
+ function supports(showdown, trace) {
60
+ if (!load()[+showdown])
61
+ return false;
62
+ if (trace === undefined)
63
+ return true;
64
+ return ADDON[+showdown].options.trace === trace;
65
+ }
66
+ exports.supports = supports;
67
+ function update(index, showdown, battle, c1, c2, log) {
68
+ return _1.Result.decode(ADDON[+showdown].bindings[index]
69
+ .update(battle, _1.Choice.encode(c1), _1.Choice.encode(c2), log));
70
+ }
71
+ exports.update = update;
72
+ function choices(index, showdown, battle, player, choice, buf) {
73
+ const request = choice[0] === 'p' ? 0 : choice[0] === 'm' ? 1 : 2;
74
+ const n = ADDON[+showdown].bindings[index].choices(battle, +(player !== 'p1'), request, buf);
75
+ // The top-level API signature means our hands our tied with respect to
76
+ // writing really fast bindings here. The simplest approach would be to return
77
+ // the ArrayBuffer the bindings populate as well as its size and only decode a
78
+ // Choice after the selection. However, given that we need to return
79
+ // `Choices[]` we need to decode all of them even if they're not all being
80
+ // used which is wasteful. This shouldn't be *that* bad as its a very small
81
+ // list, but its still wasted work. Switching the top-level API to return an
82
+ // Iterable<Choice> doesn't help as we need both the length and the ability to
83
+ // randomly access it, so the best way to make the current API fast would be
84
+ // to have the Zig bindings create Choice objects directly, only that won't
85
+ // scale well as it would require us to basically rewrite the low-level
86
+ // choices function for each generation within node.zig. We could do something
87
+ // really galaxy-brained and return some sort of frankenstein subclass of
88
+ // Array backed by ArrayBuffer which would lazily decode the Choice on access,
89
+ // but thats ultimately not worth the effort. You can't have both a high-level
90
+ // idiomatic API and performance here, hence why the choose function below
91
+ // exists.
92
+ const options = new Array(n);
93
+ const data = new Uint8Array(buf);
94
+ for (let i = 0; i < n; i++)
95
+ options[i] = _1.Choice.decode(data[i]);
96
+ return options;
97
+ }
98
+ exports.choices = choices;
99
+ function choose(index, showdown, battle, player, choice, buf, fn) {
100
+ const request = choice[0] === 'p' ? 0 : choice[0] === 'm' ? 1 : 2;
101
+ const n = ADDON[+showdown].bindings[index].choices(battle, +(player !== 'p1'), request, buf);
102
+ const data = new Uint8Array(buf);
103
+ return _1.Choice.decode(data[fn(n)]);
104
+ }
105
+ exports.choose = choose;
106
+ function size(index, type) {
107
+ const bindings = (ADDON[1] ?? ADDON[0]).bindings[index];
108
+ return type[0] === 'o' ? bindings.OPTIONS_SIZE : bindings.LOGS_SIZE;
109
+ }
110
+ exports.size = size;
111
+ //# sourceMappingURL=addon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"addon.js","sourceRoot":"","sources":["../../src/pkg/addon.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAE7B,wBAAyC;AAEzC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAE9C,IAAI,KAAK,GAAoD,SAAS,CAAC;AAcvE,SAAS,IAAI;IACX,IAAI,KAAK;QAAE,OAAO,KAAK,CAAC;IACxB,IAAI,IAAI,GAAgC,SAAS,CAAC;IAClD,IAAI,QAAQ,GAA+B,SAAS,CAAC;IACrD,IAAI;QACF,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