Last active
August 9, 2024 14:45
-
-
Save maierfelix/1802f9523dee4090e16dc44a4ac70176 to your computer and use it in GitHub Desktop.
Parsing Unity .asset - "_typelessdata" field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // input example: A simple Quad | |
| // field `_typelessdata` | |
| mesh = `000080bf000080bf0000000000000000000000000000803f00000000000000000000803f000080bf0000000000000000000000000000803f0000803f00000000000080bf0000803f0000000000000000000000000000803f000000000000803f0000803f0000803f0000000000000000000000000000803f0000803f0000803f`; | |
| // field `m_IndexBuffer` | |
| index = `0000010002000300`; | |
| // normalize | |
| mesh = normalizeString(mesh); | |
| index = normalizeString(index); | |
| function normalizeString(str) { | |
| return str.replace(`\\`, "").replace(`\n`, "").replace(` `, ""); | |
| }; | |
| function hex2float(num) { | |
| let sign = (num & 0x80000000) ? -1 : 1; | |
| let exponent = ((num >> 23) & 0xff) - 127; | |
| let mantissa = 1 + ((num & 0x7fffff) / 0x7fffff); | |
| return sign * mantissa * Math.pow(2, exponent); | |
| } | |
| function swap16(val) { | |
| return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF); | |
| }; | |
| function swap32(val) { | |
| return ( | |
| ((val << 24) & 0xff000000) | | |
| ((val << 8) & 0xff0000) | | |
| ((val >> 8) & 0xff00) | | |
| ((val >> 24) & 0xff) | |
| ); | |
| }; | |
| // process `_typelessdata` field | |
| vertices = []; | |
| normals = []; | |
| uvs = []; | |
| slices = []; | |
| for (let ii = 0; ii < mesh.length / 8; ++ii) { | |
| let slice = parseFloat(hex2float(swap32(parseInt(`0x` + mesh.substr(ii * 8, 8)))).toFixed(4)); | |
| slices.push(slice); | |
| }; | |
| for (let ii = 0; ii < slices.length / 8; ++ii) { | |
| let offset = ii * 8; | |
| let v0 = slices[offset + 0]; | |
| let v1 = slices[offset + 1]; | |
| let v2 = slices[offset + 2]; | |
| let n0 = slices[offset + 3]; | |
| let n1 = slices[offset + 4]; | |
| let n2 = slices[offset + 5]; | |
| let u0 = slices[offset + 6]; | |
| let u1 = slices[offset + 7]; | |
| vertices.push(v0, v1, v2); | |
| normals.push(n0, n1, n2); | |
| uvs.push(u0, u1); | |
| }; | |
| // process `m_IndexBuffer` field | |
| indices = []; | |
| for (let ii = 0; ii < index.length / 4; ++ii) { | |
| indices.push(swap16(parseInt(`0x` + index.substr(ii * 4, 4)))); | |
| }; | |
| console.log("Done!"); | |
| // print out | |
| console.log("Vertices:", vertices); | |
| console.log("Normals:", normals); | |
| console.log("UVs:", uvs); | |
| console.log("Indices:", indices); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment