### Install ServeZ CLI Tool (sudo npm)
Source: https://threejs.org/manual/en/setup
This command installs the 'servez' command-line interface tool globally using npm with superuser privileges on OSX systems. This is required for global package installations on Unix-like systems.
```bash
sudo npm -g install servez
```
--------------------------------
### Install ServeZ CLI Tool (npm)
Source: https://threejs.org/manual/en/setup
This command installs the 'servez' command-line interface tool globally using npm. This tool is used to serve local files via a web server, which is necessary for Three.js development.
```bash
npm -g install servez
```
--------------------------------
### Serve Local Files with ServeZ
Source: https://threejs.org/manual/en/setup
These commands demonstrate how to use the 'servez' tool to serve local files. The first command specifies a path to the directory containing the files, while the second command serves files from the current directory after navigating to it.
```bash
servez path/to/folder/where/you/unzipped/files
```
```bash
cd path/to/folder/where/you/unzipped/files
servez
```
--------------------------------
### Start Local Server with Serve for CDN Imports
Source: https://threejs.org/manual/en/installation
Starts a local static server using the 'serve' package to host your project files. This is necessary when importing Three.js from a CDN, as browsers require files to be served over HTTP for security reasons, especially for modules.
```bash
npx serve .
```
--------------------------------
### Run Python 2 Local Server
Source: https://threejs.org/manual/en/installation
Starts a simple HTTP server using Python 2.x to serve your project files locally. This is a convenient way to host static files for development or testing without installing additional Node.js packages.
```bash
python -m SimpleHTTPServer
```
--------------------------------
### Start Vite Development Server
Source: https://threejs.org/manual/en/installation
Starts the Vite development server from your terminal. This command builds your application and serves it locally, typically at http://localhost:5173, allowing you to view and test your Three.js application in real-time.
```bash
npx vite
```
--------------------------------
### Example Scene Setup with Multiple Objects (JavaScript)
Source: https://threejs.org/manual/en/align-html-elements-to-3d
This JavaScript code defines an array of objects, each with a geometry, color, position offset, and a label. This setup is used to demonstrate how multiple objects with potentially longer labels can lead to overlapping issues, which are addressed by the previously shown raycasting and frustum culling techniques. The `makeInstance` function is assumed to be defined elsewhere and creates and positions the objects.
```javascript
const cubes = [
makeInstance(geometry, 0x44aa88, 0, 'Aqua'),
makeInstance(geometry, 0x8844aa, -2, 'Purple'),
makeInstance(geometry, 0xaa8844, 2, 'Gold'),
makeInstance(geometry, 0x44aa88, 0, 'Aqua Colored Box'),
makeInstance(geometry, 0x8844aa, -2, 'Purple Colored Box'),
makeInstance(geometry, 0xaa8844, 2, 'Gold Colored Box'),
];
```
--------------------------------
### Minimal Example Structure for Stack Overflow
Source: https://threejs.org/manual/en/debugging-javascript
Illustrates a simplified structure for a Three.js example suitable for sharing on platforms like Stack Overflow. This example focuses on core rendering and interaction, removing non-essential elements like complex loading, detailed lighting, or UI controls, making it easier for others to understand and debug the specific issue.
```html
Three.js Minimal Example
```
--------------------------------
### Initialize Three.js Renderer and Scene Setup
Source: https://threejs.org/manual/en/fundamentals
This snippet demonstrates the initial setup for a Three.js application. It includes importing the 'three' library, configuring the WebGLRenderer with a canvas element, and setting up the basic camera and scene. The renderer handles drawing to the canvas, while the camera defines the viewing frustum and the scene holds all objects to be rendered. Dependencies: 'three.js'. Inputs: A canvas element with id 'c'. Outputs: Initialized renderer, camera, and scene objects.
```javascript
import * as THREE from 'three';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({antialias: true, canvas});
const fov = 75;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
const scene = new THREE.Scene();
// ... rest of the scene setup and render loop
}
```
--------------------------------
### Install Three.js using npm
Source: https://threejs.org/manual/en/installation
This command installs the Three.js library as a project dependency using npm (Node Package Manager). It's a fundamental step for projects that use a build tool and manage dependencies via npm.
```bash
npm install --save three
```
--------------------------------
### Initialize and Add SpotLight in Three.js
Source: https://threejs.org/manual/en/lights
Demonstrates the basic setup for creating and adding a SpotLight to a Three.js scene. It initializes the light with a color and intensity, adds it to the scene, and includes its helper for visualization.
```javascript
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.SpotLight(color, intensity);
scene.add(light);
scene.add(light.target);
const helper = new THREE.SpotLightHelper(light);
scene.add(helper);
```
--------------------------------
### JavaScript Three.js Fog Setup with lil-gui
Source: https://threejs.org/manual/en/fog
Initializes Three.js fog and background color, then sets up lil-gui controls using the `FogGUIHelper`. It adds sliders for 'near' and 'far' fog distances and a color picker for the fog color, demonstrating a practical application of the helper class.
```javascript
{
const near = 1;
const far = 2;
const color = 'lightblue';
scene.fog = new THREE.Fog(color, near, far);
scene.background = new THREE.Color(color);
const fogGUIHelper = new FogGUIHelper(scene.fog, scene.background);
gui.add(fogGUIHelper, 'near', near, far).listen();
gui.add(fogGUIHelper, 'far', near, far).listen();
gui.addColor(fogGUIHelper, 'color');
}
```
--------------------------------
### Run Node.js Local Servers
Source: https://threejs.org/manual/en/installation
Lists common Node.js-based command-line tools for starting a local development server. These tools serve your project files, enabling local testing of web applications, particularly those using modules or CDN imports.
```bash
npx http-server
```
```bash
npx five-server
```
--------------------------------
### Setup Custom Shader Pass with ShaderPass (JavaScript)
Source: https://threejs.org/manual/en/how-to-use-post-processing
Demonstrates how to import and instantiate a custom ShaderPass for post-processing effects. This pass is then added to the EffectComposer's chain. It requires importing ShaderPass and the custom shader (e.g., LuminosityShader).
```javascript
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
import { LuminosityShader } from 'three/addons/shaders/LuminosityShader.js';
// later in your init routine
const composer = /* your EffectComposer instance */;
const luminosityPass = new ShaderPass( LuminosityShader );
composer.addPass( luminosityPass );
```
--------------------------------
### Initialize DirectionalLight and SpotLight in Three.js
Source: https://threejs.org/manual/en/shadows
Examples of how to initialize `DirectionalLight` and `SpotLight` objects in Three.js with specified color and intensity.
```javascript
const light = new THREE.DirectionalLight(color, intensity);
```
```javascript
const light = new THREE.SpotLight(color, intensity);
```
--------------------------------
### Import Post Processing Modules (JavaScript)
Source: https://threejs.org/manual/en/how-to-use-post-processing
Imports essential modules for post-processing from the three.js examples directory. These include EffectComposer, RenderPass, GlitchPass, and OutputPass.
```javascript
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { GlitchPass } from 'three/addons/postprocessing/GlitchPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
```
--------------------------------
### Three.js Scene Setup: Box and Pyramid Examples
Source: https://threejs.org/manual/en/multiple-scenes
These JavaScript snippets demonstrate how to set up individual Three.js scenes and register them with the generic rendering system. Each snippet creates a scene, camera, geometry, material, and mesh, then adds a rendering function to the `sceneElements` list. The rendering function updates the camera's aspect ratio and mesh rotation before rendering the scene. Dependencies include `makeScene`, `THREE`, and the global `renderer` object.
```javascript
{
const elem = document.querySelector('#box');
const {scene, camera} = makeScene();
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshPhongMaterial({color: 'red'});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
addScene(elem, (time, rect) => {
camera.aspect = rect.width / rect.height;
camera.updateProjectionMatrix();
mesh.rotation.y = time * .1;
renderer.render(scene, camera);
});
}
{
const elem = document.querySelector('#pyramid');
const {scene, camera} = makeScene();
const radius = .8;
const widthSegments = 4;
const heightSegments = 2;
const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
const material = new THREE.MeshPhongMaterial({
color: 'blue',
flatShading: true,
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
addScene(elem, (time, rect) => {
camera.aspect = rect.width / rect.height;
camera.updateProjectionMatrix();
mesh.rotation.y = time * .1;
renderer.render(scene, camera);
});
}
```
--------------------------------
### Run PHP Local Server
Source: https://threejs.org/manual/en/installation
Starts a local web server using PHP 5.4 or later. This command serves your project files from the current directory, typically accessible at localhost:8000, and is useful for PHP-based development or testing.
```bash
php -S localhost:8000
```
--------------------------------
### Display Loading Progress with LoadingManager in Three.js
Source: https://threejs.org/manual/en/textures
This example shows how to implement a visual progress bar for texture loading using THREE.LoadingManager. It involves HTML structure, CSS for styling, and JavaScript to update the progress bar's width based on loaded items. Dependencies include THREE.js and basic HTML/CSS.
```html
```
```css
#loading {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#loading .progress {
margin: 1.5em;
border: 1px solid white;
width: 50vw;
}
#loading .progressbar {
margin: 2px;
background: white;
height: 1em;
transform-origin: top left;
transform: scaleX(0);
}
```
```javascript
const loadingElem = document.querySelector('#loading');
const progressBarElem = loadingElem.querySelector('.progressbar');
loadManager.onLoad = () => {
loadingElem.style.display = 'none';
const cube = new THREE.Mesh(geometry, materials);
scene.add(cube);
cubes.push(cube); // add to our list of cubes to rotate
};
loadManager.onProgress = (urlOfLastItemLoaded, itemsLoaded, itemsTotal) => {
const progress = itemsLoaded / itemsTotal;
progressBarElem.style.transform = `scaleX(${progress})`;
};
```
--------------------------------
### Integrate FogGUIHelper with lil-gui in three.js
Source: https://threejs.org/manual/en/fog
Demonstrates how to use the FogGUIHelper class with the lil-gui library to create interactive controls for fog's `near` and `far` properties. This example requires THREE.js and lil-gui. It sets initial fog and background colors and enables live updates via the GUI.
```javascript
{
const near = 1;
const far = 2;
const color = 'lightblue';
scene.fog = new THREE.Fog(color, near, far);
scene.background = new THREE.Color(color);
const fogGUIHelper = new FogGUIHelper(scene.fog);
gui.add(fogGUIHelper, 'near', near, far).listen();
gui.add(fogGUIHelper, 'far', near, far).listen();
}
```
--------------------------------
### Three.js Basic Scene Setup for Shaders
Source: https://threejs.org/manual/en/shadertoy
This JavaScript code sets up a basic Three.js scene. It includes initializing a WebGL renderer, an orthographic camera, and a scene. A simple plane geometry is created, which can later be used with a custom shader material to display shader output.
```javascript
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({antialias: true, canvas});
renderer.autoClearColor = false;
const camera = new THREE.OrthographicCamera(
-1, // left
1, // right
1, // top
-1, // bottom
-1, // near,
1 // far
);
const scene = new THREE.Scene();
const plane = new THREE.PlaneGeometry(2, 2);
const material = new THREE.MeshBasicMaterial({
color: 'red',
});
scene.add(new THREE.Mesh(plane, material));
}
```
--------------------------------
### Install Vite for Three.js Development
Source: https://threejs.org/manual/en/installation
Installs Vite, a fast frontend build tool, as a development dependency for your Three.js project. This command adds Vite to your project's package.json and installs it into node_modules. Vite simplifies development by providing features like hot module replacement and optimized builds.
```bash
npm install --save-dev vite
```
--------------------------------
### Run Python 3 Local Server
Source: https://threejs.org/manual/en/installation
Starts a simple HTTP server using Python 3.x to serve your project files locally. Similar to the Python 2 version, this provides a quick way to host static content for development purposes.
```bash
python -m http.server
```
--------------------------------
### Setup Second Scene for GPU Picking
Source: https://threejs.org/manual/en/picking
Initializes a secondary scene specifically for GPU-based picking in Three.js. This scene is configured to clear to black, which is essential for the GPU picking process where object colors are used to identify them. This setup is part of a more complex picking strategy that renders objects offscreen.
```javascript
// So, first create a second scene and make sure it clears to black.
const pickingScene = new THREE.Scene();
pickingScene.background = new THREE.Color(0); // Clears to black
```
--------------------------------
### Initialize Game and Player
Source: https://threejs.org/manual/en/game
Initializes the game by creating a player GameObject, adding the Player component, and setting up the initial conga line. This function is crucial for starting the game state.
```javascript
function init() {
* ...
* {
const gameObject = gameObjectManager.createGameObject(scene, 'player');
globals.player = gameObject.addComponent(Player);
globals.congaLine = [gameObject];
}
* }
```
--------------------------------
### Complete Three.js Setup with Import Map and ES6 Modules
Source: https://threejs.org/manual/en/fundamentals
Combines the import map configuration for both the core Three.js library and its addons with the ES6 module script for initializing Three.js and importing controls.
```html
```
--------------------------------
### Three.js Game Initialization and Component Setup
Source: https://threejs.org/manual/en/game
Initializes the game by hiding the loading bar, preparing models and animations, and setting up essential game objects like the camera and player. This function serves as the entry point for the game's core components.
```javascript
function init() {
// hide the loading bar
const loadingElem = document.querySelector('#loading');
loadingElem.style.display = 'none';
prepModelsAndAnimations();
{
const gameObject = gameObjectManager.createGameObject(camera, 'camera');
globals.cameraInfo = gameObject.addComponent(CameraInfo);
}
{
const gameObject = gameObjectManager.createGameObject(scene, 'player');
gameObject.addComponent(Player);
}
}
```
--------------------------------
### Create and Start Morph Target Tween (JavaScript)
Source: https://threejs.org/manual/en/optimize-lots-of-objects-animated
This snippet demonstrates how to create a tween animation for morph target influences on a Three.js mesh using TWEEN.js. It defines the target values and duration, then starts the animation. Assumes `TWEEN` and `tweenManager` are initialized and `mesh` is a Three.js mesh object with morph targets.
```javascript
new TWEEN.Tween(mesh.morphTargetInfluences)
.to(targets, durationInMs)
.start();
requestRenderIfNotRequested();
```
--------------------------------
### Create RingGeometry with segments, start, and length
Source: https://threejs.org/manual/en/primitives
Generates a ring geometry with detailed control over its parameters. Includes inner and outer radii, the number of segments around the circumference (thetaSegments), segments along the radius (phiSegments), and the start and length of the angular sweep (thetaStart, thetaLength).
```javascript
const innerRadius = 2;
const outerRadius = 7;
const thetaSegments = 18;
const phiSegments = 2;
const thetaStart = Math.PI * 0.25;
const thetaLength = Math.PI * 1.5;
const geometry = new THREE.RingGeometry(
innerRadius, outerRadius,
thetaSegments, phiSegments,
thetaStart, thetaLength );
```
--------------------------------
### Scene and Camera Setup with Parent Object (JavaScript)
Source: https://threejs.org/manual/en/picking
Configures the Three.js scene, perspective camera, and a parent `Object3D` for the camera. Parenting the camera allows its movement to be controlled by rotating the parent object, simulating a 'selfie stick' effect. This setup is crucial for spatial navigation within the scene.
```javascript
const fov = 60;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 200;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 30;
const scene = new THREE.Scene();
scene.background = new THREE.Color('white');
// put the camera on a pole (parent it to an object)
// so we can spin the pole to move the camera around the scene
const cameraPole = new THREE.Object3D();
scene.add(cameraPole);
cameraPole.add(camera);
```
--------------------------------
### JavaScript for Three.js Texture Loading and Uniform Setup
Source: https://threejs.org/manual/en/shadertoy
This JavaScript code demonstrates loading an image texture using Three.js's TextureLoader and configuring its properties for seamless tiling. It then sets up the shader uniforms, including the loaded texture, resolution, and time.
```javascript
const loader = new THREE.TextureLoader();
const texture = loader.load('resources/images/bayer.png');
texture.minFilter = THREE.NearestFilter;
texture.magFilter = THREE.NearestFilter;
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
const uniforms = {
iTime: { value: 0 },
iResolution: { value: new THREE.Vector3() },
iChannel0: { value: texture },
};
```
--------------------------------
### Setup OrthographicCamera (Three.js)
Source: https://threejs.org/manual/en/cameras
This code snippet shows the setup for a `THREE.OrthographicCamera`. It defines the camera's viewing frustum using `left`, `right`, `top`, `bottom`, `near`, and `far` properties, and includes setting the `zoom` level.
```javascript
const left = -1;
const right = 1;
const top = 1;
const bottom = -1;
const near = 5;
const far = 50;
const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far);
camera.zoom = 0.2;
```
--------------------------------
### Configure Points Material Size Attenuation (Three.js)
Source: https://threejs.org/manual/en/primitives
This example shows how to configure PointsMaterial to disable size attenuation, making points maintain a consistent pixel size regardless of distance from the camera. It also illustrates setting point size in pixels.
```javascript
const material = new THREE.PointsMaterial({
color: 'red',
sizeAttenuation: false,
size: 3, // in pixels
});
```
--------------------------------
### Initializing Three.js Scene and Tween Manager
Source: https://threejs.org/manual/en/optimize-lots-of-objects-animated
This code snippet shows the initialization of the main Three.js application. It sets up the WebGL renderer, obtains a reference to the canvas element, and creates an instance of the custom TweenManger. This setup is the foundation for rendering the 3D scene and managing animations.
```javascript
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({antialias: true, canvas});
const tweenManager = new TweenManger();
// ...
}
```
--------------------------------
### Frustum Culling Setup (JavaScript)
Source: https://threejs.org/manual/en/align-html-elements-to-3d
This code illustrates the setup required for more accurate frustum culling using `THREE.Frustum`. It involves creating `THREE.Frustum` and `THREE.Matrix4` objects, updating camera matrices, and then using `frustum.contains(someMesh)` to check if a mesh's bounding sphere is within the camera's view. This method is more robust for large objects but can be computationally intensive for many objects.
```javascript
// at init time
const frustum = new THREE.Frustum();
const viewProjection = new THREE.Matrix4();
// before checking
camera.updateMatrix();
camera.updateMatrixWorld();
camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
// then for each mesh
someMesh.updateMatrix();
someMesh.updateMatrixWorld();
viewProjection.multiplyMatrices(
camera.projectionMatrix,
camera.matrixWorldInverse);
frustum.setFromProjectionMatrix(viewProjection);
const inFrustum = frustum.contains(someMesh));
```
--------------------------------
### Initialize EffectComposer (JavaScript)
Source: https://threejs.org/manual/en/how-to-use-post-processing
Creates an instance of EffectComposer, which manages the chain of post-processing passes. It requires an instance of WebGLRenderer as an argument.
```javascript
const composer = new EffectComposer( renderer );
```
--------------------------------
### Setup THREE.js BufferGeometry Attributes
Source: https://threejs.org/manual/en/custom-buffergeometry
Initializes a THREE.js BufferGeometry, sets up 'position' and 'normal' attributes, and applies indices. The position attribute is marked as dynamic for frequent updates.
```javascript
const geometry = new THREE.BufferGeometry();
const positionNumComponents = 3;
const normalNumComponents = 3;
const positionAttribute = new THREE.BufferAttribute(positions, positionNumComponents);
positionAttribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute(
'position',
positionAttribute);
gEometry.setAttribute(
'normal',
new THREE.BufferAttribute(normals, normalNumComponents));
geometry.setIndex(indices);
```
--------------------------------
### CoroutineRunner Usage Example
Source: https://threejs.org/manual/en/game
Demonstrates how to instantiate and use the `CoroutineRunner` to execute a generator function. The `isBusy` method checks if any coroutines are still active, and `update` progresses them.
```javascript
const runner = new CoroutineRunner();
runner.add(count0To9);
while(runner.isBusy()) {
runner.update();
}
```
--------------------------------
### Adjust Visible Range of BufferGeometry in Three.js
Source: https://threejs.org/manual/en/how-to-update-things
Explains how to dynamically change the number of points rendered from a BufferGeometry after its initial setup. This is achieved by calling `setDrawRange` with new start and count values.
```javascript
line.geometry.setDrawRange( 0, newValue );
```
--------------------------------
### Setup Renderer, Camera, and Scene in JavaScript
Source: https://threejs.org/manual/en/drawing-lines
Initializes the WebGLRenderer, PerspectiveCamera, and Scene objects required for rendering 3D graphics. Sets the size of the renderer to match the browser window and appends the renderer's DOM element to the document body. The camera is configured with a field of view, aspect ratio, near, and far clipping planes, and positioned to look at the origin.
```javascript
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 500 );
camera.position.set( 0, 0, 100 );
camera.lookAt( 0, 0, 0 );
const scene = new THREE.Scene();
```
--------------------------------
### Transfer Canvas Control to Offscreen
Source: https://threejs.org/manual/en/offscreencanvas
This code snippet demonstrates how to get a reference to an HTML canvas element and then transfer its control to an offscreen context. This is the initial step required on the main thread before starting a web worker for rendering.
```javascript
function main() {
const canvas = document.querySelector('#c');
const offscreen = canvas.transferControlToOffscreen();
// ... other initialization
}
```
--------------------------------
### OrthographicCamera Setup for VR
Source: https://threejs.org/manual/en/webxr-look-to-select
Sets up an OrthographicCamera for use in a VR 'look to select' scenario. The camera's properties are defined to match a default canvas size, ensuring a consistent view. The camera's projection matrix is updated on canvas resize.
```javascript
const left = -2; // Use values for left
const right = 2; // right, top and bottom
const top = 1; // that match the default
const bottom = -1; // canvas size.
const near = -1;
const far = 1;
const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far);
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
const aspect = canvas.clientWidth / canvas.clientHeight;
camera.left = -aspect;
camera.right = aspect;
camera.updateProjectionMatrix();
}
...
}
```
--------------------------------
### Initialize Game Scene with Game Objects
Source: https://threejs.org/manual/en/game
Sets up the game scene by hiding the loading bar, preparing models, creating a camera, a player object, and multiple animal objects with specific positions. Dependencies: gameObjectManager, CameraInfo, Player, Animal, models, globals, scene, camera.
```javascript
function init() {
// hide the loading bar
const loadingElem = document.querySelector('#loading');
loadingElem.style.display = 'none';
prepModelsAndAnimations();
{
const gameObject = gameObjectManager.createGameObject(camera, 'camera');
globals.cameraInfo = gameObject.addComponent(CameraInfo);
}
{
const gameObject = gameObjectManager.createGameObject(scene, 'player');
globals.player = gameObject.addComponent(Player);
globals.congaLine = [gameObject];
}
const animalModelNames = [
'pig',
'cow',
'llama',
'pug',
'sheep',
'zebra',
'horse',
];
animalModelNames.forEach((name, ndx) => {
const gameObject = gameObjectManager.createGameObject(scene, name);
gameObject.addComponent(Animal, models[name]);
gameObject.transform.position.x = (ndx + 1) * 5;
});
}
```
--------------------------------
### Integrating Resize Function in Render Loop (Three.js)
Source: https://threejs.org/manual/en/responsive
This example shows how to incorporate the `resizeRendererToDisplaySize` function into the main render loop. It calls the resize function and, if a resize occurred, updates the camera's projection matrix to maintain correct aspect ratios.
```javascript
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
// ... other rendering logic
```
--------------------------------
### Set Texture Offset in Three.js
Source: https://threejs.org/manual/en/textures
Adjust the starting position of a texture using the `offset` property in Three.js. The offset values are in units where 1 unit equals the size of the texture. A value of 0 means no offset, while 1 means an offset by one full texture width or height. The `set()` method takes x and y offset values.
```javascript
const xOffset = .5; // offset by half the texture
const yOffset = .25; // offset by 1/4 the texture
someTexture.offset.set(xOffset, yOffset);
```
--------------------------------
### Setting up Import Map for Three.js Core
Source: https://threejs.org/manual/en/fundamentals
Configures an import map to specify the path to the Three.js module file. This is crucial for the browser to locate 'three' when imported using ES6 modules. Paths must start with './' or '../'.
```html
```
--------------------------------
### Setup Second PerspectiveCamera and OrbitControls
Source: https://threejs.org/manual/en/cameras
Initializes a second `PerspectiveCamera` with specified field of view, aspect ratio, near, and far clipping planes. It then sets the camera's position and look-at target. A second `OrbitControls` instance is created, linked to the second camera and a corresponding DOM element (`view2Elem`), with its target also set.
```javascript
const camera2 = new THREE.PerspectiveCamera(
60, // fov
2, // aspect
0.1, // near
500 // far
);
camera2.position.set(40, 10, 30);
camera2.lookAt(0, 5, 0);
const controls2 = new OrbitControls(camera2, view2Elem);
controls2.target.set(0, 5, 0);
controls2.update();
```
--------------------------------
### Create ParametricGeometry with custom function
Source: https://threejs.org/manual/en/primitives
Generates a surface defined by a parametric function. The function takes two parameters (u, v) representing a point on a grid and returns the corresponding 3D point. This example uses a function to create a Klein bottle surface.
```javascript
const slices = 25;
const stacks = 25;
// from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
function klein( v, u, target ) {
u *= Math.PI;
v *= 2 * Math.PI;
u = u * 2;
let x;
let z;
if ( u < Math.PI ) {
x = 3 * Math.cos( u ) * ( 1 + Math.sin( u ) ) + ( 2 * ( 1 - Math.cos( u ) / 2 ) ) * Math.cos( u ) * Math.cos( v );
z = - 8 * Math.sin( u ) - 2 * ( 1 - Math.cos( u ) / 2 ) * Math.sin( u ) * Math.cos( v );
} else {
x = 3 * Math.cos( u ) * ( 1 + Math.sin( u ) ) + ( 2 * ( 1 - Math.cos( u ) / 2 ) ) * Math.cos( v + Math.PI );
z = - 8 * Math.sin( u );
}
const y = - 2 * ( 1 - Math.cos( u ) / 2 ) * Math.sin( v );
target.set( x, y, z ).multiplyScalar( 0.75 );
}
return new ParametricGeometry(
klein, slices, stacks );
```
--------------------------------
### Manage Multiple Animations per Model
Source: https://threejs.org/manual/en/game
Extends the animation setup to handle all animation clips for each model. It stores animation actions and current index for each mixer, and provides functionality to cycle through animations.
```javascript
const mixers = [];
const mixerInfos = [];
function init() {
const loadingElem = document.querySelector('#loading');
loadingElem.style.display = 'none';
prepModelsAndAnimations();
Object.values(models).forEach((model, ndx) => {
const clonedScene = SkeletonUtils.clone(model.gltf.scene);
const root = new THREE.Object3D();
root.add(clonedScene);
scene.add(root);
root.position.x = (ndx - 3) * 3;
const mixer = new THREE.AnimationMixer(clonedScene);
const firstClip = Object.values(model.animations)[0];
const action = mixer.clipAction(firstClip);
action.play();
mixers.push(mixer);
const actions = Object.values(model.animations).map((clip) => {
return mixer.clipAction(clip);
});
const mixerInfo = {
mixer,
actions,
actionNdx: -1,
};
mixerInfos.push(mixerInfo);
playNextAction(mixerInfo);
});
}
function playNextAction(mixerInfo) {
const {actions, actionNdx} = mixerInfo;
const nextActionNdx = (actionNdx + 1) % actions.length;
mixerInfo.actionNdx = nextActionNdx;
actions.forEach((action, ndx) => {
const enabled = ndx === nextActionNdx;
action.enabled = enabled;
if (enabled) {
action.play();
}
});
}
```
--------------------------------
### Scene Setup with Pickable Object Parent
Source: https://threejs.org/manual/en/webxr-point-to-select
This JavaScript code snippet illustrates setting up a Three.js scene and a hierarchical structure for managing pickable objects. A 'pickRoot' Object3D is created and added to the scene; all objects intended to be selectable are then added as children to this 'pickRoot'. This separation helps differentiate pickable items from non-pickable scene elements like the controller's pointing lines.
```javascript
const scene = new THREE.Scene();
// object to put pickable objects on so we can easily
// separate them from non-pickable objects
const pickRoot = new THREE.Object3D();
scene.add(pickRoot);
...
function makeInstance(geometry, color, x) {
const material = new THREE.MeshPhongMaterial({color});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
pickRoot.add(cube);
...
}
```
--------------------------------
### JavaScript: Setting up Morphtargets with Geometries
Source: https://threejs.org/manual/en/optimize-lots-of-objects-animated
This snippet illustrates the process of preparing geometries for morphtargets. It maps over `fileInfos` to create geometries using `makeBoxes` and then uses the first geometry as the base, adding subsequent geometries as morphtargets.
```javascript
// make geometry for each data set
const geometries = fileInfos.map((info) => {
return makeBoxes(info.file, info.hueRange, fileInfos);
});
// use the first geometry as the base
// and add all the geometries as morphtargets
```
--------------------------------
### Initialize Scene with TrackballControls in Three.js
Source: https://threejs.org/manual/en/multiple-scenes
This code demonstrates the setup of a Three.js scene, including camera, lighting, and TrackballControls. The controls are initialized with the camera and a DOM element, allowing user interaction. It also shows how to add the camera to the scene and the light to the camera for relative positioning.
```javascript
function makeScene(elem) {
const scene = new THREE.Scene();
const fov = 45;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 1, 2);
camera.lookAt(0, 0, 0);
scene.add(camera);
const controls = new TrackballControls(camera, elem);
controls.noZoom = true;
controls.noPan = true;
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
camera.add(light);
}
return {scene, camera, controls};
}
```
--------------------------------
### JavaScript Generator Function Example
Source: https://threejs.org/manual/en/game
An example of a JavaScript generator function, denoted by `function*`, which can pause execution using `yield`. This specific generator prints numbers from 0 to 9, yielding after each print.
```javascript
function* count0To9() {
for (let i = 0; i < 10; ++i) {
console.log(i);
yield;
}
}
```
--------------------------------
### Initializing MeshBasicMaterial with Various Color Formats
Source: https://threejs.org/manual/en/materials
Illustrates how to create a `THREE.MeshBasicMaterial` and set its color using different accepted formats at creation time, including hex numbers, CSS color strings, short hex codes, RGB strings, and HSL strings.
```javascript
const m1 = new THREE.MeshBasicMaterial({color: 0xFF0000}); // red
const m2 = new THREE.MeshBasicMaterial({color: 'red'}); // red
const m3 = new THREE.MeshBasicMaterial({color: '#F00'}); // red
const m4 = new THREE.MeshBasicMaterial({color: 'rgb(255,0,0)'}); // red
const m5 = new THREE.MeshBasicMaterial({color: 'hsl(0,100%,50%)'}); // red
```
--------------------------------
### Three.js Picking Helper Initialization and Usage
Source: https://threejs.org/manual/en/picking
Demonstrates how to instantiate and use the PickHelper for selecting objects within a Three.js scene. It shows the process of picking an object based on its position and saving its original color before applying a flashing emissive effect.
```javascript
// pick the first object. It's the closest one
this.pickedObject = intersectedObject;
// save its color
this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
// set its emissive color to flashing red/yellow
this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
```
```javascript
const pickHelper = new PickHelper();
```
```javascript
pickHelper.pick(pickPosition, scene, camera, time);
```
--------------------------------
### Initialize PickHelper for Raycasting in Three.js
Source: https://threejs.org/manual/en/webxr-look-to-select
Sets up the `PickHelper` class, initializing a `THREE.Raycaster`, and defining properties to track the currently picked object and its original color. It also creates a 2x1 data texture for a cursor visual.
```javascript
class PickHelper {
constructor(camera) {
this.raycaster = new THREE.Raycaster();
this.pickedObject = null;
this.pickedObjectSavedColor = 0;
const cursorColors = new Uint8Array([
64, 64, 64, 64, // dark gray
255, 255, 255, 255, // white
]);
this.cursorTexture = makeDataTexture(cursorColors, 2, 1);
}
// ... other methods
```
--------------------------------
### Create and Configure Cube Instances with lil-gui
Source: https://threejs.org/manual/en/rendering-on-demand
Defines a function to create cube instances with specified geometry, color, and position. It integrates lil-gui to add color and scale controls for each cube. Changes made via the GUI trigger a render request via `requestRenderIfNotRequested`. This setup allows for on-demand rendering.
```javascript
function makeInstance(geometry, color, x) {
const material = new THREE.MeshPhongMaterial({color});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
cube.position.x = x;
const folder = gui.addFolder(`Cube${x}`);
folder.addColor(new ColorGUIHelper(material, 'color'), 'value')
.name('color')
.onChange(requestRenderIfNotRequested);
folder.add(cube.scale, 'x', .1, 1.5)
.name('scale x')
.onChange(requestRenderIfNotRequested);
folder.open();
return cube;
}
```
--------------------------------
### Create GUI for BloomPass and FilmPass Parameters
Source: https://threejs.org/manual/en/post-processing
This code sets up a lil-gui interface to control the 'strength' of the BloomPass and the 'grayscale' and 'intensity' of the FilmPass. It creates folders for each pass and adds sliders or toggles for their respective parameters.
```javascript
const gui = new GUI();
{
const folder = gui.addFolder('BloomPass');
folder.add(bloomPass.combineUniforms.strength, 'value', 0, 2).name('strength');
folder.open();
}
{
const folder = gui.addFolder('FilmPass');
folder.add(filmPass.uniforms.grayscale, 'value').name('grayscale');
folder.add(filmPass.uniforms.intensity, 'value', 0, 1).name('intensity');
folder.open();
}
```
--------------------------------
### Apply Six Textures to a Cube with Multiple Materials (JavaScript)
Source: https://threejs.org/manual/en/textures
Demonstrates creating a cube where each face has a distinct texture. It involves creating an array of `MeshBasicMaterial` instances, each mapped to a loaded texture, and passing this array to the `THREE.Mesh` constructor. It also includes a helper function `loadColorTexture` to manage texture loading and color space conversion.
```javascript
const loader = new THREE.TextureLoader();
const texture = loader.load( 'resources/images/wall.jpg' );
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.MeshBasicMaterial({
map: texture,
});
const materials = [
new THREE.MeshBasicMaterial({map: loadColorTexture('resources/images/flower-1.jpg')}),
new THREE.MeshBasicMaterial({map: loadColorTexture('resources/images/flower-2.jpg')}),
new THREE.MeshBasicMaterial({map: loadColorTexture('resources/images/flower-3.jpg')}),
new THREE.MeshBasicMaterial({map: loadColorTexture('resources/images/flower-4.jpg')}),
new THREE.MeshBasicMaterial({map: loadColorTexture('resources/images/flower-5.jpg')}),
new THREE.MeshBasicMaterial({map: loadColorTexture('resources/images/flower-6.jpg')}),
];
const cube = new THREE.Mesh(geometry, material);
const cube = new THREE.Mesh(geometry, materials);
function loadColorTexture( path ) {
const texture = loader.load( path );
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
```
--------------------------------
### Handling UI and Mouse Events for Data Visualization
Source: https://threejs.org/manual/en/optimize-lots-of-objects-animated
This snippet outlines the process of setting up a user interface to interact with the data visualization. It iterates through file information, creates DOM elements for each file, and attaches event listeners for mouseover and touchstart events to trigger the display of specific file data. This enhances user interaction by providing a visual way to select data sets.
```javascript
const uiElem = document.querySelector('#ui');
fileInfos.forEach((info) => {
const boxes = addBoxes(info.file, info.hueRange);
info.root = boxes;
const div = document.createElement('div');
info.elem = div;
div.textContent = info.name;
uiElem.appendChild(div);
function show() {
showFileInfo(fileInfos, info);
}
div.addEventListener('mouseover', show);
div.addEventListener('touchstart', show);
});
// show the first set of data
showFileInfo(fileInfos, fileInfos[0]);
```
--------------------------------
### Inspecting a GLTF Scene Object in Console (JavaScript)
Source: https://threejs.org/manual/en/debugging-javascript
This example shows how to load a GLTF model using `GLTFLoader` and then log the entire scene object to the JavaScript console. This allows for detailed inspection of the loaded model's structure and properties, aiding in debugging scene composition.
```javascript
const gltfLoader = new GLTFLoader();
gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => {
const root = gltf.scene;
scene.add(root);
console.log(root);
});
```
--------------------------------
### Initialize Three.js Scene, Camera, and Renderer
Source: https://threejs.org/manual/en/creating-a-scene
Sets up the core components for a Three.js application: the scene to hold objects, a perspective camera for viewing, and a WebGL renderer to draw the scene to the canvas. The renderer's DOM element is appended to the body. Dependencies: 'three'.
```javascript
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
```
--------------------------------
### Import lil-gui for Runtime Parameter Control
Source: https://threejs.org/manual/en/post-processing
This import statement includes the lil-gui library, which is used to create an interactive graphical user interface. This GUI allows for real-time adjustment of post-processing effect parameters.
```javascript
import {GUI} from 'three/addons/libs/lil-gui.module.min.js';
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.