@zardoy/flying-squid 0.0.128 → 0.0.130

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.
@@ -0,0 +1,45 @@
1
+ import { DataRegistry } from 'minecraft-worldgen/dist/data/registry';
2
+ /**
3
+ * Vanilla game data the server needs at run time and `minecraft-data` does not have: loot tables and cooking recipes (smelting, blasting, smoking).
4
+ * It reads the datapack layers like minecraft-worldgen does (a `DataRegistry`):
5
+ * 1. the vanilla client jar (node: `MC_WORLDGEN_VANILLA_JAR` / `~/.cache/mc-worldgen/client.jar`, or `options.gameDataJars`),
6
+ * 2. zip URL(s) of `globalThis.__MC_GAMEDATA_URL` (browser hosts; a string, a list or a function returning one; a small zip with `data/minecraft/loot_table/chests` and the cooking `data/minecraft/recipe`
7
+ * files is enough, it is not the worldgen pack),
8
+ * 3. datapack zips in `<worldFolder>/datapacks/`,
9
+ * 4. `options.lootTables` (`{ 'minecraft:chests/foo': {...} }` or a function) which wins over everything.
10
+ * Without any of them loot tables are unknown (chests with a `LootTable` stay as they are) and a built-in list of the vanilla cooking recipes is used.
11
+ */
12
+ export interface CookingRecipe {
13
+ kind: 'smelting' | 'blasting' | 'smoking' | 'campfire_cooking';
14
+ /** item names without namespace, or `#tag` ids */
15
+ ingredients: string[];
16
+ result: string;
17
+ count: number;
18
+ /** ticks in a plain furnace (blast furnace / smoker take half) */
19
+ time: number;
20
+ experience: number;
21
+ }
22
+ export declare class GameData {
23
+ private readonly options;
24
+ private readonly renamed?;
25
+ readonly registry: DataRegistry;
26
+ private loaded;
27
+ get isLoaded(): boolean;
28
+ /** resolves when the datapack layers are read; `lootTable` / `recipes` work after that */
29
+ readonly ready: Promise<void>;
30
+ private recipeCache?;
31
+ constructor(options: {
32
+ gameDataJars?: string[];
33
+ worldFolder?: string | false;
34
+ lootTables?: Record<string, any> | ((id: string) => any);
35
+ version: string;
36
+ }, renamed?: ((kind: "items", name: string) => string) | undefined);
37
+ private load;
38
+ /** parsed loot table (`minecraft:chests/simple_dungeon`), undefined when unknown */
39
+ lootTable(id: string): any | undefined;
40
+ itemTag(id: string): string[];
41
+ /** all cooking recipes (datapack ones, else the built-in vanilla list) */
42
+ recipes(): CookingRecipe[];
43
+ }
44
+ /** burn time in ticks of a furnace fuel (vanilla `FuelValues`); 0 when the item is not a fuel */
45
+ export declare function fuelTicks(name: string): number;
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.GameData = void 0;
7
+ exports.fuelTicks = fuelTicks;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const registry_1 = require("minecraft-worldgen/dist/data/registry");
11
+ const strip = (id) => id.replace(/^minecraft:/, '');
12
+ /** the vanilla smelting recipes when no datapack is available */
13
+ const BUILTIN_SMELTING = [
14
+ [['iron_ore', 'deepslate_iron_ore', 'raw_iron'], 'iron_ingot', 0.7], [['gold_ore', 'deepslate_gold_ore', 'raw_gold', 'nether_gold_ore'], 'gold_ingot', 1],
15
+ [['copper_ore', 'deepslate_copper_ore', 'raw_copper'], 'copper_ingot', 0.7], [['ancient_debris'], 'netherite_scrap', 2],
16
+ [['coal_ore', 'deepslate_coal_ore'], 'coal', 0.1], [['diamond_ore', 'deepslate_diamond_ore'], 'diamond', 1], [['emerald_ore', 'deepslate_emerald_ore'], 'emerald', 1],
17
+ [['lapis_ore', 'deepslate_lapis_ore'], 'lapis_lazuli', 0.2], [['redstone_ore', 'deepslate_redstone_ore'], 'redstone', 0.7], [['nether_quartz_ore'], 'quartz', 1],
18
+ [['sand', 'red_sand'], 'glass', 0.1], [['cobblestone'], 'stone', 0.1], [['stone'], 'smooth_stone', 0.1], [['cobbled_deepslate'], 'deepslate', 0.1], [['stone_bricks'], 'cracked_stone_bricks', 0.1],
19
+ [['clay_ball'], 'brick', 0.3], [['clay'], 'terracotta', 0.35], [['netherrack'], 'nether_brick', 0.1], [['cactus'], 'green_dye', 1], [['kelp'], 'dried_kelp', 0.1],
20
+ [['sandstone'], 'smooth_sandstone', 0.1], [['red_sandstone'], 'smooth_red_sandstone', 0.1], [['quartz_block'], 'smooth_quartz', 0.1], [['wet_sponge'], 'sponge', 0.15],
21
+ [['oak_log', 'spruce_log', 'birch_log', 'jungle_log', 'acacia_log', 'dark_oak_log', 'mangrove_log', 'cherry_log', 'oak_wood', 'spruce_wood', 'birch_wood', 'jungle_wood', 'acacia_wood', 'dark_oak_wood', 'stripped_oak_log', 'stripped_spruce_log', 'stripped_birch_log', 'stripped_jungle_log', 'stripped_acacia_log', 'stripped_dark_oak_log'], 'charcoal', 0.15],
22
+ [['beef'], 'cooked_beef', 0.35], [['porkchop'], 'cooked_porkchop', 0.35], [['chicken'], 'cooked_chicken', 0.35], [['mutton'], 'cooked_mutton', 0.35], [['rabbit'], 'cooked_rabbit', 0.35],
23
+ [['cod'], 'cooked_cod', 0.35], [['salmon'], 'cooked_salmon', 0.35], [['potato'], 'baked_potato', 0.35], [['chorus_fruit'], 'popped_chorus_fruit', 0.1],
24
+ [['white_terracotta'], 'white_glazed_terracotta', 0.1], [['iron_sword', 'iron_pickaxe', 'iron_axe', 'iron_shovel', 'iron_hoe', 'iron_helmet', 'iron_chestplate', 'iron_leggings', 'iron_boots'], 'iron_nugget', 0.1],
25
+ [['gold_helmet', 'gold_chestplate', 'gold_leggings', 'gold_boots', 'golden_sword', 'golden_pickaxe', 'golden_axe', 'golden_shovel', 'golden_hoe'], 'gold_nugget', 0.1]
26
+ ];
27
+ class GameData {
28
+ options;
29
+ renamed;
30
+ registry = new registry_1.DataRegistry({ jars: [] });
31
+ loaded = false;
32
+ get isLoaded() { return this.loaded; }
33
+ /** resolves when the datapack layers are read; `lootTable` / `recipes` work after that */
34
+ ready;
35
+ recipeCache;
36
+ constructor(options, renamed) {
37
+ this.options = options;
38
+ this.renamed = renamed;
39
+ this.ready = this.load().catch(err => { console.warn('[gameData] could not read loot tables / recipes: ' + err.message); });
40
+ }
41
+ async load() {
42
+ const { options } = this;
43
+ for (const jar of options.gameDataJars ?? [registry_1.DEFAULT_VANILLA_JAR]) {
44
+ try {
45
+ if (fs_1.default.existsSync(jar))
46
+ this.registry.addJar(jar);
47
+ }
48
+ catch { }
49
+ }
50
+ const g = globalThis;
51
+ let urls = g.__MC_GAMEDATA_URL;
52
+ if (typeof urls === 'function')
53
+ urls = await urls();
54
+ for (const url of Array.isArray(urls) ? urls : urls ? [urls] : []) {
55
+ try {
56
+ const res = await fetch(url);
57
+ if (res.ok)
58
+ this.registry.addZipBuffer(`gamedata:${url}`.slice(0, 80), new Uint8Array(await res.arrayBuffer()));
59
+ }
60
+ catch { }
61
+ }
62
+ if (options.worldFolder) {
63
+ try {
64
+ const dir = path_1.default.join(options.worldFolder, 'datapacks');
65
+ for (const f of (await fs_1.default.promises.readdir(dir)).filter(f => f.endsWith('.zip') || f.endsWith('.jar')).sort()) {
66
+ this.registry.addZipBuffer(f, await fs_1.default.promises.readFile(path_1.default.join(dir, f)));
67
+ }
68
+ }
69
+ catch { } // no datapacks folder
70
+ }
71
+ this.loaded = true;
72
+ }
73
+ /** parsed loot table (`minecraft:chests/simple_dungeon`), undefined when unknown */
74
+ lootTable(id) {
75
+ const { lootTables } = this.options;
76
+ const fromOptions = typeof lootTables === 'function' ? lootTables(id) : lootTables?.[id] ?? lootTables?.[strip(id)];
77
+ if (fromOptions)
78
+ return fromOptions;
79
+ if (!this.loaded)
80
+ return undefined;
81
+ for (const dir of ['loot_table', 'loot_tables']) {
82
+ try {
83
+ if (this.registry.has(dir, id))
84
+ return this.registry.json(dir, id);
85
+ }
86
+ catch { }
87
+ }
88
+ return undefined;
89
+ }
90
+ itemTag(id) {
91
+ try {
92
+ return this.registry.tag('item', id.replace(/^#/, '')).map(strip);
93
+ }
94
+ catch {
95
+ return [];
96
+ }
97
+ }
98
+ /** all cooking recipes (datapack ones, else the built-in vanilla list) */
99
+ recipes() {
100
+ if (this.recipeCache)
101
+ return this.recipeCache;
102
+ // before the datapack layers are read only the built-in list is known: do not cache it
103
+ const cache = (list) => this.loaded ? (this.recipeCache = list) : list;
104
+ const out = [];
105
+ if (this.loaded) {
106
+ for (const dir of ['recipe', 'recipes']) {
107
+ for (const id of this.registry.list(dir)) {
108
+ let r;
109
+ try {
110
+ r = this.registry.json(dir, id);
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ const kind = strip(String(r?.type));
116
+ if (!['smelting', 'blasting', 'smoking', 'campfire_cooking'].includes(kind))
117
+ continue;
118
+ const ing = (v) => typeof v === 'string' ? [v.startsWith('#') ? v : strip(v)] : Array.isArray(v) ? v.flatMap(ing) : v?.item ? [strip(v.item)] : v?.tag ? ['#' + v.tag] : [];
119
+ const result = typeof r.result === 'string' ? r.result : r.result?.id ?? r.result?.item;
120
+ if (!result)
121
+ continue;
122
+ out.push({ kind, ingredients: ing(r.ingredient), result: strip(result), count: r.result?.count ?? 1, time: r.cookingtime ?? (kind === 'campfire_cooking' ? 600 : kind === 'smelting' ? 200 : 100), experience: r.experience ?? 0 });
123
+ }
124
+ }
125
+ if (out.length)
126
+ return cache(out);
127
+ }
128
+ for (const [ingredients, result, experience] of BUILTIN_SMELTING) {
129
+ out.push({ kind: 'smelting', ingredients, result, count: 1, time: 200, experience });
130
+ // blast furnaces cook ores and metal tools, smokers food, both in half the time
131
+ if (/ingot$|nugget$|^(coal|diamond|emerald|lapis_lazuli|redstone|quartz|netherite_scrap)$/.test(result))
132
+ out.push({ kind: 'blasting', ingredients, result, count: 1, time: 100, experience });
133
+ if (/^cooked_|^baked_potato$|^dried_kelp$/.test(result))
134
+ out.push({ kind: 'smoking', ingredients, result, count: 1, time: 100, experience });
135
+ }
136
+ return cache(out);
137
+ }
138
+ }
139
+ exports.GameData = GameData;
140
+ /** burn time in ticks of a furnace fuel (vanilla `FuelValues`); 0 when the item is not a fuel */
141
+ function fuelTicks(name) {
142
+ if (name === 'lava_bucket')
143
+ return 20000;
144
+ if (name === 'coal_block')
145
+ return 16000;
146
+ if (name === 'dried_kelp_block')
147
+ return 4001;
148
+ if (name === 'blaze_rod')
149
+ return 2400;
150
+ if (name === 'coal' || name === 'charcoal')
151
+ return 1600;
152
+ if (name === 'bamboo' || name === 'scaffolding')
153
+ return 50;
154
+ if (name === 'stick' || name === 'bowl' || /_sapling$|_button$|^wooden_(sword|pickaxe|axe|shovel|hoe)$/.test(name))
155
+ return /_button$/.test(name) && !/^(oak|spruce|birch|jungle|acacia|dark_oak|mangrove|cherry|pale_oak|bamboo|crimson|warped)_button$/.test(name) ? 0 : 100;
156
+ if (/_slab$/.test(name))
157
+ return /^(oak|spruce|birch|jungle|acacia|dark_oak|mangrove|cherry|pale_oak|bamboo|crimson|warped)_slab$/.test(name) ? 150 : 0;
158
+ if (/_(sign|hanging_sign|door|boat|chest_boat)$/.test(name))
159
+ return /^(iron|copper|[a-z]+_copper)_/.test(name) ? 0 : 200;
160
+ if (/_wool$|_carpet$/.test(name))
161
+ return 67;
162
+ if (/^(oak|spruce|birch|jungle|acacia|dark_oak|mangrove|cherry|pale_oak|crimson|warped|bamboo)_(planks|log|wood|stem|hyphae|fence|fence_gate|stairs|trapdoor|pressure_plate|mosaic|block)$|^stripped_.*_(log|wood|stem|hyphae|block)$/.test(name))
163
+ return 300;
164
+ if (/^(crafting_table|chest|trapped_chest|barrel|bookshelf|chiseled_bookshelf|lectern|loom|note_block|jukebox|daylight_detector|composter|cartography_table|fletching_table|smithing_table|bow|crossbow|fishing_rod|ladder|[a-z_]+_banner)$/.test(name))
165
+ return 300;
166
+ return 0;
167
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Loot table evaluation for containers (chests, barrels, ...): the part of vanilla's `LootTable.fill` that matters for a chest:
3
+ * pools -> weighted entries -> item functions (set_count, set_damage, enchant_*, set_potion, ...) -> stacks split / shuffled into the free slots.
4
+ *
5
+ * Both datapack formats are read: 1.20.x (`functions`, `conditions`, `function`) and 1.21.x+ (`modifier`, `condition`, `type`).
6
+ * The random source is java.util.Random (as `LegacyRandomSource` in vanilla), seeded with the `LootTableSeed` of the container, so the same seed gives the same loot.
7
+ */
8
+ /** java.util.Random (48-bit LCG) */
9
+ export declare class JavaRandom {
10
+ private seed;
11
+ private static readonly MASK;
12
+ constructor(seed?: bigint | number);
13
+ private next;
14
+ nextInt(bound?: number): number;
15
+ nextBoolean(): boolean;
16
+ nextFloat(): number;
17
+ nextLong(): bigint;
18
+ /** `Mth.nextInt(random, min, max)` */
19
+ intBetween(min: number, maxInclusive: number): number;
20
+ }
21
+ /** an item stack before it is turned into a prismarine item */
22
+ export interface LootStack {
23
+ /** item name without namespace */
24
+ name: string;
25
+ count: number;
26
+ damage?: number;
27
+ /** [enchantment name, level] */
28
+ enchantments?: Array<[string, number]>;
29
+ potion?: string;
30
+ customName?: string;
31
+ }
32
+ export interface LootEnchantment {
33
+ name: string;
34
+ maxLevel: number;
35
+ weight: number;
36
+ minCost: {
37
+ a: number;
38
+ b: number;
39
+ };
40
+ maxCost: {
41
+ a: number;
42
+ b: number;
43
+ };
44
+ category?: string;
45
+ exclude?: string[];
46
+ }
47
+ export interface LootEnv {
48
+ /** parsed loot table json by id (`minecraft:chests/simple_dungeon`) */
49
+ getTable: (id: string) => any | undefined;
50
+ /** max stack size / durability of an item, undefined when the item does not exist in the running version (the stack is dropped) */
51
+ itemInfo: (name: string) => {
52
+ stackSize: number;
53
+ maxDurability?: number;
54
+ } | undefined;
55
+ enchantments?: LootEnchantment[];
56
+ /** names of the items of an item tag (`#minecraft:foo`) */
57
+ getItemTag?: (id: string) => string[];
58
+ }
59
+ /** the item categories an enchantment applies to (names of `minecraft-data` enchantment `category`) */
60
+ export declare function categoriesOf(name: string): string[];
61
+ /** `Collections.shuffle` with a java random */
62
+ export declare function shuffle<T>(list: T[], rnd: JavaRandom): void;
63
+ /**
64
+ * Evaluates a loot table into a container of `size` slots: returns `[slot, stack]` pairs for the slots in `freeSlots` (default: all).
65
+ * The stack size of each item is respected (a rolled count over the stack size is split over more slots).
66
+ */
67
+ export declare function fillContainer(table: any, size: number, seed: bigint | number | undefined, env: LootEnv, freeSlots?: number[]): Array<[number, LootStack]>;
@@ -0,0 +1,388 @@
1
+ "use strict";
2
+ /**
3
+ * Loot table evaluation for containers (chests, barrels, ...): the part of vanilla's `LootTable.fill` that matters for a chest:
4
+ * pools -> weighted entries -> item functions (set_count, set_damage, enchant_*, set_potion, ...) -> stacks split / shuffled into the free slots.
5
+ *
6
+ * Both datapack formats are read: 1.20.x (`functions`, `conditions`, `function`) and 1.21.x+ (`modifier`, `condition`, `type`).
7
+ * The random source is java.util.Random (as `LegacyRandomSource` in vanilla), seeded with the `LootTableSeed` of the container, so the same seed gives the same loot.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.JavaRandom = void 0;
11
+ exports.categoriesOf = categoriesOf;
12
+ exports.shuffle = shuffle;
13
+ exports.fillContainer = fillContainer;
14
+ /** java.util.Random (48-bit LCG) */
15
+ class JavaRandom {
16
+ seed;
17
+ static MASK = (1n << 48n) - 1n;
18
+ constructor(seed = BigInt(Date.now()) ^ BigInt(Math.floor(Math.random() * 2 ** 32))) {
19
+ this.seed = (BigInt(seed) ^ 0x5deece66dn) & JavaRandom.MASK;
20
+ }
21
+ next(bits) {
22
+ this.seed = (this.seed * 0x5deece66dn + 0xbn) & JavaRandom.MASK;
23
+ return Number(BigInt.asIntN(32, this.seed >> BigInt(48 - bits)));
24
+ }
25
+ nextInt(bound) {
26
+ if (bound === undefined)
27
+ return this.next(32);
28
+ if (bound <= 0)
29
+ throw new Error('bound must be positive');
30
+ if ((bound & -bound) === bound)
31
+ return Number((BigInt(bound) * BigInt(this.next(31))) >> 31n);
32
+ let bits;
33
+ let val;
34
+ do {
35
+ bits = this.next(31);
36
+ val = bits % bound;
37
+ } while (bits - val + (bound - 1) > 0x7FFFFFFF);
38
+ return val;
39
+ }
40
+ nextBoolean() { return this.next(1) !== 0; }
41
+ nextFloat() { return this.next(24) / (1 << 24); }
42
+ nextLong() { return BigInt.asIntN(64, (BigInt(this.next(32)) << 32n) + BigInt(this.next(32))); }
43
+ /** `Mth.nextInt(random, min, max)` */
44
+ intBetween(min, maxInclusive) { return min >= maxInclusive ? min : this.nextInt(maxInclusive - min + 1) + min; }
45
+ }
46
+ exports.JavaRandom = JavaRandom;
47
+ const strip = (id) => id.replace(/^minecraft:/, '');
48
+ const typeOf = (o) => strip(String(o?.type ?? o?.function ?? o?.condition ?? ''));
49
+ const asList = (v) => v === undefined || v === null ? [] : Array.isArray(v) ? v : [v];
50
+ /** number provider: a constant, `{min,max}`, `{type: uniform|binomial|constant}` */
51
+ function number(p, rnd, integer = false) {
52
+ if (typeof p === 'number')
53
+ return p;
54
+ if (p === undefined || p === null)
55
+ return 0;
56
+ const t = typeOf(p);
57
+ if (t === 'constant')
58
+ return p.value;
59
+ if (t === 'binomial') {
60
+ let n = 0;
61
+ for (let i = 0; i < number(p.n, rnd, true); i++)
62
+ if (rnd.nextFloat() < number(p.p, rnd))
63
+ n++;
64
+ return n;
65
+ }
66
+ // uniform (also the untyped {min, max} form)
67
+ const min = number(p.min, rnd);
68
+ const max = number(p.max, rnd);
69
+ if (integer || (Number.isInteger(min) && Number.isInteger(max) && t !== 'uniform_float'))
70
+ return rnd.intBetween(Math.floor(min), Math.floor(max));
71
+ return rnd.nextFloat() * (max - min) + min;
72
+ }
73
+ function conditionHolds(c, rnd) {
74
+ switch (typeOf(c)) {
75
+ case 'random_chance': return rnd.nextFloat() < number(c.chance, rnd);
76
+ case 'inverted': return typeOf(c.term) === 'random_chance' ? !conditionHolds(c.term, rnd) : true;
77
+ case 'all_of': return asList(c.terms).every(t => conditionHolds(t, rnd));
78
+ case 'any_of': return asList(c.terms).some(t => conditionHolds(t, rnd));
79
+ case 'killed_by_player':
80
+ case 'entity_properties':
81
+ case 'damage_source_properties':
82
+ case 'match_tool':
83
+ case 'block_state_property': return false;
84
+ default: return true; // location_check, table_bonus, ... need a world context a chest does not have
85
+ }
86
+ }
87
+ const holds = (o, rnd) => [...asList(o.conditions), ...asList(o.condition)].every(c => conditionHolds(c, rnd));
88
+ /** the item categories an enchantment applies to (names of `minecraft-data` enchantment `category`) */
89
+ function categoriesOf(name) {
90
+ const out = [];
91
+ if (/_helmet$|^turtle_helmet$/.test(name))
92
+ out.push('armor_head', 'armor', 'wearable');
93
+ else if (/_chestplate$/.test(name))
94
+ out.push('armor_chest', 'armor_torso', 'armor', 'wearable');
95
+ else if (/_leggings$/.test(name))
96
+ out.push('armor_legs', 'armor', 'wearable');
97
+ else if (/_boots$/.test(name))
98
+ out.push('armor_feet', 'armor', 'wearable');
99
+ else if (/_sword$|_axe$|_spear$/.test(name))
100
+ out.push('weapon');
101
+ if (/_(pickaxe|shovel|hoe|axe)$/.test(name))
102
+ out.push('digger');
103
+ if (name === 'bow')
104
+ out.push('bow');
105
+ if (name === 'crossbow')
106
+ out.push('crossbow');
107
+ if (name === 'trident')
108
+ out.push('trident');
109
+ if (name === 'fishing_rod')
110
+ out.push('fishing_rod');
111
+ if (name === 'elytra' || name === 'shears' || name === 'flint_and_steel' || name === 'shield' || name === 'carrot_on_a_stick' || name === 'mace' || name === 'brush')
112
+ out.push('breakable');
113
+ if (out.some(c => ['weapon', 'digger', 'armor', 'bow', 'crossbow', 'trident', 'fishing_rod'].includes(c)))
114
+ out.push('breakable', 'vanishable');
115
+ return out;
116
+ }
117
+ /** the enchantment a random level gets: `Mth.nextInt` over the cost ranges like `EnchantmentHelper.getAvailableEnchantmentResults` */
118
+ function enchantWithLevels(stack, levels, rnd, env, allowedNames) {
119
+ const all = env.enchantments ?? [];
120
+ const isBook = stack.name === 'book' || stack.name === 'enchanted_book';
121
+ const cats = categoriesOf(stack.name);
122
+ const applicable = all.filter(e => (isBook || (cats.length > 0 && (!e.category || cats.includes(e.category)))) && (!allowedNames || allowedNames.has(e.name)));
123
+ if (!applicable.length)
124
+ return;
125
+ // enchantability ~ 10 (iron), as the loot function uses the item's enchantability: level + 1 + rand(enchantability/4+1) + rand(enchantability/4+1), +-15 %
126
+ const enchantability = 10;
127
+ let level = levels + 1 + rnd.nextInt(Math.floor(enchantability / 4) + 1) + rnd.nextInt(Math.floor(enchantability / 4) + 1);
128
+ const bonus = (rnd.nextFloat() + rnd.nextFloat() - 1) * 0.15;
129
+ level = Math.max(1, Math.round(level + level * bonus));
130
+ let pool = applicable.filter(e => {
131
+ for (let l = e.maxLevel; l >= 1; l--)
132
+ if (level >= e.minCost.a * l + e.minCost.b && level <= e.maxCost.a * l + e.maxCost.b)
133
+ return true;
134
+ return false;
135
+ });
136
+ const chosen = [];
137
+ while (pool.length) {
138
+ const total = pool.reduce((a, e) => a + (e.weight || 1), 0);
139
+ let r = rnd.nextInt(total);
140
+ const pick = pool.find(e => (r -= (e.weight || 1)) < 0) ?? pool[0];
141
+ let lvl = 1;
142
+ for (let l = pick.maxLevel; l >= 1; l--)
143
+ if (level >= pick.minCost.a * l + pick.minCost.b && level <= pick.maxCost.a * l + pick.maxCost.b) {
144
+ lvl = l;
145
+ break;
146
+ }
147
+ chosen.push([pick.name, lvl]);
148
+ if (rnd.nextInt(50) <= level) {
149
+ level = Math.floor(level / 2);
150
+ pool = pool.filter(e => e !== pick && !(pick.exclude ?? []).includes(e.name) && !(e.exclude ?? []).includes(pick.name) && level >= e.minCost.b);
151
+ }
152
+ else
153
+ break;
154
+ }
155
+ stack.enchantments = [...(stack.enchantments ?? []), ...chosen];
156
+ }
157
+ function applyFunction(fn, stack, rnd, env) {
158
+ if (!holds(fn, rnd))
159
+ return stack;
160
+ switch (typeOf(fn)) {
161
+ case 'set_count': {
162
+ const n = Math.floor(number(fn.count, rnd));
163
+ stack.count = fn.add ? stack.count + n : n;
164
+ break;
165
+ }
166
+ case 'limit_count': {
167
+ const lim = fn.limit;
168
+ const [min, max] = typeof lim === 'number' ? [lim, lim] : [lim?.min ?? -Infinity, lim?.max ?? Infinity];
169
+ stack.count = Math.max(min, Math.min(max, stack.count));
170
+ break;
171
+ }
172
+ case 'set_damage': {
173
+ const max = env.itemInfo(stack.name)?.maxDurability;
174
+ if (max)
175
+ stack.damage = Math.floor(max * (1 - Math.max(0, Math.min(1, number(fn.damage, rnd)))));
176
+ break;
177
+ }
178
+ case 'enchant_with_levels': {
179
+ const allowed = typeof fn.options === 'string' && fn.options.startsWith('#') ? undefined : asList(fn.options).map(strip);
180
+ enchantWithLevels(stack, number(fn.levels, rnd, true), rnd, env, allowed?.length ? new Set(allowed) : undefined);
181
+ break;
182
+ }
183
+ case 'enchant_randomly': {
184
+ const names = Array.isArray(fn.options) ? fn.options.map(strip) : typeof fn.options === 'string' && !fn.options.startsWith('#') ? [strip(fn.options)] : undefined;
185
+ const cats = categoriesOf(stack.name);
186
+ const isBook = stack.name === 'book' || stack.name === 'enchanted_book';
187
+ const all = (env.enchantments ?? []).filter(e => (!names || names.includes(e.name)) && (isBook || fn.only_compatible === false || (cats.length > 0 && (!e.category || cats.includes(e.category)))));
188
+ if (all.length) {
189
+ const pick = all[rnd.nextInt(all.length)];
190
+ stack.enchantments = [...(stack.enchantments ?? []), [pick.name, rnd.intBetween(1, pick.maxLevel)]];
191
+ }
192
+ break;
193
+ }
194
+ case 'set_enchantments': {
195
+ const entries = Object.entries(fn.enchantments ?? {});
196
+ stack.enchantments = [...(fn.add ? stack.enchantments ?? [] : []), ...entries.map(([n, l]) => [strip(n), Math.floor(number(l, rnd, true))])];
197
+ break;
198
+ }
199
+ case 'set_potion':
200
+ stack.potion = strip(String(fn.id));
201
+ break;
202
+ case 'set_name': {
203
+ const n = fn.name;
204
+ stack.customName = typeof n === 'string' ? n : n?.translate ?? n?.text;
205
+ break;
206
+ }
207
+ case 'filtered': {
208
+ // item filters (e.g. "has a map id") need components the server does not build: the wrapped modifier is applied as it is
209
+ for (const f of asList(fn.modifier ?? fn.functions)) {
210
+ const r = applyFunction(f, stack, rnd, env);
211
+ if (!r)
212
+ return undefined;
213
+ }
214
+ break;
215
+ }
216
+ case 'sequence': {
217
+ for (const f of asList(fn.functions ?? fn.modifiers)) {
218
+ const r = applyFunction(f, stack, rnd, env);
219
+ if (!r)
220
+ return undefined;
221
+ }
222
+ break;
223
+ }
224
+ default: break; // explosion_decay, furnace_smelt, set_stew_effect, exploration_map, set_components, ...: the plain item is kept
225
+ }
226
+ return stack;
227
+ }
228
+ function applyFunctions(owner, stack, rnd, env) {
229
+ let cur = stack;
230
+ for (const fn of [...asList(owner.functions), ...asList(owner.modifier)]) {
231
+ cur = applyFunction(fn, cur, rnd, env);
232
+ if (!cur)
233
+ return undefined;
234
+ }
235
+ return cur;
236
+ }
237
+ /** returns whether the entry produced something (used by alternatives / sequence) */
238
+ function runEntry(entry, rnd, env, emit, depth) {
239
+ if (!holds(entry, rnd))
240
+ return false;
241
+ switch (typeOf(entry)) {
242
+ case 'item': {
243
+ const name = strip(String(entry.name));
244
+ const info = env.itemInfo(name);
245
+ if (!info)
246
+ return true; // counts as chosen (consumed the roll) but the item does not exist in this version
247
+ const stack = applyFunctions(entry, { name, count: 1 }, rnd, env);
248
+ if (stack && stack.count > 0)
249
+ emit(stack);
250
+ return true;
251
+ }
252
+ case 'tag': {
253
+ const names = env.getItemTag?.(String(entry.name)) ?? [];
254
+ const expand = entry.expand === true;
255
+ if (!names.length)
256
+ return true;
257
+ const list = expand ? [names[rnd.nextInt(names.length)]] : names;
258
+ for (const n of list) {
259
+ const stack = applyFunctions(entry, { name: strip(n), count: 1 }, rnd, env);
260
+ if (stack && env.itemInfo(stack.name) && stack.count > 0)
261
+ emit(stack);
262
+ }
263
+ return true;
264
+ }
265
+ case 'loot_table': {
266
+ if (depth > 8)
267
+ return true;
268
+ const ref = entry.value ?? entry.name;
269
+ const table = typeof ref === 'string' ? env.getTable(ref) : ref;
270
+ if (table)
271
+ runTable(table, rnd, env, s => { const r = applyFunctions(entry, s, rnd, env); if (r)
272
+ emit(r); }, depth + 1);
273
+ return true;
274
+ }
275
+ case 'alternatives': {
276
+ for (const child of asList(entry.children))
277
+ if (runEntry(child, rnd, env, emit, depth))
278
+ return true;
279
+ return false;
280
+ }
281
+ case 'sequence': {
282
+ for (const child of asList(entry.children))
283
+ if (!runEntry(child, rnd, env, emit, depth))
284
+ return false;
285
+ return true;
286
+ }
287
+ case 'group': {
288
+ for (const child of asList(entry.children))
289
+ runEntry(child, rnd, env, emit, depth);
290
+ return true;
291
+ }
292
+ case 'empty': return true;
293
+ default: return true;
294
+ }
295
+ }
296
+ function runPool(pool, rnd, env, emit, depth) {
297
+ if (!holds(pool, rnd))
298
+ return;
299
+ const entries = asList(pool.entries);
300
+ const rolls = Math.floor(number(pool.rolls, rnd, true));
301
+ const out = (s) => { const r = applyFunctions(pool, s, rnd, env); if (r)
302
+ emit(r); };
303
+ for (let i = 0; i < rolls; i++) {
304
+ // weighted pick among the entries whose conditions hold (conditions of composite entries are checked when they run)
305
+ const candidates = entries.filter(e => !(e.conditions || e.condition) || holds(e, rnd));
306
+ const total = candidates.reduce((a, e) => a + (e.weight ?? 1), 0);
307
+ if (total <= 0)
308
+ continue;
309
+ if (candidates.length === 1) {
310
+ runEntry({ ...candidates[0], conditions: undefined, condition: undefined }, rnd, env, out, depth);
311
+ continue;
312
+ }
313
+ let r = rnd.nextInt(total);
314
+ const pick = candidates.find(e => (r -= (e.weight ?? 1)) < 0) ?? candidates[0];
315
+ runEntry({ ...pick, conditions: undefined, condition: undefined }, rnd, env, out, depth);
316
+ }
317
+ }
318
+ function runTable(table, rnd, env, emit, depth = 0) {
319
+ const out = (s) => { const r = applyFunctions(table, s, rnd, env); if (r)
320
+ emit(r); };
321
+ for (const pool of asList(table.pools))
322
+ runPool(pool, rnd, env, out, depth);
323
+ }
324
+ /** `Collections.shuffle` with a java random */
325
+ function shuffle(list, rnd) {
326
+ for (let i = list.length; i > 1; i--) {
327
+ const j = rnd.nextInt(i);
328
+ [list[i - 1], list[j]] = [list[j], list[i - 1]];
329
+ }
330
+ }
331
+ /** `LootTable.shuffleAndSplitItems`: big stacks are split so a chest gets spread-out loot, then everything is shuffled */
332
+ function shuffleAndSplit(stacks, freeSlots, rnd) {
333
+ const items = [];
334
+ const splittable = [];
335
+ for (const s of stacks) {
336
+ if (s.count <= 0)
337
+ continue;
338
+ if (s.count > 1)
339
+ splittable.push(s);
340
+ else
341
+ items.push(s);
342
+ }
343
+ while (freeSlots - items.length - splittable.length > 0 && splittable.length > 0) {
344
+ const s = splittable.splice(rnd.nextInt(splittable.length), 1)[0];
345
+ const n = rnd.intBetween(1, Math.floor(s.count / 2));
346
+ const split = { ...s, count: n, enchantments: s.enchantments?.map(e => [...e]) };
347
+ s.count -= n;
348
+ if (s.count > 1 && rnd.nextBoolean())
349
+ splittable.push(s);
350
+ else
351
+ items.push(s);
352
+ if (split.count > 1 && rnd.nextBoolean())
353
+ splittable.push(split);
354
+ else
355
+ items.push(split);
356
+ }
357
+ items.push(...splittable);
358
+ shuffle(items, rnd);
359
+ return items;
360
+ }
361
+ /**
362
+ * Evaluates a loot table into a container of `size` slots: returns `[slot, stack]` pairs for the slots in `freeSlots` (default: all).
363
+ * The stack size of each item is respected (a rolled count over the stack size is split over more slots).
364
+ */
365
+ function fillContainer(table, size, seed, env, freeSlots) {
366
+ const rnd = seed ? new JavaRandom(seed) : new JavaRandom();
367
+ const rolled = [];
368
+ runTable(table, rnd, env, s => {
369
+ // merge into an existing stack of the same item like `LootTable.getRandomItems` does (items over the stack size are cut to stack-size parts)
370
+ const max = env.itemInfo(s.name)?.stackSize ?? 64;
371
+ let left = s.count;
372
+ while (left > 0) {
373
+ const n = Math.min(left, max);
374
+ rolled.push({ ...s, count: n });
375
+ left -= n;
376
+ }
377
+ });
378
+ const slots = freeSlots ? [...freeSlots] : Array.from({ length: size }, (_, i) => i);
379
+ shuffle(slots, rnd);
380
+ const items = shuffleAndSplit(rolled, slots.length, rnd);
381
+ const out = [];
382
+ for (const item of items) {
383
+ if (!slots.length)
384
+ break;
385
+ out.push([slots.shift(), item]);
386
+ }
387
+ return out;
388
+ }
@@ -0,0 +1 @@
1
+ export {};