--!strict -- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists, -- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh -- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute -- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x). local Blend = require("@rosetta/containers/Blend") local Mesh = {} export type Layer = { name: string, domain: string, -- "point" | "edge" | "face" | "corner" | "tess" kind: string, -- a generic kind (float, float2, float3, color, bytecolor, int32, int2, int8, bool, short2, quat, -- float4x4) or an SDNA struct name (MVert, MEdge, MPoly, MLoop, MFace, MTFace, MCol, MLoopUV, MDeformVert) offset: number, -- data start in file.buf bytes: number, -- data bytes available elem: number, -- bytes per element single: boolean?, -- one value for every element (AttributeStorage single storage) activeRender: boolean?, cdtype: number?, } export type Color = { name: string, domain: string, data: buffer } -- f32 x 4 (linear) per point or corner export type Poly = { name: string?, nv: number, nf: number, nc: number, pos: buffer, -- f32 x 3 per vertex cornerVert: buffer, -- u32 per corner faceStart: buffer, -- u32 per face + 1 faceMat: buffer, -- i32 per face faceSmooth: buffer, -- u8 per face uvs: { { name: string, data: buffer } }, -- f32 x 2 per corner activeUV: number, -- 1-based index into uvs (the active render layer) colors: { Color }, customNormals: buffer?, -- f32 x 3 per corner (free custom normals) encodedNormals: buffer?, -- i16 x 2 per corner (custom normals in Blender's corner-fan space) sharp: { [number]: boolean }, -- edge keys (min * nv + max) that split smooth fans autoSmooth: number?, -- radians (Mesh.smoothresh with ME_AUTOSMOOTH, before 4.1) weights: { { number } }?, -- per vertex: def_nr, weight, def_nr, weight, ... generation: string, -- "mface" | "mpoly" | "attributes" | "storage" layers: { Layer }, } local CD_KIND: { [number]: string } = { [0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float", [11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8", [46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat", } -- AttributeStorage (5.x) data types and domains local ATTR_KIND: { [number]: string } = { [0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3", [8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat", } local DOMAIN: { [number]: string } = { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" } local SIZE: { [string]: number } = { bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4, color = 16, quat = 16, } local ME_SMOOTH = 1 local ME_SHARP = 0x200 local ME_AUTOSMOOTH = 0x20 local readu8, readi16 = buffer.readu8, buffer.readi16 -- sRGB byte -> linear local SRGB = table.create(256, 0) for i = 0, 255 do local c = i / 255 SRGB[i + 1] = if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 end Mesh.SRGB = SRGB local function customData(f: Blend.File, me: Blend.View, names: { string }, domain: string, out: { Layer }) local cd = me:sub(table.unpack(names)) if not cd then return end local layers = cd:array("layers", "CustomDataLayer") local n = cd:num("totlayer") or #layers for i = 1, math.min(n, #layers) do local L = layers[i] local t = L:num("type") or -1 local kind = CD_KIND[t] local blk = L:target("data") if kind and blk then local st = f.dna.byName[kind] local elem = if st then st.size else SIZE[kind] or 0 if elem > 0 then table.insert(out, { name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t, }) end end end end local function storage(f: Blend.File, me: Blend.View, out: { Layer }) local st = me:sub("attribute_storage") if not st then return end local attrs = st:array("dna_attributes", "Attribute") local n = st:num("dna_attributes_num") or #attrs for i = 1, math.min(n, #attrs) do local a = attrs[i] local kind = ATTR_KIND[a:num("data_type") or -1] local domain = DOMAIN[a:num("domain") or -1] local single = (a:num("storage_type") or 0) == 1 local holder = a:deref("data", 0, if single then "AttributeSingle" else "AttributeArray") local blk = holder and holder:target("data") if kind and domain and blk then table.insert(out, { name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = SIZE[kind], single = single, }) end end end local function find(layers: { Layer }, domain: string, kind: string?, name: string?): Layer? for _, L in layers do if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then return L end end return nil end -- a raw pointer field (Mesh.mvert, ...) as a layer when no CustomData layer has it local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string, domain: string): Layer? local blk = me:target(field) local st = f.dna.byName[kind] if not blk or not st or st.size <= 0 then return nil end return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } end -- reads element i (0-based) of a layer as number component c (0-based) of a generic kind local function reader(f: Blend.File, L: Layer): (number, number) -> number local b = f.buf local o, elem, k = L.offset, L.elem, L.kind local max = L.bytes local single = L.single local f32, i32, i16 = f.f32, f.i32, f.i16 local comp = if k == "short2" then 2 elseif k == "int8" or k == "bool" or k == "bytecolor" then 1 else 4 return function(i: number, c: number): number local at = (if single then 0 else i * elem) + c * comp if at < 0 or at + comp > max then return 0 end if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then return f32(b, o + at) elseif k == "int32" or k == "int2" then return i32(b, o + at) elseif k == "short2" then return i16(b, o + at) elseif k == "int8" then return buffer.readi8(b, o + at) end return readu8(b, o + at) end end Mesh.reader = reader -- a field of an SDNA-struct layer: element i -> value (number) of component c local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, number) -> number)? local st = f.dna.byName[L.kind] local fld = st and st.byName[field] if not fld then return nil end local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes local t, esz = fld.type, fld.elem local fo = fld.offset local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16 return function(i: number, c: number): number local at = i * elem + fo + c * esz if at < 0 or at + esz > max then return 0 end at += o if t == "float" then return f32(b, at) elseif t == "int" or t == "int32_t" then return i32(b, at) elseif t == "uint" or t == "uint32_t" then return u32(b, at) elseif t == "short" or t == "int16_t" then return i16(b, at) elseif t == "ushort" or t == "uint16_t" then return u16(b, at) end return readu8(b, at) end end function Mesh.layers(f: Blend.File, me: Blend.View): { Layer } local layers: { Layer } = {} customData(f, me, { "vdata", "vert_data" }, "point", layers) customData(f, me, { "edata", "edge_data" }, "edge", layers) customData(f, me, { "pdata", "face_data" }, "face", layers) customData(f, me, { "ldata", "corner_data" }, "corner", layers) customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers) storage(f, me, layers) return layers end local function count(me: Blend.View, ...: string): number local v = me:num(...) return if v and v > 0 then v else 0 end export type Limits = { maxVertices: number? } function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, string?) local layers = Mesh.layers(f, me) local nv = count(me, "totvert", "verts_num") local np = count(me, "totpoly", "faces_num") local nl = count(me, "totloop", "corners_num") local nt = count(me, "totface", "totface_legacy") local maxV = limits and limits.maxVertices or 2 ^ 25 if nv > maxV or nl > maxV or nt > maxV or np > maxV then return nil, "limit: mesh over maxVertices" end -- positions local pos = buffer.create(nv * 12) local P = find(layers, "point", "float3", "position") local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") local get: ((number, number) -> number)? = nil if P then get = reader(f, P) elseif mv then get = fieldReader(f, mv, "co") end if not get then if nv > 0 then return nil, "mesh without positions" end get = function(_: number, _: number): number return 0 end end local g = get :: (number, number) -> number for i = 0, nv - 1 do for c = 0, 2 do buffer.writef32(pos, (i * 3 + c) * 4, g(i, c)) end end local poly: Poly = { name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4), faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {}, generation = if P and P.cdtype == nil then "storage" elseif P then "attributes" else "mpoly", layers = layers, } local corner: { [string]: any } = {} if np > 0 then local offs = me:target("poly_offset_indices", "face_offset_indices") local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face") local cv = find(layers, "corner", "int32", ".corner_vert") local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner") local starts = buffer.create((np + 1) * 4) if offs and offs.size >= (np + 1) * 4 then for i = 0, np do buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl)) end elseif mp then local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop") if not ls or not tl then return nil, "bad MPoly" end -- MPoly faces are usually in loop order; faces that are not get copied corners below local at = 0 for i = 0, np - 1 do buffer.writeu32(starts, i * 4, at) at += math.max(0, tl(i, 0)) end buffer.writeu32(starts, np * 4, at) if at > maxV * 4 then return nil, "limit: too many corners" end local verts = buffer.create(at * 4) local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil if not vr then return nil, "mesh without corners" end local remap = buffer.create(at * 4) local w = 0 for i = 0, np - 1 do local s0, n0 = ls(i, 0), tl(i, 0) for k = 0, n0 - 1 do local src = s0 + k buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0))) buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0))) w += 1 end end corner.remap = remap corner.verts = verts nl = at else return nil, "mesh without face offsets" end poly.faceStart = starts poly.nf = np if not corner.verts then local verts = buffer.create(nl * 4) local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil if not vr then return nil, "mesh without corners" end for i = 0, nl - 1 do buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0))) end corner.verts = verts end poly.cornerVert = corner.verts poly.nc = nl -- material index and smooth flags local mats = buffer.create(np * 4) local smooth = buffer.create(np) local mi = find(layers, "face", "int32", "material_index") local sf = find(layers, "face", "bool", "sharp_face") local mr = if mi then reader(f, mi) elseif mp then fieldReader(f, mp, "mat_nr") else nil local flag = if mp then fieldReader(f, mp, "flag") else nil local sr = if sf then reader(f, sf) else nil for i = 0, np - 1 do buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) local s if sr then s = sr(i, 0) == 0 elseif flag then s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 else s = poly.generation ~= "mpoly" end buffer.writeu8(smooth, i, if s then 1 else 0) end poly.faceMat, poly.faceSmooth = mats, smooth elseif nt > 0 then local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess") if not mf then return nil, "mesh without faces" end poly.generation = "mface" local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") } local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag") if not (v[1] and v[2] and v[3] and v[4]) then return nil, "bad MFace" end local starts = buffer.create((nt + 1) * 4) local verts = buffer.create(nt * 16) local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner local mats, smooth = buffer.create(nt * 4), buffer.create(nt) local at = 0 for i = 0, nt - 1 do buffer.writeu32(starts, i * 4, at) local k = if (v[4] :: any)(i, 0) ~= 0 then 4 else 3 for c = 1, k do buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] :: any)(i, 0), 0, math.max(nv - 1, 0))) buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1) end at += k buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) buffer.writeu8(smooth, i, if flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 then 1 else 0) end buffer.writeu32(starts, nt * 4, at) poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at poly.faceMat, poly.faceSmooth = mats, smooth corner.tess = tessCorner end local nc = poly.nc -- corner index -> the element index in the source corner layers local remap: buffer? = corner.remap local function src(i: number): number return if remap then buffer.readu32(remap, i * 4) else i end -- UV maps for _, L in layers do if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then local r = if L.kind == "float2" then reader(f, L) else fieldReader(f, L, "uv") if r then local d = buffer.create(nc * 8) for i = 0, nc - 1 do local s = src(i) buffer.writef32(d, i * 8, r(s, 0)) buffer.writef32(d, i * 8 + 4, r(s, 1)) end table.insert(poly.uvs, { name = L.name, data = d }) if L.activeRender and L.kind == "MLoopUV" then poly.activeUV = #poly.uvs end end elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then local r = fieldReader(f, L, "uv") if r then local d = buffer.create(nc * 8) for i = 0, nc - 1 do local tc = buffer.readu32(corner.tess, i * 4) local face, k = tc // 4, tc % 4 buffer.writef32(d, i * 8, r(face, k * 2)) buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) end table.insert(poly.uvs, { name = L.name, data = d }) end end end local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") if active then for k, u in poly.uvs do if u.name == active then poly.activeUV = k end end end -- colour attributes: f32 x 4 linear per element for _, L in layers do if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then local n = if L.domain == "corner" then nc else nv local r = reader(f, L) local d = buffer.create(n * 16) for i = 0, n - 1 do local s = if L.domain == "corner" then src(i) else i for c = 0, 3 do local x = r(s, c) if L.kind == "bytecolor" then x = if c == 3 then x / 255 else SRGB[math.clamp(x, 0, 255) + 1] end buffer.writef32(d, (i * 4 + c) * 4, x) end end table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then -- MCol keeps alpha, blue, green, red in its a, r, g, b fields local st = f.dna.byName.MCol local d = buffer.create(nc * 16) local stride = if st then st.size else 4 for i = 0, nc - 1 do local tc = buffer.readu32(corner.tess, i * 4) local at = (tc // 4) * 4 * stride + (tc % 4) * stride if at + 4 <= L.bytes then local o = L.offset + at local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) buffer.writef32(d, i * 16, SRGB[rr + 1]) buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) buffer.writef32(d, i * 16 + 12, aa / 255) end end table.insert(poly.colors, { name = L.name, domain = "corner", data = d }) end end -- MLoopCol layers carry the CD_PROP_BYTE_COLOR type (17) and are read above as bytecolor (r, g, b, a bytes) -- custom normals local cn = find(layers, "corner", "short2", "custom_normal") for _, L in layers do if not cn and L.domain == "corner" and L.cdtype == 41 then cn = L end end if cn then local r = reader(f, cn) local d = buffer.create(nc * 4) for i = 0, nc - 1 do local s = src(i) buffer.writei16(d, i * 4, r(s, 0)) buffer.writei16(d, i * 4 + 2, r(s, 1)) end poly.encodedNormals = d end local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal") or find(layers, "face", "float3", "custom_normal") if free then local r = reader(f, free) local d = buffer.create(nc * 12) local starts = poly.faceStart for fi = 0, poly.nf - 1 do local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4) for i = s0, s1 - 1 do local e = if free.domain == "corner" then src(i) elseif free.domain == "face" then fi else buffer.readu32(poly.cornerVert, i * 4) for c = 0, 2 do buffer.writef32(d, (i * 3 + c) * 4, r(e, c)) end end end poly.customNormals = d end -- sharp edges local ne = count(me, "totedge", "edges_num") local ev = find(layers, "edge", "int2", ".edge_verts") local se = find(layers, "edge", "bool", "sharp_edge") local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") local flags = me:num("flag") or 0 local smoothresh = me:num("smoothresh") local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 if autoSmooth then poly.autoSmooth = smoothresh or math.rad(30) end local useSharp = f.version >= 401 or autoSmooth if useSharp and ne > 0 then local v1, v2, sharp if ev and se then local er, sr = reader(f, ev), reader(f, se) v1 = function(i: number): number return er(i, 0) end v2 = function(i: number): number return er(i, 1) end sharp = function(i: number): boolean return sr(i, 0) ~= 0 end elseif medge then local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") if a and b and fl then v1 = function(i: number): number return a(i, 0) end v2 = function(i: number): number return b(i, 0) end local ser = if se then reader(f, se) else nil sharp = function(i: number): boolean if ser then return ser(i, 0) ~= 0 end return bit32.band(fl(i, 0), ME_SHARP) ~= 0 end end end if v1 and v2 and sharp then for i = 0, ne - 1 do if sharp(i) then local a, b = v1(i), v2(i) local lo, hi = math.min(a, b), math.max(a, b) poly.sharp[lo * nv + hi] = true end end end end -- deform weights local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point") if dv then local st = f.dna.byName.MDeformVert local dwf, twf = st and st.byName.dw, st and st.byName.totweight local mw = f.dna.byName.MDeformWeight local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight if dwf and twf and mw and nrf and wf then local weights = table.create(nv) for i = 0, nv - 1 do local list = {} local at = i * dv.elem if at + dv.elem <= dv.bytes then local vw = Blend.view(f, "MDeformVert", dv.offset + at) local blk = vw and vw:target("dw") local n = vw and vw:num("totweight") or 0 if blk then n = math.min(n, blk.size // mw.size) for k = 0, n - 1 do local o = blk.offset + k * mw.size table.insert(list, f.i32(f.buf, o + nrf.offset)) table.insert(list, f.f32(f.buf, o + wf.offset)) end end end weights[i + 1] = list end poly.weights = weights end end return poly, nil end -- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean } function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) local key = me:deref("key", 0, "Key") if not key then return {}, nil, nil end local blocks = key:list("block", "KeyBlock") local refAddr = key:ptr("refkey") local out: { Shape } = {} local ref: number? = nil for i, kb in blocks do local blk = kb:target("data") local d = buffer.create(nv * 12) if blk then local n = math.min(nv * 12, blk.size) buffer.copy(d, 0, f.buf, blk.offset, n) if not f.little then for k = 0, n // 4 - 1 do buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4)) end end end if kb.block and kb.block.addr == refAddr then ref = i end table.insert(out, { name = kb:str("name") or ("Key " .. i), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, }) end if ref == nil and #out > 0 then ref = 1 end return out, ref, key end return Mesh