model/t3d: Unreal T3D (UE1-4) brushes through codecs/model/Brush and actors as nodes
This commit is contained in:
1 parent
37aa29d03e
commit
8d305bb942
10 files changed
+1084
-4
No files matched your search
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
|
||||
## Formats
|
||||
|
||||
<!-- formats:begin -->
|
||||
186 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
|
||||
187 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 |
|
||||
@@ -138,6 +138,7 @@ adds each format's capabilities.
|
||||
| 3D models | schematic | .schem .schematic .litematic | yes | yes |
|
||||
| 3D models | smd | .smd | yes | yes |
|
||||
| 3D models | stl | .stl | yes | yes |
|
||||
| 3D models | t3d | .t3d | yes | - |
|
||||
| 3D models | usda | .usda .usd .usdz | yes | yes |
|
||||
| 3D models | vox | .vox | yes | yes |
|
||||
| 3D models | vrml | .wrl .wrz .vrml | yes | yes |
|
||||
|
||||
@@ -94,6 +94,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` |
|
||||
| model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` |
|
||||
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
|
||||
| model | t3d | .t3d | yes | - | text: true, brushes: true, actors: true | `tests/model/t3d.luau` |
|
||||
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
|
||||
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
|
||||
| model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` |
|
||||
|
||||
@@ -831,6 +831,39 @@ surfaces with positions, normals, tangents, colours, two UV sets) and StandardMa
|
||||
`ext_resource` per texture with a `uri`. Skins, animations and morph targets are not written. Godot resources
|
||||
(`.tres`) are data: see [data.md](data.md).
|
||||
|
||||
## Unreal T3D
|
||||
|
||||
UnrealEd's text export (`.t3d`: `Begin Map` / `Begin Actor` / `Begin Brush` / `Begin PolyList` / `Begin Polygon`,
|
||||
UE1 to UE4) loads as a Scene in Unreal's own Z-up, left-handed coordinates (`meta.handedness = "left"`; nothing is
|
||||
mirrored). Every actor is a root node with its class, properties, CSG operation and components in
|
||||
`node.extras.t3d`; its matrix is the brush transform (PrePivot, MainScale, Rotation, PostScale, Location; rotations
|
||||
in 65536ths of a turn, or degrees in UE4 text) or the actor's Location / Rotation / DrawScale (UE4: the root
|
||||
component's `Relative*`). Brush polygons become one primitive per texture through `codecs/model/Brush`, with UVs from
|
||||
`TextureU` / `TextureV` / `Origin` / `Pan` divided by the texture size (`opts.textureSize`: a function or a
|
||||
`{ [name] = { w, h } }` table, default 256). Triangles wind counter-clockwise about each polygon's stored normal;
|
||||
subtractive brushes are turned inside out (a room is seen from within), the red builder brush is skipped unless
|
||||
`builder = true`. No BSP CSG is done: overlapping brushes stay separate meshes. Lights (UE1 hue / saturation /
|
||||
brightness, UE3-4 light components) and cameras map across; static mesh actors keep their mesh path in
|
||||
`extras.t3d.staticMesh`.
|
||||
|
||||
```luau
|
||||
local level = assert(F.load(t3dText, { textureSize = { Bricks = { 128, 64 }, Floor = { 256, 256 } } }))
|
||||
assert(level.meta.source.format == "t3d" and level.meta.up == "z")
|
||||
local room
|
||||
for _, n in level.nodes do
|
||||
if n.name == "Brush0" then
|
||||
room = n
|
||||
end
|
||||
end
|
||||
assert(room.extras.t3d.csg == "CSG_Subtract" and room.mesh)
|
||||
assert(room.matrix[13] == 64) -- Location X
|
||||
local names = {}
|
||||
for _, p in level.meshes[room.mesh].primitives do
|
||||
names[level.materials[p.material].name] = true
|
||||
end
|
||||
assert(names.Bricks and names.Floor)
|
||||
```
|
||||
|
||||
## Formats
|
||||
|
||||
| Format | Read | Write | Notes |
|
||||
@@ -862,6 +895,7 @@ surfaces with positions, normals, tangents, colours, two UV sets) and StandardMa
|
||||
| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above; BSP lightmaps, hulls, PVS: "Quake maps" |
|
||||
| Quake / Half-Life / Quake II / Quake III `.map` | yes | yes | entities as nodes, brushes CSG'd, patches: see "Quake maps" |
|
||||
| SMD | yes | yes | Valve studiomdl data |
|
||||
| Unreal T3D (`.t3d`) | yes | - | brushes as polygons per texture (no CSG), actors with properties, lights, cameras; Z up, left-handed |
|
||||
| Godot `.tscn` / `.escn` | yes | yes (`.tscn`) | Node3D trees, ArrayMesh and primitive meshes, StandardMaterial3D, cameras, lights, instances; 2D nodes in extras |
|
||||
| ASE (3ds Max ASCII) | yes | yes | Multi/Sub-Object materials, texture channels, vertex colours, normals, helpers, cameras, lights; no animation; Z up |
|
||||
| Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) |
|
||||
|
||||
@@ -1082,6 +1082,18 @@ local list: { Entry } = {
|
||||
return require("@rosetta/model/stl")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "t3d",
|
||||
category = "model",
|
||||
path = "model/t3d",
|
||||
extensions = { "t3d" },
|
||||
mime = { "text/x-unreal-t3d" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Text", "codecs/model/Brush" },
|
||||
caps = { decode = true, encode = false, text = true, brushes = true, actors = true },
|
||||
load = function()
|
||||
return require("@rosetta/model/t3d")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "usda",
|
||||
category = "model",
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
--!strict
|
||||
-- model/t3d/Build: parsed T3D blocks into a Scene: one node per actor (Unreal's own Z-up, left-handed coordinates,
|
||||
-- kept as they are), brush polygons as primitives per texture (codecs/model/Brush). Brush transform as UnrealEd's
|
||||
-- ABrush coords: v - PrePivot, MainScale, Rotation, PostScale, + Location. Rotation as FRotationMatrix (Pitch / Yaw /
|
||||
-- Roll: 65536 units per turn, or degrees in UE4 text). Polygon winding follows the stored Normal; subtractive
|
||||
-- brushes face inwards.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Brush = require("@rosetta/codecs/model/Brush")
|
||||
local Parse = require("@rosetta/model/t3d/Parse")
|
||||
|
||||
type Block = Parse.Block
|
||||
|
||||
local Build = {}
|
||||
|
||||
local S = Types.Scene
|
||||
|
||||
local function num(v: any, d: number): number
|
||||
return if type(v) == "number" and v == v then v else d
|
||||
end
|
||||
|
||||
local function vec3(s: string?): { number }?
|
||||
if type(s) ~= "string" then
|
||||
return nil
|
||||
end
|
||||
local a, b, c = string.match(s, "^%s*([^,%s]+)%s*,%s*([^,%s]+)%s*,%s*([^,%s]+)")
|
||||
if not a then
|
||||
return nil
|
||||
end
|
||||
local x, y, z = tonumber((string.gsub(a, "^%+", ""))), tonumber((string.gsub(b :: string, "^%+", ""))), tonumber((string.gsub(c :: string, "^%+", "")))
|
||||
if x and y and z then
|
||||
return { x, y, z }
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function xyz(v: any, d: { number }): { number }
|
||||
if type(v) == "table" then
|
||||
return { num(v.X, d[1]), num(v.Y, d[2]), num(v.Z, d[3]) }
|
||||
end
|
||||
return d
|
||||
end
|
||||
|
||||
-- FRotationMatrix rows are the X / Y / Z axes: the columns of a column-major matrix
|
||||
local function rotation(r: any, degrees: boolean): { number }
|
||||
if type(r) ~= "table" then
|
||||
return S.IDENTITY
|
||||
end
|
||||
local k = if degrees then math.pi / 180 else math.pi * 2 / 65536
|
||||
local p, y, ro = num(r.Pitch, 0) * k, num(r.Yaw, 0) * k, num(r.Roll, 0) * k
|
||||
local SP, CP, SY, CY, SR, CR = math.sin(p), math.cos(p), math.sin(y), math.cos(y), math.sin(ro), math.cos(ro)
|
||||
return {
|
||||
CP * CY, CP * SY, SP, 0,
|
||||
SR * SP * CY - CR * SY, SR * SP * SY + CR * CY, -SR * CP, 0,
|
||||
-(CR * SP * CY + SR * SY), CY * SR - CR * SP * SY, CR * CP, 0,
|
||||
0, 0, 0, 1,
|
||||
}
|
||||
end
|
||||
|
||||
local function scaling(s: { number }): { number }
|
||||
return { s[1], 0, 0, 0, 0, s[2], 0, 0, 0, 0, s[3], 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
local function translation(t: { number }): { number }
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t[1], t[2], t[3], 1 }
|
||||
end
|
||||
|
||||
local function plain(b: Block): { [string]: any }
|
||||
local out: { [string]: any } = {}
|
||||
for _, k in b.order do
|
||||
out[k] = b.props[k]
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the component holding the actor's transform (UE4: RootComponent's Relative* properties)
|
||||
local function component(actor: Block, objects: { [string]: { [string]: any } }): { [string]: any }?
|
||||
local root = actor.props.RootComponent
|
||||
if type(root) == "string" then
|
||||
local name = string.match(root, "'\"?([^'\"]+)\"?'") or root
|
||||
name = string.match(name, "([^%.:]+)$") or name
|
||||
if objects[name] then
|
||||
return objects[name]
|
||||
end
|
||||
end
|
||||
for _, o in objects do
|
||||
if o.RelativeLocation ~= nil or o.RelativeRotation ~= nil or o.RelativeScale3D ~= nil then
|
||||
return o
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function polygons(b: Block, out: { Block })
|
||||
for _, c in b.children do
|
||||
local k = string.lower(c.kind)
|
||||
if k == "polygon" then
|
||||
table.insert(out, c)
|
||||
elseif k == "polylist" or k == "brush" then
|
||||
polygons(c, out)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
type Ctx = { scene: Types.Scene, materials: { [string]: number }, opts: any, polys: number }
|
||||
|
||||
local function material(ctx: Ctx, name: string): number
|
||||
local m = ctx.materials[name]
|
||||
if m then
|
||||
return m
|
||||
end
|
||||
local mat = S.material(if name ~= "" then name else nil)
|
||||
mat.metallic = 0
|
||||
if name ~= "" then
|
||||
table.insert(ctx.scene.textures, { name = name })
|
||||
mat.baseColorTexture = { texture = #ctx.scene.textures }
|
||||
end
|
||||
mat.extras = { t3d = { texture = name } }
|
||||
table.insert(ctx.scene.materials, mat)
|
||||
ctx.materials[name] = #ctx.scene.materials
|
||||
return #ctx.scene.materials
|
||||
end
|
||||
|
||||
-- the brush's polygons as Scene primitives (local brush space)
|
||||
local function brushMesh(ctx: Ctx, brush: Block, subtract: boolean): (Types.Mesh?, string?)
|
||||
local list: { Block } = {}
|
||||
polygons(brush, list)
|
||||
if #list == 0 then
|
||||
return nil, nil
|
||||
end
|
||||
local faces: { Brush.Face } = {}
|
||||
local polys: { Brush.Polygon } = {}
|
||||
local flags: { number } = {}
|
||||
for _, pb in list do
|
||||
local rec: { [string]: string } = {}
|
||||
local verts: { number } = {}
|
||||
for _, r in pb.records do
|
||||
local name = string.lower(r[1])
|
||||
if name == "vertex" then
|
||||
local v = vec3(r[2])
|
||||
if v then
|
||||
table.insert(verts, v[1])
|
||||
table.insert(verts, v[2])
|
||||
table.insert(verts, v[3])
|
||||
end
|
||||
elseif rec[name] == nil then
|
||||
rec[name] = r[2]
|
||||
end
|
||||
end
|
||||
local nv = #verts // 3
|
||||
if nv >= 3 then
|
||||
ctx.polys += 1
|
||||
if ctx.polys > (ctx.opts.maxPolygons or 2 ^ 20) then
|
||||
return nil, "limit: over " .. (ctx.opts.maxPolygons or 2 ^ 20) .. " polygons"
|
||||
end
|
||||
-- Newell normal of the vertex order
|
||||
local nx, ny, nz = 0, 0, 0
|
||||
for k = 0, nv - 1 do
|
||||
local j = (k + 1) % nv
|
||||
local ax, ay, az = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3]
|
||||
local bx, by, bz = verts[j * 3 + 1], verts[j * 3 + 2], verts[j * 3 + 3]
|
||||
nx += (ay - by) * (az + bz)
|
||||
ny += (az - bz) * (ax + bx)
|
||||
nz += (ax - bx) * (ay + by)
|
||||
end
|
||||
local stated = vec3(rec.normal)
|
||||
local n = stated or { nx, ny, nz }
|
||||
local l = math.sqrt(n[1] * n[1] + n[2] * n[2] + n[3] * n[3])
|
||||
if l > 0 then
|
||||
n = { n[1] / l, n[2] / l, n[3] / l }
|
||||
end
|
||||
local reverse = nx * n[1] + ny * n[2] + nz * n[3] < 0
|
||||
if subtract then
|
||||
reverse = not reverse
|
||||
n = { -n[1], -n[2], -n[3] }
|
||||
end
|
||||
if reverse then
|
||||
local r: { number } = {}
|
||||
for k = nv - 1, 0, -1 do
|
||||
table.insert(r, verts[k * 3 + 1])
|
||||
table.insert(r, verts[k * 3 + 2])
|
||||
table.insert(r, verts[k * 3 + 3])
|
||||
end
|
||||
verts = r
|
||||
end
|
||||
local tex = if type(pb.attrs.Texture) == "string" then pb.attrs.Texture else (if pb.attrs.Texture ~= nil then tostring(pb.attrs.Texture) else "")
|
||||
local o = vec3(rec.origin) or { 0, 0, 0 }
|
||||
local u = vec3(rec.textureu) or { 1, 0, 0 }
|
||||
local v = vec3(rec.texturev) or { 0, 1, 0 }
|
||||
local panU, panV = 0, 0
|
||||
if rec.pan then
|
||||
panU = tonumber(string.match(rec.pan, "U=%s*([-+]?[%d%.]+)")) or 0
|
||||
panV = tonumber(string.match(rec.pan, "V=%s*([-+]?[%d%.]+)")) or 0
|
||||
end
|
||||
-- texel = (p - Origin) . TextureU + PanU
|
||||
local face: Brush.Face = {
|
||||
plane = { n[1], n[2], n[3], n[1] * o[1] + n[2] * o[2] + n[3] * o[3] },
|
||||
texture = tex,
|
||||
vecs = {
|
||||
{ u[1], u[2], u[3], panU - (o[1] * u[1] + o[2] * u[2] + o[3] * u[3]) },
|
||||
{ v[1], v[2], v[3], panV - (o[1] * v[1] + o[2] * v[2] + o[3] * v[3]) },
|
||||
},
|
||||
}
|
||||
table.insert(faces, face)
|
||||
table.insert(polys, { brush = 1, face = #faces, points = verts, normal = n })
|
||||
table.insert(flags, num(pb.attrs.Flags, 0))
|
||||
end
|
||||
end
|
||||
local size = ctx.opts.textureSize
|
||||
local built = Brush.primitives(polys, { faces }, function(name: string): (number, number)
|
||||
if type(size) == "function" then
|
||||
local ok, w, h = pcall(size, name)
|
||||
if ok and type(w) == "number" then
|
||||
return w, if type(h) == "number" then h else w
|
||||
end
|
||||
elseif type(size) == "table" and type(size[name]) == "table" then
|
||||
return num(size[name][1], 256), num(size[name][2], 256)
|
||||
end
|
||||
return 256, 256
|
||||
end)
|
||||
local mesh: Types.Mesh = { name = if type(brush.attrs.Name) == "string" then brush.attrs.Name else nil, primitives = {} }
|
||||
for _, b in built do
|
||||
b.primitive.material = material(ctx, b.texture)
|
||||
table.insert(mesh.primitives, b.primitive)
|
||||
end
|
||||
mesh.extras = { t3d = { polygons = #polys } }
|
||||
return mesh, nil
|
||||
end
|
||||
|
||||
local LIGHTS: { [string]: "point" | "spot" | "directional" } = {
|
||||
Light = "point", PointLight = "point", SpotLight = "spot", DirectionalLight = "directional", TriggerLight = "point",
|
||||
SkyLight = "directional", Spotlight = "spot", SunLight = "directional", DominantDirectionalLight = "directional",
|
||||
PointLightMovable = "point", SpotLightMovable = "spot", DirectionalLightMovable = "directional",
|
||||
}
|
||||
|
||||
-- HSV of UE1 lights: LightHue / LightSaturation (255 = white) / LightBrightness, all 0..255
|
||||
local function hsv(h: number, s: number): { number }
|
||||
local hh = (h % 256) / 256 * 6
|
||||
local i = math.floor(hh)
|
||||
local f = hh - i
|
||||
local p, q, t = 1 - s, 1 - s * f, 1 - s * (1 - f)
|
||||
local rgb = ({ { 1, t, p }, { q, 1, p }, { p, 1, t }, { p, q, 1 }, { t, p, 1 }, { 1, p, q } })[i % 6 + 1]
|
||||
return rgb
|
||||
end
|
||||
|
||||
local function light(ctx: Ctx, class: string, p: { [string]: any }, comp: { [string]: any }?): number
|
||||
local typ = LIGHTS[class]
|
||||
local l: Types.Light = { type = typ, color = { 1, 1, 1 }, intensity = 1 }
|
||||
if p.LightBrightness ~= nil or p.LightHue ~= nil or p.LightSaturation ~= nil then
|
||||
l.color = hsv(num(p.LightHue, 0), 1 - num(p.LightSaturation, 255) / 255)
|
||||
l.intensity = num(p.LightBrightness, 64) / 255
|
||||
end
|
||||
local c: any = comp or {}
|
||||
local col = c.LightColor or p.LightColor
|
||||
if type(col) == "table" then
|
||||
l.color = { num(col.R, 255) / 255, num(col.G, 255) / 255, num(col.B, 255) / 255 }
|
||||
end
|
||||
if c.Intensity ~= nil or c.Brightness ~= nil then
|
||||
l.intensity = num(c.Intensity, num(c.Brightness, 1))
|
||||
end
|
||||
local radius = c.AttenuationRadius or c.Radius
|
||||
if type(radius) == "number" then
|
||||
l.range = radius
|
||||
end
|
||||
if typ == "spot" then
|
||||
l.outerCone = math.rad(num(c.OuterConeAngle, num(p.LightCone, 44)))
|
||||
l.innerCone = math.rad(num(c.InnerConeAngle, 0))
|
||||
end
|
||||
table.insert(ctx.scene.lights, l)
|
||||
return #ctx.scene.lights
|
||||
end
|
||||
|
||||
local function actors(b: Block, out: { Block })
|
||||
for _, c in b.children do
|
||||
local k = string.lower(c.kind)
|
||||
if k == "actor" then
|
||||
table.insert(out, c)
|
||||
elseif k == "map" or k == "level" or k == "surface" then
|
||||
actors(c, out)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Build.scene(root: Block, opts: any): (Types.Scene?, string?)
|
||||
local sc = S.new()
|
||||
sc.meta.up = "z"
|
||||
sc.meta.handedness = "left"
|
||||
local list: { Block } = {}
|
||||
actors(root, list)
|
||||
local ctx: Ctx = { scene = sc, materials = {}, opts = opts or {}, polys = 0 }
|
||||
local ue4 = false
|
||||
for _, a in list do
|
||||
local rawClass = if a.attrs.Class ~= nil then tostring(a.attrs.Class) else "Actor"
|
||||
local class = string.match(rawClass, "([%w_]+)$") or rawClass
|
||||
if string.find(rawClass, "/Script/", 1, true) then
|
||||
ue4 = true
|
||||
end
|
||||
local p = a.props
|
||||
local objects: { [string]: { [string]: any } } = {}
|
||||
local objectClass: { [string]: string } = {}
|
||||
for _, c in a.children do
|
||||
if string.lower(c.kind) == "object" then
|
||||
local name = if c.attrs.Name ~= nil then tostring(c.attrs.Name) else ("Object" .. #a.children)
|
||||
local o = objects[name] or {}
|
||||
for _, k in c.order do
|
||||
o[k] = c.props[k]
|
||||
end
|
||||
objects[name] = o
|
||||
if c.attrs.Class ~= nil then
|
||||
objectClass[name] = tostring(c.attrs.Class)
|
||||
end
|
||||
end
|
||||
end
|
||||
local comp = component(a, objects)
|
||||
local node: Types.Node = { name = if a.attrs.Name ~= nil then tostring(a.attrs.Name) else class, children = {} }
|
||||
local m: { number }
|
||||
if comp and p.Location == nil then
|
||||
local deg = true
|
||||
local loc = xyz(comp.RelativeLocation, { 0, 0, 0 })
|
||||
local sc3 = xyz(comp.RelativeScale3D, { 1, 1, 1 })
|
||||
m = S.mul(translation(loc), S.mul(rotation(comp.RelativeRotation, deg), scaling(sc3)))
|
||||
else
|
||||
local loc = xyz(p.Location, { 0, 0, 0 })
|
||||
local deg = a.degrees.Rotation == true
|
||||
local rot = rotation(p.Rotation, deg)
|
||||
local isBrush = false
|
||||
for _, c in a.children do
|
||||
if string.lower(c.kind) == "brush" then
|
||||
isBrush = true
|
||||
end
|
||||
end
|
||||
if isBrush then
|
||||
local pre = xyz(p.PrePivot, { 0, 0, 0 })
|
||||
local main = xyz(type(p.MainScale) == "table" and p.MainScale.Scale, { 1, 1, 1 })
|
||||
local post = xyz(type(p.PostScale) == "table" and p.PostScale.Scale, { 1, 1, 1 })
|
||||
m = S.mul(translation(loc), S.mul(scaling(post), S.mul(rot, S.mul(scaling(main), translation({ -pre[1], -pre[2], -pre[3] })))))
|
||||
else
|
||||
local ds = num(p.DrawScale, 1)
|
||||
local s3 = xyz(p.DrawScale3D, { 1, 1, 1 })
|
||||
m = S.mul(translation(loc), S.mul(rot, scaling({ s3[1] * ds, s3[2] * ds, s3[3] * ds })))
|
||||
end
|
||||
end
|
||||
node.matrix = m
|
||||
local csg = if type(p.CsgOper) == "string" then p.CsgOper
|
||||
elseif p.BrushType == "Brush_Subtract" then "CSG_Subtract"
|
||||
elseif p.BrushType == "Brush_Add" then "CSG_Add"
|
||||
else nil
|
||||
local extras: { [string]: any } = { class = rawClass, properties = plain(a), csg = csg }
|
||||
if next(objects) then
|
||||
extras.objects = objects
|
||||
extras.objectClasses = objectClass
|
||||
end
|
||||
for _, c in a.children do
|
||||
if string.lower(c.kind) == "brush" then
|
||||
local builder = csg == "CSG_Active" or (class == "Brush" and csg == nil and node.name == "Brush")
|
||||
extras.builder = if builder then true else nil
|
||||
if not builder or ctx.opts.builder then
|
||||
local mesh, err = brushMesh(ctx, c, csg == "CSG_Subtract")
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
if mesh then
|
||||
table.insert(sc.meshes, mesh)
|
||||
node.mesh = #sc.meshes
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if LIGHTS[class] then
|
||||
local lc: { [string]: any }? = nil
|
||||
for name, o in objects do
|
||||
if string.find(objectClass[name] or name, "Light", 1, true) then
|
||||
lc = o
|
||||
end
|
||||
end
|
||||
node.light = light(ctx, class, p, lc)
|
||||
elseif class == "CameraActor" or class == "Camera" then
|
||||
local fov = num(p.FOVAngle, 90)
|
||||
for _, o in objects do
|
||||
if o.FieldOfView ~= nil then
|
||||
fov = num(o.FieldOfView, fov)
|
||||
end
|
||||
end
|
||||
table.insert(sc.cameras, { type = "perspective", yfov = math.rad(fov), znear = 1 } :: any)
|
||||
node.camera = #sc.cameras
|
||||
end
|
||||
local sm = p.StaticMesh
|
||||
for _, o in objects do
|
||||
if o.StaticMesh ~= nil then
|
||||
sm = o.StaticMesh
|
||||
end
|
||||
end
|
||||
if type(sm) == "string" then
|
||||
extras.staticMesh = string.match(sm, "'\"?([^'\"]+)\"?'") or sm
|
||||
end
|
||||
node.extras = { t3d = extras }
|
||||
table.insert(sc.nodes, node)
|
||||
table.insert(sc.roots, #sc.nodes)
|
||||
end
|
||||
sc.meta.source = { format = "t3d", engine = if ue4 then "ue4" else "ue1-3", actors = #list, polygons = ctx.polys }
|
||||
return sc, nil
|
||||
end
|
||||
|
||||
return Build
|
||||
@@ -0,0 +1,166 @@
|
||||
--!strict
|
||||
-- model/t3d/Parse: Unreal T3D text into nested blocks. A line `Begin <Kind> Key=Value ...` opens a block, `End <Kind>`
|
||||
-- closes it; other lines are `Key=Value` properties or, inside polygons, `Origin x,y,z` / `Vertex x,y,z` style
|
||||
-- records. Values: numbers, quoted strings, structs `(X=1,Y=2)` as tables, object references
|
||||
-- (`Model'MyLevel.Model1'`) as strings.
|
||||
local Parse = {}
|
||||
|
||||
export type Value = any
|
||||
export type Block = {
|
||||
kind: string,
|
||||
attrs: { [string]: Value },
|
||||
props: { [string]: Value },
|
||||
order: { string },
|
||||
records: { { string } },
|
||||
children: { Block },
|
||||
degrees: { [string]: boolean },
|
||||
}
|
||||
|
||||
-- "(X=1.0,Y=2,Z=-3)" / "(Scale=(X=1,Y=1,Z=1),SheerAxis=SHEER_ZX)"; i at '('
|
||||
local function struct(s: string, i: number, depth: number): (any, number)
|
||||
local out: { [any]: any } = {}
|
||||
local n = #s
|
||||
i += 1
|
||||
while i <= n do
|
||||
local c = string.sub(s, i, i)
|
||||
if c == ")" then
|
||||
return out, i + 1
|
||||
elseif c == "," or c == " " or c == "\t" then
|
||||
i += 1
|
||||
else
|
||||
local k, e = string.match(s, "^([^=,()]+)=()", i)
|
||||
if not k then
|
||||
-- an array element without a key: (1,2,3)
|
||||
local v, ni = Parse.value(s, i, depth + 1)
|
||||
table.insert(out, v)
|
||||
i = ni
|
||||
else
|
||||
local key = string.gsub(k :: string, "^%s+", "")
|
||||
local v, ni = Parse.value(s, e :: number, depth + 1)
|
||||
out[key] = v
|
||||
i = ni
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, i
|
||||
end
|
||||
|
||||
-- a value starting at i, up to the next unbracketed ',' / ')' (inside structs) or the end
|
||||
function Parse.value(s: string, i: number, depth: number): (any, number)
|
||||
local n = #s
|
||||
local c = string.sub(s, i, i)
|
||||
if c == "(" and depth < 32 then
|
||||
return struct(s, i, depth)
|
||||
elseif c == "\"" then
|
||||
local e = string.find(s, "\"", i + 1, true) or (n + 1)
|
||||
return string.sub(s, i + 1, e - 1), e + 1
|
||||
end
|
||||
-- a bare token; object references may hold quotes ('...' and "...")
|
||||
local j = i
|
||||
local q: string? = nil
|
||||
while j <= n do
|
||||
local ch = string.sub(s, j, j)
|
||||
if q then
|
||||
if ch == q then
|
||||
q = nil
|
||||
end
|
||||
elseif ch == "'" or ch == "\"" then
|
||||
q = ch
|
||||
elseif depth > 0 and (ch == "," or ch == ")") then
|
||||
break
|
||||
end
|
||||
j += 1
|
||||
end
|
||||
local tok = string.match(string.sub(s, i, j - 1), "^%s*(.-)%s*$") :: string
|
||||
local num = tonumber(tok)
|
||||
if num ~= nil and string.match(tok, "^[-+]?[%d%.]+[eE]?[-+]?%d*$") then
|
||||
return num, j
|
||||
end
|
||||
return tok, j
|
||||
end
|
||||
|
||||
-- Key=Value pairs of a Begin line ("Begin Actor Class=Light Name=Light0"); quoted values may hold spaces
|
||||
local function attrs(rest: string): { [string]: any }
|
||||
local out: { [string]: any } = {}
|
||||
local i, n = 1, #rest
|
||||
while i <= n do
|
||||
local k, e = string.match(rest, "^%s*([%w_%.]+)=()", i)
|
||||
if not k then
|
||||
break
|
||||
end
|
||||
local v: string
|
||||
if string.sub(rest, e :: number, e :: number) == "\"" then
|
||||
local q = string.find(rest, "\"", (e :: number) + 1, true) or (n + 1)
|
||||
v = string.sub(rest, (e :: number) + 1, q - 1)
|
||||
i = q + 1
|
||||
else
|
||||
local stop = string.find(rest, "%s", e :: number) or (n + 1)
|
||||
v = string.sub(rest, e :: number, stop - 1)
|
||||
i = stop
|
||||
end
|
||||
out[k :: string] = tonumber(v) or v
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function block(kind: string, a: { [string]: any }): Block
|
||||
return { kind = kind, attrs = a, props = {}, order = {}, records = {}, children = {}, degrees = {} }
|
||||
end
|
||||
|
||||
function Parse.tree(text: string, maxBlocks: number): (Block?, string?)
|
||||
local root = block("", {})
|
||||
local stack: { Block } = { root }
|
||||
local count = 0
|
||||
local lineNo = 0
|
||||
for raw in string.gmatch(text, "[^\n]*") do
|
||||
lineNo += 1
|
||||
local line = string.match(raw, "^%s*(.-)%s*$") :: string
|
||||
if line ~= "" and string.sub(line, 1, 2) ~= "//" then
|
||||
local cur = stack[#stack]
|
||||
local word, rest = string.match(line, "^(%a+)%s*(.*)$")
|
||||
local lw = if word then string.lower(word) else ""
|
||||
if lw == "begin" then
|
||||
local kind, after = string.match(rest :: string, "^(%S+)%s*(.*)$")
|
||||
if not kind then
|
||||
return nil, "Begin without a kind at line " .. lineNo
|
||||
end
|
||||
count += 1
|
||||
if count > maxBlocks then
|
||||
return nil, "limit: over " .. maxBlocks .. " blocks"
|
||||
end
|
||||
if #stack > 64 then
|
||||
return nil, "limit: blocks nested too deep"
|
||||
end
|
||||
local b = block(kind :: string, attrs(after :: string))
|
||||
table.insert(cur.children, b)
|
||||
table.insert(stack, b)
|
||||
elseif lw == "end" and #stack > 1 and (rest == "" or string.lower(string.match(rest :: string, "^(%S+)") or "") == string.lower(cur.kind)) then
|
||||
table.remove(stack)
|
||||
else
|
||||
local k, e = string.match(line, "^([%w_%(%)%[%]%.]+)%s*=()")
|
||||
if k then
|
||||
local v = Parse.value(line, e :: number, 0)
|
||||
if cur.props[k :: string] == nil then
|
||||
table.insert(cur.order, k :: string)
|
||||
end
|
||||
cur.props[k :: string] = v
|
||||
if string.find(string.sub(line, e :: number), "Pitch=[-+]?%d*%.") or string.find(string.sub(line, e :: number), "Yaw=[-+]?%d*%.") then
|
||||
cur.degrees[k :: string] = true
|
||||
end
|
||||
else
|
||||
-- a record: Origin / Normal / TextureU / TextureV / Vertex / Pan U=0 V=0
|
||||
local name, data = string.match(line, "^(%a+)%s+(.*)$")
|
||||
if name then
|
||||
table.insert(cur.records, { name :: string, data :: string })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #stack > 1 then
|
||||
return nil, "truncated: " .. stack[#stack].kind .. " block not closed"
|
||||
end
|
||||
return root, nil
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,92 @@
|
||||
--!strict
|
||||
-- model/t3d: Unreal T3D text (UnrealEd map / brush export: Begin Map / Level / Actor / Brush / PolyList / Polygon,
|
||||
-- Begin Object components), read only. Supports: brush polygons with texture projection (TextureU / TextureV /
|
||||
-- Origin / Pan; sizes through opts.textureSize, default 256) as primitives per texture, CSG operation in extras
|
||||
-- (subtractive brushes face inwards; the builder brush is skipped), actors as nodes with their properties and
|
||||
-- transforms (UE1-3 Location / Rotation / DrawScale, UE4 RootComponent Relative*), lights, cameras, static mesh
|
||||
-- references. Not supported: BSP CSG between brushes, sheared brush scales, terrain, static mesh geometry.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Sniff = require("@rosetta/core/Sniff")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Text = require("@rosetta/codecs/text/Text")
|
||||
local Parse = require("@rosetta/model/t3d/Parse")
|
||||
local Build = require("@rosetta/model/t3d/Build")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local T3d = {
|
||||
name = "t3d",
|
||||
category = "model",
|
||||
extensions = { "t3d" },
|
||||
mime = { "text/x-unreal-t3d" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Text", "codecs/model/Brush" },
|
||||
caps = { decode = true, encode = false, text = true, brushes = true, actors = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- default 2^28
|
||||
maxBlocks: number?, -- default 2^22
|
||||
maxPolygons: number?, -- default 2^20
|
||||
textureSize: ((name: string) -> (number, number))? | { [string]: { number } }?, -- texture width, height (default 256)
|
||||
builder: boolean?, -- include the builder brush's geometry (default false)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function T3d.sniff(r: Bytes.Reader): number
|
||||
local h = Sniff.text(r, 512)
|
||||
local first = string.match(h, "^%s*(Begin%s+%a+)")
|
||||
if first == nil then
|
||||
return 0
|
||||
end
|
||||
local kind = string.lower(string.match(first, "%a+$") or "")
|
||||
if kind == "map" or kind == "actor" or kind == "level" or kind == "brush" or kind == "polylist" then
|
||||
return 0.9
|
||||
end
|
||||
return 0.3
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function T3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
local o: any = opts or {}
|
||||
if r.limit - r.base > (o.maxBytes or 2 ^ 28) then
|
||||
return nil, Err.new(Err.LIMIT, "file is over the byte limit")
|
||||
end
|
||||
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
if string.sub(text, 1, 2) == "\255\254" then
|
||||
text = Text.utf16(r.buf, r.base + 2, r.limit - r.base - 2, false)
|
||||
else
|
||||
text = Text.toUtf8(text)
|
||||
end
|
||||
local ok, root, msg = pcall(Parse.tree, text, o.maxBlocks or 2 ^ 22)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root))
|
||||
end
|
||||
if not root then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
if #root.children == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no Begin blocks")
|
||||
end
|
||||
-- a bare brush export (Begin PolyList / Begin Brush): wrap it in an actor
|
||||
local k = string.lower(root.children[1].kind)
|
||||
if k == "polylist" or k == "brush" then
|
||||
local function block(kind: string, attrs: any, props: any, children: any): Parse.Block
|
||||
return { kind = kind, attrs = attrs, props = props, order = { "CsgOper" }, records = {}, degrees = {}, children = children }
|
||||
end
|
||||
local brush = if k == "brush" then root.children else { block("Brush", { Name = "Brush0" }, {}, root.children) }
|
||||
root = block("", {}, {}, { block("Actor", { Class = "Brush", Name = "Brush0" }, { CsgOper = "CSG_Add" }, brush) })
|
||||
end
|
||||
local ok2, scene, msg2 = pcall(Build.scene, root, o)
|
||||
if not ok2 then
|
||||
return nil, Err.from(tostring(scene))
|
||||
end
|
||||
if not scene then
|
||||
return nil, Err.from(msg2)
|
||||
end
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return T3d
|
||||
@@ -0,0 +1,165 @@
|
||||
-- model/t3d tests: UE1-3 and UE4 T3D maps against reference values computed by tools/fixtures/t3d.py (brush world
|
||||
-- vertices through PrePivot / MainScale / FRotationMatrix / PostScale / Location, polygon areas per texture, bounds,
|
||||
-- texel probes), actors, lights, components, static mesh references; errors; fuzz.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@rosetta")
|
||||
local T3d = require("@rosetta/model/t3d")
|
||||
local MeshOps = require("@rosetta/ops/MeshOps")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Fx = require("@tests/gen/t3d")
|
||||
|
||||
local t = T.suite("t3d")
|
||||
local S = Types.Scene
|
||||
|
||||
local function decode(s: string | buffer, opts: any?): (any, any)
|
||||
local b = if type(s) == "string" then buffer.fromstring(s) else s
|
||||
return T3d.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(T3d.name, "t3d", "name")
|
||||
t:eq(T3d.category, "model", "category")
|
||||
t:check(T3d.caps.decode and not T3d.caps.encode, "caps")
|
||||
|
||||
local function near(a: number, b: number, eps: number): boolean
|
||||
return math.abs(a - b) <= eps * math.max(1, math.abs(b))
|
||||
end
|
||||
|
||||
local function triArea(prim: any, m: { number }): number
|
||||
local P = S.reader(prim.attributes.POSITION) :: any
|
||||
local I = S.reader(prim.indices) :: any
|
||||
local a = 0
|
||||
local function w(i: number): (number, number, number)
|
||||
local x, y, z = P(i, 0), P(i, 1), P(i, 2)
|
||||
return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
|
||||
end
|
||||
for k = 0, prim.indices.count // 3 - 1 do
|
||||
local ax, ay, az = w(I(k * 3, 0))
|
||||
local bx, by, bz = w(I(k * 3 + 1, 0))
|
||||
local cx, cy, cz = w(I(k * 3 + 2, 0))
|
||||
local ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az
|
||||
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
|
||||
a += math.sqrt(nx * nx + ny * ny + nz * nz) / 2
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
local scene, err = decode(c.data, { textureSize = c.sizes })
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
t:eq(T3d.sniff(Bytes.reader(buffer.fromstring(c.data))), 0.9, c.name .. ": sniff")
|
||||
table.insert(samples, c.data)
|
||||
if scene then
|
||||
t:eq(scene.meta.up, "z", c.name .. ": up")
|
||||
local byName = {}
|
||||
for _, n in scene.nodes do
|
||||
byName[n.name] = n
|
||||
end
|
||||
for _, a in c.actors do
|
||||
local n = byName[a.name]
|
||||
t:check(n, c.name .. ": actor " .. a.name)
|
||||
if n then
|
||||
t:eq(n.extras.t3d.class, a.class, c.name .. ": " .. a.name .. " class")
|
||||
local m = S.nodeMatrix(n)
|
||||
if a.origin then
|
||||
t:check(near(m[13], a.origin[1], 1e-9) and near(m[14], a.origin[2], 1e-9) and near(m[15], a.origin[3], 1e-9), c.name .. ": " .. a.name .. " location")
|
||||
end
|
||||
if a.staticMesh then
|
||||
t:eq(n.extras.t3d.staticMesh, a.staticMesh, c.name .. ": static mesh reference")
|
||||
end
|
||||
t:eq(n.mesh ~= nil, a.mesh == true, c.name .. ": " .. a.name .. " has geometry")
|
||||
if a.mesh and n.mesh then
|
||||
local mesh = scene.meshes[n.mesh]
|
||||
local areas, tris = {}, 0
|
||||
for _, p in mesh.primitives do
|
||||
local name = scene.materials[p.material].name or ""
|
||||
areas[name] = (areas[name] or 0) + triArea(p, m)
|
||||
tris += p.indices.count // 3
|
||||
end
|
||||
t:eq(tris, a.triangles, c.name .. ": " .. a.name .. " triangles")
|
||||
for tex, want in a.area do
|
||||
t:check(areas[tex] and near(areas[tex], want, 1e-6), c.name .. ": " .. a.name .. " area of " .. tex .. ": " .. tostring(areas[tex]) .. " vs " .. want)
|
||||
end
|
||||
local one = Types.Scene.new()
|
||||
one.meshes = { mesh }
|
||||
one.nodes = { { children = {}, mesh = 1, matrix = m } }
|
||||
one.roots = { 1 }
|
||||
local lo, hi = MeshOps.bounds(MeshOps.merge(one))
|
||||
local ok = true
|
||||
for k = 1, 3 do
|
||||
ok = ok and near(lo[k], a.min[k], 1e-6) and near(hi[k], a.max[k], 1e-6)
|
||||
end
|
||||
t:check(ok, c.name .. ": " .. a.name .. " world bounds")
|
||||
-- the probe vertex (local) has the reference texel coordinates
|
||||
local pr = a.probe
|
||||
local found = false
|
||||
for _, p in mesh.primitives do
|
||||
local P = S.reader(p.attributes.POSITION) :: any
|
||||
local U = S.reader(p.attributes.TEXCOORD_0) :: any
|
||||
for i = 0, p.attributes.POSITION.count - 1 do
|
||||
if near(P(i, 0), pr[1], 1e-6) and near(P(i, 1), pr[2], 1e-6) and near(P(i, 2), pr[3], 1e-6) and near(U(i, 0), pr[4], 1e-5) and near(U(i, 1), pr[5], 1e-5) then
|
||||
found = true
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(found, c.name .. ": " .. a.name .. " texel probe")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
local s = assert(decode(Fx.cases[1].data, { textureSize = Fx.cases[1].sizes }))
|
||||
local room, light
|
||||
for _, n in s.nodes do
|
||||
if n.name == "Brush0" then
|
||||
room = n
|
||||
elseif n.name == "Light0" then
|
||||
light = n
|
||||
end
|
||||
end
|
||||
t:eq(room.extras.t3d.csg, "CSG_Subtract", "csg operation")
|
||||
-- a subtracted room faces inwards: the floor's normal points up (+z) in the brush frame
|
||||
local prim
|
||||
for _, p in s.meshes[room.mesh].primitives do
|
||||
if s.materials[p.material].name == "Floor" then
|
||||
prim = p
|
||||
end
|
||||
end
|
||||
local N = S.reader(prim.attributes.NORMAL) :: any
|
||||
local P = S.reader(prim.attributes.POSITION) :: any
|
||||
t:check(P(0, 2) < 0 and N(0, 2) > 0.99, "subtractive brush faces inwards")
|
||||
t:check(s.lights[s.nodes[table.find(s.nodes, light) :: number].light].type == "point", "UE1 light")
|
||||
t:eq(s.nodes[1].extras.t3d.properties.Title, "Test Level", "actor properties")
|
||||
local withBuilder = assert(decode(Fx.cases[1].data, { builder = true }))
|
||||
t:eq(#withBuilder.meshes, #s.meshes + 1, "builder brush on request")
|
||||
local u4 = assert(decode(Fx.cases[2].data))
|
||||
t:eq(u4.meta.source.engine, "ue4", "UE4 text")
|
||||
local pl
|
||||
for _, n in u4.nodes do
|
||||
if n.light then
|
||||
pl = u4.lights[n.light]
|
||||
end
|
||||
end
|
||||
t:check(pl and pl.intensity == 3000 and pl.range == 500 and near(pl.color[1], 1, 1e-9), "UE4 point light component")
|
||||
local bare = assert(decode("Begin PolyList\nBegin Polygon Texture=X\nVertex 0,0,0\nVertex 0,1,0\nVertex 1,0,0\nEnd Polygon\nEnd PolyList\n"))
|
||||
t:eq(#bare.meshes, 1, "a bare polylist")
|
||||
t:eq(F.detect(Fx.cases[1].data), "t3d", "F.detect")
|
||||
end
|
||||
|
||||
do
|
||||
local _, e = decode("Begin Map\nBegin Actor Class=Brush Name=B\n")
|
||||
t:check(e and e.code == Err.TRUNCATED, "unclosed blocks: " .. tostring(e))
|
||||
local _, e2 = decode("hello")
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "no blocks")
|
||||
local _, e3 = decode(Fx.cases[1].data, { maxBlocks = 3 })
|
||||
t:check(e3 and e3.code == Err.LIMIT, "block limit")
|
||||
end
|
||||
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return T3d.decode(Bytes.reader(b))
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -1,6 +1,7 @@
|
||||
# Docs inputs for the engine / level-editor sections of the scene, tile map, archive and data pages (tools/fixtures.py,
|
||||
# tools/docs_check.py): the hand-written ASE of tools/fixtures/ase.py, LDtk's AutoLayers_2_stamps sample (tools/fixtures/ldtk.py),
|
||||
# HaxeFlixel's TurnBasedRPG Ogmo project and level (tests/fixtures/ogmo), a small Godot scene and resource.
|
||||
# HaxeFlixel's TurnBasedRPG Ogmo project and level (tests/fixtures/ogmo), a small Godot scene and resource, the
|
||||
# UE1 map of tools/fixtures/t3d.py.
|
||||
# tests/gen/docs_engines.luau { files = { [name] = bytes }, vars = { aseText = "hand.ase", ... } }
|
||||
import importlib.util, os
|
||||
|
||||
@@ -38,7 +39,7 @@ metallic = 0.25
|
||||
roughness = 1.0
|
||||
"""
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/ase.py", "tools/fixtures/ldtk.py", "tests/fixtures/ogmo"]
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/t3d.py", "tools/fixtures/ase.py", "tools/fixtures/ldtk.py", "tests/fixtures/ogmo"]
|
||||
|
||||
|
||||
def mod(ctx, name):
|
||||
@@ -55,6 +56,7 @@ def generate(ctx):
|
||||
for f in ("turnBasedRPG.ogmo", "room-001.json"):
|
||||
files[f] = ctx.read("tests/fixtures/ogmo/" + f)
|
||||
files["world.tscn"] = TSCN.encode()
|
||||
files["level.t3d"] = mod(ctx, "t3d").ue1()[0].encode()
|
||||
files["brick.tres"] = TRES.encode()
|
||||
vars = {"tscnText": "world.tscn", "tresText": "brick.tres", "aseText": "hand.ase", "ldtkText": "stamps.ldtk", "ogmoProjectText": "turnBasedRPG.ogmo", "ogmoLevelText": "room-001.json"}
|
||||
vars = {"t3dText": "level.t3d", "tscnText": "world.tscn", "tresText": "brick.tres", "aseText": "hand.ase", "ldtkText": "stamps.ldtk", "ogmoProjectText": "turnBasedRPG.ogmo", "ogmoLevelText": "room-001.json"}
|
||||
check.emit_inputs(ctx, files, vars)
|
||||
@@ -0,0 +1,204 @@
|
||||
# Unreal T3D fixtures (tools/fixtures.py): maps written here in UnrealEd's export layout (UE1-3: Begin Map / Actor /
|
||||
# Brush / PolyList / Polygon with Origin / Normal / TextureU / TextureV / Pan / Vertex records, Location / Rotation in
|
||||
# 65536ths of a turn, PrePivot / MainScale / PostScale; UE4: Begin Level, components with Relative* in degrees), with
|
||||
# reference values computed here independently: each brush's world vertices (ABrush coords: v - PrePivot, MainScale,
|
||||
# FRotationMatrix, PostScale, + Location), polygon areas per texture, bounds, and the texel coordinates of probe
|
||||
# vertices; actors, lights and static mesh references.
|
||||
# tests/gen/t3d.luau { cases = { { name, data, sizes = { [texture] = { w, h } }, actors = { { name, class, mesh?,
|
||||
# area = { [texture] = a }, triangles, min, max, probe = { x, y, z, u, v }, origin } } } } }
|
||||
import math
|
||||
|
||||
INPUTS = ["src/Rosetta/model/t3d"]
|
||||
|
||||
|
||||
def box(sx, sy, sz, tex):
|
||||
"""an axis box centred on 0: six quads as UnrealEd's cube builder lists them (CCW about the outward normal)"""
|
||||
hx, hy, hz = sx / 2, sy / 2, sz / 2
|
||||
faces = []
|
||||
for axis in range(3):
|
||||
for sign in (-1, 1):
|
||||
n = [0, 0, 0]
|
||||
n[axis] = sign
|
||||
a, b = [(1, 2), (2, 0), (0, 1)][axis]
|
||||
h = [hx, hy, hz]
|
||||
pts = []
|
||||
for ca, cb in ((-1, -1), (-1, 1), (1, 1), (1, -1)) if sign < 0 else ((-1, -1), (1, -1), (1, 1), (-1, 1)):
|
||||
p = [0, 0, 0]
|
||||
p[axis] = sign * h[axis]
|
||||
p[a] = ca * h[a]
|
||||
p[b] = cb * h[b]
|
||||
pts.append(p)
|
||||
# make it CCW about n (right-handed cross)
|
||||
e1 = [pts[1][i] - pts[0][i] for i in range(3)]
|
||||
e2 = [pts[2][i] - pts[0][i] for i in range(3)]
|
||||
c = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]
|
||||
if sum(c[i] * n[i] for i in range(3)) < 0:
|
||||
pts.reverse()
|
||||
u = [0, 0, 0]
|
||||
v = [0, 0, 0]
|
||||
u[a] = 1
|
||||
v[b] = -1
|
||||
faces.append({"tex": tex(axis, sign), "normal": n, "origin": pts[0], "u": u, "v": v, "pan": (axis * 8, sign * 4), "verts": pts, "flags": 0})
|
||||
return faces
|
||||
|
||||
|
||||
def fmt(v):
|
||||
return ",".join("%+013.6f" % x for x in v)
|
||||
|
||||
|
||||
def polylist(faces, ind=" "):
|
||||
out = [ind + "Begin PolyList"]
|
||||
for f in faces:
|
||||
out.append(ind + " Begin Polygon Texture=%s Flags=%d Link=0" % (f["tex"], f["flags"]))
|
||||
out.append(ind + " Origin " + fmt(f["origin"]))
|
||||
out.append(ind + " Normal " + fmt(f["normal"]))
|
||||
out.append(ind + " TextureU " + fmt(f["u"]))
|
||||
out.append(ind + " TextureV " + fmt(f["v"]))
|
||||
out.append(ind + " Pan U=%d V=%d" % f["pan"])
|
||||
for p in f["verts"]:
|
||||
out.append(ind + " Vertex " + fmt(p))
|
||||
out.append(ind + " End Polygon")
|
||||
out.append(ind + "End PolyList")
|
||||
return out
|
||||
|
||||
|
||||
def rotmat(pitch, yaw, roll, k):
|
||||
p, y, r = pitch * k, yaw * k, roll * k
|
||||
SP, CP, SY, CY, SR, CR = math.sin(p), math.cos(p), math.sin(y), math.cos(y), math.sin(r), math.cos(r)
|
||||
# FRotationMatrix rows = axes
|
||||
return [[CP * CY, CP * SY, SP], [SR * SP * CY - CR * SY, SR * SP * SY + CR * CY, -SR * CP], [-(CR * SP * CY + SR * SY), CY * SR - CR * SP * SY, CR * CP]]
|
||||
|
||||
|
||||
def world(v, a):
|
||||
x = [v[i] - a["prepivot"][i] for i in range(3)]
|
||||
x = [x[i] * a["main"][i] for i in range(3)]
|
||||
R = a["rot"]
|
||||
x = [x[0] * R[0][i] + x[1] * R[1][i] + x[2] * R[2][i] for i in range(3)]
|
||||
x = [x[i] * a["post"][i] for i in range(3)]
|
||||
return [x[i] + a["loc"][i] for i in range(3)]
|
||||
|
||||
|
||||
def area(pts):
|
||||
ax = ay = az = 0
|
||||
for k in range(1, len(pts) - 1):
|
||||
u = [pts[k][i] - pts[0][i] for i in range(3)]
|
||||
v = [pts[k + 1][i] - pts[0][i] for i in range(3)]
|
||||
ax += u[1] * v[2] - u[2] * v[1]
|
||||
ay += u[2] * v[0] - u[0] * v[2]
|
||||
az += u[0] * v[1] - u[1] * v[0]
|
||||
return math.sqrt(ax * ax + ay * ay + az * az) / 2
|
||||
|
||||
|
||||
def reference(a, faces, sizes, builder=False):
|
||||
ref = {"name": a["name"], "class": a["class"]}
|
||||
if builder:
|
||||
return ref
|
||||
ar, tris = {}, 0
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
for f in faces:
|
||||
w = [world(p, a) for p in f["verts"]]
|
||||
ar[f["tex"]] = ar.get(f["tex"], 0) + area(w)
|
||||
tris += len(w) - 2
|
||||
for p in w:
|
||||
lo = [min(lo[i], p[i]) for i in range(3)]
|
||||
hi = [max(hi[i], p[i]) for i in range(3)]
|
||||
f = faces[0]
|
||||
p = f["verts"][2]
|
||||
W, H = sizes.get(f["tex"], (256, 256))
|
||||
du = sum((p[i] - f["origin"][i]) * f["u"][i] for i in range(3)) + f["pan"][0]
|
||||
dv = sum((p[i] - f["origin"][i]) * f["v"][i] for i in range(3)) + f["pan"][1]
|
||||
ref.update({"mesh": True, "area": ar, "triangles": tris, "min": lo, "max": hi, "probe": list(p) + [du / W, dv / H]})
|
||||
return ref
|
||||
|
||||
|
||||
K = math.pi * 2 / 65536
|
||||
|
||||
|
||||
def ue1():
|
||||
sizes = {"Bricks": (128, 64), "Floor": (256, 256), "Glass": (64, 64)}
|
||||
lines = ["Begin Map", "Begin Actor Class=LevelInfo Name=LevelInfo0", " Title=\"Test Level\"", " Author=\"rosetta\"", "End Actor"]
|
||||
actors = []
|
||||
# the builder brush (skipped)
|
||||
builder = {"name": "Brush", "class": "Brush", "loc": [0, 0, 0], "rot": rotmat(0, 0, 0, K), "prepivot": [0, 0, 0], "main": [1, 1, 1], "post": [1, 1, 1]}
|
||||
fb = box(256, 256, 256, lambda a, s: "Bricks")
|
||||
lines += ["Begin Actor Class=Brush Name=Brush", " MainScale=(SheerAxis=SHEER_ZX)", " PostScale=(SheerAxis=SHEER_ZX)", " Begin Brush Name=Brush"] + polylist(fb) + [" End Brush", " Brush=Model'MyLevel.Brush'", "End Actor"]
|
||||
actors.append(reference(builder, fb, sizes, True))
|
||||
# a subtracted room: yawed a quarter turn, pre-pivot, main scale
|
||||
room = {"name": "Brush0", "class": "Brush", "loc": [64, -32, 16], "rot": rotmat(0, 16384, 0, K), "prepivot": [16, 0, 8], "main": [2, 1, 0.5], "post": [1, 1, 1]}
|
||||
fr = box(512, 384, 256, lambda a, s: "Floor" if a == 2 else "Bricks")
|
||||
lines += ["Begin Actor Class=Brush Name=Brush0", " CsgOper=CSG_Subtract", " MainScale=(Scale=(X=2.000000,Z=0.500000),SheerAxis=SHEER_ZX)",
|
||||
" PostScale=(SheerAxis=SHEER_ZX)", " Location=(X=64.000000,Y=-32.000000,Z=16.000000)", " Rotation=(Yaw=16384)",
|
||||
" PrePivot=(X=16.000000,Z=8.000000)", " Begin Brush Name=Model1"] + polylist(fr) + [" End Brush", " Brush=Model'MyLevel.Model1'", "End Actor"]
|
||||
actors.append(reference(room, fr, sizes))
|
||||
# an added pillar: pitch + roll, post scale
|
||||
pil = {"name": "Brush1", "class": "Brush", "loc": [-100, 50, 0], "rot": rotmat(8192, 0, 4096, K), "prepivot": [0, 0, 0], "main": [1, 1, 1], "post": [1, 1.5, 2]}
|
||||
fp = box(32, 32, 200, lambda a, s: "Glass")
|
||||
for f in fp[:2]:
|
||||
f["flags"] = 2
|
||||
lines += ["Begin Actor Class=Brush Name=Brush1", " CsgOper=CSG_Add", " PostScale=(Scale=(Y=1.500000,Z=2.000000),SheerAxis=SHEER_ZX)",
|
||||
" Location=(X=-100.000000,Y=50.000000)", " Rotation=(Pitch=8192,Roll=4096)", " Begin Brush Name=Model2"] + polylist(fp) + [" End Brush", " Brush=Model'MyLevel.Model2'", "End Actor"]
|
||||
actors.append(reference(pil, fp, sizes))
|
||||
lines += ["Begin Actor Class=Light Name=Light0", " LightBrightness=128", " LightHue=40", " LightSaturation=64", " LightRadius=32",
|
||||
" Location=(X=0.000000,Y=0.000000,Z=96.000000)", "End Actor"]
|
||||
actors.append({"name": "Light0", "class": "Light", "origin": [0, 0, 96]})
|
||||
lines += ["Begin Actor Class=PlayerStart Name=PlayerStart0", " Location=(X=10.000000,Y=20.000000,Z=30.000000)", " Rotation=(Yaw=-16384)", " DrawScale=2.000000", "End Actor"]
|
||||
actors.append({"name": "PlayerStart0", "class": "PlayerStart", "origin": [10, 20, 30]})
|
||||
lines += ["End Map", ""]
|
||||
return "\r\n".join(lines), sizes, actors
|
||||
|
||||
|
||||
def ue4():
|
||||
sizes = {}
|
||||
lines = ["Begin Map", " Begin Level"]
|
||||
actors = []
|
||||
a = {"name": "Brush_1", "class": "/Script/Engine.Brush", "loc": [100, 200, 300], "rot": rotmat(0, 45, 0, math.pi / 180), "prepivot": [0, 0, 0], "main": [1, 1, 1], "post": [1, 1, 1]}
|
||||
fb = box(200, 200, 100, lambda ax, s: "/Game/Materials/M_Wall.M_Wall")
|
||||
lines += [" Begin Actor Class=/Script/Engine.Brush Name=Brush_1 Archetype=/Script/Engine.Brush'/Script/Engine.Default__Brush'",
|
||||
" Begin Object Class=/Script/Engine.BrushComponent Name=\"BrushComponent0\" Archetype=BrushComponent'/Script/Engine.Default__Brush:BrushComponent0'",
|
||||
" End Object",
|
||||
" Begin Object Name=\"BrushComponent0\"",
|
||||
" Brush=Model'\"Model_1\"'",
|
||||
" RelativeLocation=(X=100.000000,Y=200.000000,Z=300.000000)",
|
||||
" RelativeRotation=(Pitch=0.000000,Yaw=45.000000,Roll=0.000000)",
|
||||
" End Object",
|
||||
" BrushType=Brush_Add",
|
||||
" Begin Brush Name=Model_1"] + polylist(fb, " ") + [" End Brush",
|
||||
" Brush=Model'\"Model_1\"'", " BrushComponent=BrushComponent'\"BrushComponent0\"'", " RootComponent=BrushComponent'\"BrushComponent0\"'",
|
||||
" ActorLabel=\"Box Brush\"", " End Actor"]
|
||||
actors.append(reference(a, fb, sizes))
|
||||
lines += [" Begin Actor Class=/Script/Engine.StaticMeshActor Name=StaticMeshActor_3",
|
||||
" Begin Object Class=/Script/Engine.StaticMeshComponent Name=\"StaticMeshComponent0\"",
|
||||
" End Object",
|
||||
" Begin Object Name=\"StaticMeshComponent0\"",
|
||||
" StaticMesh=StaticMesh'\"/Game/Meshes/SM_Chair.SM_Chair\"'",
|
||||
" RelativeLocation=(X=-50.000000,Y=0.000000,Z=10.000000)",
|
||||
" RelativeScale3D=(X=2.000000,Y=2.000000,Z=2.000000)",
|
||||
" End Object",
|
||||
" StaticMeshComponent=StaticMeshComponent0",
|
||||
" RootComponent=StaticMeshComponent0",
|
||||
" End Actor"]
|
||||
actors.append({"name": "StaticMeshActor_3", "class": "/Script/Engine.StaticMeshActor", "origin": [-50, 0, 10], "staticMesh": "/Game/Meshes/SM_Chair.SM_Chair"})
|
||||
lines += [" Begin Actor Class=/Script/Engine.PointLight Name=PointLight_0",
|
||||
" Begin Object Class=/Script/Engine.PointLightComponent Name=\"LightComponent0\"",
|
||||
" End Object",
|
||||
" Begin Object Name=\"LightComponent0\"",
|
||||
" AttenuationRadius=500.000000",
|
||||
" Intensity=3000.000000",
|
||||
" LightColor=(B=64,G=128,R=255,A=255)",
|
||||
" RelativeLocation=(X=0.000000,Y=0.000000,Z=250.000000)",
|
||||
" End Object",
|
||||
" PointLightComponent=LightComponent0",
|
||||
" LightComponent=LightComponent0",
|
||||
" RootComponent=LightComponent0",
|
||||
" End Actor"]
|
||||
actors.append({"name": "PointLight_0", "class": "/Script/Engine.PointLight", "origin": [0, 0, 250]})
|
||||
lines += [" End Level", "Begin Surface", "End Surface", "End Map", ""]
|
||||
return "\n".join(lines), sizes, actors
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for name, f in (("ue1.t3d", ue1), ("ue4.t3d", ue4)):
|
||||
text, sizes, actors = f()
|
||||
cases.append({"name": name, "data": text.encode(), "sizes": {k: list(v) for k, v in sizes.items()}, "actors": actors})
|
||||
ctx.emit("t3d", {"cases": cases})
|
||||
Reference in new issue
Block a user