Runtime 3D Geometry Construction with p5.js createModel
The createModel() function enables instantiation of p5.Geometry objects directly from textual mesh data, bypassing external file dependencies. Unlike loadModel() which fetches binary assets asynchronously from URLs, this method processes OBJ or STL formatted strings already present in memory—ideal for procedurally generated meshes, user-uploaded content, or API-delivered geometry.
Function Signature
createModel(sourceString, format, normalize, [successCallback], [failureCallback], [flipU], [flipV])
| Paramter | Type | Description |
|---|---|---|
sourceString |
String | Raw OBJ or STL content, typically obtained via loadStrings() or generated algorithmically |
format |
String | File specification: 'obj' or 'stl' (lowercase, without dot) |
normalize |
Boolean | When true, auto-scales geometry to unit dimensions based on bounding box maximum extent |
successCallback |
Function | Optional handler receiving the finalized p5.Geometry instance |
failureCallback |
Function | Optional error handler receiving expection details |
flipU/flipV |
Boolean | Optional texture coordinate inversion flags for mapped materials |
Implementation Example
The following generates a tetrahedron from inline vertex data:
let pyramid;
function setup() {
createCanvas(600, 600, WEBGL);
const tetrahedronData = [
'v 0 1 0',
'v -0.816 -0.5 0.577',
'v 0.816 -0.5 0.577',
'v 0 -0.5 -1.155',
'f 1 2 3',
'f 1 3 4',
'f 1 4 2',
'f 2 4 3'
].join('\n');
pyramid = createModel(
tetrahedronData,
'obj',
true,
(geom) => console.log(`Vertices loaded: ${geom.vertices.length}`),
(err) => console.warn('Parsing error:', err)
);
}
function draw() {
background(220);
orbitControl();
ambientLight(60);
pointLight(255, 200, 150, 200, -200, 200);
push();
rotateZ(frameCount * 0.015);
rotateX(frameCount * 0.012);
specularMaterial(100, 150, 255);
shininess(50);
model(pyramid);
pop();
}