Loading OBJ files
Trid can load 3D models saved as Wavefront .obj files — the format almost every 3D tool (Blender, Maya, SketchUp…) can export.
import { parseOBJ, loadOBJ, readOBJFile, pickOBJFile, fitMesh } from "./trid/loaders/obj.js";
import { ObjUploader } from "./trid/tools/index.js";import { Scene } from "./trid/scene.js";
import { OrbitCamera, ObjUploader } from "./trid/tools/index.js";
const scene = new Scene(document.getElementById("canvas"), {
color: "#E9806E",
camera: { z: -2 },
});
scene.use(new OrbitCamera());
// Drop an .obj on the canvas, or pick one with a button
const uploader = scene.use(new ObjUploader());
document.getElementById("open").onclick = () => uploader.open();
scene.start();From a URL
const mesh = await loadOBJ("models/teapot.obj", { fit: 1 });
scene.add({ mesh });From an upload
The easiest way is the ObjUploader tool. To build your own upload UI, pass the File to readOBJFile:
input.addEventListener("change", async () => {
const mesh = await readOBJFile(input.files[0], { fit: 1 });
scene.add({ mesh });
});What gets loaded
- Vertices (
v), texture coordinates (vt), normals (vn), faces (f), lines (l) and material names (usemtl). Material files (.mtl) and groups are skipped for now, so load textures yourself withloadTexture. - Texture coordinates are kept as
mesh.uvsandmesh.faceUVs, and used by textures. A model without them can still be textured with a mapping. - Normals are kept as
mesh.normalsandmesh.faceNormals(each face's corner normal indices), and used by smooth shading. - Faces become edges, and an edge shared by two faces is drawn once.
- The mesh also keeps its
faces, so a model can be filled and shaded:scene.add({ mesh, material: { fill: "#8ab4f8" } }). - Z is flipped on load. OBJ files are right-handed and Trid is left-handed, so without the flip models would come out mirrored.
- Faces or lines pointing at a vertex that doesn't exist throw an
Errorwith the line number.
Materials
From the .mtl file
Most OBJ files come with a .mtl file (named on their mtllib line) that holds each part's color and texture. loadOBJ(url, { materials: true }) reads it and loads the textures, into mesh.materials, one per name:
const chair = await loadOBJ("models/chair.obj", { fit: 1, materials: true });
scene.add({ mesh: chair, material: chair.materials });Texture files are found next to the .mtl file. A missing file only gives a warning in the console (that part keeps a plain color). From an upload (readOBJFile), the browser can't read the other files, so set the materials yourself as below. parseMTL(text) reads an MTL file's text: { name: { fill, opacity, textureFile } }.
Setting them yourself
When a file uses material names (usemtl), the mesh gets materialNames, in the order they first appear, and faceMaterials, the index of each face's name. Give the object a list of materials in the same order:
const car = await loadOBJ("car.obj", { fit: 1 });
console.log(car.materialNames); // ["body", "glass", "tires"]
scene.add({
mesh: car,
material: [
{ fill: "#E9806E", smooth: true }, // body
{ fill: "rgba(150, 200, 255, 0.4)" }, // glass
{ fill: "#222" }, // tires
],
});Or build the list from the names:
const looks = { body: { fill: "#E9806E" }, glass: { fill: "rgba(150, 200, 255, 0.4)" } };
const material = car.materialNames.map((name) => looks[name] ?? { fill: "#888" });See A texture per face.
To save meshes as OBJ files, see Exporting.
Example: the fox, saved and loaded back
The fox from the home page is made in code. Here it's saved as an OBJ file and its MTL file (with exportOBJ and exportMTL), and the text is read straight back with parseOBJ and parseMTL: the fox you see is the copy from the file. The buttons save the two files, to open in Blender or load with loadOBJ(url, { materials: true }) (keep them in the same folder).
import { Scene, WebGLRenderer, OrbitCamera, exportOBJ, exportMTL, parseOBJ, parseMTL, download } from "./trid/index.js";
import { makeFox, makePlatform, foxLights } from "./fox.js";
const p = (x, y, z) => ({ x, y, z });
export default function (canvas) {
const webgl = WebGLRenderer.isSupported();
const scene = new Scene(canvas, {
width: 800, height: 360, camera: { fov: 0.6 },
renderer: webgl ? new WebGLRenderer() : undefined,
lights: foxLights(),
});
// The fox made in code (a group of parts), not added to the scene...
const fox = { children: [makePlatform(), makeFox({ detail: webgl ? 1 : 0.5 })] };
// ...saved as the text of an OBJ file and its MTL file (the parts' colors)...
const obj = exportOBJ(fox, { mtllib: "fox.mtl", precision: 4 });
const mtl = exportMTL(fox);
// ...and read back: one mesh, with a material name per face
const mesh = parseOBJ(obj);
const colors = parseMTL(mtl);
const material = mesh.materialNames.map((name) => ({ fill: colors[name].fill, smooth: true }));
scene.add({ mesh, material });
// One button per file: browsers block a click that starts several downloads
const bar = document.createElement("div");
bar.className = "trid-demo-bar";
for (const [name, text] of [["fox.obj", obj], ["fox.mtl", mtl]]) {
const b = document.createElement("button");
b.textContent = `${name} (${text.length < 1e5 ? `${Math.ceil(text.length / 1e3)} KB` : `${(text.length / 1e6).toFixed(1)} MB`})`;
b.onclick = () => download(text, name);
bar.append(b);
}
canvas.parentElement.append(bar);
scene.use(new OrbitCamera({ target: p(0, 0.33, 0), distance: 2.4, yaw: Math.PI + 0.5, pitch: -0.25 }));
scene.start();
return () => {
bar.remove();
scene.destroy();
};
}It looks the same as the original, but it's one mesh instead of a group of parts: each face keeps its material name (mesh.materialNames and mesh.faceMaterials), so the colors come back, and the file's normals keep it smooth. An app would usually do this once, ship the .obj file, and skip building the model on every visit: the fox takes about half a second to build, and about a third of that to read from the file (plus the download).
Use fit
OBJ files come in any size and are rarely centered. { fit: 1 } centers the model on the origin and scales it so its largest side is 1 unit.
Functions
All of them take the same options: { fit } (see above). Without fit, the file's own coordinates are kept.
| Function | Returns | Meaning |
|---|---|---|
parseOBJ(text, opts?) | mesh | Parses the text of an OBJ file |
loadOBJ(url, opts?) | Promise<mesh> | Downloads a file, then parses it |
readOBJFile(file, opts?) | Promise<mesh> | Parses a File or Blob (from an <input> or a drop) |
pickOBJFile() | Promise<File | null> | Opens the file dialog for .obj files. Call it from a click. null if cancelled |
fitMesh(mesh, size = 1) | the same mesh | Centers and scales any mesh in place |
The mesh is { vertices, edges, faces } (plus normals, faceNormals, uvs, faceUVs, materialNames and faceMaterials when the file has them): pass it to scene.add({ mesh }) like any other.
ObjUploader
A tool that loads .obj files into the scene. Drop a file on the canvas, or call open() from a button to show the file dialog. By default the new model replaces the last one it loaded.
const uploader = scene.use(new ObjUploader());
button.onclick = () => uploader.open();| Option | Default | Meaning |
|---|---|---|
fit | 1 | Size of the model's largest side. null keeps the file's units |
color | scene's color | Color of loaded models |
replace | true | Remove the previously loaded model first |
hint | "Drop an .obj file here" | Text shown on the canvas while nothing is loaded ("" for none) |
onLoad | — | (obj, file, scene) => void: called after the model is added |
onError | logs the error | (err, file) => void: called when a file can't be read |
| Member | Meaning |
|---|---|
open() | Shows the file dialog and loads the chosen file. Returns the added object, or null |
load(file) | Loads a File or Blob. Returns the added object, or null on error |
object | The last object it added, or null |
While a file is dragged over the canvas, the tool draws a dashed border. It works whether or not the scene is running.