ThreeJS Updating Things

If an item has been added to the scene with the specified code, it will immediately update its matrices.

const object = new THREE.Object3D();
scene.add( object );

or, if they are the child of another object that has been added to the scene:

const object1 = new THREE.Object3D();
const object2 = new THREE.Object3D();


object1.add( object2 );
scene.add( object1 ); //object1 and object2 will automatically update their matrices

If you know the item will be static, though, you can disable this and manually update the transform matrix as needed.

object.matrixAutoUpdate  = false;
object.updateMatrix();

BufferGeometry

BufferGeometries use typed arrays to store data (such as vertex coordinates, face indices, normals, colours, UVs, and any custom properties). This makes them speedier than regular Geometries, but they're also a little more difficult to work with.

The most important thing to remember about changing BufferGeometries is that buffers cannot be resized (this is very costly, basically the equivalent to creating a new geometry). Buffers, on the other hand, can be updated.

This means that if you know an attribute of your BufferGeometry will grow, such as the number of vertices, you must pre-allocate a buffer large enough to accommodate any newly produced vertices. Of course, this means that your BufferGeometry will have a maximum size - there is no way to design a BufferGeometry that can be expanded indefinitely.

We'll use the example of a rendered line that gets stretched. Using BufferGeometry, we'll allocate room in the buffer for 500 vertices but only render two at initially. drawRange.

const MAX_POINTS = 500;


// geometry
const geometry = new THREE.BufferGeometry();


// attributes
const positions = new Float32Array( MAX_POINTS * 3 ); // 3 vertices per point
geometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );


// draw range
const drawCount = 2; // draw the first 2 points, only
geometry.setDrawRange( 0, drawCount );


// material
const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );


// line
const line = new THREE.Line( geometry,  material );
scene.add( line );

Next, we'll randomly add points to the line using a pattern like:

const positions = line.geometry.attributes.position.array;


let x, y, z, index;
x = y = z = index = 0;


for ( let i = 0, l = MAX_POINTS; i < l; i ++ ) {


    positions[ index ++ ] = x;
    positions[ index ++ ] = y;
    positions[ index ++ ] = z;


    x += ( Math.random() - 0.5 ) * 30;
    y += ( Math.random() - 0.5 ) * 30;
    z += ( Math.random() - 0.5 ) * 30;


}

After the first render, you can alter the number of points rendered by doing the following:

line.geometry.setDrawRange( 0, newValue );

If you want to update the values of the location data after the first render, set the needsUpdate flag as follows:

line.geometry.attributes.position.needsUpdate = true; // required after the first render

If the position data values change after the initial render, you may need to recompute bounding volumes in order for additional engine functions like view frustum culling or helpers to work properly.

line.geometry.computeBoundingBox();
line.geometry.computeBoundingSphere();

Materials

All uniform values (colours, textures, opacity, etc.) can be altered at any time, and values are given to the shader every frame.

GLstate-related characteristics may also change at any time (depthTest, blending, polygonOffset, etc).

At runtime (after the material has been rendered at least once), the following properties are not easily changed:

  • numbers and types of uniforms
  • presence or not of
    • texture
    • fog
    • vertex colors
    • morphing
    • shadow map
    • alpha test

Changes in these require building of new shader program. You'll need to set

material.needsUpdate = true

Keep in mind that this could be quite sluggish and cause framerate jerkiness (especially on Windows, as shader compilation is slower in DirectX than OpenGL).

You can simulate changes in these elements to some extent by using "dummy" variables such as zero intensity lighting, white texturing, or zero density fog for a smoother experience.

You can alter the material used for geometry chunks at any time, but you can't modify how an object is broken down into chunks (according to face materials).

If you need to have different configurations of materials during runtime:

If the object has a small number of materials/chunks, you can pre-divide it (for example, hair, face, torso, upper garments, and trousers for a human, front, sides, top, glass, tyre, and inside for an automobile).

Consider a different method, such as leveraging attributes/textures to drive diverse per-face looks, if the number is significant (e.g. each face might be possibly different).

Textures

Image, canvas, video, and data textures need to have the following flag set if they are changed:

texture.needsUpdate = true;

Render targets update automatically.

Cameras

A camera's position and target is updated automatically. If you need to change

  • fov
  • aspect
  • near
  • far

then, you'll need to recompute the projection matrix:

camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();

Related Topics

ThreeJS Disposing an Object

The disposal of unwanted library entities is a crucial component of improving performance and avoiding memory leaks in your programme. When you create a three.js type instance, you set aside...

4 minutes read.

ThreeJS Keyframe Tracks and Animation

A KeyframeTrack is a timed series of keyframes that are made up of lists of times and related values and are used to animate an object's unique property. BooleanKeyframeTrack A Track of...

3 minutes read.

ThreeJS Materials 3

RawShaderMaterial This class works just like ShaderMaterial, except that definitions of built-in uniforms and attributes are not automatically prepended to the GLSL shader code. Code Example const material = new THREE.RawShaderMaterial( {    ...

9 minutes read.

ThreeJS Material

Abstract base class for materials. Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use...

6 minutes read.

ThreeJS AnimationObjectGroup and Utils

AnimationObjectGroup A group of objects that receives a shared animation state. Usage Add items you'd normally send as 'root' to AnimationMixer's function Object() { [native code] } or clipAction method, and instead pass...

2 minutes read.

ThreeJS Objects

Bone A bone that is part of a Skeleton. The skeleton in turn is used by the SkinnedMesh. Bones are almost identical to a blank Object3D. Code Example const root = new THREE.Bone(); const...

12 minutes read.

ThreeJS Loader 1

AnimationLoader Class for loading AnimationClips in JSON format. This uses the FileLoader internally for loading files. Code Example // instantiate a loader const loader = new THREE.AnimationLoader(); // load a resource loader.load( // resource URL 'animations/animation.js', // onLoad callback function...

8 minutes read.

ThreeJS Cameras

ArrayCamera ArrayCamera can be used to render a scene using a preset group of cameras quickly. This is an important feature of VR scene rendering performance. An array of sub cameras is...

6 minutes read.

ThreeJS Updating Things

If an item has been added to the scene with the specified code, it will immediately update its matrices. const object = new THREE.Object3D(); scene.add( object ); or, if they are the child...

4 minutes read.

ThreeJS Creating VR Content

This article gives a quick introduction of the main components of a three.js-based web-based VR application. Workflow      First, you have to include VRButton.js into your project. import { VRButton } from...

1 minute read.

ThreeJS BufferAttribute

This class stores data for an attribute associated with a BufferGeometry (such as vertex positions, face indices, normals, colours, UVs, and any custom attributes), allowing for more efficient data passing...

4 minutes read.

ThreeJS Math

Box2 Represents an axis-aligned bounding box (AABB) in 2D space. Constructor Box2( min : Vector2, max : Vector2 ) min - (optional) Vector2 representing the lower (x, y) boundary of the box. Default is...

48 minutes read.

ThreeJS Compatibiliy Check and Running Locally

Even though this is becoming less of an issue, some devices or browsers may still be incompatible with WebGL. The method below enables you to check if it is supported...

3 minutes read.

ThreeJS Layers

A Layers object assigns an Object3D to one or more of the 32 layers numbered 0 to 31 - the layers are internally stored as a bit mask, and all...

1 minute read.

ThreeJS Using post-processing

Many three.js applications render their 3D objects directly to the screen. Sometimes, however, you want to apply one or more graphical effects like Depth-Of-Field, Bloom, Film Grain or various types...

2 minutes read.

ThreeJS Raycaster

This class is intended to help with raycasting. Raycasting is used for a variety of purposes, including mouse picking (determining which objects in 3D space the mouse is over). Code Example const...

4 minutes read.

ThreeJS Installation

You can use npm and modern build tools to install three.js, or you can get started quickly with static hosting or a CDN. Installing from npm is the best option...

4 minutes read.

ThreeJS Lines and Texts

Drawing Lines Let's say you want to draw a line or a circle, not a wireframe Mesh. First, we need to set up the renderer, scene, and camera. Here is the...

3 minutes read.

ThreeJS Keyframe Track

A KeyframeTrack is a timed series of keyframes that are made up of lists of times and related values and are used to animate an object's unique property. The "Animation System"...

4 minutes read.

ThreeJS Shadows

LightShadow Serves as a base class for the other shadow classes. Constructor LightShadow( camera : Camera ) camera - the light's view of the world. Create a new LightShadow. This is not intended to be...

7 minutes read.