Exporting Wonderland Engine Mesh as OBJ file

When generating meshes at runtime, it can be useful to use other applications to inspect the result. This helps when the generated mesh doesn’t render at all.

Wavefront OBJ is a very simple text based format that can be written out from your Wonderland Engine JavaScript component.

Code snippet 

The following code snippet receives a Mesh, writes an OBJ file for positions and indices, to finally auto-download the file programmatically.

 1import {MeshAttribute} from '@wonderlandengine/api';
 2
 3export function wleMeshToOBJ(wleMesh) {
 4    /* Retrieve an attribute accessor for positions.
 5     * You can easily extend this script to also export normals
 6     * and texture attributes. */
 7    const positions = wleMesh.attribute(MeshAttribute.Position);
 8
 9    const lines = [];
10    for(let i = 0; i < positions.length; ++i) {
11        const [x, y, z] = positions.get(i);
12        lines.push(`v ${x} ${y} ${z}`);
13    }
14
15    const indexCount = wleMesh.indexData.length;
16    for (let i = 0; i < indexCount;) {
17        /* .obj indices start a 1, not 0 */
18        lines.push(`f ${wleMesh.indexData[i++] + 1} ${wleMesh.indexData[i++] + 1} ${wleMesh.indexData[i++] + 1}`);
19    }
20
21    /* Concatenate all the lines and generate a binary blob for download */
22    const blob = new Blob([lines.join('\n')], {type: 'text/plain'});
23    const url = URL.createObjectURL(blob);
24
25    /* Auto download the blob programatically as a file called 'mesh.obj' */
26    const link = document.createElement('a');
27    link.href = url;
28    link.download = 'mesh.obj';
29
30    document.body.appendChild(link);
31    link.click();
32    document.body.removeChild(link);
33}