merge master into ws/arch2

This commit is contained in:
4DBug committed 2026-10-31 15:22:43 -05:00
commit 0ee0859298
64 files changed
+13113 -30

No files matched your search

@@ -62,9 +62,10 @@ local function grow(out: buffer, op: number, need: number): (buffer, number)
end
-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in
-- cap bytes (an error otherwise), false = grow as needed.
-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and
-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing).
-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message.
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean): (buffer?, any, number?)
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?): (buffer?, any, number?)
local out = bcreate(cap)
local op = 0
local pos = start
@@ -123,6 +124,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
end
if op + n > cap then
if exact then
if prefix then
return out, op, pos
end
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + n)
@@ -295,6 +299,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
if sym < 256 then
if op >= cap then
if exact then
if prefix then
return out, op, pos
end
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + 1)
@@ -388,6 +395,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
end
if op + len > cap then
if exact then
if prefix then
return out, op, pos
end
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + len)
+66 -24
View File
@@ -9,6 +9,7 @@
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
-- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw
--
-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG).
local Err = require("@formats/core/Err")
@@ -101,6 +102,36 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex
return out, consumed + 4
end
-- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err
local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?)
local flg = buffer.readu8(b, p + 3)
if flg >= 0x20 then
return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3)
end
local q = p + 10
if bit32.band(flg, 4) ~= 0 then -- FEXTRA
if q + 2 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
q += 2 + buffer.readu16(b, q)
end
for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated
if bit32.band(flg, bit) ~= 0 then
while q < e and buffer.readu8(b, q) ~= 0 do
q += 1
end
q += 1
end
end
if bit32.band(flg, 2) ~= 0 then -- FHCRC
q += 2
end
if q >= e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
return q, nil
end
-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is
-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does.
function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
@@ -127,30 +158,9 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?):
if buffer.readu8(b, p + 2) ~= 8 then
return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2)
end
local flg = buffer.readu8(b, p + 3)
if flg >= 0x20 then
return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3)
end
local q = p + 10
if bit32.band(flg, 4) ~= 0 then -- FEXTRA
if q + 2 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
q += 2 + buffer.readu16(b, q)
end
for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated
if bit32.band(flg, bit) ~= 0 then
while q < e and buffer.readu8(b, q) ~= 0 do
q += 1
end
q += 1
end
end
if bit32.band(flg, 2) ~= 0 then -- FHCRC
q += 2
end
if q >= e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
local q, herr = gzipBody(b, p, e)
if not q then
return nil, herr
end
local out, consumed = Deflate.inflate(b, q, e - q)
if not out then
@@ -191,6 +201,38 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?):
return res, nil
end
-- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to
-- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating
-- the rest or checking checksums: for sniffing compressed files cheaply.
function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?)
local b, o, l, aerr = args("Deflate.peek", buf, offset, length)
if not b then
return nil, aerr
end
if type(n) ~= "number" or n < 1 then
return nil, Err.new(Err.ARG, "Deflate.peek: bad size " .. tostring(n))
end
local e = o + l
local q = o
if l >= 18 and buffer.readu8(b, o) == 0x1f and buffer.readu8(b, o + 1) == 0x8b and buffer.readu8(b, o + 2) == 8 then
local herr
q, herr = gzipBody(b, o, e)
if not q then
return nil, herr
end
elseif l >= 6 then
local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1)
if cmf % 16 == 8 and cmf // 16 <= 7 and (cmf * 256 + flg) % 31 == 0 and bit32.band(flg, 0x20) == 0 then
q = o + 2
end
end
local out, k = Inflate.raw(b, q :: number, e, n, true, true)
if not out then
return nil, inflateErr(tostring(k), q)
end
return shrink(out, k), nil
end
export type CompressOptions = {
level: number?, -- 0 (stored) .. 9 (best); default 6
}
@@ -0,0 +1,81 @@
--!strict
-- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured
-- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were
-- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs /
-- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa.
local Colors = {}
Colors.BLOCKS = [[
stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889
polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c
mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996
suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5
red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f
sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d
iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010
netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284
cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8
budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660
obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d
ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd
ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a
carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055
polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518
red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202
warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab
prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c
terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0
chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969
cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51
polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737
cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67
polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757
moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165
bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4
lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29
vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22
kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051
mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8
honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86
lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32
cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26
crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50
mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab
redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c
sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444
chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853
activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638
soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032
fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26
beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060
wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60
cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97
dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536
cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64
trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f
repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a
dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b
orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8
lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0
torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c
flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a
beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c
weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23
frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27
muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea
creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a
]]
-- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES)
Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" }
Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519"
Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f"
Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610"
-- wood types: planks, bark (log / wood), leaves
Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" }
Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963"
Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d"
Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265"
return Colors
@@ -0,0 +1,108 @@
--!strict
-- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with
-- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code):
-- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it
-- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks).
local Legacy = {}
local function words(s: string): { string }
local out = {}
for w in string.gmatch(s, "%S+") do
table.insert(out, w)
end
return out
end
-- ids 0 .. 255 (NAMES[id + 1]), "-" = unused
Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava
lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock
bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension
yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt
bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block
crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever
stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch
stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal
lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick
brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate
brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart
enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp
lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire
emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots
potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate
unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs
activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime
barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant
standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2
stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence
birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door
end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks
beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block
red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box
light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box
cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box
black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta
light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta
gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta
blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta
concrete concrete_powder - - structure_block]])
-- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact:
-- lit_furnace, powered_repeater, ... keep their legacy names)
Legacy.RENAMED = {
grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta",
melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block",
red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks",
mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block",
quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad",
tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone",
stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion",
fence = "oak_fence", fence_gate = "oak_fence_gate",
wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate",
wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign",
wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston",
silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta",
monster_egg = "infested_stone",
standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull",
bed = "red_bed",
} :: { [string]: string }
-- legacy names whose data value selects the variant: the modern names by data value (0-based)
local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black"
local function dyed(suffix: string): { string }
local out = {}
for i, d in words(DYED) do
out[i] = d .. "_" .. suffix
end
return out
end
Legacy.VARIANTS = {
stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" },
dirt = { "dirt", "coarse_dirt", "podzol" },
planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" },
wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" },
sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" },
sand = { "sand", "red_sand" },
log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4
log2 = { "acacia_log", "dark_oak_log" },
leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" },
leaves2 = { "acacia_leaves", "dark_oak_leaves" },
sponge = { "sponge", "wet_sponge" },
sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" },
red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" },
stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" },
quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" },
prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" },
cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" },
red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" },
double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" },
wool = dyed("wool"),
carpet = dyed("carpet"),
stained_glass = dyed("stained_glass"),
stained_glass_pane = dyed("stained_glass_pane"),
stained_hardened_clay = dyed("terracotta"),
concrete = dyed("concrete"),
concrete_powder = dyed("concrete_powder"),
} :: { [string]: { string } }
Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } :: { [string]: number }
return Legacy
@@ -0,0 +1,220 @@
--!strict
--!native
--!optimize 2
-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and
-- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding
-- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16:
-- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written
-- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws.
local Packed = {}
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
local writeu8, writeu16 = buffer.writeu8, buffer.writeu16
local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor
-- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes
function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number
if spanning then
return (count * bits + 63) // 64
end
local per = 64 // bits
return (count + per - 1) // per
end
-- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte
-- 0); an index >= max is an error. bits 1 .. 16.
function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?)
if bits < 1 or bits > 16 then
return false, "unsupported: " .. bits .. "-bit packed indices"
end
local need = Packed.longsNeeded(count, bits, spanning)
if buffer.len(longs) < need * 8 then
return false, "packed array too short (" .. buffer.len(longs) // 8 .. " longs, need " .. need .. ")"
end
if buffer.len(out) < count * 2 then
return false, "output too small"
end
-- a copy with 4 bytes of padding, so every 32-bit read stays in range
local n = need * 8
local src = buffer.create(n + 4)
buffer.copy(src, 0, longs, 0, n)
if spanning then
local p = 0
for i = 0, count - 1 do
local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits)
if v >= max then
return false, "index " .. v .. " past the palette (" .. max .. ")"
end
writeu16(out, i * 2, v)
p += bits
end
else
local per = 64 // bits
local i = 0
local base = 0
while i < count do
local p = 0
for _ = 1, per do
if i >= count then
break
end
local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits)
if v >= max then
return false, "index " .. v .. " past the palette (" .. max .. ")"
end
writeu16(out, i * 2, v)
i += 1
p += bits
end
base += 8
end
end
return true, nil
end
-- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack
function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer
local need = Packed.longsNeeded(count, bits, spanning)
local out = buffer.create(need * 8 + 4)
local per = 64 // bits
for i = 0, count - 1 do
local v = readu16(indices, i * 2)
local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits
local at = rshift(p, 3)
local sh = band(p, 7)
-- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7)
local x = lshift(v, sh)
for k = 0, 2 do
local bits8 = band(rshift(x, k * 8), 0xff)
if bits8 ~= 0 then
writeu8(out, at + k, bor(readu8(out, at + k), bits8))
end
end
end
local res = buffer.create(need * 8)
buffer.copy(res, 0, out, 0, need * 8)
return res
end
-- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min)
function Packed.bitsFor(n: number, min: number): number
local b = min
while lshift(1, b) < n and b < 31 do
b += 1
end
return b
end
-- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge
-- BlockData) into out (u16 LE)
function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?)
if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then
return false, "bad varint array arguments"
end
local p, e = offset, offset + length
for i = 0, count - 1 do
local v, sh = 0, 0
while true do
if p >= e then
return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries"
end
local c = readu8(src, p)
p += 1
v += band(c, 0x7f) * 2 ^ sh
if c < 128 then
break
end
sh += 7
if sh > 28 then
return false, "varint too long"
end
end
if v >= max then
return false, "index " .. v .. " past the palette (" .. max .. ")"
end
writeu16(out, i * 2, v)
end
return true, nil
end
-- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints
function Packed.toVarints(indices: buffer, count: number): buffer
local out = buffer.create(count * 3)
local p = 0
for i = 0, count - 1 do
local v = readu16(indices, i * 2)
while v >= 128 do
writeu8(out, p, band(v, 0x7f) + 128)
p += 1
v = rshift(v, 7)
end
writeu8(out, p, v)
p += 1
end
local res = buffer.create(p)
buffer.copy(res, 0, out, 0, p)
return res
end
-- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's
-- AddBlocks: high nibble first)
function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number
local b = readu8(src, offset + rshift(i, 1))
local odd = band(i, 1) == 1
if odd == highFirst then
return band(b, 15)
end
return rshift(b, 4)
end
-- setNibble(dst, offset, i, v, highFirst)
function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean)
local at = offset + rshift(i, 1)
local b = readu8(dst, at)
local odd = band(i, 1) == 1
if odd == highFirst then
writeu8(dst, at, bor(band(b, 0xf0), band(v, 15)))
else
writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4)))
end
end
-- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then
-- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new
-- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges.
function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer
local out = dst or buffer.create(sx * sy * sz * 2)
local bx, by, bz = ox or 0, oy or 0, oz or 0
local wx, wy = dsx or sx, dsy or sy
local i = 0
for y = 0, sy - 1 do
for z = 0, sz - 1 do
local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2
for _ = 0, sx - 1 do
writeu16(out, d, readu16(src, i))
i += 2
d += 2
end
end
end
return out
end
-- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx)
function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer
local out = buffer.create(sx * sy * sz * 2)
local i = 0
for y = 0, sy - 1 do
for z = 0, sz - 1 do
local s = (sx * (y + sy * z)) * 2
for _ = 0, sx - 1 do
writeu16(out, i, readu16(src, s))
i += 2
s += 2
end
end
end
return out
end
return Packed
@@ -0,0 +1,587 @@
--!strict
-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code.
-- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default
-- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids
-- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block
-- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data /
-- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour.
--
-- local Mc = require("@formats/codecs/model/Minecraft")
-- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } }
-- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air
-- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks
-- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour)
local Types = require("@formats/Types")
local Nbt = require("@formats/codecs/text/Nbt")
local Colors = require("@formats/codecs/model/Minecraft/Colors")
local Legacy = require("@formats/codecs/model/Minecraft/Legacy")
local Packed = require("@formats/codecs/model/Minecraft/Packed")
local Minecraft = {}
Minecraft.Packed = Packed
Minecraft.Legacy = Legacy
-- ------------------------------------------------------------------------------------------------ block states
-- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order
function Minecraft.parseState(s: string): (string, { { string } })
local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$")
local n = name or ""
if n ~= "" and not string.find(n, ":", 1, true) then
n = "minecraft:" .. n
end
local props = {}
local body = rest and string.match(rest :: string, "^%[(.*)%]%s*$")
if body then
for pair in string.gmatch(body, "[^,]+") do
local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$")
if k then
table.insert(props, { k, v :: string })
end
end
end
return n, props
end
-- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted)
function Minecraft.stateString(name: string, props: { any }?): string
if not props or next(props) == nil then
return name
end
local parts = {}
if props[1] ~= nil then
for _, kv in props do
table.insert(parts, kv[1] .. "=" .. tostring(kv[2]))
end
else
for _, k in Types.keys(props) do
table.insert(parts, tostring(k) .. "=" .. tostring((props :: any)[k]))
end
end
return name .. "[" .. table.concat(parts, ",") .. "]"
end
-- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections)
function Minecraft.stateFromNbt(c: any): string?
if type(c) ~= "table" or type(c.Name) ~= "string" then
return nil
end
local props = {}
if type(c.Properties) == "table" then
for _, k in Types.keys(c.Properties) do
local v = c.Properties[k]
table.insert(props, { k, if type(v) == "string" then v else tostring(Nbt.number(v) or v) })
end
end
return Minecraft.stateString(c.Name, props)
end
-- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order)
function Minecraft.stateToNbt(s: string): { [string]: any }
local name, props = Minecraft.parseState(s)
local c = Types.object({ Name = name }, { "Name" })
if #props > 0 then
local p, keys = {}, {}
for _, kv in props do
p[kv[1]] = kv[2]
table.insert(keys, kv[1])
end
Types.set(c, "Properties", Types.object(p, keys))
end
return c
end
-- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log")
function Minecraft.baseName(s: string): string
local name = string.match(s, "^%s*([^%[%s]*)") or ""
return string.match(name, ":(.*)$") or name
end
local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true }
-- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier)
function Minecraft.isAir(s: string): boolean
return AIR[Minecraft.baseName(s)] == true
end
-- ------------------------------------------------------------------------------------------------ colours
local function hex(h: string): { number }
local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 }
if #h >= 8 then
c[4] = tonumber(string.sub(h, 7, 8), 16) or 255
end
return c
end
local function list(s: string): { { number } }
local out = {}
for h in string.gmatch(s, "%x+") do
table.insert(out, hex(h))
end
return out
end
local EXACT: { [string]: { number } } = {}
for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do
EXACT[name :: string] = hex(h :: string)
end
local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA)
local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES)
-- longest prefixes first, so light_blue wins over blue and dark_oak over oak
local function byLength(names: { string }): { { any } }
local out: { { any } } = {}
for i, n in names do
table.insert(out, { n, i })
end
table.sort(out, function(a: { any }, b: { any }): boolean
return #(a[1] :: string) > #(b[1] :: string)
end)
return out
end
local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS)
local SUFFIXES = {
"_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button",
"_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars",
}
local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" }
local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") }
local FALLBACK = hex("909090")
local function mix(c: { number }, w: { number }, t: number): { number }
return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] }
end
local resolve: (string, number) -> { number }?
local function family(n: string): { number }?
for _, d in DYES do
local pre = d[1] .. "_"
if string.sub(n, 1, #pre) == pre then
local rest = string.sub(n, #pre + 1)
local i = d[2]
if rest == "concrete" then
return CONCRETE[i]
elseif rest == "concrete_powder" then
return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2)
elseif rest == "terracotta" then
return TERRACOTTA[i]
elseif string.find(rest, "glass", 1, true) then
local c = table.clone(WOOL[i])
c[4] = 0x80
return c
end
return WOOL[i]
end
end
local stripped = string.match(n, "^stripped_(.*)$")
for _, w in WOODS do
local pre = w[1] .. "_"
local m = stripped or n
if string.sub(m, 1, #pre) == pre then
local rest = string.sub(m, #pre + 1)
local i = w[2]
if stripped then
return PLANKS[i]
elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then
return BARK[i]
elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then
return LEAVES[i]
elseif rest == "block" and w[1] == "bamboo" then
return EXACT.bamboo_block
end
return PLANKS[i]
end
end
return nil
end
local function keywords(n: string): { number }?
if string.find(n, "copper", 1, true) then
return if string.find(n, "oxidized", 1, true) then EXACT.oxidized_copper
elseif string.find(n, "weathered", 1, true) then EXACT.weathered_copper
elseif string.find(n, "exposed", 1, true) then EXACT.exposed_copper
else EXACT.copper_block
elseif string.find(n, "coral", 1, true) then
if string.find(n, "dead", 1, true) then
return hex("857e79")
end
for k, c in CORAL do
if string.find(n, k, 1, true) then
return c
end
end
elseif string.find(n, "_ore$") then
return if string.find(n, "deepslate", 1, true) then EXACT.deepslate
elseif string.find(n, "nether", 1, true) then EXACT.netherrack
else EXACT.stone
end
for _, k in { "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" } do
if string.find(n, k, 1, true) then
local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } :: any)[k]
return EXACT[alias]
end
end
return nil
end
resolve = function(n: string, depth: number): { number }?
if depth > 4 then
return nil
end
local c = EXACT[n]
if c then
return c
end
local renamed = Legacy.RENAMED[n]
if renamed then
return resolve(renamed, depth + 1)
end
for _, p in PREFIXES do
if string.sub(n, 1, #p) == p then
return resolve(string.sub(n, #p + 1), depth + 1)
end
end
c = family(n)
if c then
return c
end
for _, sfx in SUFFIXES do
if #n > #sfx and string.sub(n, -#sfx) == sfx then
local base = string.sub(n, 1, #n - #sfx)
for _, form in { base, base .. "s", base .. "_block", base .. "_planks" } do
local fc = EXACT[form] or family(form)
if fc then
return fc
end
end
return resolve(base, depth + 1)
end
end
return keywords(n)
end
local cache: { [string]: { number } | false } = {}
-- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords
function Minecraft.color(s: string): { number }?
local hit = cache[s]
if hit ~= nil then
return hit or nil
end
local name, props = Minecraft.parseState(s)
local n = string.match(name, ":(.*)$") or name
local res: { number }? = nil
if not AIR[n] then
-- pre-1.13 names whose data value picks the variant
local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil)
if variants then
local data = 0
for _, kv in props do
if kv[1] == "data" then
data = tonumber(kv[2]) or 0
end
end
local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1]
res = resolve(v, 0)
end
res = res or resolve(n, 0) or FALLBACK
end
cache[s] = res or false
return res
end
-- ------------------------------------------------------------------------------------------------ legacy ids
local REVERSE: { [string]: { number } }? = nil
local function reverse(): { [string]: { number } }
if REVERSE then
return REVERSE
end
local r: { [string]: { number } } = {}
local byName: { [string]: number } = {}
for i, n in Legacy.NAMES do
if n ~= "-" then
byName[n] = i - 1
end
end
for legacy, modern in Legacy.RENAMED do
r[modern] = { byName[legacy], 0 }
end
for legacy, variants in Legacy.VARIANTS do
for d, v in variants do
if r[v] == nil then
r[v] = { byName[legacy], d - 1 }
end
end
end
for n, id in byName do
if r[n] == nil then
r[n] = { id, 0 }
end
end
REVERSE = r
return r
end
-- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the
-- rest of the data value kept as [data=N] so legacyId gives it back exactly)
function Minecraft.legacyState(id: number, data: number): string
local n = Legacy.NAMES[id + 1]
if n == nil or n == "-" then
return "minecraft:legacy_" .. id .. (if data ~= 0 then "[data=" .. data .. "]" else "")
end
local variants = Legacy.VARIANTS[n]
if variants then
local idx = data % (Legacy.MASK[n] or 16)
local v = variants[idx + 1]
if v then
return "minecraft:" .. v .. (if data ~= idx then "[data=" .. data .. "]" else "")
end
end
return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "")
end
-- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their
-- properties are not converted to data values)
function Minecraft.legacyId(s: string): (number?, number?)
local name, props = Minecraft.parseState(s)
local n = string.match(name, ":(.*)$") or name
local id: number?, data = nil, 0
local lid = string.match(n, "^legacy_(%d+)$")
if lid then
id = tonumber(lid)
else
local e = reverse()[n]
if e then
id, data = e[1], e[2]
end
end
if id == nil then
return nil, nil
end
for _, kv in props do
if kv[1] == "data" then
data = (tonumber(kv[2]) or data) % 16
end
end
return id, data
end
-- ------------------------------------------------------------------------------------------------ voxels
-- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest,
-- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into
-- the nearest one)
function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels
local v = Types.Voxels.new(sx, sy, sz)
local lut = buffer.create(#states)
local slots: { [string]: number } = {}
local used = 0
for i, s in states do
local c = Minecraft.color(s)
local slot = 0
if c then
local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4])
slot = slots[key]
if not slot then
if used < 255 then
used += 1
slot = used
v.palette[slot] = { c[1], c[2], c[3], c[4] }
else
local best, bd = 1, math.huge
for k = 1, 255 do
local p = v.palette[k]
local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2
if d < bd then
best, bd = k, d
end
end
slot = best
end
slots[key] = slot
end
end
buffer.writeu8(lut, i - 1, slot)
end
local n = sx * sy * sz
local data, nstates = v.data, #states
for i = 0, n - 1 do
local s = buffer.readu16(indices, i * 2)
buffer.writeu8(data, i, if s < nstates then buffer.readu8(lut, s) else 0)
end
v.blocks = { palette = states, data = indices }
return v
end
-- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones)
local CANDIDATES: { { any } }? = nil
local function candidates(): { { any } }
if CANDIDATES then
return CANDIDATES
end
local out = {}
for _, d in Colors.DYES do
for _, kind in { "wool", "concrete", "terracotta" } do
local s = "minecraft:" .. d .. "_" .. kind
table.insert(out, { s, Minecraft.color(s) })
end
end
for _, w in Colors.WOODS do
local s = "minecraft:" .. w .. "_planks"
table.insert(out, { s, Minecraft.color(s) })
end
for _, n in { "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" } do
local s = "minecraft:" .. n
table.insert(out, { s, Minecraft.color(s) })
end
CANDIDATES = out
return out
end
-- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass)
function Minecraft.nearestBlock(c: { number }): string
local a = c[4] or 255
if a < 200 then
local best, bd = "minecraft:glass", math.huge
for i, d in Colors.DYES do
local w = WOOL[i]
local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2
if dist < bd then
best, bd = "minecraft:" .. d .. "_stained_glass", dist
end
end
return best
end
local best, bd = "minecraft:stone", math.huge
for _, cand in candidates() do
local k = cand[2]
local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2
if dist < bd then
best, bd = cand[1], dist
end
end
return best
end
-- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per
-- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message
function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any)
local n = v.size[1] * v.size[2] * v.size[3]
local b = v.blocks
if b then
if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then
return nil, "voxels.blocks must hold a palette and a u16 per cell"
end
if #b.palette == 0 or #b.palette > 65536 then
return nil, "voxels.blocks.palette must have 1 .. 65536 states"
end
return b.palette, b.data
end
local states = { "minecraft:air" }
local slotOf: { [number]: number } = { [0] = 0 }
local byState: { [string]: number } = { ["minecraft:air"] = 0 }
local out = buffer.create(n * 2)
local data = v.data
for i = 0, n - 1 do
local p = buffer.readu8(data, i)
local s = slotOf[p]
if s == nil then
local col = v.palette[p] or { 128, 128, 128, 255 }
local st = Minecraft.nearestBlock(col)
s = byState[st]
if s == nil then
table.insert(states, st)
s = #states - 1
byState[st] = s
end
slotOf[p] = s
end
buffer.writeu16(out, i * 2, s :: number)
end
return states, out
end
-- ------------------------------------------------------------------------------------------------ block entities
-- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat
-- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }.
local function int(v: any): number?
local n = Nbt.number(v)
if n == nil or n ~= n or n % 1 ~= 0 then
return nil
end
return n
end
local function ints(v: any): { number }?
if Nbt.isTag(v) and v.type == "intArray" then
return v.value
elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then
local out: { number } = {}
for i, x in v :: { any } do
out[i] = Nbt.number(x) or 0
end
return out
end
return nil
end
Minecraft.int = int -- the integer value of an NBT number | nil
Minecraft.ints = ints -- the numbers of an intArray or a list | nil
local function rest(c: any, skip: { [string]: boolean }): { [string]: any }
local out, keys = {}, {}
for _, k in Types.keys(c) do
if not skip[k] then
out[k] = c[k]
table.insert(keys, k)
end
end
return Types.object(out, keys)
end
local FLAT_SKIP = { x = true, y = true, z = true, id = true }
local POS_SKIP = { Pos = true, Id = true }
-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2),
-- "data" (Sponge v3)
function Minecraft.blockEntity(c: any, style: string): any
if type(c) ~= "table" or Nbt.isTag(c) then
return nil
end
if style == "flat" then
return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) }
end
local p = ints(c.Pos) or { 0, 0, 0 }
local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP)
return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data }
end
-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity)
function Minecraft.flatBlockEntity(be: any, style: string): any
local o = Types.object()
local data = if type(be.data) == "table" then be.data else Types.object()
if style == "flat" then
Types.set(o, "x", be.pos[1])
Types.set(o, "y", be.pos[2])
Types.set(o, "z", be.pos[3])
if be.id then
Types.set(o, "id", be.id)
end
for _, k in Types.keys(data) do
if not FLAT_SKIP[k] then
Types.set(o, k, data[k])
end
end
return o
end
Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] }))
if be.id then
Types.set(o, "Id", be.id)
end
if style == "data" then
Types.set(o, "Data", data)
else
for _, k in Types.keys(data) do
if not POS_SKIP[k] then
Types.set(o, k, data[k])
end
end
end
return o
end
return Minecraft
+774
View File
@@ -0,0 +1,774 @@
--!strict
--!native
--!optimize 2
-- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk
-- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte
-- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated"
-- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws.
--
-- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms)
-- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message
-- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT)
--
-- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none),
-- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }.
-- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know /
-- a layout it cannot read, which the format keeps raw).
local Rbx = require("@formats/codecs/model/Rbx")
local Bytes = require("@formats/core/Bytes")
local Binary = {}
local readu8, readu16, readi16, readu32, readf32, readf64 =
buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64
local writeu32, readstring = buffer.writeu32, buffer.readstring
local writef32 = buffer.writef32
local floor = math.floor
local scratch = buffer.create(8)
local TWO32 = 4294967296
-- ------------------------------------------------------------------------------------------------ transforms
-- the rotated float encoding: bits rotated left by one (sign in bit 0)
local function unrotate(x: number): number
writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648)
return readf32(scratch, 0)
end
local function rotate(v: number): number
writef32(scratch, 0, v)
local bits = readu32(scratch, 0)
return (bits * 2) % TWO32 + bits // 2147483648
end
local function unzigzag(x: number): number
return if x % 2 == 0 then x // 2 else -(x + 1) // 2
end
local function zigzag32(v: number): number
v = floor(v)
return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32
end
-- n big-endian u32 values interleaved at p (4n bytes)
local function u32s(b: buffer, p: number, n: number): { number }
local out = table.create(n, 0)
local n2, n3 = n * 2, n * 3
for i = 0, n - 1 do
out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i)
end
return out
end
local function i32s(b: buffer, p: number, n: number): { number }
local out = u32s(b, p, n)
for i = 1, n do
out[i] = unzigzag(out[i])
end
return out
end
local function f32s(b: buffer, p: number, n: number): { number }
local out = u32s(b, p, n)
for i = 1, n do
out[i] = unrotate(out[i])
end
return out
end
-- n zigzag i64 values (8n interleaved bytes), as doubles
local function i64s(b: buffer, p: number, n: number): { number }
local out = table.create(n, 0)
for i = 0, n - 1 do
local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i)
local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i)
local half = hi * 2147483648 + lo // 2
out[i + 1] = if lo % 2 == 0 then half else -half - 1
end
return out
end
-- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64
local function putU32s(w: Bytes.Writer, vals: { number })
local n = #vals
local p = w:reserve(4 * n)
local b = w.buf
for i = 0, n - 1 do
local v = vals[i + 1] % TWO32
buffer.writeu8(b, p + i, v // 16777216)
buffer.writeu8(b, p + n + i, (v // 65536) % 256)
buffer.writeu8(b, p + 2 * n + i, (v // 256) % 256)
buffer.writeu8(b, p + 3 * n + i, v % 256)
end
w.pos = p + 4 * n
end
local function putI32s(w: Bytes.Writer, vals: { number })
local t = table.create(#vals, 0)
for i, v in vals do
t[i] = zigzag32(v)
end
putU32s(w, t)
end
local function putF32s(w: Bytes.Writer, vals: { number })
local t = table.create(#vals, 0)
for i, v in vals do
t[i] = rotate(v)
end
putU32s(w, t)
end
local function putI64s(w: Bytes.Writer, vals: { number })
local n = #vals
local p = w:reserve(8 * n)
local b = w.buf
for i = 0, n - 1 do
local v = floor(vals[i + 1])
local z = if v >= 0 then v * 2 else -v * 2 - 1
local hi, lo = (z // TWO32) % TWO32, z % TWO32
buffer.writeu8(b, p + i, hi // 16777216)
buffer.writeu8(b, p + n + i, (hi // 65536) % 256)
buffer.writeu8(b, p + 2 * n + i, (hi // 256) % 256)
buffer.writeu8(b, p + 3 * n + i, hi % 256)
buffer.writeu8(b, p + 4 * n + i, lo // 16777216)
buffer.writeu8(b, p + 5 * n + i, (lo // 65536) % 256)
buffer.writeu8(b, p + 6 * n + i, (lo // 256) % 256)
buffer.writeu8(b, p + 7 * n + i, lo % 256)
end
w.pos = p + 8 * n
end
-- referent arrays: zigzag i32, interleaved, each the difference from the previous one
function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number)
if n < 0 or p + 4 * n > limit then
return nil, p
end
local out = i32s(b, p, n)
local acc = 0
for i = 1, n do
acc += out[i]
out[i] = acc
end
return out, p + 4 * n
end
function Binary.writeRefs(w: Bytes.Writer, refs: { number })
local d = table.create(#refs, 0)
local prev = 0
for i, r in refs do
d[i] = r - prev
prev = r
end
putI32s(w, d)
end
-- ------------------------------------------------------------------------------------------------ decode
export type Ctx = {
ref: ((number) -> any)?,
refOf: ((any) -> number)?,
shared: { string }?,
sharedIndex: ((string) -> number)?,
}
-- a length-prefixed string at p: string, next p (nil when it runs past limit)
local function str(b: buffer, p: number, limit: number): (string?, number)
if p + 4 > limit then
return nil, p
end
local len = readu32(b, p)
if p + 4 + len > limit then
return nil, p
end
return readstring(b, p + 4, len), p + 4 + len
end
local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number)
local rots: { { number } } = table.create(n) :: any
for i = 1, n do
if p >= limit then
return nil, p
end
local id = readu8(b, p)
p += 1
if id == 0 then
if p + 36 > limit then
return nil, p
end
local m = table.create(9, 0)
for k = 0, 8 do
m[k + 1] = readf32(b, p + 4 * k)
end
rots[i] = m
p += 36
else
local m = Rbx.ROTATIONS[id]
if not m then
return nil, -1
end
rots[i] = m
end
end
if p + 12 * n > limit then
return nil, p
end
local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n)
local out = table.create(n)
for i = 1, n do
local m = rots[i]
out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] }
end
return out, p + 12 * n
end
local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types
[0x02] = 1,
[0x03] = 4,
[0x04] = 4,
[0x05] = 8,
[0x06] = 8,
[0x07] = 16,
[0x08] = 24,
[0x09] = 1,
[0x0A] = 1,
[0x0B] = 4,
[0x0C] = 12,
[0x0D] = 8,
[0x0E] = 12,
[0x0F] = 4,
[0x12] = 4,
[0x13] = 4,
[0x14] = 6,
[0x17] = 8,
[0x18] = 16,
[0x1A] = 3,
[0x1B] = 8,
[0x1C] = 4,
[0x1F] = 16,
[0x21] = 8,
}
-- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message
function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any)
if limit > buffer.len(b) or p < 0 or n < 0 then
return nil, "corrupt: bad ranges"
end
local size = FIXED[t]
if size and p + size * n > limit then
return nil, "truncated property values"
end
if t == 0x01 or t == 0x1D then
local out = table.create(n, "")
for i = 1, n do
local s, q = str(b, p, limit)
if not s then
return nil, "truncated string"
end
out[i] = s
p = q
end
return out, p
elseif t == 0x02 then
local out = table.create(n, false)
for i = 1, n do
out[i] = readu8(b, p + i - 1) ~= 0
end
return out, p + n
elseif t == 0x03 then
return i32s(b, p, n), p + 4 * n
elseif t == 0x04 then
return f32s(b, p, n), p + 4 * n
elseif t == 0x05 then
local out = table.create(n, 0)
for i = 1, n do
out[i] = readf64(b, p + 8 * (i - 1))
end
return out, p + 8 * n
elseif t == 0x06 then
local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n)
local out = table.create(n)
for i = 1, n do
out[i] = { s[i], o[i] }
end
return out, p + 8 * n
elseif t == 0x07 then
local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n)
local out = table.create(n)
for i = 1, n do
out[i] = { xs[i], xo[i], ys[i], yo[i] }
end
return out, p + 16 * n
elseif t == 0x08 then
local out = table.create(n)
for i = 1, n do
local q = p + 24 * (i - 1)
out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) }
end
return out, p + 24 * n
elseif t == 0x09 or t == 0x0A then
local out = table.create(n, 0)
for i = 1, n do
out[i] = readu8(b, p + i - 1)
end
return out, p + n
elseif t == 0x0B or t == 0x12 then
return u32s(b, p, n), p + 4 * n
elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then
local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3
local cols: { { number } } = table.create(k) :: any
for c = 1, k do
cols[c] = f32s(b, p + 4 * n * (c - 1), n)
end
local out = table.create(n)
for i = 1, n do
local v = table.create(k, 0)
for c = 1, k do
v[c] = cols[c][i]
end
out[i] = v
end
return out, p + 4 * k * n
elseif t == 0x0F or t == 0x14 then
local k = if t == 0x0F then 2 else 3
local out = table.create(n)
for i = 1, n do
local q = p + 2 * k * (i - 1)
out[i] = if k == 2 then { readi16(b, q), readi16(b, q + 2) } else { readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) }
end
return out, p + 2 * k * n
elseif t == 0x10 then
local out, q = cframes(b, p, limit, n)
if not out then
return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values"
end
return out, q
elseif t == 0x13 then
local refs, q = Binary.readRefs(b, p, limit, n)
if not refs then
return nil, "truncated referents"
end
local out = table.create(n)
local ref = ctx.ref
for i = 1, n do
out[i] = if ref and refs[i] >= 0 then ref(refs[i]) else nil
end
return out, q
elseif t == 0x15 or t == 0x16 then
local k = if t == 0x15 then 3 else 5
local out = table.create(n)
for i = 1, n do
if p + 4 > limit then
return nil, "truncated sequence"
end
local count = readu32(b, p)
p += 4
if p + count * 4 * k > limit then
return nil, "truncated sequence"
end
local seq = table.create(count)
for j = 1, count do
local key = table.create(k, 0)
for c = 1, k do
key[c] = readf32(b, p + 4 * (c - 1))
end
seq[j] = key
p += 4 * k
end
out[i] = seq
end
return out, p
elseif t == 0x17 then
local out = table.create(n)
for i = 1, n do
out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) }
end
return out, p + 8 * n
elseif t == 0x19 then
local out = table.create(n)
for i = 1, n do
if p >= limit then
return nil, "truncated physical properties"
end
local flag = readu8(b, p)
p += 1
if flag % 2 == 1 then
local k = if flag // 2 % 2 == 1 then 6 else 5
if p + 4 * k > limit then
return nil, "truncated physical properties"
end
local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out
for c = 1, k do
v[c] = readf32(b, p + 4 * (c - 1))
end
out[i] = v
p += 4 * k
elseif flag ~= 0 then
return nil, "unknown"
end
end
return out, p
elseif t == 0x1A then
local out = table.create(n)
for i = 1, n do
out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) }
end
return out, p + 3 * n
elseif t == 0x1B or t == 0x21 then
return i64s(b, p, n), p + 8 * n
elseif t == 0x1C then
local idx = u32s(b, p, n)
local shared: { string } = ctx.shared or {}
local out: { string } = table.create(n, "")
for i = 1, n do
local s = shared[idx[i] + 1]
if s == nil then
return nil, "corrupt: shared string index out of range"
end
out[i] = s
end
return out, p + 4 * n
elseif t == 0x1E then
if p >= limit or readu8(b, p) ~= 0x10 then
return nil, "unknown"
end
local cfs, q = cframes(b, p + 1, limit, n)
if not cfs then
return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values"
end
if q + 1 + n > limit or readu8(b, q) ~= 0x02 then
return nil, "truncated optional CFrame flags"
end
local out = table.create(n)
for i = 1, n do
out[i] = if readu8(b, q + i) ~= 0 then cfs[i] else nil
end
return out, q + 1 + n
elseif t == 0x1F then
local out = table.create(n, "")
local hex = table.create(16, "")
for i = 0, n - 1 do
local by = table.create(16, 0)
for k = 0, 15 do
by[k + 1] = readu8(b, p + k * n + i)
end
-- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it
local carry = by[16] % 2
for k = 9, 16 do
local v = by[k]
by[k] = v // 2 + carry * 128
carry = v % 2
end
for k = 1, 8 do
hex[k] = string.format("%02x", by[8 + k])
end
for k = 1, 8 do
hex[8 + k] = string.format("%02x", by[k + 4 - (if k > 4 then 8 else 0)])
end
out[i + 1] = table.concat(hex)
end
return out, p + 16 * n
elseif t == 0x20 then
local out = table.create(n)
for i = 1, n do
local fam, q = str(b, p, limit)
if not fam or q + 3 > limit then
return nil, "truncated font"
end
local weight, style = readu16(b, q), readu8(b, q + 2)
local face, q2 = str(b, q + 3, limit)
if not face then
return nil, "truncated font"
end
out[i] = { family = fam, weight = weight, style = if style == 1 then "Italic" else "Normal", cachedFaceId = if face ~= "" then face else nil }
p = q2
end
return out, p
elseif t == 0x22 then
if p + 4 * n > limit then
return nil, "truncated content"
end
local kinds = i32s(b, p, n)
p += 4 * n
if p + 4 > limit then
return nil, "truncated content"
end
local nu = readu32(b, p)
p += 4
local uris = table.create(math.min(nu, n))
for j = 1, nu do
local s, q = str(b, p, limit)
if not s then
return nil, "truncated content"
end
uris[j] = s
p = q
end
if p + 4 > limit then
return nil, "truncated content"
end
local no = readu32(b, p)
local objs, q = Binary.readRefs(b, p + 4, limit, no)
if not objs or q + 4 > limit then
return nil, "truncated content"
end
if readu32(b, q) ~= 0 then
return nil, "unknown" -- external objects: kept raw
end
p = q + 4
local out = table.create(n)
local iu, io = 1, 1
for i = 1, n do
local k = kinds[i]
if k == 1 then
if iu > nu then
return nil, "corrupt: content uri count"
end
out[i] = uris[iu]
iu += 1
elseif k == 2 then
if io > no then
return nil, "corrupt: content object count"
end
local r = objs[io]
out[i] = if ctx.ref and r >= 0 then ctx.ref(r) else nil
io += 1
elseif k ~= 0 then
return nil, "unknown"
end
end
return out, p
end
return nil, "unknown"
end
-- ------------------------------------------------------------------------------------------------ encode
local function num(v: any): number
return if type(v) == "number" and v == v then v else 0
end
-- column c of n array values (missing components 0)
local function column(vals: { any }, n: number, c: number): { number }
local out = table.create(n, 0)
for i = 1, n do
local v = vals[i]
out[i] = if type(v) == "table" then num(v[c]) else 0
end
return out
end
local function putString(w: Bytes.Writer, s: string)
w:u32le(#s)
w:string(s)
end
local function putCFrames(w: Bytes.Writer, vals: { any }, n: number)
for i = 1, n do
local v = vals[i]
local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
local id = Rbx.rotationId(cf)
w:u8(id)
if id == 0 then
for k = 4, 12 do
w:f32le(num(cf[k]))
end
end
end
putF32s(w, column(vals, n, 1))
putF32s(w, column(vals, n, 2))
putF32s(w, column(vals, n, 3))
end
local function hexByte(s: string, i: number): number
return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0
end
-- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are
-- the type's none / default)
function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string?
if t == 0x01 or t == 0x1D then
for i = 1, n do
local v = vals[i]
putString(w, if type(v) == "string" then v else "")
end
elseif t == 0x02 then
for i = 1, n do
w:u8(if vals[i] then 1 else 0)
end
elseif t == 0x03 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putI32s(w, c)
elseif t == 0x04 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putF32s(w, c)
elseif t == 0x05 then
for i = 1, n do
w:f64le(num(vals[i]))
end
elseif t == 0x06 then
putF32s(w, column(vals, n, 1))
putI32s(w, column(vals, n, 2))
elseif t == 0x07 then
putF32s(w, column(vals, n, 1))
putF32s(w, column(vals, n, 3))
putI32s(w, column(vals, n, 2))
putI32s(w, column(vals, n, 4))
elseif t == 0x08 then
for i = 1, n do
local v = vals[i]
for c = 1, 6 do
w:f32le(if type(v) == "table" then num(v[c]) else 0)
end
end
elseif t == 0x09 or t == 0x0A then
for i = 1, n do
w:u8(num(vals[i]) % 256)
end
elseif t == 0x0B or t == 0x12 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = floor(num(vals[i]))
end
putU32s(w, c)
elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then
local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3
for c = 1, k do
putF32s(w, column(vals, n, c))
end
elseif t == 0x0F or t == 0x14 then
local k = if t == 0x0F then 2 else 3
for i = 1, n do
local v = vals[i]
for c = 1, k do
local x = floor(if type(v) == "table" then num(v[c]) else 0) % 65536
w:u16le(x)
end
end
elseif t == 0x10 then
putCFrames(w, vals, n)
elseif t == 0x13 then
local refs = table.create(n, -1)
local refOf = ctx.refOf
for i = 1, n do
refs[i] = if refOf and vals[i] ~= nil then refOf(vals[i]) else -1
end
Binary.writeRefs(w, refs)
elseif t == 0x15 or t == 0x16 then
local k = if t == 0x15 then 3 else 5
for i = 1, n do
local seq = vals[i]
if type(seq) ~= "table" then
seq = {}
end
w:u32le(#seq)
for _, key in seq do
for c = 1, k do
w:f32le(if type(key) == "table" then num(key[c]) else 0)
end
end
end
elseif t == 0x17 then
for i = 1, n do
local v = vals[i]
w:f32le(if type(v) == "table" then num(v[1]) else 0)
w:f32le(if type(v) == "table" then num(v[2]) else 0)
end
elseif t == 0x19 then
for i = 1, n do
local v = vals[i]
if type(v) ~= "table" then
w:u8(0)
else
local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out)
w:u8(if acoustic then 3 else 1)
for c = 1, if acoustic then 6 else 5 do
w:f32le(num(v[c]))
end
end
end
elseif t == 0x1A then
for c = 1, 3 do
for i = 1, n do
local v = vals[i]
w:u8(math.clamp(floor(if type(v) == "table" then num(v[c]) else 0), 0, 255))
end
end
elseif t == 0x1B or t == 0x21 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putI64s(w, c)
elseif t == 0x1C then
local idx = table.create(n, 0)
local si = ctx.sharedIndex
for i = 1, n do
local v = vals[i]
idx[i] = if si then si(if type(v) == "string" then v else "") else 0
end
putU32s(w, idx)
elseif t == 0x1E then
w:u8(0x10)
putCFrames(w, vals, n)
w:u8(0x02)
for i = 1, n do
w:u8(if type(vals[i]) == "table" then 1 else 0)
end
elseif t == 0x1F then
local p = w:reserve(16 * n)
local b = w.buf
for i = 0, n - 1 do
local s = vals[i + 1]
if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then
return "a UniqueId is 32 hex digits"
end
-- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit
local by = table.create(16, 0)
for k = 1, 4 do
by[k] = hexByte(s, 12 + k)
by[4 + k] = hexByte(s, 8 + k)
end
local top = hexByte(s, 1) // 128
for k = 1, 8 do
local v = hexByte(s, k)
local nxt = if k < 8 then hexByte(s, k + 1) // 128 else top
by[8 + k] = (v * 2) % 256 + nxt
end
for k = 0, 15 do
buffer.writeu8(b, p + k * n + i, by[k + 1])
end
end
w.pos = p + 16 * n
elseif t == 0x20 then
for i = 1, n do
local v = vals[i]
if type(v) ~= "table" then
v = Rbx.default("Font")
end
putString(w, if type(v.family) == "string" then v.family else "")
w:u16le(math.clamp(floor(num(v.weight)), 0, 65535))
w:u8(if v.style == "Italic" then 1 else 0)
putString(w, if type(v.cachedFaceId) == "string" then v.cachedFaceId else "")
end
elseif t == 0x22 then
local kinds, uris, objs = table.create(n, 0), {}, {}
local refOf = ctx.refOf
for i = 1, n do
local v = vals[i]
if type(v) == "string" then
kinds[i] = 1
table.insert(uris, v)
elseif type(v) == "table" then
kinds[i] = 2
table.insert(objs, if refOf then refOf(v) else -1)
end
end
putI32s(w, kinds)
w:u32le(#uris)
for _, s in uris do
putString(w, s)
end
w:u32le(#objs)
Binary.writeRefs(w, objs)
w:u32le(0)
else
return "unknown type id " .. t
end
return nil
end
return Binary
+281
View File
@@ -0,0 +1,281 @@
--!strict
-- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl,
-- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the
-- binary format's property column codecs. Shared here because a format cannot require another one. Written from the
-- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library,
-- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself.
--
-- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... }
-- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} }
-- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} }
-- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests
-- for inst, depth in Rbx.descendants(tree) do ... end
--
-- Property values are { type = <name>, value = <v> } with these value forms (arrays follow the Roblox constructor
-- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox):
-- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes)
-- SharedString string (the content; writers deduplicate)
-- Bool boolean
-- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53)
-- Enum, BrickColor, SecurityCapabilities number
-- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32
-- Axes number: bits X 1, Y 2, Z 4
-- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max }
-- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1)
-- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz }
-- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none)
-- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... }
-- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight,
-- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out)
-- Ref an Instance of the tree, or nil
-- UniqueId 32 hex digits: random (16), time (8), index (8)
-- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? }
-- Content nil (none) | string (a URI) | an Instance (object)
-- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column),
-- index, count }; written back verbatim while the class keeps the same instances in the same order
-- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is
-- Name is not a property here: it is inst.name. Never throws.
local Rbx = {}
export type Value = { type: string, value: any }
export type Instance = {
className: string,
name: string,
properties: { [string]: Value },
children: { Instance },
parent: Instance?, -- nil for roots
referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own
service: boolean?, -- a service (binary INST object format 1; rbxl roots)
}
export type Tree = {
kind: "rbxtree",
roots: { Instance },
place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model
metadata: { [string]: string }, -- binary META / XML <Meta> entries (ExplicitAutoJoints, ...)
extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back
meta: { source: { format: string, [string]: any }?, [string]: any },
}
-- ------------------------------------------------------------------------------------------------ tree
function Rbx.tree(place: boolean?): Tree
return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} }
end
function Rbx.instance(className: string, name: string?): Instance
return { className = className, name = name or className, properties = {}, children = {} }
end
-- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance
function Rbx.add(parent: any, child: Instance): Instance
if parent.kind == "rbxtree" then
child.parent = nil
table.insert(parent.roots, child)
else
child.parent = parent
table.insert(parent.children, child)
end
return child
end
-- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...)
function Rbx.set(inst: Instance, name: string, typ: string, value: any)
inst.properties[name] = { type = typ, value = value }
end
-- get(inst, name) -> the property's value (not the Value table), nil when absent
function Rbx.get(inst: Instance, name: string): any
local v = inst.properties[name]
return if v then v.value else nil
end
-- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children
-- at depth 1)
function Rbx.descendants(root: any): () -> (Instance?, number?)
local stack: { any } = {}
local list = if root.kind == "rbxtree" then root.roots else root.children
for i = #list, 1, -1 do
table.insert(stack, { list[i], 1 })
end
return function(): (Instance?, number?)
local top = table.remove(stack)
if not top then
return nil, nil
end
local inst, depth = top[1], top[2]
for i = #inst.children, 1, -1 do
table.insert(stack, { inst.children[i], depth + 1 })
end
return inst, depth
end
end
-- list(tree) -> every instance, depth first
function Rbx.list(tree: any): { Instance }
local out = {}
for inst in Rbx.descendants(tree) do
table.insert(out, inst :: Instance)
end
return out
end
-- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil
function Rbx.find(root: any, path: string): Instance?
local cur: any = root
for part in string.gmatch(path, "[^/]+") do
local list = if cur.kind == "rbxtree" then cur.roots else cur.children
local found = nil
for _, c in list do
if c.name == part then
found = c
break
end
end
if not found then
return nil
end
cur = found
end
return if cur.kind == "rbxtree" then nil else cur
end
-- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root)
function Rbx.fullName(inst: Instance): string
local parts = {}
local cur: Instance? = inst
while cur do
table.insert(parts, 1, cur.name)
cur = cur.parent
end
return table.concat(parts, ".")
end
-- ------------------------------------------------------------------------------------------------ CFrame rotation ids
-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is
-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product.
local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } }
-- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation
local ROTATIONS: { [number]: { number } } = {}
for a = 0, 5 do
for b = 0, 5 do
if a % 3 ~= b % 3 then
local r, u = AXES[a + 1], AXES[b + 1]
local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] }
-- columns: right, up, back (= right x up)
ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 }
end
end
end
Rbx.ROTATIONS = ROTATIONS
local function axisIndex(x: number, y: number, z: number): number?
for i, a in AXES do
if a[1] == x and a[2] == y and a[3] == z then
return i - 1
end
end
return nil
end
-- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned
function Rbx.rotationId(cf: { number }): number
local a = axisIndex(cf[4], cf[7], cf[10])
local b = axisIndex(cf[5], cf[8], cf[11])
if not a or not b then
return 0
end
local id = 6 * a + b + 1
local rot = ROTATIONS[id]
if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then
return 0
end
return id
end
-- ------------------------------------------------------------------------------------------------ values
-- binary type ids (rbx-dom docs/binary.md) by type name, and back
Rbx.TYPE_IDS = table.freeze({
String = 0x01,
BinaryString = 0x01,
ProtectedString = 0x01,
ContentId = 0x01,
Bool = 0x02,
Int32 = 0x03,
Float32 = 0x04,
Float64 = 0x05,
UDim = 0x06,
UDim2 = 0x07,
Ray = 0x08,
Faces = 0x09,
Axes = 0x0A,
BrickColor = 0x0B,
Color3 = 0x0C,
Vector2 = 0x0D,
Vector3 = 0x0E,
Vector2int16 = 0x0F,
CFrame = 0x10,
Enum = 0x12,
Ref = 0x13,
Vector3int16 = 0x14,
NumberSequence = 0x15,
ColorSequence = 0x16,
NumberRange = 0x17,
Rect = 0x18,
PhysicalProperties = 0x19,
Color3uint8 = 0x1A,
Int64 = 0x1B,
SharedString = 0x1C,
Bytecode = 0x1D,
OptionalCFrame = 0x1E,
UniqueId = 0x1F,
Font = 0x20,
SecurityCapabilities = 0x21,
Content = 0x22,
} :: { [string]: number })
local NAMES: { [number]: string } = {}
for name, id in Rbx.TYPE_IDS do
if NAMES[id] == nil or name == "String" then
NAMES[id] = name
end
end
Rbx.TYPE_NAMES = table.freeze(NAMES)
-- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the
-- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1)
local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
function Rbx.default(typ: string): any
if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then
return ""
elseif typ == "Bool" then
return false
elseif typ == "BrickColor" then
return 194
elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then
return { 0, 0 }
elseif typ == "UDim2" or typ == "Rect" then
return { 0, 0, 0, 0 }
elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then
return { 0, 0, 0 }
elseif typ == "Ray" then
return { 0, 0, 0, 0, 0, 0 }
elseif typ == "CFrame" then
return table.clone(IDENTITY_CF)
elseif typ == "NumberSequence" then
return { { 0, 0, 0 }, { 1, 0, 0 } }
elseif typ == "ColorSequence" then
return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } }
elseif typ == "UniqueId" then
return string.rep("0", 32)
elseif typ == "Font" then
return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" }
elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then
return nil
end
return 0
end
-- STRINGS: the string-valued types (one binary type, several XML tags)
Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean })
return Rbx
+698
View File
@@ -0,0 +1,698 @@
--!strict
-- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT".
-- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from
-- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int /
-- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against
-- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft).
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Value = require("@formats/codecs/text/Nbt/Value")
local Binary = {}
export type Options = {
endian: ("big" | "little")?, -- default "big" (Java)
varint: boolean?, -- Bedrock network NBT (little-endian, varint ints / lengths); implies endian = "little"
nameless: boolean?, -- the root tag has no name (Java network NBT since 1.20.2)
maxDepth: number?, -- nesting limit (default 512)
name: string?, -- write: the root name (default "")
}
local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16
local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring
local byteswap = bit32.byteswap
local TWO32 = 4294967296
local NAMES, IDS = Value.NAMES, Value.IDS
local newTag = Value.TagMeta
type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer }
-- ------------------------------------------------------------------------------------------------ modified UTF-8
-- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8)
local function fromModified(s: string): string
if not string.find(s, "[\192\237]") then
return s
end
local out = {}
local i, n = 1, #s
while i <= n do
local c = string.byte(s, i)
if c == 0xC0 and string.byte(s, i + 1) == 0x80 then
table.insert(out, "\0")
i += 2
elseif c == 0xED and i + 5 <= n then
local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5)
if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then
local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80)
local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80)
table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00)))
i += 6
else
table.insert(out, string.char(c))
i += 1
end
else
local j = string.find(s, "[\192\237]", i + 1) or n + 1
table.insert(out, string.sub(s, i, j - 1))
i = j
end
end
return table.concat(out)
end
local function toModified(s: string): string
if not string.find(s, "[%z\240-\244]") then
return s
end
local out = {}
local i, n = 1, #s
while i <= n do
local c = string.byte(s, i)
if c == 0 then
table.insert(out, "\192\128")
i += 1
elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then
local b2, b3, b4 = string.byte(s, i + 1, i + 3)
local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000
local hiS, loS = 0xD800 + cp // 1024, 0xDC00 + cp % 1024
table.insert(out, string.char(0xED, 0x80 + (hiS - 0xD000) // 64, 0x80 + hiS % 64))
table.insert(out, string.char(0xED, 0x80 + (loS - 0xD000) // 64, 0x80 + loS % 64))
i += 4
else
local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1
table.insert(out, string.sub(s, i, j - 1))
i = j
end
end
return table.concat(out)
end
Binary.fromModified = fromModified
Binary.toModified = toModified
-- ------------------------------------------------------------------------------------------------ read
local function fail(s: State, msg: string): nil
if not s.err then
s.err = msg
end
s.p = s.e
return nil
end
local function need(s: State, n: number): boolean
if s.p + n > s.e then
fail(s, "truncated")
return false
end
return true
end
local function u8(s: State): number
if not need(s, 1) then
return 0
end
local v = readu8(s.b, s.p)
s.p += 1
return v
end
local function varuint(s: State): number -- up to 32 bits (5 bytes)
local v, mul = 0, 1
for _ = 1, 5 do
if not need(s, 1) then
return 0
end
local c = readu8(s.b, s.p)
s.p += 1
v += (c % 128) * mul
if c < 128 then
return v % TWO32
end
mul *= 128
end
fail(s, "varint too long")
return 0
end
local function i16(s: State): number
if not need(s, 2) then
return 0
end
local p = s.p
s.p = p + 2
if s.le then
return readi16(s.b, p)
end
local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1)
return if v >= 32768 then v - 65536 else v
end
local function u32raw(s: State): number
if not need(s, 4) then
return 0
end
local p = s.p
s.p = p + 4
local v = readu32(s.b, p)
return if s.le then v else byteswap(v)
end
local function i32(s: State): number
if s.net then
local n = varuint(s)
return if n % 2 == 0 then n // 2 else -(n + 1) // 2
end
local v = u32raw(s)
return if v >= 0x80000000 then v - TWO32 else v
end
-- a length: i32 (zigzag varint in network NBT)
local function len(s: State): number
return i32(s)
end
local function i64(s: State): (number, number) -- hi, lo
if s.net then
local lo, hi, sh = 0, 0, 0
while true do
if sh >= 70 or not need(s, 1) then
fail(s, "varint too long")
return 0, 0
end
local c = readu8(s.b, s.p)
s.p += 1
local d = c % 128
if sh < 32 then
local x = d * 2 ^ sh
lo += x % TWO32
hi = (hi + x // TWO32) % TWO32
else
hi = (hi + d * 2 ^ (sh - 32)) % TWO32
end
sh += 7
if c < 128 then
break
end
end
local odd = lo % 2 == 1
lo = lo // 2 + (hi % 2) * 0x80000000
hi = hi // 2
if odd then
hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo
end
return hi, lo
end
if s.le then
local lo = u32raw(s)
return u32raw(s), lo
end
local hi = u32raw(s)
return hi, u32raw(s)
end
local function f32(s: State): number
local v = u32raw(s)
writeu32(s.scratch, 0, v)
return readf32(s.scratch, 0)
end
local function f64(s: State): number
local hi, lo
if s.le then
lo = u32raw(s)
hi = u32raw(s)
else
hi = u32raw(s)
lo = u32raw(s)
end
writeu32(s.scratch, 0, lo)
writeu32(s.scratch, 4, hi)
return readf64(s.scratch, 0)
end
local function str(s: State): string
local n
if s.net then
n = varuint(s)
else
n = i16(s) % 65536
end
if not need(s, n) then
return ""
end
local v = readstring(s.b, s.p, n)
s.p += n
return if s.java then fromModified(v) else v
end
local function tag(name: string, v: any): any
return setmetatable({ type = name, value = v }, newTag)
end
-- the smallest encoded size of one element, to bound list lengths before allocating
local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 }
local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 }
local payload: (State, number) -> any
local function count(s: State, n: number, size: number): boolean
if n < 0 then
fail(s, "negative length " .. n)
return false
end
if n * size > s.e - s.p then
fail(s, "truncated: " .. n .. " elements past the end")
return false
end
return true
end
payload = function(s: State, id: number): any
if id == 3 then
return i32(s)
elseif id == 8 then
return str(s)
elseif id == 10 then
s.depth += 1
if s.depth > s.maxDepth then
return fail(s, "limit: nested deeper than " .. s.maxDepth)
end
local o, keys = {}, {}
while true do
local t = u8(s)
if s.err then
return nil
end
if t == 0 then
break
end
if t > 12 then
return fail(s, "bad tag type " .. t)
end
local k = str(s)
local v = payload(s, t)
if s.err then
return nil
end
if o[k] == nil then
table.insert(keys, k)
end
o[k] = v
end
s.depth -= 1
return Types.object(o, keys)
elseif id == 1 then
if not need(s, 1) then
return nil
end
s.p += 1
return tag("byte", readi8(s.b, s.p - 1))
elseif id == 2 then
return tag("short", i16(s))
elseif id == 4 then
local hi, lo = i64(s)
return tag("long", Value.fromHiLo(hi, lo))
elseif id == 5 then
return tag("float", f32(s))
elseif id == 6 then
return tag("double", f64(s))
elseif id == 7 then
local n = len(s)
if not count(s, n, 1) then
return nil
end
local out = buffer.create(n)
buffer.copy(out, 0, s.b, s.p, n)
s.p += n
return out
elseif id == 9 then
local et = u8(s)
local n = len(s)
if s.err then
return nil
end
if et > 12 then
return fail(s, "bad list element type " .. et)
end
if et == 0 and n > 0 then
return fail(s, "list of end tags with " .. n .. " elements")
end
if not count(s, n, (if s.net then MIN_NET else MIN)[et]) then
return nil
end
s.depth += 1
if s.depth > s.maxDepth then
return fail(s, "limit: nested deeper than " .. s.maxDepth)
end
local out = table.create(n)
for i = 1, n do
local v = payload(s, et)
if s.err then
return nil
end
out[i] = v
end
s.depth -= 1
Value.setListType(out, NAMES[et])
return out
elseif id == 11 then
local n = len(s)
if not count(s, n, if s.net then 1 else 4) then
return nil
end
local out = table.create(n)
for i = 1, n do
out[i] = i32(s)
end
return tag("intArray", out)
elseif id == 12 then
local n = len(s)
if not count(s, n, if s.net then 1 else 8) then
return nil
end
local out = buffer.create(n * 8)
if s.net then
for i = 0, n - 1 do
local hi, lo = i64(s)
writeu32(out, i * 8, lo)
writeu32(out, i * 8 + 4, hi)
end
elseif s.le then
buffer.copy(out, 0, s.b, s.p, n * 8)
s.p += n * 8
else
local b, p = s.b, s.p
for i = 0, n - 1 do
local q = p + i * 8
writeu32(out, i * 8 + 4, byteswap(readu32(b, q)))
writeu32(out, i * 8, byteswap(readu32(b, q + 4)))
end
s.p = p + n * 8
end
return tag("longArray", out)
end
return fail(s, "bad tag type " .. id)
end
-- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at
function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?)
local o: Options = opts or {}
local net = o.varint == true
local le = net or o.endian == "little"
local s: State = {
b = b,
p = pos,
e = limit,
le = le,
net = net,
java = not le,
depth = 0,
maxDepth = o.maxDepth or 512,
err = nil,
scratch = buffer.create(8),
}
local id = u8(s)
if s.err then
return nil, s.err, pos
end
if id == 0 or id > 12 then
return nil, "bad root tag type " .. id, pos
end
local name = if o.nameless then "" else str(s)
local v = payload(s, id)
if s.err then
return nil, s.err, s.p
end
return v, name, s.p
end
-- ------------------------------------------------------------------------------------------------ write
type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number }
local function wvaruint(w: Bytes.Writer, v: number)
v %= TWO32
while v >= 128 do
w:u8(v % 128 + 128)
v //= 128
end
w:u8(v)
end
local function wi32(ws: WState, v: number)
v %= TWO32 -- two's complement
if ws.net then
local sv = if v >= 0x80000000 then v - TWO32 else v
wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1)
elseif ws.le then
ws.w:u32le(v)
else
ws.w:u32be(v)
end
end
local function wi16(ws: WState, v: number)
v %= 65536
if ws.le then
ws.w:u16le(v)
else
ws.w:u16be(v)
end
end
local function wi64(ws: WState, hi: number, lo: number)
if ws.net then
-- zigzag: (n << 1) ^ (n >> 63)
local neg = hi >= 0x80000000
local zh = (hi * 2) % TWO32 + (if lo >= 0x80000000 then 1 else 0)
local zl = (lo * 2) % TWO32
if neg then
zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl
end
while zh > 0 or zl >= 128 do
ws.w:u8(zl % 128 + 128)
zl = zl // 128 + (zh % 128) * 0x2000000
zh //= 128
end
ws.w:u8(zl)
elseif ws.le then
ws.w:u32le(lo)
ws.w:u32le(hi)
else
ws.w:u32be(hi)
ws.w:u32be(lo)
end
end
local function wstr(ws: WState, s: string): string?
local v = if ws.java then toModified(s) else s
if ws.net then
wvaruint(ws.w, #v)
else
if #v > 65535 then
return "string longer than 65535 bytes"
end
wi16(ws, #v)
end
ws.w:string(v)
return nil
end
local function integer(v: any, lo: number, hi: number, what: string): (number?, string?)
local n = if type(v) == "boolean" then (if v then 1 else 0) else v
if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then
return nil, "bad " .. what .. " value " .. tostring(n)
end
return n, nil
end
local wpayload: (WState, string, any) -> string?
local function wlist(ws: WState, v: { any }): string?
local lt = Value.listType(v)
local n = #v
local wrap = false
if not lt then
if n == 0 then
lt = "end"
else
local t1, e1 = Value.typeOf(v[1])
if not t1 then
return e1
end
lt = t1
end
end
for i = 1, n do
local t, e = Value.typeOf(v[i])
if not t then
return e
end
if t ~= lt then
wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does
end
end
if wrap then
lt = "compound"
end
if lt == "end" and n > 0 then
return "a list of end tags cannot hold elements"
end
ws.w:u8(IDS[lt :: string])
wi32(ws, n)
for i = 1, n do
local x = v[i]
if wrap and Value.typeOf(x) ~= "compound" then
x = Types.object({ [""] = x }, { "" })
end
local e = wpayload(ws, lt :: string, x)
if e then
return e
end
end
return nil
end
wpayload = function(ws: WState, t: string, v: any): string?
local w = ws.w
local x = if Value.isTag(v) then v.value else v
if t == "int" then
local n, e = integer(x, -2147483648, 4294967295, "int")
if not n then
return e
end
wi32(ws, n)
elseif t == "string" then
if type(x) ~= "string" then
return "bad string value"
end
return wstr(ws, x)
elseif t == "compound" then
ws.depth += 1
if ws.depth > ws.maxDepth then
return "nested deeper than " .. ws.maxDepth .. " (a cycle?)"
end
for _, k in Types.keys(v) do
if type(k) ~= "string" then
return "compound key " .. tostring(k) .. " is not a string"
end
local c = v[k]
local ct, e = Value.typeOf(c)
if not ct then
return e .. " (key " .. k .. ")"
end
w:u8(IDS[ct :: string])
e = wstr(ws, k)
if e then
return e
end
e = wpayload(ws, ct :: string, c)
if e then
return e
end
end
w:u8(0)
ws.depth -= 1
elseif t == "list" then
ws.depth += 1
if ws.depth > ws.maxDepth then
return "nested deeper than " .. ws.maxDepth .. " (a cycle?)"
end
local e = wlist(ws, v)
if e then
return e
end
ws.depth -= 1
elseif t == "byte" then
local n, e = integer(x, -128, 255, "byte")
if not n then
return e
end
w:u8(n % 256)
elseif t == "short" then
local n, e = integer(x, -32768, 65535, "short")
if not n then
return e
end
wi16(ws, n)
elseif t == "long" then
local hi, lo = Value.toHiLo(x)
if not hi then
return "bad long value " .. tostring(x)
end
wi64(ws, hi, lo :: number)
elseif t == "float" or t == "double" then
if type(x) ~= "number" then
return "bad " .. t .. " value " .. tostring(x)
end
if t == "float" then
if ws.le then
w:f32le(x)
else
w:f32be(x)
end
elseif ws.le then
w:f64le(x)
else
w:f64be(x)
end
elseif t == "byteArray" then
if type(x) ~= "buffer" then
return "bad byteArray value"
end
wi32(ws, buffer.len(x))
w:bytes(x)
elseif t == "intArray" then
if type(x) ~= "table" then
return "bad intArray value"
end
wi32(ws, #x)
for i = 1, #x do
local n, e = integer(x[i], -2147483648, 4294967295, "intArray element")
if not n then
return e
end
wi32(ws, n)
end
elseif t == "longArray" then
if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then
return "bad longArray value (a buffer of 8-byte little-endian longs)"
end
local n = buffer.len(x) // 8
wi32(ws, n)
if ws.le and not ws.net then
w:bytes(x)
else
for i = 0, n - 1 do
wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8))
end
end
else
return "cannot write tag type " .. t
end
return nil
end
-- write(value, opts?) -> buffer | nil, message
function Binary.write(v: any, opts: Options?): (buffer?, string?)
local o: Options = opts or {}
local net = o.varint == true
local le = net or o.endian == "little"
local t, e = Value.typeOf(v)
if not t then
return nil, e
end
local ws: WState = { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 }
ws.w:u8(IDS[t :: string])
if not o.nameless then
e = wstr(ws, o.name or "")
if e then
return nil, e
end
end
e = wpayload(ws, t :: string, v)
if e then
return nil, e
end
return ws.w:finish(), nil
end
return Binary
+649
View File
@@ -0,0 +1,649 @@
--!strict
-- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the
-- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...]
-- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted
-- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex
-- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing
-- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's
-- compact form (or indented); floats print as the shortest text that reads back to the same value.
local Types = require("@formats/Types")
local Value = require("@formats/codecs/text/Nbt/Value")
local Snbt = {}
export type ParseOptions = { maxDepth: number? }
export type PrintOptions = {
indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact)
quote: string?, -- the string quote, '"' (default) or "'"; the other one is used when it needs fewer escapes
}
local byte, sub, find = string.byte, string.sub, string.find
local TWO32 = 4294967296
local function tag(name: string, v: any): any
return setmetatable({ type = name, value = v }, Value.TagMeta)
end
-- ------------------------------------------------------------------------------------------------ parse
type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number }
local function fail(p: P, msg: string): nil
if not p.err then
p.err, p.at = msg, p.i
end
p.i = p.n + 1
return nil
end
local function ws(p: P)
local _, e = find(p.s, "^%s*", p.i)
p.i = (e :: number) + 1
end
local function isUnquoted(c: number): boolean
return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43
end
local ESC: { [string]: string } = { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " }
local function quoted(p: P): string?
local q = sub(p.s, p.i, p.i)
p.i += 1
local out = {}
while true do
local j = find(p.s, if q == '"' then '["\\]' else "['\\]", p.i)
if not j then
return fail(p, "unterminated string")
end
table.insert(out, sub(p.s, p.i, j - 1))
if sub(p.s, j, j) == q then
p.i = j + 1
return table.concat(out)
end
local c = sub(p.s, j + 1, j + 1)
if ESC[c] then
table.insert(out, ESC[c])
p.i = j + 2
elseif c == "x" or c == "u" or c == "U" then
local nd = if c == "x" then 2 elseif c == "u" then 4 else 8
local hex = sub(p.s, j + 2, j + 1 + nd)
if #hex ~= nd or find(hex, "[^%x]") then
p.i = j
return fail(p, "bad \\" .. c .. " escape")
end
local cp = tonumber(hex, 16) :: number
if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then
p.i = j
return fail(p, "bad code point in \\" .. c .. " escape")
end
table.insert(out, utf8.char(cp))
p.i = j + 2 + nd
else
p.i = j
return fail(p, "bad escape \\" .. c)
end
end
end
-- number text -> a value, or nil when it is not a number (then it is an unquoted string)
local INT_RANGE: { [string]: { number } } = {
b = { -128, 127, 255 },
s = { -32768, 32767, 65535 },
i = { -2147483648, 2147483647, 4294967295 },
}
local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" }
local function integer(t: string): any
local sign, body = string.match(t, "^([+-]?)(.+)$")
body = string.gsub(body :: string, "_", "") :: string
local radix, digits, suffix = 10, body, ""
local low = string.lower(body)
local m, sfx
if sub(low, 1, 2) == "0x" then
-- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub)
m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$")
if not m then
m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$")
end
if not m then
return nil
end
radix = 16
elseif sub(low, 1, 2) == "0b" then
m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$")
if m then
radix = 2
end
end
if not m then
m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$")
if not m then
return nil
end
end
digits, suffix = m :: string, string.lower(sfx :: string)
local unsigned = false
if #suffix == 2 then
unsigned = sub(suffix, 1, 1) == "u"
suffix = sub(suffix, 2)
elseif suffix == "u" then
return nil
end
if suffix == "" then
suffix = "i"
end
if unsigned and sign == "-" then
return nil
end
-- the magnitude as (hi, lo)
local hi, lo = 0, 0
for k = 1, #digits do
local c = byte(digits, k)
local d = if c <= 57 then c - 48 elseif c >= 97 then c - 87 else c - 55
local x = lo * radix + d
local carry = x // TWO32
lo = x - carry * TWO32
hi = hi * radix + carry
if hi >= TWO32 then
return nil
end
end
if suffix == "l" then
local neg = sign == "-"
if radix == 10 then
if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then
return nil
end
end
if neg and (hi > 0 or lo > 0) then
lo = (TWO32 - lo) % TWO32
hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32
end
return tag("long", Value.fromHiLo(hi, lo))
end
if hi > 0 then
return nil
end
local r = INT_RANGE[suffix]
local v = lo
if sign == "-" then
v = -v
end
if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then
v -= r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b)
elseif unsigned then
if v > r[3] then
return nil
end
if v > r[2] then
v -= r[3] + 1
end
end
if v < r[1] or v > r[2] then
return nil
end
if suffix == "i" then
return v
end
return tag(INT_NAME[suffix], v)
end
local function number(t: string): any
local low = string.lower(t)
if low == "true" then
return tag("byte", 1)
elseif low == "false" then
return tag("byte", 0)
end
local sfx = sub(low, -1)
local special = string.match(low, "^([+-]?)infinity[fd]$")
if special then
return tag(if sfx == "f" then "float" else "double", if special == "-" then -math.huge else math.huge)
elseif low == "nanf" or low == "nand" then
return tag(if sfx == "f" then "float" else "double", 0 / 0)
end
local iv = integer(t)
if iv ~= nil then
return iv
end
local body = string.gsub(t, "_", "")
local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$")
if not m then
return nil
end
-- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed
local mant, ex = string.match(m :: string, "^(.-)([eE][+-]?%d+)$")
if not mant then
mant = m
end
if not (string.match(mant :: string, "^[+-]?%d+%.?%d*$") or string.match(mant :: string, "^[+-]?%.%d+$")) then
return nil
end
if fs == "" and not ex and not find(mant :: string, ".", 1, true) then
return nil
end
local v = tonumber(m)
if not v then
return nil
end
if string.lower(fs :: string) == "f" then
local b = buffer.create(4)
buffer.writef32(b, 0, v)
return tag("float", buffer.readf32(b, 0))
end
return tag("double", v)
end
local parseValue: (P) -> any
local function token(p: P): string
local j = p.i
while j <= p.n and isUnquoted(byte(p.s, j)) do
j += 1
end
local t = sub(p.s, p.i, j - 1)
p.i = j
return t
end
local function key(p: P): string?
ws(p)
local c = sub(p.s, p.i, p.i)
if c == '"' or c == "'" then
return quoted(p)
end
local t = token(p)
if t == "" then
return fail(p, "expected a key")
end
return t
end
local ARRAY = { B = "byte", I = "int", L = "long" }
local function array(p: P, kind: string): any
local items = {}
ws(p)
if sub(p.s, p.i, p.i) ~= "]" then
while true do
ws(p)
local at = p.i
local t = token(p)
local v = if t ~= "" then number(t) else nil
local vt = Value.typeOf(v)
if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then
p.i = at
return fail(p, "expected an integer in a " .. kind .. " array")
end
local x: any = if Value.isTag(v) then (v :: any).value else v
if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then
p.i = at
return fail(p, "value out of range in a " .. kind .. " array")
end
table.insert(items, x)
ws(p)
local c = sub(p.s, p.i, p.i)
p.i += 1
if c == "]" then
break
elseif c ~= "," then
p.i -= 1
return fail(p, "expected , or ]")
end
ws(p)
if sub(p.s, p.i, p.i) == "]" then
p.i += 1
break
end
end
else
p.i += 1
end
if kind == "byte" then
local b = buffer.create(#items)
for i, x in items do
buffer.writei8(b, i - 1, x)
end
return b
elseif kind == "int" then
return tag("intArray", items)
end
return Value.longArray(items)
end
parseValue = function(p: P): any
ws(p)
if p.i > p.n then
return fail(p, "expected a value")
end
local c = sub(p.s, p.i, p.i)
if c == "{" then
p.depth += 1
if p.depth > p.maxDepth then
return fail(p, "limit: nested deeper than " .. p.maxDepth)
end
p.i += 1
local o, keys = {}, {}
ws(p)
if sub(p.s, p.i, p.i) == "}" then
p.i += 1
else
while true do
local k = key(p)
if p.err then
return nil
end
ws(p)
if sub(p.s, p.i, p.i) ~= ":" then
return fail(p, "expected :")
end
p.i += 1
local v = parseValue(p)
if p.err then
return nil
end
if o[k :: string] == nil then
table.insert(keys, k)
end
o[k :: string] = v
ws(p)
local d = sub(p.s, p.i, p.i)
p.i += 1
if d == "}" then
break
elseif d ~= "," then
p.i -= 1
return fail(p, "expected , or }")
end
ws(p)
if sub(p.s, p.i, p.i) == "}" then
p.i += 1
break
end
end
end
p.depth -= 1
return Types.object(o, keys)
elseif c == "[" then
p.depth += 1
if p.depth > p.maxDepth then
return fail(p, "limit: nested deeper than " .. p.maxDepth)
end
p.i += 1
local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i)
if kind then
local _, e = find(p.s, "^%s*[BIL]%s*;", p.i)
p.i = (e :: number) + 1
local v = array(p, ARRAY[kind])
p.depth -= 1
return v
end
local items = {}
local lt: string? = nil
local mixed = false
ws(p)
if sub(p.s, p.i, p.i) == "]" then
p.i += 1
else
while true do
local v = parseValue(p)
if p.err then
return nil
end
local t = Value.typeOf(v)
if lt == nil then
lt = t
elseif t ~= lt then
mixed = true
end
table.insert(items, v)
ws(p)
local d = sub(p.s, p.i, p.i)
p.i += 1
if d == "]" then
break
elseif d ~= "," then
p.i -= 1
return fail(p, "expected , or ]")
end
ws(p)
if sub(p.s, p.i, p.i) == "]" then
p.i += 1
break
end
end
end
p.depth -= 1
if not mixed then
Value.setListType(items, lt or "end")
end
return items
elseif c == '"' or c == "'" then
return quoted(p)
end
local at = p.i
local t = token(p)
if t == "" then
return fail(p, "unexpected character " .. string.format("%q", c))
end
local v = number(t)
if v == nil then
if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then
p.i = at
return fail(p, "number out of range: " .. t)
end
return t
end
return v
end
-- parse(text, opts?) -> value | nil, message, position (1-based)
function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?)
local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 }
local v = parseValue(p)
if p.err then
return nil, p.err, p.at
end
ws(p)
if p.i <= p.n then
return nil, "trailing characters after the value", p.i
end
return v, nil, nil
end
-- ------------------------------------------------------------------------------------------------ print
local function shortest(v: number, single: boolean): string
if v ~= v then
return "NaN"
elseif v == math.huge then
return "Infinity"
elseif v == -math.huge then
return "-Infinity"
end
local b = buffer.create(4)
if single then
buffer.writef32(b, 0, v)
v = buffer.readf32(b, 0)
end
local s = ""
for digits = if single then 6 else 15, 17 do
s = string.format("%." .. digits .. "g", v)
local back = tonumber(s) :: number
if single then
buffer.writef32(b, 0, back)
back = buffer.readf32(b, 0)
end
if back == v then
break
end
end
if not find(s, "[%.eEn]") then
s ..= ".0"
end
return s
end
Snbt.shortest = shortest
local function quote(s: string, q: string): string
local other = if q == '"' then "'" else '"'
local _, nq = string.gsub(s, q, "")
local _, no = string.gsub(s, other, "")
if nq > no then
q = other
end
local e = string.gsub(s, "[\\" .. q .. "%c]", function(c: string): string
if c == "\\" or c == q then
return "\\" .. c
elseif c == "\n" then
return "\\n"
elseif c == "\t" then
return "\\t"
elseif c == "\r" then
return "\\r"
end
return string.format("\\x%02x", byte(c))
end)
return q .. e .. q
end
local function keyText(k: string, q: string): string
if k ~= "" and not find(k, "[^%w_%-%.%+]") then
return k
end
return quote(k, q)
end
type Pr = { out: { string }, indent: string?, q: string, depth: number }
local printValue: (Pr, any, number) -> string?
local function scalar(v: any, q: string): string?
local tv = type(v)
if tv == "number" then
if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then
return string.format("%d", v)
end
return shortest(v, false) .. "d"
elseif tv == "string" then
return quote(v, q)
elseif tv == "boolean" then
return if v then "1b" else "0b"
elseif Value.isTag(v) then
local t, x = v.type, v.value
if t == "byte" then
return string.format("%db", x)
elseif t == "short" then
return string.format("%ds", x)
elseif t == "int" then
return string.format("%d", x)
elseif t == "long" then
return (if type(x) == "string" then x else string.format("%d", x)) .. "L"
elseif t == "float" then
return shortest(x, true) .. "f"
elseif t == "double" then
return shortest(x, false) .. "d"
elseif t == "string" then
return quote(x, q)
end
end
return nil
end
local function seq(pr: Pr, head: string, items: { string }, close: string)
if pr.indent and #items > 0 then
local pad = string.rep(pr.indent, pr.depth)
table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close)
else
table.insert(pr.out, head .. table.concat(items, if pr.indent then ", " else ",") .. close)
end
end
local function sub1(pr: Pr, v: any): (string?, string?)
local inner: Pr = { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 }
local e = printValue(inner, v, inner.depth)
if e then
return nil, e
end
return table.concat(inner.out), nil
end
printValue = function(pr: Pr, v: any, depth: number): string?
if depth > 512 then
return "nested deeper than 512 (a cycle?)"
end
local s = scalar(v, pr.q)
if s then
table.insert(pr.out, s)
return nil
end
local t, terr = Value.typeOf(v)
if not t then
return terr
end
if t == "byteArray" then
local items = table.create(buffer.len(v)) :: { string }
for i = 0, buffer.len(v) - 1 do
items[i + 1] = buffer.readi8(v, i) .. "b"
end
seq(pr, "[B;", items, "]")
elseif t == "intArray" then
local items = {}
for i, x in v.value do
items[i] = string.format("%d", x)
end
seq(pr, "[I;", items, "]")
elseif t == "longArray" then
local items = {}
for i, x in Value.longs(v) do
items[i] = (if type(x) == "string" then x else string.format("%d", x)) .. "L"
end
seq(pr, "[L;", items, "]")
elseif t == "list" then
local items: { string } = {}
for i = 1, #v do
local x, e = sub1(pr, v[i])
if e then
return e
end
items[i] = x :: string
end
seq(pr, "[", items, "]")
else
local items = {}
for _, k in Types.keys(v) do
if type(k) ~= "string" then
return "compound key " .. tostring(k) .. " is not a string"
end
local x, e = sub1(pr, v[k])
if e then
return e
end
table.insert(items, keyText(k, pr.q) .. (if pr.indent then ": " else ":") .. (x :: string))
end
seq(pr, "{", items, "}")
end
return nil
end
-- print(value, opts?) -> text | nil, message
function Snbt.print(v: any, opts: PrintOptions?): (string?, string?)
local o: PrintOptions = opts or {}
local ind = o.indent
local pr: Pr = {
out = {},
indent = if type(ind) == "number" then string.rep(" ", ind) elseif type(ind) == "string" then ind else nil,
q = if o.quote == "'" then "'" else '"',
depth = 0,
}
local e = printValue(pr, v, 0)
if e then
return nil, e
end
return table.concat(pr.out), nil
end
Value.print = function(v: any): string
return Snbt.print(v) or "?"
end
return Snbt
+256
View File
@@ -0,0 +1,256 @@
--!strict
-- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code.
-- Plain Luau values with typed numbers, so a decode / encode round trip is exact:
-- int -> number string -> string byteArray -> buffer
-- compound -> Types.object (key order kept) list -> array (element type in Value.listType)
-- byte / short / long / float / double / intArray / longArray -> a tag { type = "<name>", value = ... } with a
-- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal
-- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s.
-- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as
-- byte 1 / 0; a plain table with string keys as a compound.
local Types = require("@formats/Types")
local Value = {}
-- tag ids (the binary format) <-> names
Value.NAMES = {
[0] = "end",
"byte",
"short",
"int",
"long",
"float",
"double",
"byteArray",
"string",
"list",
"compound",
"intArray",
"longArray",
} :: { [number]: string }
Value.IDS = {} :: { [string]: number }
for id = 0, 12 do
Value.IDS[Value.NAMES[id]] = id
end
export type Tag = { type: string, value: any }
local TagMeta: { [string]: any } = {}
Value.TagMeta = TagMeta
-- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer)
Value.print = function(v: any): string
return tostring(v.value)
end
TagMeta.__tostring = function(v: any): string
return Value.print(v)
end
TagMeta.__eq = function(a: any, b: any): boolean
if a.type ~= b.type then
return false
end
local x, y = a.value, b.value
if type(x) == "buffer" and type(y) == "buffer" then
return buffer.tostring(x) == buffer.tostring(y)
elseif type(x) == "table" and type(y) == "table" then
if #x ~= #y then
return false
end
for i = 1, #x do
if x[i] ~= y[i] then
return false
end
end
return true
end
return x == y
end
local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any
-- ------------------------------------------------------------------------------------------------ 64-bit integers
local TWO32 = 4294967296
-- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the
-- two's complement int64)
function Value.fromHiLo(hi: number, lo: number): number | string
local s = if hi >= 0x80000000 then hi - TWO32 else hi
if s >= -0x200000 and s < 0x200000 then
return s * TWO32 + lo
end
local neg = s < 0
if neg then -- magnitude = 2^64 - v
lo = (TWO32 - lo) % TWO32
hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32
end
local parts = {}
while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32
local qh = hi // 10000
local x = (hi - qh * 10000) * TWO32 + lo
local ql = x // 10000
local d = x - ql * 10000
hi, lo = qh, ql
table.insert(parts, 1, string.format(if hi > 0 or lo > 0 then "%04d" else "%d", d))
end
return (if neg then "-" else "") .. table.concat(parts)
end
-- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text
function Value.toHiLo(v: any): (number?, number?)
if type(v) == "number" then
if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then
return nil, nil
end
local hi = v // TWO32
local lo = v - hi * TWO32
return hi % TWO32, lo
elseif type(v) == "string" then
local neg, digits = string.match(v, "^(%-?)(%d+)$")
if not digits or #digits > 19 then
return nil, nil
end
local hi, lo = 0, 0
for i = 1, #digits do
local x = lo * 10 + (string.byte(digits, i) - 48)
local carry = x // TWO32
lo = x - carry * TWO32
hi = hi * 10 + carry
end
if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then
return nil, nil
end
if neg == "-" and (hi > 0 or lo > 0) then
lo = (TWO32 - lo) % TWO32
hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32
end
return hi, lo
end
return nil, nil
end
-- ------------------------------------------------------------------------------------------------ constructors
local function tag(name: string, v: any): Tag
return setmetatable({ type = name, value = v }, TagMeta) :: any
end
function Value.byte(n: number): Tag
return tag("byte", n)
end
function Value.short(n: number): Tag
return tag("short", n)
end
function Value.int(n: number): number
return n
end
-- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number)
function Value.long(v: number | string): Tag
if type(v) == "string" then
local hi, lo = Value.toHiLo(v)
if hi then
v = Value.fromHiLo(hi, lo :: number)
end
end
return tag("long", v)
end
local f32 = buffer.create(4)
-- float(n) -> a float tag holding n rounded to single precision
function Value.float(n: number): Tag
buffer.writef32(f32, 0, n)
return tag("float", buffer.readf32(f32, 0))
end
function Value.double(n: number): Tag
return tag("double", n)
end
function Value.intArray(t: { number }?): Tag
return tag("intArray", t or {})
end
-- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE)
function Value.longArray(t: { any } | buffer | nil): Tag
if type(t) == "buffer" then
return tag("longArray", t)
end
local list: { any } = (t or {}) :: any
local b = buffer.create(#list * 8)
for i, x in list do
local hi, lo = Value.toHiLo(x)
buffer.writeu32(b, (i - 1) * 8, lo or 0)
buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0)
end
return tag("longArray", b)
end
-- longs(longArray) -> { number | string }: the elements as long values
function Value.longs(a: Tag): { number | string }
local b: buffer = a.value
local out = table.create(buffer.len(b) // 8) :: { number | string }
for i = 0, buffer.len(b) // 8 - 1 do
out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8))
end
return out
end
-- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type)
function Value.list(name: string, items: { any }?): { any }
local t = items or {}
listTypes[t] = name
return t
end
function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any }
return Types.object(t, keys)
end
-- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list)
function Value.listType(t: any): string?
return listTypes[t]
end
function Value.setListType(t: any, name: string)
listTypes[t] = name
end
function Value.isTag(v: any): boolean
return type(v) == "table" and getmetatable(v) == TagMeta
end
-- typeOf(v) -> the tag name v writes as, or nil + why
function Value.typeOf(v: any): (string?, string?)
local tv = type(v)
if tv == "number" then
return if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then "int" else "double", nil
elseif tv == "string" then
return "string", nil
elseif tv == "boolean" then
return "byte", nil
elseif tv == "buffer" then
return "byteArray", nil
elseif tv == "table" then
if getmetatable(v) == TagMeta then
local n = v.type
if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then
if n == "int" or n == "string" or n == "byteArray" then
return n, nil
end
return nil, "bad tag type " .. tostring(n)
end
return n, nil
elseif Types.isObject(v) then
return "compound", nil
elseif listTypes[v] or v[1] ~= nil or next(v) == nil then
return "list", nil
end
return "compound", nil
end
return nil, "cannot write a " .. tv .. " as NBT"
end
-- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate)
function Value.number(v: any): number?
if type(v) == "number" then
return v
elseif type(v) == "boolean" then
return if v then 1 else 0
elseif Value.isTag(v) then
local x = v.value
if type(x) == "number" then
return x
elseif type(x) == "string" then
return tonumber(x)
end
end
return nil
end
return Value
+380
View File
@@ -0,0 +1,380 @@
--!strict
-- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt,
-- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT").
-- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat
-- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/
-- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers
-- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order
-- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact.
--
-- local Nbt = require("@formats/codecs/text/Nbt")
-- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored
-- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value
-- v.Data.Difficulty = Nbt.byte(2)
-- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts
-- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}}
-- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}')
-- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag
--
-- Never throws: bad data and bad values return nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Deflate = require("@formats/codecs/compress/Deflate")
local Value = require("@formats/codecs/text/Nbt/Value")
local Binary = require("@formats/codecs/text/Nbt/Binary")
local Snbt = require("@formats/codecs/text/Nbt/Snbt")
local Nbt = {}
export type Tag = Value.Tag
export type Info = {
name: string, -- the root tag's name
endian: "big" | "little",
varint: boolean?, -- Bedrock network NBT
compression: "gzip" | "zlib" | "none",
header: number?, -- Bedrock level.dat: the storage version from the 8-byte header
}
export type DecodeOptions = {
endian: ("big" | "little")?, -- default: detected (Java big-endian first)
varint: boolean?, -- Bedrock network NBT
nameless: boolean?, -- no root name (Java network NBT since 1.20.2)
maxDepth: number?, -- nesting limit (default 512)
maxBytes: number?, -- refuse compressed data that inflates past this (default 2^28)
}
export type EncodeOptions = {
endian: ("big" | "little")?, -- default: Nbt.info(value).endian, else "big"
varint: boolean?,
nameless: boolean?,
name: string?, -- the root name (default: Nbt.info(value).name, else "")
compression: ("gzip" | "zlib" | "none")?, -- default: Nbt.info(value).compression, else gzip for big-endian
header: number?, -- write the Bedrock level.dat header with this version
level: number?, -- deflate level 0..9 (default 6)
}
Nbt.TAG = Value.IDS -- name -> id
Nbt.TAG_NAMES = Value.NAMES -- id -> name
Nbt.byte = Value.byte
Nbt.short = Value.short
Nbt.int = Value.int
Nbt.long = Value.long
Nbt.float = Value.float
Nbt.double = Value.double
Nbt.intArray = Value.intArray
Nbt.longArray = Value.longArray
Nbt.longs = Value.longs
Nbt.list = Value.list
Nbt.listType = Value.listType
Nbt.compound = Value.compound
Nbt.typeOf = Value.typeOf
Nbt.isTag = Value.isTag
Nbt.number = Value.number
Nbt.fromHiLo = Value.fromHiLo
Nbt.toHiLo = Value.toHiLo
local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any
-- info(value) -> how a decoded root was stored (nil for values not from decode)
function Nbt.info(v: any): Info?
return if type(v) == "table" then infos[v] else nil
end
-- setInfo(value, info): what encode uses as defaults
function Nbt.setInfo(v: any, info: Info)
if type(v) == "table" then
infos[v] = info
end
end
-- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag
function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?)
local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length)
if not b then
return nil, aerr
end
local v, name, at = Binary.read(b, o, o + l, opts :: any)
if v == nil then
return nil, Err.from(name, (at or o) - o)
end
return v, name, at
end
-- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag
function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local out, e = Binary.write(v, opts :: any)
if not out then
return nil, Err.new(Err.ARG, tostring(e))
end
return out, nil
end
-- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic
function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?)
local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length)
if not b then
return nil, aerr
end
local c0 = if l >= 2 then buffer.readu8(b, o) else 0
local c1 = if l >= 2 then buffer.readu8(b, o + 1) else 0
local out, err, comp
if c0 == 0x1f and c1 == 0x8b then
out, err = Deflate.gunzip(b, o, l)
comp = "gzip"
elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then
out, err = Deflate.zlib(b, o, l)
comp = "zlib"
else
return b, o, o + l, "none"
end
if not out then
return nil, err
end
if buffer.len(out) > (maxBytes or 2 ^ 28) then
return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes")
end
return out, 0, buffer.len(out), comp
end
export type Peek = {
compression: string, -- "gzip" | "zlib" | "none"
endian: "big" | "little",
header: boolean, -- a Bedrock level.dat header
rootType: string, -- "compound" (or "list")
name: string, -- the root name
firstType: string?, -- the first child of a root compound (type and name; "end" when empty), when peeked
firstName: string?,
head: buffer, -- the first (up to 1024) uncompressed bytes
}
local function plausibleName(b: buffer, p: number, n: number): string?
if p + n > buffer.len(b) or n > 256 then
return nil
end
local s = buffer.readstring(b, p, n)
if string.find(s, "[%z\1-\31\127]") then
return nil
end
return s
end
-- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a
-- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly.
function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek?
local o = offset or 0
local l = length or (buffer.len(buf) - o)
if l < 3 then
return nil
end
local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1)
local head: buffer
local comp = "none"
if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then
local h = Deflate.peek(buf, o, l, 1024)
if not h then
return nil
end
head, comp = h, if c0 == 0x1f then "gzip" else "zlib"
else
local n = math.min(l, 1024)
head = buffer.create(n)
buffer.copy(head, 0, buf, o, n)
end
local hn = buffer.len(head)
local function at(p: number, endian: string, header: boolean): Peek?
if p + 3 > hn then
return nil
end
local t = buffer.readu8(head, p)
if t ~= 10 and t ~= 9 then
return nil
end
local function u16(q: number): number
local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1)
return if endian == "big" then a * 256 + b else b * 256 + a
end
local nl = u16(p + 1)
local name = plausibleName(head, p + 3, nl)
if not name then
return nil
end
local res: Peek = { compression = comp, endian = endian :: any, header = header, rootType = Value.NAMES[t], name = name, head = head }
local q = p + 3 + nl
if t == 10 and q < hn then
local ft = buffer.readu8(head, q)
if ft > 12 then
return nil
end
if ft == 0 then
res.firstType = "end" -- an empty root compound
elseif q + 3 <= hn then
local fname = plausibleName(head, q + 3, u16(q + 1))
if fname == nil and q + 3 + u16(q + 1) <= hn then
return nil
end
res.firstType, res.firstName = Value.NAMES[ft], fname
end
end
return res
end
if hn >= 12 and buffer.readu32(head, 4) == (if comp == "none" then l else -1) - 8 then
local r = at(8, "little", true)
if r then
return r
end
end
return at(0, "big", false) or at(0, "little", false)
end
-- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java
-- or Bedrock)
function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any)
local o: DecodeOptions = opts or {}
local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes)
if not b then
return nil, s
end
local data: buffer, start: number, stop: number = b, s, e :: number
local function try(endian: string, from: number, varint: boolean?): (any, any, number?)
return Binary.read(data, from, stop, { endian = endian :: any, varint = varint, nameless = o.nameless, maxDepth = o.maxDepth })
end
local header: number? = nil
local v, name, at
if o.varint then
v, name, at = try("little", start, true)
elseif o.endian then
local from = start
if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then
header, from = buffer.readu32(data, start), start + 8
end
v, name, at = try(o.endian, from)
else
-- Bedrock level.dat: version, length (u32le), then little-endian NBT
if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then
v, name, at = try("little", start + 8)
if v ~= nil then
header = buffer.readu32(data, start)
o = table.clone(o)
o.endian = "little"
end
end
if v == nil then
local bv, bn, ba = try("big", start)
if bv ~= nil and ba == stop then
v, name, at, o = bv, bn, ba, table.clone(o)
o.endian = "big"
else
local lv, ln, la = try("little", start)
if lv ~= nil and (la == stop or bv == nil) then
v, name, at, o = lv, ln, la, table.clone(o)
o.endian = "little"
elseif bv ~= nil then
v, name, at, o = bv, bn, ba, table.clone(o)
o.endian = "big"
else
v, name, at = nil, bn, ba
end
end
end
end
if v == nil then
return nil, Err.from(name, (at or start) - start)
end
local info: Info = {
name = name,
endian = if o.varint or o.endian == "little" then "little" else "big",
varint = if o.varint then true else nil,
compression = comp :: any,
header = header,
}
if type(v) == "table" then
infos[v] = info
end
return v, info
end
-- encode(value, opts?) -> buffer | nil, Err: a whole NBT file
function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local info = Nbt.info(v)
local endian = o.endian or (info and info.endian) or "big"
local varint = if o.varint ~= nil then o.varint else (info and info.varint)
local raw, e = Binary.write(v, {
endian = endian,
varint = varint,
nameless = o.nameless,
name = o.name or (info and info.name) or "",
})
if not raw then
return nil, Err.new(Err.ARG, tostring(e))
end
local header = if o.header ~= nil then o.header else (info and info.header)
if header then
local h = buffer.create(buffer.len(raw) + 8)
buffer.writeu32(h, 0, header)
buffer.writeu32(h, 4, buffer.len(raw))
buffer.copy(h, 8, raw)
raw = h
end
local comp = o.compression or (info and info.compression) or (if endian == "big" then "gzip" else "none")
if comp == "gzip" then
return Deflate.gzip(raw, { level = o.level })
elseif comp == "zlib" then
return Deflate.zlibCompress(raw, { level = o.level })
elseif comp ~= "none" then
return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp))
end
return raw, nil
end
-- parse(text, opts?) -> value | nil, Err: SNBT
function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?)
local s = if type(text) == "buffer" then buffer.tostring(text) else text
if type(s) ~= "string" then
return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string")
end
local v, e, at = Snbt.parse(s, opts)
if v == nil then
return nil, Err.from(e, (at or 1) - 1)
end
return v, nil
end
-- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent)
function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?)
local s, e = Snbt.print(v, opts)
if not s then
return nil, Err.new(Err.ARG, tostring(e))
end
return s, nil
end
-- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's)
function Nbt.get(v: any, path: string): any
local cur = v
for part in string.gmatch(path, "[^%.]+") do
local k, rest = string.match(part, "^([^%[]*)(.*)$")
if k ~= "" then
if type(cur) ~= "table" or Value.isTag(cur) then
return nil
end
cur = cur[k]
end
for idx in string.gmatch(rest :: string, "%[(%-?%d+)%]") do
local i = tonumber(idx) :: number
if type(cur) == "table" and not Value.isTag(cur) then
cur = cur[i + 1]
elseif Value.isTag(cur) and type(cur.value) == "table" then
cur = cur.value[i + 1]
elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then
cur = buffer.readi8(cur, i)
else
return nil
end
end
end
return cur
end
Nbt.object = Types.object
Nbt.shortest = Snbt.shortest
return Nbt