This example demonstrates the basic lifecycle of a t3d application: initializing a WebGL2 renderer, creating a scene with a PBR mesh, adding lights and a camera, and running an animation loop.
Key steps in the loop:
- Update mesh rotation.
- Call
scene.updateMatrix(). - Call
scene.updateRenderStates(camera). - Call
scene.updateRenderQueue(camera). - Call
renderer.renderScene(scene, camera, screenRenderTarget).
// Initialize renderer with WebGL2
const width = window.innerWidth || 2;
const height = window.innerHeight || 2;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
// Create WebGL2 context and renderer
const gl = canvas.getContext('webgl2', {
antialias: true,
alpha: false
});
const renderer = new t3d.WebGLRenderer(gl);
const screenRenderTarget = new t3d.ScreenRenderTarget(canvas);
screenRenderTarget.setColorClearValue(0.1, 0.1, 0.1, 1);
// Create scene
const scene = new t3d.Scene();
// Create mesh with PBR material
const geometry = new t3d.BoxGeometry(8, 8, 8);
const material = new t3d.PBRMaterial();
const mesh = new t3d.Mesh(geometry, material);
scene.add(mesh);
// Add lighting
const ambientLight = new t3d.AmbientLight(0xffffff);
scene.add(ambientLight);
const directionalLight = new t3d.DirectionalLight(0xffffff);
directionalLight.position.set(-5, 5, 5);
directionalLight.lookAt(new t3d.Vector3(), new t3d.Vector3(0, 1, 0));
scene.add(directionalLight);
// Set up camera
const camera = new t3d.Camera();
camera.position.set(0, 10, 30);
camera.lookAt(new t3d.Vector3(0, 0, 0), new t3d.Vector3(0, 1, 0));
camera.setPerspective(45 / 180 * Math.PI, width / height, 1, 1000);
scene.add(camera);
// Animation loop
function loop(count) {
requestAnimationFrame(loop);
// Rotate cube
mesh.euler.y = count / 1000 * .5;
scene.updateMatrix();
scene.updateRenderStates(camera);
scene.updateRenderQueue(camera);
renderer.renderScene(scene, camera, screenRenderTarget);
}
requestAnimationFrame(loop);