How to upload a texture and apply it to a standard material. This example uses a PNG image.
You are viewing: Browser (WASM) · Switch
canvas with id vulfram-canvas.1. Load the image into bytes.
2. Send it with uploadBuffer using image-data.
3. Create the texture with source: { type: 'buffer', bufferId }.
4. Attach the texture to the standard material (baseTexId).
This repository already includes static/textures/color_test_texture.png, available at /textures/color_test_texture.png.
You can swap it with other textures from static/textures to test different
materials.
import {
initEngine,
Mount,
World3D,
createWindow,
uploadBuffer,
tick,
} from '@vulfram/engine';
import { initWasmTransport, transportWasm } from '@vulfram/transport-browser';
const IMAGE_BUFFER_ID = 1;
async function boot() {
await initWasmTransport();
initEngine({ transport: transportWasm });
const worldId = World3D.create3DWorld();
const { windowId } = createWindow({
title: 'Textures & Materials',
size: [1100, 700],
position: [0, 0],
canvasId: 'vulfram-canvas',
});
Mount.mountWorldToWindow(worldId, windowId);
const camera = World3D.create3DEntity(worldId);
World3D.update3DTransform(worldId, camera, {
position: [0, 2.5, 9],
rotation: [0, 0, 0, 1],
scale: [1, 1, 1],
});
World3D.create3DCamera(worldId, camera, { kind: 'perspective', near: 0.1, far: 100.0 });
const light = World3D.create3DEntity(worldId);
World3D.update3DTransform(worldId, light, { position: [2, 4, 6], rotation: [0, 0, 0, 1], scale: [1, 1, 1] });
World3D.create3DLight(worldId, light, { kind: 'point', intensity: 16, range: 30 });
const response = await fetch('/textures/color_test_texture.png');
const bytes = new Uint8Array(await response.arrayBuffer());
uploadBuffer(IMAGE_BUFFER_ID, 'image-data', bytes);
const textureId = World3D.create3DTexture(worldId, {
source: { type: 'buffer', bufferId: IMAGE_BUFFER_ID },
srgb: true,
});
const materialId = World3D.create3DMaterial(worldId, {
kind: 'standard',
options: {
type: 'standard',
content: {
baseColor: [1, 1, 1, 1],
surfaceType: 'opaque',
baseTexId: textureId,
baseSampler: 'linear-repeat',
flags: 0,
},
},
});
const geom = World3D.create3DGeometry(worldId, { type: 'primitive', shape: 'cube' });
const model = World3D.create3DEntity(worldId);
World3D.update3DTransform(worldId, model, { position: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [2, 2, 2] });
World3D.create3DModel(worldId, model, { geometryId: geom, materialId });
let last = performance.now();
function frame(now: number) {
const delta = now - last;
last = now;
tick(now, delta);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
boot().catch(console.error);