archive/unitypackage: Unity asset packages read + write as an Archive keyed by asset paths (.meta beside each asset, guids, folders, previews)
This commit is contained in:
1 parent
0b6773db8b
commit
5096eb4898
8 files changed
+538
-1
No files matched your search
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
|
||||
## Formats
|
||||
|
||||
<!-- formats:begin -->
|
||||
175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
|
||||
176 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
|
||||
adds each format's capabilities.
|
||||
|
||||
| Category | Format | Extensions | Read | Write |
|
||||
@@ -173,6 +173,7 @@ adds each format's capabilities.
|
||||
| Archives | pak | .pak .sin | yes | yes |
|
||||
| Archives | rpm | .rpm | yes | - |
|
||||
| Archives | tar | .tar | yes | yes |
|
||||
| Archives | unitypackage | .unitypackage | yes | yes |
|
||||
| Archives | uu | .uu .uue .xxe .b64 | yes | yes |
|
||||
| Archives | vpk | .vpk | yes | yes |
|
||||
| Archives | wad | .wad | yes | yes |
|
||||
|
||||
@@ -129,6 +129,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| archive | pak | .pak .sin | yes | yes | variants: "quake", "sin" | `tests/archive/pak.luau` |
|
||||
| archive | rpm | .rpm | yes | - | compressors: "gzip", "bzip2", "xz", "lzma", "zstd" | `tests/archive/rpm.luau` |
|
||||
| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` |
|
||||
| archive | unitypackage | .unitypackage | yes | yes | | `tests/archive/unitypackage.luau` |
|
||||
| archive | uu | .uu .uue .xxe .b64 | yes | yes | variants: "uu", "xx", "base64" | `tests/archive/uu.luau` |
|
||||
| archive | vpk | .vpk | yes | yes | versions: 1, 2, multipart: true | `tests/archive/vpk.luau` |
|
||||
| archive | wad | .wad | yes | yes | images: true, maps: true, variants: "iwad", "pwad" | `tests/archive/wad.luau` |
|
||||
|
||||
@@ -418,6 +418,26 @@ local out = assert(F.save(cab, nil, { format = "cab", compression = "none" }))
|
||||
assert(F.archive.load(out):list()[1].method == "store")
|
||||
```
|
||||
|
||||
## Unity packages
|
||||
|
||||
A `.unitypackage` is a gzip'd tar of one folder per asset guid (`asset`, `asset.meta`, `pathname`). It loads as an
|
||||
Archive keyed by the asset paths, each `.meta` next to its asset as in a Unity project folder; folders are `dir`
|
||||
entries with their own `.meta`. Every entry carries its `guid`, and an asset's `preview` (when the package has a
|
||||
`preview.png`) is a function returning its bytes. Without a name the file is plain gzip (it unwraps to the tar of
|
||||
guid folders): pass a `.unitypackage` name or `format = "unitypackage"`. Any Archive saves as a package: guids come
|
||||
from `entry.guid`, then the `.meta` entry's `guid:` line, else the path's MD5; missing `.meta` files are made.
|
||||
|
||||
```luau
|
||||
local pack = F.format("unitypackage").new()
|
||||
pack:add("Assets/Scripts", "", { dir = true })
|
||||
pack:add("Assets/Scripts/Player.cs", "public class Player { }\n")
|
||||
local bytes = assert(F.save(pack))
|
||||
local back = assert(F.load(bytes, { name = "game.unitypackage" }))
|
||||
assert(back.format == "unitypackage")
|
||||
local meta = buffer.tostring(assert(back:read("Assets/Scripts/Player.cs.meta")))
|
||||
assert(string.match(meta, "guid: (%x+)") == back:list()[3].guid)
|
||||
```
|
||||
|
||||
## Formats
|
||||
|
||||
| Format | Read | Write | Notes |
|
||||
@@ -452,6 +472,7 @@ assert(F.archive.load(out):list()[1].method == "store")
|
||||
| C64 disks (`.d64`, `.d71`, `.d81`) | yes | yes | PETSCII names; no GEOS VLIR |
|
||||
| Amiga disks (`.adf`) | yes | - | OFS / FFS; no long-name (DOS 6 / 7) volumes |
|
||||
| FAT images (`.img`, `.ima`) | yes | yes | FAT12 / 16 / 32, VFAT names, MBR partitions; writes FAT12 floppies |
|
||||
| Unity package (`.unitypackage`) | yes | yes | assets by path, `.meta` files beside them, guids, previews; needs the extension to beat gzip |
|
||||
| Cabinet (`.cab`) | yes | yes | stored / MSZIP / LZX / Quantum (read), stored / MSZIP (write); no spanned files |
|
||||
|
||||
Full capability list: [FORMATS.md](../FORMATS.md).
|
||||
|
||||
@@ -1502,6 +1502,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/archive/tar")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "unitypackage",
|
||||
category = "archive",
|
||||
path = "archive/unitypackage",
|
||||
extensions = { "unitypackage" },
|
||||
mime = { "application/x-unitypackage" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true },
|
||||
load = function()
|
||||
return require("@rosetta/archive/unitypackage")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "uu",
|
||||
category = "archive",
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
--!strict
|
||||
-- archive/unitypackage: Unity asset packages, a gzip'd tar of <guid>/asset, <guid>/asset.meta, <guid>/pathname
|
||||
-- (+ preview.png), read + write as an Archive keyed by the asset paths (Assets/...), each .meta next to its asset as
|
||||
-- in a Unity project. Supports: folders (meta only), lazy entries, guids kept (entry.guid) or made from the path.
|
||||
-- Not supported: pre-5.x packages without pathname files.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Md5 = require("@rosetta/core/Md5")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Tar = require("@rosetta/containers/Tar")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local UnityPackage = {
|
||||
name = "unitypackage",
|
||||
category = "archive",
|
||||
extensions = { "unitypackage" },
|
||||
mime = { "application/x-unitypackage" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxEntries: number?, -- default 1e6
|
||||
maxBytes: number?, -- inflated size, default 2^31
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
level: number?, -- deflate 0..9, default 6
|
||||
mtime: number?, -- tar entry time, default 0
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function guidOf(name: string): (string?, string?)
|
||||
local n = string.gsub(name, "^%./", "")
|
||||
local guid, rest = string.match(n, "^(%x+)/?(.*)$")
|
||||
if guid and #guid == 32 then
|
||||
return string.lower(guid), rest
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
function UnityPackage.sniff(r: Bytes.Reader): number
|
||||
if r:peek(3) ~= "\31\139\8" then
|
||||
return 0
|
||||
end
|
||||
local head = Deflate.peek(r.buf, r.pos, r.limit - r.pos, 512)
|
||||
if not head or buffer.len(head) < 512 or not Tar.valid(head, 0) then
|
||||
return 0
|
||||
end
|
||||
local z = 0
|
||||
while z < 100 and buffer.readu8(head, z) ~= 0 do
|
||||
z += 1
|
||||
end
|
||||
return if guidOf(buffer.readstring(head, 0, z)) then 1 else 0 -- ties with archive/gzip go to the extension
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return UnityPackage.encode(archive, opts)
|
||||
end
|
||||
|
||||
type Asset = { asset: Tar.Entry?, meta: Tar.Entry?, pathname: Tar.Entry?, preview: Tar.Entry? }
|
||||
|
||||
local function text(b: buffer, e: Tar.Entry): string
|
||||
return buffer.readstring(b, e.offset, e.size)
|
||||
end
|
||||
|
||||
function UnityPackage.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o = opts or {}
|
||||
local tar, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base)
|
||||
if not tar then
|
||||
return nil, err
|
||||
end
|
||||
if buffer.len(tar) > (o.maxBytes or 2 ^ 31) then
|
||||
return nil, Err.new(Err.LIMIT, "inflated size over the byte limit")
|
||||
end
|
||||
local list, terr = Tar.read(tar, 0, buffer.len(tar), { maxEntries = o.maxEntries })
|
||||
if not list then
|
||||
return nil, terr
|
||||
end
|
||||
local byGuid: { [string]: Asset } = {}
|
||||
local order: { string } = {}
|
||||
for _, e in list do
|
||||
local guid, rest = guidOf(e.name)
|
||||
if guid and not e.dir then
|
||||
local a = byGuid[guid]
|
||||
if not a then
|
||||
a = {}
|
||||
byGuid[guid] = a
|
||||
table.insert(order, guid)
|
||||
end
|
||||
if rest == "asset" then
|
||||
a.asset = e
|
||||
elseif rest == "asset.meta" then
|
||||
a.meta = e
|
||||
elseif rest == "pathname" then
|
||||
a.pathname = e
|
||||
elseif rest == "preview.png" then
|
||||
a.preview = e
|
||||
end
|
||||
end
|
||||
end
|
||||
local arc = Archive.new("unitypackage", encode)
|
||||
local skipped = 0
|
||||
for _, guid in order do
|
||||
local a = byGuid[guid]
|
||||
local pn = a.pathname
|
||||
if not pn then
|
||||
skipped += 1
|
||||
else
|
||||
-- the first line is the path (Unity 5+ may add a second line, e.g. "00")
|
||||
local path = string.match(text(tar, pn), "^[^\r\n]*") or ""
|
||||
path = string.gsub(path, "\\", "/")
|
||||
if path ~= "" then
|
||||
local asset, meta = a.asset, a.meta
|
||||
local isDir = asset == nil
|
||||
Archive.put(arc, {
|
||||
name = path,
|
||||
size = if asset then asset.size else 0,
|
||||
dir = isDir,
|
||||
mtime = if asset then asset.mtime elseif meta then meta.mtime else nil,
|
||||
method = "deflate",
|
||||
guid = guid,
|
||||
load = if asset and asset.size > 0 then Archive.slice(tar, asset.offset, asset.size) else nil,
|
||||
preview = if a.preview then Archive.slice(tar, a.preview.offset, a.preview.size) else nil,
|
||||
})
|
||||
if meta then
|
||||
Archive.put(arc, {
|
||||
name = path .. ".meta",
|
||||
size = meta.size,
|
||||
dir = false,
|
||||
mtime = meta.mtime,
|
||||
method = "deflate",
|
||||
guid = guid,
|
||||
load = if meta.size > 0 then Archive.slice(tar, meta.offset, meta.size) else nil,
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
arc.meta.source = { format = "unitypackage", assets = #order - skipped, skipped = if skipped > 0 then skipped else nil }
|
||||
return arc, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function metaGuid(b: buffer): string?
|
||||
local s = buffer.readstring(b, 0, math.min(buffer.len(b), 4096))
|
||||
local g = string.match(s, "\nguid:%s*(%x+)") or string.match(s, "^guid:%s*(%x+)")
|
||||
if g and #g == 32 then
|
||||
return string.lower(g)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function defaultMeta(guid: string, dir: boolean): string
|
||||
if dir then
|
||||
return "fileFormatVersion: 2\nguid: " .. guid .. "\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n userData: \n assetBundleName: \n assetBundleVariant: \n"
|
||||
end
|
||||
return "fileFormatVersion: 2\nguid: " .. guid .. "\nDefaultImporter:\n externalObjects: {}\n userData: \n assetBundleName: \n assetBundleVariant: \n"
|
||||
end
|
||||
|
||||
function UnityPackage.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o = opts or {}
|
||||
local items = Archive.entries(archive)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local byName: { [string]: any } = {}
|
||||
for _, it in items do
|
||||
byName[string.gsub(it.entry.name, "\\", "/")] = it
|
||||
end
|
||||
local mtime = o.mtime or 0
|
||||
local list: { Tar.WriteEntry } = {}
|
||||
local used: { [string]: boolean } = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
local path = string.gsub((string.gsub(e.name, "\\", "/")), "/+$", "")
|
||||
local metaIt = byName[path .. ".meta"]
|
||||
local isMeta = string.sub(path, -5) == ".meta" and byName[string.sub(path, 1, -6)] ~= nil
|
||||
if path ~= "" and not isMeta then
|
||||
local data: buffer? = nil
|
||||
if not e.dir then
|
||||
local b, rerr = it.read()
|
||||
if not b then
|
||||
return nil, rerr
|
||||
end
|
||||
data = b
|
||||
end
|
||||
local metaData: buffer? = nil
|
||||
if metaIt then
|
||||
local mb, merr = metaIt.read()
|
||||
if not mb then
|
||||
return nil, merr
|
||||
end
|
||||
metaData = mb
|
||||
end
|
||||
local guid = if type(e.guid) == "string" and #e.guid == 32 and string.match(e.guid, "^%x+$") then string.lower(e.guid) else nil
|
||||
guid = guid or (if metaData then metaGuid(metaData) else nil) or Md5.of(buffer.fromstring(path))
|
||||
if used[guid :: string] then
|
||||
guid = Md5.of(buffer.fromstring(path .. "\0" .. guid))
|
||||
end
|
||||
used[guid :: string] = true
|
||||
local g = guid :: string
|
||||
metaData = metaData or buffer.fromstring(defaultMeta(g, e.dir == true))
|
||||
table.insert(list, { name = g .. "/", dir = true, mtime = mtime })
|
||||
if data then
|
||||
table.insert(list, { name = g .. "/asset", data = data, mtime = mtime })
|
||||
end
|
||||
table.insert(list, { name = g .. "/asset.meta", data = metaData, mtime = mtime })
|
||||
table.insert(list, { name = g .. "/pathname", data = buffer.fromstring(path), mtime = mtime })
|
||||
if type(e.preview) == "function" then
|
||||
local ok, pb = pcall(e.preview)
|
||||
if ok and type(pb) == "buffer" then
|
||||
table.insert(list, { name = g .. "/preview.png", data = pb, mtime = mtime })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local tar, terr = Tar.write(list, { format = "ustar" })
|
||||
if not tar then
|
||||
return nil, terr
|
||||
end
|
||||
return Deflate.gzip(tar, { level = o.level or 6 })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
function UnityPackage.new(): any
|
||||
local a = Archive.new("unitypackage", encode)
|
||||
a.meta.source = { format = "unitypackage" }
|
||||
return a
|
||||
end
|
||||
|
||||
return UnityPackage
|
||||
@@ -0,0 +1,136 @@
|
||||
-- archive/unitypackage tests: packages built with Python's tarfile against their asset tables (paths, guids, asset
|
||||
-- and meta MD5s, folders); our writer's output read by Python's tarfile; api detection; errors; fuzz.
|
||||
-- Fixtures: tools/fixtures/unitypackage.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@rosetta")
|
||||
local UnityPackage = require("@rosetta/archive/unitypackage")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Md5 = require("@rosetta/core/Md5")
|
||||
local Fx = require("@tests/gen/unitypackage")
|
||||
|
||||
local t = T.suite("unitypackage")
|
||||
|
||||
local function decode(s: string | buffer, opts: any?): (any, any)
|
||||
local b = if type(s) == "string" then buffer.fromstring(s) else s
|
||||
return UnityPackage.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(UnityPackage.name, "unitypackage", "name")
|
||||
t:eq(UnityPackage.category, "archive", "category")
|
||||
t:check(UnityPackage.caps.decode and UnityPackage.caps.encode, "caps")
|
||||
|
||||
local function checkAssets(a: any, assets: { any }, label: string)
|
||||
local entries = {}
|
||||
for _, e in a:list() do
|
||||
entries[e.name] = e
|
||||
end
|
||||
local n = 0
|
||||
for _, want in assets do
|
||||
local e = entries[want.path]
|
||||
t:check(e, label .. ": " .. want.path .. " listed")
|
||||
if e then
|
||||
n += 1
|
||||
t:eq(e.dir, want.dir, label .. ": " .. want.path .. " dir")
|
||||
t:eq(e.guid, want.guid, label .. ": " .. want.path .. " guid")
|
||||
if not want.dir then
|
||||
local b = a:read(want.path)
|
||||
t:eq(Md5.of(b), want.md5, label .. ": " .. want.path .. " data")
|
||||
end
|
||||
local m = a:read(want.path .. ".meta")
|
||||
t:check(m and Md5.of(m) == want.metaMd5, label .. ": " .. want.path .. ".meta")
|
||||
end
|
||||
end
|
||||
t:eq(#a:list(), n * 2, label .. ": an entry and a .meta per asset, nothing else")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
local a, err = decode(c.data)
|
||||
t:check(a, c.name .. ": decode: " .. tostring(err))
|
||||
if a then
|
||||
checkAssets(a, c.assets, c.name)
|
||||
t:eq(a.meta.source.assets, #c.assets, c.name .. ": asset count")
|
||||
local e
|
||||
for _, x in a:list() do
|
||||
if x.name == "Assets/Textures/brick.png" then
|
||||
e = x
|
||||
end
|
||||
end
|
||||
local pv = e and e.preview and e.preview()
|
||||
t:check(pv and buffer.readstring(pv, 8, 7) == "preview", c.name .. ": preview.png")
|
||||
-- round trip through our writer
|
||||
local out, werr = UnityPackage.encode(a)
|
||||
t:check(out, c.name .. ": encode: " .. tostring(werr))
|
||||
local back = out and decode(out)
|
||||
t:check(back, c.name .. ": re-decode")
|
||||
if back then
|
||||
checkAssets(back, c.assets, c.name .. " round trip")
|
||||
end
|
||||
end
|
||||
t:eq(UnityPackage.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
|
||||
t:eq(F.detect(c.data, { name = "pack.unitypackage" }), "unitypackage", c.name .. ": F.detect with the extension")
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
|
||||
-- Python's tarfile reads ours
|
||||
for _, o in Fx.ours do
|
||||
t:check(o.ok, o.name .. ": Python reads it: " .. tostring(o.error))
|
||||
local want: any = nil
|
||||
for _, c in Fx.cases do
|
||||
if c.name .. ".unitypackage" == o.name then
|
||||
want = c.assets
|
||||
end
|
||||
end
|
||||
if want then
|
||||
local got = {}
|
||||
for _, x in o.assets do
|
||||
got[x.path] = x
|
||||
end
|
||||
for _, w in want do
|
||||
local g = got[w.path]
|
||||
t:check(g and g.guid == w.guid and g.md5 == w.md5 and g.metaMd5 == w.metaMd5 and g.dir == w.dir, o.name .. ": " .. w.path)
|
||||
end
|
||||
t:eq(#o.assets, #want, o.name .. ": asset count")
|
||||
elseif o.name == "scratch.unitypackage" then
|
||||
local got = {}
|
||||
for _, x in o.assets do
|
||||
got[x.path] = x
|
||||
end
|
||||
t:check(got["Assets/Models"] and got["Assets/Models"].dir, "scratch: folder")
|
||||
t:check(got["Assets/Models/cube.obj"] and not got["Assets/Models/cube.obj"].dir, "scratch: file")
|
||||
t:eq(got["Assets/readme.txt"] and got["Assets/readme.txt"].guid, "0123456789abcdef0123456789abcdef", "scratch: guid from the .meta")
|
||||
t:eq(#o.assets, 3, "scratch: assets")
|
||||
end
|
||||
end
|
||||
|
||||
-- from any archive (a tar) through F.save
|
||||
do
|
||||
local tar = F.format("tar").new()
|
||||
tar:add("Assets/a.txt", "a")
|
||||
tar:add("Assets/b/", "", { dir = true })
|
||||
local out = assert(F.save(tar, nil, { format = "unitypackage" }))
|
||||
local back = assert(decode(out))
|
||||
local names = {}
|
||||
for _, e in back:list() do
|
||||
names[e.name] = e.dir
|
||||
end
|
||||
t:check(names["Assets/a.txt"] == false and names["Assets/a.txt.meta"] == false and names["Assets/b"] == true, "tar -> unitypackage")
|
||||
local meta = buffer.tostring(back:read("Assets/b.meta"))
|
||||
t:check(string.find(meta, "folderAsset: yes", 1, true) ~= nil, "folder meta")
|
||||
end
|
||||
|
||||
do
|
||||
local _, e = decode("\31\139\8\0\0\0\0\0\0\255garbage")
|
||||
t:check(e ~= nil, "bad deflate data")
|
||||
local _, e2 = decode(Fx.cases[1].data, { maxEntries = 2 })
|
||||
t:check(e2 and e2.code == Err.LIMIT, "entry limit: " .. tostring(e2))
|
||||
local _, e3 = UnityPackage.encode({} :: any)
|
||||
t:check(e3 and e3.code == Err.ARG, "encode arg")
|
||||
t:eq(UnityPackage.sniff(Bytes.reader(buffer.fromstring("hello"))), 0, "sniff text")
|
||||
end
|
||||
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return decode(b)
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -0,0 +1,36 @@
|
||||
-- tools/fixtures/_unitypackage_encode: run by tools/fixtures/unitypackage.py (luau CLI, repo root): re-encodes every
|
||||
-- package case and a package built from scratch, printing "<file>\t<hex>" lines for Python's tarfile to read.
|
||||
local UnityPackage = require("@rosetta/archive/unitypackage")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Fx = require("@tests/gen/unitypackage")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = HEX[buffer.readu8(b, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for _, c in Fx.cases do
|
||||
local a = UnityPackage.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if a then
|
||||
local out = UnityPackage.encode(a)
|
||||
if out then
|
||||
print(c.name .. ".unitypackage\t" .. hex(out))
|
||||
end
|
||||
end
|
||||
end
|
||||
local a = UnityPackage.new()
|
||||
a:add("Assets/Models", "", { dir = true })
|
||||
a:add("Assets/Models/cube.obj", "v 0 0 0\n")
|
||||
a:add("Assets/readme.txt", "hello\n")
|
||||
a:add("Assets/readme.txt.meta", "fileFormatVersion: 2\nguid: 0123456789abcdef0123456789abcdef\n")
|
||||
local out = UnityPackage.encode(a)
|
||||
if out then
|
||||
print("scratch.unitypackage\t" .. hex(out))
|
||||
end
|
||||
@@ -0,0 +1,95 @@
|
||||
# .unitypackage fixtures (tools/fixtures.py): packages built here with Python's tarfile + gzip to the layout Unity
|
||||
# writes (<guid>/asset, <guid>/asset.meta, <guid>/pathname, optional preview.png; folders carry only a meta), with
|
||||
# the expected asset table; then our encoder's output (tools/fixtures/_unitypackage_encode.luau) read back by
|
||||
# Python's tarfile.
|
||||
# tests/gen/unitypackage.luau { cases = { { name, data, assets = { { path, guid, md5?, metaMd5, dir } } } },
|
||||
# ours = { { name, ok, assets = { { path, guid, md5?, metaMd5, dir } }, error? } } }
|
||||
import gzip, hashlib, importlib.util, io, os, tarfile, uuid
|
||||
|
||||
INPUTS = ["src/Rosetta/archive/unitypackage", "tools/fixtures/_unitypackage_encode.luau", "tools/fixtures/_model_ref.py"]
|
||||
|
||||
|
||||
def meta(guid, folder=False):
|
||||
s = "fileFormatVersion: 2\nguid: %s\n" % guid
|
||||
if folder:
|
||||
s += "folderAsset: yes\n"
|
||||
return (s + "DefaultImporter:\n externalObjects: {}\n userData: \n").encode()
|
||||
|
||||
|
||||
def build(items, dot=False, extra_line=False, mtime=1600000000):
|
||||
"""items: [(path, data or None for a folder, preview bytes or None)]"""
|
||||
raw = io.BytesIO()
|
||||
assets = []
|
||||
with tarfile.open(fileobj=raw, mode="w", format=tarfile.GNU_FORMAT) as tf:
|
||||
def add(name, data):
|
||||
ti = tarfile.TarInfo(("./" if dot else "") + name)
|
||||
ti.size = len(data)
|
||||
ti.mtime = mtime
|
||||
tf.addfile(ti, io.BytesIO(data))
|
||||
for path, data, preview in items:
|
||||
guid = uuid.uuid5(uuid.NAMESPACE_URL, path).hex
|
||||
d = tarfile.TarInfo(("./" if dot else "") + guid)
|
||||
d.type = tarfile.DIRTYPE
|
||||
d.mtime = mtime
|
||||
tf.addfile(d)
|
||||
m = meta(guid, data is None)
|
||||
if data is not None:
|
||||
add(guid + "/asset", data)
|
||||
add(guid + "/asset.meta", m)
|
||||
add(guid + "/pathname", (path + ("\n00" if extra_line else "")).encode())
|
||||
if preview:
|
||||
add(guid + "/preview.png", preview)
|
||||
a = {"path": path, "guid": guid, "metaMd5": hashlib.md5(m).hexdigest(), "dir": data is None}
|
||||
if data is not None:
|
||||
a["md5"] = hashlib.md5(data).hexdigest()
|
||||
assets.append(a)
|
||||
return gzip.compress(raw.getvalue(), mtime=0), assets
|
||||
|
||||
|
||||
def read_package(data):
|
||||
out = []
|
||||
with tarfile.open(fileobj=io.BytesIO(gzip.decompress(data))) as tf:
|
||||
files = {}
|
||||
for m in tf.getmembers():
|
||||
if m.isfile():
|
||||
files[m.name] = tf.extractfile(m).read()
|
||||
guids = sorted({n.split("/")[0] for n in files})
|
||||
for g in guids:
|
||||
path = files[g + "/pathname"].decode().split("\n")[0]
|
||||
m = files[g + "/asset.meta"]
|
||||
if ("guid: " + g).encode() not in m:
|
||||
raise ValueError("meta guid mismatch for " + path)
|
||||
a = {"path": path, "guid": g, "metaMd5": hashlib.md5(m).hexdigest(), "dir": (g + "/asset") not in files}
|
||||
if not a["dir"]:
|
||||
a["md5"] = hashlib.md5(files[g + "/asset"]).hexdigest()
|
||||
out.append(a)
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(7)
|
||||
png = b"\x89PNG\r\n\x1a\n" + rng.randbytes(200)
|
||||
items = [
|
||||
("Assets", None, None),
|
||||
("Assets/Textures", None, None),
|
||||
("Assets/Textures/brick.png", png, b"\x89PNG\r\n\x1a\npreview"),
|
||||
("Assets/Scripts/Player.cs", b"using UnityEngine;\npublic class Player : MonoBehaviour { }\n", None),
|
||||
("Assets/Scenes/Main Scene.unity", b"%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &1\n", None),
|
||||
("Assets/Audio/empty.wav", b"", None),
|
||||
("Assets/Big/blob.bin", rng.randbytes(70000), None),
|
||||
]
|
||||
cases = []
|
||||
for name, kw in (("plain", {}), ("dot", {"dot": True}), ("extra-line", {"extra_line": True})):
|
||||
data, assets = build(items, **kw)
|
||||
cases.append({"name": name, "data": data, "assets": assets})
|
||||
ctx.emit("unitypackage", {"cases": cases, "ours": []})
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
M = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(M)
|
||||
ours = []
|
||||
for name, data in sorted(M.luau_encode(ctx, "tools/fixtures/_unitypackage_encode.luau").items()):
|
||||
try:
|
||||
ours.append({"name": name, "ok": True, "assets": read_package(data)})
|
||||
except Exception as e:
|
||||
ours.append({"name": name, "ok": False, "assets": [], "error": str(e)})
|
||||
ctx.emit("unitypackage", {"cases": cases, "ours": ours})
|
||||
Reference in new issue
Block a user