### Full Physics Simulation Setup - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This comprehensive example integrates all previously shown concepts: initializing the physics world, creating a dynamic sphere, setting up a static ground plane, and running the simulation loop with `world.fixedStep()`. It also includes a `console.log` to observe the sphere's falling position. ```JavaScript import * as CANNON from 'cannon-es' // Setup our physics world const world = new CANNON.World({ gravity: new CANNON.Vec3(0, -9.82, 0), // m/s² }) // Create a sphere body const radius = 1 // m const sphereBody = new CANNON.Body({ mass: 5, // kg shape: new CANNON.Sphere(radius), }) sphereBody.position.set(0, 10, 0) // m world.addBody(sphereBody) // Create a static plane for the ground const groundBody = new CANNON.Body({ type: CANNON.Body.STATIC, // can also be achieved by setting the mass to 0 shape: new CANNON.Plane(), }) groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up world.addBody(groundBody) // Start the simulation loop function animate() { requestAnimationFrame(animate) world.fixedStep() // the sphere y position shows the sphere falling console.log(`Sphere y position: ${sphereBody.position.y}`) } animate() ``` -------------------------------- ### Stepping Physics Simulation with Manual Delta Time - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This advanced example shows how to manually control the physics simulation step using `world.step()`. It calculates the `dt` (delta time) between frames based on `performance.now()` and passes it along with a fixed `timeStep` to ensure precise simulation progression. ```JavaScript const timeStep = 1 / 60 // seconds let lastCallTime function animate() { requestAnimationFrame(animate) const time = performance.now() / 1000 // seconds if (!lastCallTime) { world.step(timeStep) } else { const dt = time - lastCallTime world.step(timeStep, dt) } lastCallTime = time } // Start the simulation loop animate() ``` -------------------------------- ### Initial Setup and Cannon.js Imports in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/canvas_interpolation.html This snippet handles initial DOM utility imports, adds a title and source button, and imports the "cannon-es" library. It also declares global variables for the rendering context, physics world, sphere body, and time tracking, and initiates the setup and animation loops. ```JavaScript import { addTitle, addSourceButton } from './js/dom-utils.js' addTitle() addSourceButton() import * as CANNON from '../dist/cannon-es.js' /** * Example of interpolatedPosition and interpolatedQuaternion * using a canvas for simplicity */ let ctx let world let sphereBody const radius = 1 let lastCallTime = getTime() init() animate() ``` -------------------------------- ### Dynamically Populating Examples Container in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/index.html This code block selects the HTML container for examples and then iterates through the `examples` array. For each example name, it generates the corresponding HTML using `exampleTemplate`, converts the HTML string into a DOM element using `createElementFromHTML`, and finally appends this element to the examples container, dynamically displaying all available examples on the page. ```javascript // generate and add the examples to the DOM const examplesContainer = document.querySelector('.examples') examples.forEach((example) => { const exampleNode = createElementFromHTML(exampleTemplate(example)) examplesContainer.appendChild(exampleNode) }) ``` -------------------------------- ### Creating Three.js Mesh for Physics Simulation Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This snippet demonstrates how to create a basic `THREE.Mesh` using a given geometry and material, and then add it to the Three.js scene. This mesh will later be visually linked to a Cannon.js physics body to represent it in the 3D environment. ```javascript const sphereMesh = new THREE.Mesh(geometry, material) scene.add(sphereMesh) ``` -------------------------------- ### Setting Up Three.js and Cannon.js Environment - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs.html This snippet handles the necessary module imports for DOM utilities, Cannon.js, and Three.js, along with declaring global variables for both the rendering and physics engines. It also initiates the setup and animation loops by calling the respective initialization functions. ```JavaScript import { addTitle, addSourceButton } from './js/dom-utils.js' addTitle() addSourceButton() import * as CANNON from '../dist/cannon-es.js' import * as THREE from 'https://unpkg.com/three@0.122.0/build/three.module.js' // three.js variables let camera, scene, renderer let mesh // cannon.js variables let world let body initThree() initCannon() animate() ``` -------------------------------- ### Generating HTML Template for cannon-es Examples in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/index.html This JavaScript function generates an HTML string for a single example entry. It takes an example `name` as input, converts it into a more readable format, and then constructs a `div` element containing a link to the example, an image thumbnail, and a link to its source code on GitHub. It relies on the `replaceAll` utility function. ```javascript function exampleTemplate(name) { const readableName = replaceAll(name, '_', ' ') .replace('threejs', 'three.js') .replace('sharedarraybuffer', 'SharedArrayBuffer') return `
${readableName} GitHub
` } ``` -------------------------------- ### Creating a Dynamic Sphere Body - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This snippet demonstrates how to create a dynamic rigid body in cannon-es. It initializes a `CANNON.Body` with a specified mass (5 kg) and a `CANNON.Sphere` shape, then sets its initial position and adds it to the physics world. ```JavaScript const radius = 1 // m const sphereBody = new CANNON.Body({ mass: 5, // kg shape: new CANNON.Sphere(radius), }) sphereBody.position.set(0, 10, 0) // m world.addBody(sphereBody) ``` -------------------------------- ### Defining Example List for cannon-es in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/index.html This array defines a comprehensive list of example names used throughout the cannon-es project. Each string represents a specific physics simulation or feature demonstration, often corresponding to an HTML file in the 'examples' directory. This list is iterated over to dynamically generate links and display information for each example. ```javascript const examples = [ 'threejs_cloth', 'threejs_fps', 'threejs_mousepick', 'threejs_voxel_fps', 'threejs', 'worker', 'worker_sharedarraybuffer', 'body_types', 'bounce', 'bunny', 'callbacks', 'canvas_interpolation', 'collision_filter', 'collisions', 'compound', 'constraints', 'container', 'convex', 'events', 'fixed_rotation', 'friction', 'friction_gravity', 'heightfield', 'hinge', 'impulses', 'jenga', 'pile', 'performance', 'ragdoll', 'raycast_vehicle', 'rigid_vehicle', 'shapes', 'simple_friction', 'single_body_on_plane', 'sleep', 'sph', 'split_solver', 'spring', 'stacks', 'tear', 'trigger', 'trimesh', 'tween', ] ``` -------------------------------- ### Stepping Physics Simulation with Fixed Timestep - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This code defines an `animate` function that uses `requestAnimationFrame` to create a continuous loop. Inside the loop, `world.fixedStep()` is called to advance the physics simulation at a consistent rate (defaulting to 60fps), ensuring simulation speed is independent of the rendering framerate. ```JavaScript function animate() { requestAnimationFrame(animate) // Run the simulation independently of framerate every 1 / 60 ms world.fixedStep() } // Start the simulation loop animate() ``` -------------------------------- ### Starting the CANNON.js Demo Simulation Source: https://github.com/pmndrs/cannon-es/blob/master/examples/simple_friction.html This line initiates the CANNON.js simulation and visualization. It calls the `start` method on the `demo` object, which typically begins the physics loop and renders the scene. ```JavaScript demo.start() ``` -------------------------------- ### Starting the CANNON.js Demo in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/container.html This line initiates the CANNON.js simulation and rendering loop. It's typically called after all scenes and initial setup are complete to begin the physics simulation and visualize the bodies in the demo environment. ```JavaScript demo.start() ``` -------------------------------- ### Starting the Cannon-ES Demo Application - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/trimesh.html This line initiates the Cannon-ES demo application, starting the physics simulation and rendering loop for the added scenes. It is the final call required to make the defined physics environments active and visible. ```JavaScript demo.start() ``` -------------------------------- ### Creating a Sphere Geometry in Three.js - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This snippet demonstrates how to create a basic sphere geometry and a normal material using the Three.js library. This is typically used in conjunction with a physics engine like cannon-es to visually represent the simulated physics bodies on screen. ```JavaScript const radius = 1 // m const geometry = new THREE.SphereGeometry(radius) const material = new THREE.MeshNormalMaterial() ``` -------------------------------- ### Creating a Static Ground Plane - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This code creates a static rigid body to serve as a ground plane in the physics world. It sets the body's type to `CANNON.Body.STATIC` and uses a `CANNON.Plane` shape, then rotates it to face upwards before adding it to the world. ```JavaScript const groundBody = new CANNON.Body({ type: CANNON.Body.STATIC, shape: new CANNON.Plane(), }) groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up world.addBody(groundBody) ``` -------------------------------- ### Starting the Demo Simulation in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/performance.html This line initiates the `Demo` application, which typically starts the physics simulation loop and rendering process, allowing the configured scenes to be run and observed. ```JavaScript demo.start() ``` -------------------------------- ### Starting the CANNON.js Demo Simulation - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/collisions.html This line initiates the CANNON.js simulation and visualization. After all scenes are defined, calling `demo.start()` begins the physics world's step-by-step updates and renders the visual representations of the bodies. ```JavaScript demo.start() ``` -------------------------------- ### Initializing Three.js Scene and Objects - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs.html This function sets up the Three.js rendering environment, including the camera, scene, and WebGL renderer. It also creates and adds a basic wireframe box mesh to the scene and attaches a window resize event listener to handle responsive rendering. ```JavaScript function initThree() { // Camera camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100) camera.position.z = 5 // Scene scene = new THREE.Scene() // Renderer renderer = new THREE.WebGLRenderer({ antialias: true }) renderer.setSize(window.innerWidth, window.innerHeight) document.body.appendChild(renderer.domElement) window.addEventListener('resize', onWindowResize) // Box const geometry = new THREE.BoxBufferGeometry(2, 2, 2) const material = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }) mesh = new THREE.Mesh(geometry, material) scene.add(mesh) } ``` -------------------------------- ### Initializing Cannon.js Demo in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/body_types.html This snippet imports the `cannon-es` physics library and a custom `Demo` utility, then initializes the `Demo` instance to prepare for setting up and running physics simulations. This is the foundational setup for the application. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() ``` -------------------------------- ### Initiating Cannon.js Physics Simulation Source: https://github.com/pmndrs/cannon-es/blob/master/examples/body_types.html This line calls the `start` method on the `demo` instance, which begins the physics simulation loop and rendering. It's the final step to activate the defined scenes and observe the physics interactions. ```JavaScript demo.start() ``` -------------------------------- ### Helper Function for CANNON.js World Setup (JavaScript) Source: https://github.com/pmndrs/cannon-es/blob/master/examples/tear.html This helper function, `setupWorld`, is responsible for initializing the CANNON.js physics world. It retrieves the world instance from the demo object and sets its gravity. This function promotes code reusability and keeps the main scene setup cleaner. ```JavaScript function setupWorld(demo) { const world = demo.getWorld() world.gravity.set(0, -10, 0) return world } ``` -------------------------------- ### Initializing CANNON.js Demo in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/container.html This snippet imports the core CANNON.js library and a custom `Demo` class, then initializes a new `Demo` instance. The `Demo` class is presumed to handle the setup of the simulation environment, rendering, and scene management for the physics visualization. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() ``` -------------------------------- ### Complete Basic Physics Simulation Example in cannon-es (JavaScript) Source: https://github.com/pmndrs/cannon-es/blob/master/docs/index.html This comprehensive example combines all previous concepts to create a basic physics simulation. It initializes a CANNON.World with gravity, creates a dynamic sphere body that falls, and a static ground plane for it to collide with. The animate function continuously steps the simulation forward using world.fixedStep() and logs the sphere's Y-position, demonstrating the falling behavior. ```JavaScript import * as CANNON from 'cannon-es' // Setup our physics world const world = new CANNON.World({ gravity: new CANNON.Vec3(0, -9.82, 0), // m/s² }) // Create a sphere body const radius = 1 // m const sphereBody = new CANNON.Body({ mass: 5, // kg shape: new CANNON.Sphere(radius), }) sphereBody.position.set(0, 10, 0) // m world.addBody(sphereBody) // Create a static plane for the ground const groundBody = new CANNON.Body({ type: CANNON.Body.STATIC, // can also be achieved by setting the mass to 0 shape: new CANNON.Plane(), }) groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up world.addBody(groundBody) // Start the simulation loop function animate() { requestAnimationFrame(animate) world.fixedStep() // the sphere y position shows the sphere falling console.log(`Sphere y position: ${sphereBody.position.y}`) } animate() ``` -------------------------------- ### Starting the CANNON.js Demo Simulation - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/convex.html Initiates the CANNON.js physics simulation and rendering loop. This call begins the execution of the defined scenes and allows the physics world to update and render. ```JavaScript demo.start() ``` -------------------------------- ### Starting Demo Simulation - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/single_body_on_plane.html This line initiates the physics simulation and rendering loop managed by the 'Demo' instance, allowing the created bodies to interact within the physics world. ```JavaScript demo.start() ``` -------------------------------- ### Starting the CANNON.js Demo Simulation Source: https://github.com/pmndrs/cannon-es/blob/master/examples/shapes.html This line initiates the CANNON.js simulation and visualization loop. It begins the rendering and physics updates, allowing the created bodies to interact within the defined world. ```JavaScript demo.start() ``` -------------------------------- ### Initializing Application Components - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs_voxel_fps.html Calls the main initialization functions for Three.js rendering, Cannon.js physics, and PointerLock controls, then starts the animation loop. ```javascript initThree() initCannon() initPointerLock() animate() ``` -------------------------------- ### Styling Instructions Overlay (CSS) Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs_fps.html Defines the CSS styles for the instructions overlay, positioning it centrally, making it full screen, and styling its text content. This overlay is designed to be clickable to start the game. ```CSS #instructions { position: fixed; left: 0; top: 0; width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; background-color: rgba(0, 0, 0, 0.5); color: #ffffff; text-align: center; cursor: pointer; } #instructions span { font-size: 40px; } ``` -------------------------------- ### Starting the Cannon.js Physics Demo (JavaScript) Source: https://github.com/pmndrs/cannon-es/blob/master/examples/ragdoll.html Initiates the Cannon.js physics demonstration, beginning the simulation and rendering of the defined scenes. This function call is essential to run the physics world. ```JavaScript demo.start() ``` -------------------------------- ### Installing cannon-es with Yarn Source: https://github.com/pmndrs/cannon-es/blob/master/readme.md This snippet demonstrates the command-line instruction to add the cannon-es library to your project using the Yarn package manager. This is the recommended way to install the library for development. ```Shell yarn add cannon-es ``` -------------------------------- ### Starting the CANNON.js Simulation Demo Source: https://github.com/pmndrs/cannon-es/blob/master/examples/collision_filter.html This final line initiates the CANNON.js demo, starting the physics simulation and rendering loop. This function typically sets up event listeners and begins the animation frame updates. ```JavaScript demo.start() ``` -------------------------------- ### Calling Main Initialization Functions (JavaScript) Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs_fps.html Initiates the Three.js rendering environment, the Cannon.js physics world, the pointer lock controls for user input, and starts the animation loop for the game. ```JavaScript initThree() initCannon() initPointerLock() animate() ``` -------------------------------- ### Importing CANNON.js and Demo Module - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/single_body_on_plane.html This snippet imports the necessary modules: the core CANNON.js library for physics simulations and a 'Demo' utility class, likely used for scene management and visualization in the example. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' ``` -------------------------------- ### Initializing a Ray Instance in cannon-es Source: https://github.com/pmndrs/cannon-es/blob/master/docs/classes/Ray.html Demonstrates how to create a new Ray object, optionally specifying its starting and ending points in 3D space. This allows for defining the ray's path for subsequent intersection tests. ```TypeScript import { Ray, Vec3 } from 'cannon-es'; // Create a ray from (0,0,0) to (10,0,0) const from = new Vec3(0, 0, 0); const to = new Vec3(10, 0, 0); const ray = new Ray(from, to); // Or create an empty ray and set properties later const emptyRay = new Ray(); emptyRay.from.set(0, 0, 0); emptyRay.to.set(0, 0, 10); ``` -------------------------------- ### Setting Up Physics World with Gravity and Ground Plane - Cannon-ES JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/trimesh.html The `setupWorld` function configures the Cannon-ES physics environment. It sets a downward gravity, adjusts default contact material properties for stiffness and relaxation, and creates a static ground plane. This function is designed to be reusable for scenes requiring a standard physics setup. ```JavaScript function setupWorld(demo) { const world = demo.getWorld() world.gravity.set(0, -10, 0) // Tweak contact properties. // Contact stiffness - use to make softer/harder contacts world.defaultContactMaterial.contactEquationStiffness = 1e7 // Stabilization time in number of timesteps world.defaultContactMaterial.contactEquationRelaxation = 4 // Static ground plane const groundShape = new CANNON.Plane() const groundBody = new CANNON.Body({ mass: 0 }) groundBody.addShape(groundShape) groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) world.addBody(groundBody) demo.addVisual(groundBody) return world } ``` -------------------------------- ### Initializing Three.js Renderer, Stats, and OrbitControls - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/worker.html This snippet initializes the Three.js renderer's DOM element, appends a Stats.js instance for performance monitoring, and sets up OrbitControls for camera interaction. It configures damping, disables panning, and defines min/max zoom distances for the camera. ```JavaScript cument.body.appendChild(renderer.domElement); // Stats.js stats = new Stats(); document.body.appendChild(stats.dom); // Orbit controls controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.enablePan = false; controls.dampingFactor = 0.3; controls.minDistance = 10; controls.maxDistance = 500; ``` -------------------------------- ### Initializing Cannon.js Physics World and Body - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs.html This function initializes the Cannon.js physics world and creates a dynamic rigid body with a box shape. It sets the body's mass, adds the shape, applies an initial angular velocity, and configures angular damping before adding it to the physics world for simulation. ```JavaScript function initCannon() { world = new CANNON.World() // Box const shape = new CANNON.Box(new CANNON.Vec3(1, 1, 1)) body = new CANNON.Body({ mass: 1, }) body.addShape(shape) body.angularVelocity.set(0, 10, 0) body.angularDamping = 0.5 world.addBody(body) } ``` -------------------------------- ### Initializing Cannon.js Demo Scenes with SplitSolver Comparison Source: https://github.com/pmndrs/cannon-es/blob/master/examples/split_solver.html This snippet initializes the Cannon.js demo environment and registers two distinct scenes. One scene is configured to use the SplitSolver for physics calculations, while the other uses a standard solver, enabling a direct comparison of their performance and stability characteristics. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() demo.addScene('With SplitSolver', () => { createScene({ split: true }) }) demo.addScene('Without SplitSolver', () => { createScene({ split: false }) }) demo.start() ``` -------------------------------- ### Initializing Physics World with Gravity - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This snippet demonstrates how to create a new physics world instance using `CANNON.World`. It initializes the world with a specific gravity vector, set to Earth's gravity (-9.82 m/s² on the Y-axis), emphasizing the use of SI units. ```JavaScript const world = new CANNON.World({ gravity: new CANNON.Vec3(0, -9.82, 0), // m/s² }) ``` -------------------------------- ### Configuring Physics World Properties in cannon-es Source: https://github.com/pmndrs/cannon-es/blob/master/examples/sph.html This function `setupWorld` configures global properties for the cannon-es physics world. It sets the gravitational force, adjusts the stiffness and relaxation of default contact materials to control collision behavior, and specifies the number of solver iterations for improved simulation accuracy. This setup is crucial for the stability and realism of the physics simulation. ```JavaScript function setupWorld(demo) { const world = demo.getWorld() world.gravity.set(0, -10, 0) world.defaultContactMaterial.contactEquationStiffness = 1e11 world.defaultContactMaterial.contactEquationRelaxation = 2 world.solver.iterations = 10 return world } ``` -------------------------------- ### Initializing Three.js Scene (JavaScript) Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs_fps.html Sets up the Three.js rendering environment, including camera, scene, WebGL renderer, performance stats, ambient and spotlight lighting, and a generic material. It also creates a floor plane and attaches a window resize listener. ```JavaScript function initThree() { // Camera camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) // Scene scene = new THREE.Scene() scene.fog = new THREE.Fog(0x000000, 0, 500) // Renderer renderer = new THREE.WebGLRenderer({ antialias: true }) renderer.setSize(window.innerWidth, window.innerHeight) renderer.setClearColor(scene.fog.color) renderer.shadowMap.enabled = true renderer.shadowMap.type = THREE.PCFSoftShadowMap document.body.appendChild(renderer.domElement) // Stats.js stats = new Stats() document.body.appendChild(stats.dom) // Lights const ambientLight = new THREE.AmbientLight(0xffffff, 0.1) scene.add(ambientLight) const spotlight = new THREE.SpotLight(0xffffff, 0.9, 0, Math.PI / 4, 1) spotlight.position.set(10, 30, 20) spotlight.target.position.set(0, 0, 0) spotlight.castShadow = true spotlight.shadow.camera.near = 10 spotlight.shadow.camera.far = 100 spotlight.shadow.camera.fov = 30 // spotlight.shadow.bias = -0.0001 spotlight.shadow.mapSize.width = 2048 spotlight.shadow.mapSize.height = 2048 scene.add(spotlight) // Generic material material = new THREE.MeshLambertMaterial({ color: 0xdddddd }) // Floor const floorGeometry = new THREE.PlaneBufferGeometry(300, 300, 100, 100) floorGeometry.rotateX(-Math.PI / 2) const floor = new THREE.Mesh(floorGeometry, material) floor.receiveShadow = true scene.add(floor) window.addEventListener('resize', onWindowResize) } ``` -------------------------------- ### Initializing Cannon.js and Demo Environment - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/friction_gravity.html This snippet imports the necessary Cannon.js library and a custom Demo utility, then initializes the Demo instance and declares variables for physics bodies. It sets up the basic environment for the physics simulation. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() let boxBody1 let boxBody2 ``` -------------------------------- ### Initializing Three.js Scene and Objects Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs_mousepick.html Sets up the Three.js environment, including camera, scene, WebGL renderer, lights, a static floor, a visual click marker, a draggable cube mesh, and a movement plane used during dragging. It also attaches a window resize listener. ```JavaScript function initThree() { // Camera camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 0.5, 1000) camera.position.set(0, 2, 10) // Scene scene = new THREE.Scene() scene.fog = new THREE.Fog(0x000000, 500, 1000) // Renderer renderer = new THREE.WebGLRenderer({ antialias: true }) renderer.setSize(window.innerWidth, window.innerHeight) renderer.setClearColor(scene.fog.color) renderer.outputEncoding = THREE.sRGBEncoding renderer.shadowMap.enabled = true renderer.shadowMap.type = THREE.PCFSoftShadowMap document.body.appendChild(renderer.domElement) // Stats.js stats = new Stats() document.body.appendChild(stats.dom) // Lights const ambientLight = new THREE.AmbientLight(0x666666) scene.add(ambientLight) const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2) const distance = 20 directionalLight.position.set(-distance, distance, distance) directionalLight.castShadow = true directionalLight.shadow.mapSize.width = 2048 directionalLight.shadow.mapSize.height = 2048 directionalLight.shadow.camera.left = -distance directionalLight.shadow.camera.right = distance directionalLight.shadow.camera.top = distance directionalLight.shadow.camera.bottom = -distance directionalLight.shadow.camera.far = 3 * distance directionalLight.shadow.camera.near = distance scene.add(directionalLight) // Raycaster for mouse interaction raycaster = new THREE.Raycaster() // Floor const floorGeometry = new THREE.PlaneBufferGeometry(100, 100, 1, 1) floorGeometry.rotateX(-Math.PI / 2) const floorMaterial = new THREE.MeshLambertMaterial({ color: 0x777777 }) const floor = new THREE.Mesh(floorGeometry, floorMaterial) floor.receiveShadow = true scene.add(floor) // Click marker to be shown on interaction const markerGeometry = new THREE.SphereBufferGeometry(0.2, 8, 8) const markerMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 }) clickMarker = new THREE.Mesh(markerGeometry, markerMaterial) clickMarker.visible = false // Hide it.. scene.add(clickMarker) // Cube const cubeGeometry = new THREE.BoxBufferGeometry(1, 1, 1, 10, 10) const cubeMaterial = new THREE.MeshPhongMaterial({ color: 0x999999 }) cubeMesh = new THREE.Mesh(cubeGeometry, cubeMaterial) cubeMesh.castShadow = true meshes.push(cubeMesh) scene.add(cubeMesh) // Movement plane when dragging const planeGeometry = new THREE.PlaneBufferGeometry(100, 100) movementPlane = new THREE.Mesh(planeGeometry, floorMaterial) movementPlane.visible = false // Hide it.. scene.add(movementPlane) window.addEventListener('resize', onWindowResize) } ``` -------------------------------- ### Synchronizing Three.js Mesh with Cannon.js Body in Animation Loop Source: https://github.com/pmndrs/cannon-es/blob/master/getting-started.md This `animate` function is the core of the Three.js rendering loop, responsible for continuously updating the scene. It copies the position and quaternion (rotation) data from a `cannon-es` physics body (`sphereBody`) to its corresponding `three.js` mesh (`sphereMesh`) each frame, ensuring the visual representation matches the physics simulation. This function should be called after the physics world has been stepped. ```javascript function animate() { requestAnimationFrame(animate) // world stepping... sphereMesh.position.copy(sphereBody.position) sphereMesh.quaternion.copy(sphereBody.quaternion) // three.js render... } animate() ``` -------------------------------- ### Initializing CANNON.js Worker and Handling Main Thread Messages - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/worker_sharedarraybuffer.html This snippet initializes the CANNON.js physics world within a web worker. It sets up gravity and solver tolerance. It then listens for 'message' events from the main thread, parsing serialized Three.js geometries and setting up SharedArrayBuffers for positions and quaternions. It creates CANNON.js bodies from the received geometries and adds them to the world, finally starting the physics update loop. ```JavaScript import { addTitle, addSourceButton } from './js/dom-utils.js' addTitle() addSourceButton() import * as CANNON from '../dist/cannon-es.js' import * as THREE from 'https://unpkg.com/three@0.122.0/build/three.module.js' import { geometryToShape } from './js/three-conversion-utils.js' const timeStep = 1 / 60 // The bodies passed down from three.js const bodies = [] let positions let quaternions // Setup world const world = new CANNON.World() world.gravity.set(0, -10, 0) world.solver.tolerance = 0.001 // Ground plane const groundShape = new CANNON.Plane() const groundBody = new CANNON.Body({ mass: 0 }) groundBody.addShape(groundShape) groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) world.addBody(groundBody) // When we get the init message self.addEventListener('message', (event) => { const { geometries: geometriesSerialized, positionsSharedBuffer, quaternionsSharedBuffer } = event.data // Parse the serialized geometries received from // the main thread const unserialized = new THREE.ObjectLoader().parseGeometries(geometriesSerialized) const geometries = geometriesSerialized.map(g => unserialized[g.uuid]) // Save the reference to the SharedArrayBuffer positions = new Float32Array(positionsSharedBuffer) quaternions = new Float32Array(quaternionsSharedBuffer) // Create the bodies from the three.js geometries for (let i = 0; i < geometries.length; i++) { const geometry = geometries[i] const shape = geometryToShape(geometry) const body = new CANNON.Body({ mass: 1 }) body.addShape(shape) body.position.set(positions[i * 3 + 0], positions[i * 3 + 1], positions[i * 3 + 2]) body.quaternion.set( quaternions[i * 4 + 0], quaternions[i * 4 + 1], quaternions[i * 4 + 2], quaternions[i * 4 + 3] ) bodies.push(body) world.addBody(body) } // Start the loop setInterval(update, timeStep * 1000) }) ``` -------------------------------- ### Setting Up Physics World in CANNON.js (JavaScript) Source: https://github.com/pmndrs/cannon-es/blob/master/examples/impulses.html This helper function initializes and returns the CANNON.js physics world instance used across all demonstration scenes. It retrieves the world from the `Demo` object, ensuring a consistent physics environment for all simulations. ```JavaScript function setupWorld(demo) { const world = demo.getWorld() return world } ``` -------------------------------- ### Initializing Cannon.js Worker with SharedArrayBuffers in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/worker_sharedarraybuffer.html This function sets up a Web Worker for Cannon.js physics simulation, leveraging `SharedArrayBuffer`s for efficient data transfer between the main thread and the worker. It initializes buffers for mesh positions and quaternions, copies initial mesh data, dynamically loads and modifies worker script content, and then creates and communicates with the worker, sending initial geometry and buffer data for physics body setup. ```JavaScript function initCannonWorker() { // Initialize the SharedArrayBuffers. // SharedArrayBuffers are shared between the main // and worker thread. Cannon.js will update the data while // three.js will read from them. const positionsSharedBuffer = new SharedArrayBuffer(meshes.length * 3 * Float32Array.BYTES_PER_ELEMENT) const quaternionsSharedBuffer = new SharedArrayBuffer(meshes.length * 4 * Float32Array.BYTES_PER_ELEMENT) positions = new Float32Array(positionsSharedBuffer) quaternions = new Float32Array(quaternionsSharedBuffer) // Copy the initial meshes data into the buffers for (let i = 0; i < meshes.length; i++) { const mesh = meshes[i] positions[i * 3 + 0] = mesh.position.x positions[i * 3 + 1] = mesh.position.y positions[i * 3 + 2] = mesh.position.z quaternions[i * 4 + 0] = mesh.quaternion.x quaternions[i * 4 + 1] = mesh.quaternion.y quaternions[i * 4 + 2] = mesh.quaternion.z quaternions[i * 4 + 3] = mesh.quaternion.w } // Get the worker code let workerScript = document.querySelector('#worker1').textContent // BUG Relative urls don't currently work in an inline // module worker in Chrome // https://bugs.chromium.org/p/chromium/issues/detail?id=1161710 const href = window.location.href.replace('/examples/worker_sharedarraybuffer', '') workerScript = workerScript .replace(/from '\.\.\//g, `from '${href}/`) .replace(/from '\.\//g, `from '${href}/examples/`) // Create a blob for the inline worker code const blob = new Blob([workerScript], { type: 'text/javascript' }) // Create worker const worker = new Worker(window.URL.createObjectURL(blob), { type: 'module' }) worker.addEventListener('message', (event) => { console.log('Message from worker', event.data) }) worker.addEventListener('error', (event) => { console.error('Error in worker', event.message) }) // Send the geometry data to setup the cannon.js bodies // and the initial position and rotation data worker.postMessage({ // serialize the geometries as json to pass // them to the worker geometries: meshes.map((m) => m.geometry.toJSON()), positionsSharedBuffer, quaternionsSharedBuffer, }) } ``` -------------------------------- ### Initializing Cannon.js and Demo in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/performance.html This snippet imports the `cannon-es` physics engine and a custom `Demo` utility class, then initializes an instance of the `Demo` class. These are essential prerequisites for setting up and running physics simulations and visualizations. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() ``` -------------------------------- ### Initializing CANNON.js Demo Environment and Imports Source: https://github.com/pmndrs/cannon-es/blob/master/examples/collision_filter.html This snippet imports the necessary CANNON.js library and the custom `Demo` class, then initializes a new demo instance. The `Demo` class provides a framework for setting up and running physics simulations with visual representations. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() ``` -------------------------------- ### Setting Up Cannon.js Physics World in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/bounce.html This helper function, `setupWorld`, retrieves the physics world instance from the provided `demo` object. It then configures the world's gravity, setting it to -10 along the Y-axis, simulating a downward pull, and returns the initialized world object. ```JavaScript function setupWorld(demo) { const world = demo.getWorld() world.gravity.set(0, -10, 0) return world } ``` -------------------------------- ### Initializing Three.js Scene and Renderer - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/threejs_voxel_fps.html Sets up the Three.js camera, scene with fog, WebGL renderer with shadow mapping, and appends it to the document. It also adds performance stats, ambient and spotlight, a generic material, and a floor plane, along with a window resize listener. ```javascript function initThree() { // Camera camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) // Scene scene = new THREE.Scene() scene.fog = new THREE.Fog(0x000000, 0, 500) // Renderer renderer = new THREE.WebGLRenderer({ antialias: true }) renderer.setSize(window.innerWidth, window.innerHeight) renderer.setClearColor(scene.fog.color) renderer.shadowMap.enabled = true renderer.shadowMap.type = THREE.PCFSoftShadowMap document.body.appendChild(renderer.domElement) // Stats.js stats = new Stats() document.body.appendChild(stats.dom) // Lights const ambientLight = new THREE.AmbientLight(0xffffff, 0.1) scene.add(ambientLight) const spotlight = new THREE.SpotLight(0xffffff, 0.7, 0, Math.PI / 4, 1) spotlight.position.set(10, 30, 20) spotlight.target.position.set(0, 0, 0) spotlight.castShadow = true spotlight.shadow.camera.near = 20 spotlight.shadow.camera.far = 50 spotlight.shadow.camera.fov = 40 spotlight.shadow.bias = -0.001 spotlight.shadow.mapSize.width = 2048 spotlight.shadow.mapSize.height = 2048 scene.add(spotlight) // Generic material material = new THREE.MeshLambertMaterial({ color: 0xdddddd }) // Floor const floorGeometry = new THREE.PlaneBufferGeometry(300, 300, 50, 50) floorGeometry.rotateX(-Math.PI / 2) floor = new THREE.Mesh(floorGeometry, material) floor.receiveShadow = true scene.add(floor) window.addEventListener('resize', onWindowResize) } ``` -------------------------------- ### Importing CANNON.js and Initializing Demo Source: https://github.com/pmndrs/cannon-es/blob/master/examples/simple_friction.html This snippet imports the CANNON.js physics library and a custom `Demo` utility class. It then initializes an instance of the `Demo` class, which is used to set up and manage the physics scenes. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() ``` -------------------------------- ### Initializing CANNON.js Demo Environment - JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/convex.html Imports necessary modules for the CANNON.js physics engine and initializes the `Demo` class, which provides the environment for setting up and running physics simulations. This is a prerequisite for all subsequent scene definitions. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() ``` -------------------------------- ### Getting Inverse Quaternion Rotation in cannon-es (TypeScript) Source: https://github.com/pmndrs/cannon-es/blob/master/docs/classes/Quaternion.html Computes the inverse of the quaternion. The inverse of a unit quaternion is its conjugate. If a target quaternion is provided, the result is stored there; otherwise, a new quaternion is returned. ```TypeScript inverse(target?: Quaternion): Quaternion ``` -------------------------------- ### Initializing Cannon.js and Demo Scene Source: https://github.com/pmndrs/cannon-es/blob/master/examples/rigid_vehicle.html This snippet sets up the basic environment for a Cannon.js simulation using a custom 'Demo' class. It imports necessary modules and defines the main scene where the car simulation will take place. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() demo.addScene('Car', () => { /* ... scene content ... */ }) demo.start() ``` -------------------------------- ### Initializing Trimesh Scene with Sphere and Torus - Cannon-ES JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/trimesh.html This snippet defines a 'Trimesh' scene, which first calls `setupWorld` to configure the physics environment. It then creates a dynamic sphere body and a static Trimesh torus body, adding both to the world. The torus is positioned and oriented to demonstrate collision detection with the falling sphere. ```JavaScript demo.addScene('Trimesh', () => { const world = setupWorld(demo) // Sphere const sphereShape = new CANNON.Sphere(1) const sphereBody = new CANNON.Body({ mass: 1, shape: sphereShape, position: new CANNON.Vec3(-3, 11, 3), }) world.addBody(sphereBody) demo.addVisual(sphereBody) // Torus const torusShape = CANNON.Trimesh.createTorus(4, 3.5, 16, 16) const torusBody = new CANNON.Body({ mass: 1 }) torusBody.addShape(torusShape) torusBody.position.set(0, 4, 0) torusBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) torusBody.velocity.set(0, 1, 1) world.addBody(torusBody) demo.addVisual(torusBody) }) ``` -------------------------------- ### Importing Cannon.js and Initializing Demo in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/pile.html This snippet imports the necessary Cannon.js library and a local `Demo` utility, then initializes an instance of the `Demo` class to set up the simulation environment. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() ``` -------------------------------- ### Initializing CANNON.js and Demo Environment in JavaScript Source: https://github.com/pmndrs/cannon-es/blob/master/examples/shapes.html This snippet imports the CANNON.js library and a custom `Demo` class, then initializes a new `Demo` instance. It sets up the basic environment for creating and visualizing physics simulations. ```JavaScript import * as CANNON from '../dist/cannon-es.js' import { Demo } from './js/Demo.js' const demo = new Demo() ``` -------------------------------- ### Initializing Documentation Theme (JavaScript) Source: https://github.com/pmndrs/cannon-es/blob/master/docs/classes/Shape.html This JavaScript snippet sets the initial theme for the documentation page. It attempts to retrieve a saved theme from `localStorage` using the key 'tsd-theme' and falls back to 'os' (operating system default) if no theme is found, applying the chosen theme as a class to the `body` element. ```JavaScript document.body.classList.add(localStorage.getItem("tsd-theme") || "os") ``` -------------------------------- ### Calculating Volume of Box Shape (TypeScript) Source: https://github.com/pmndrs/cannon-es/blob/master/docs/classes/Box.html This method calculates and returns the volume of the box shape. It provides a direct way to get the physical volume of the box. This method overrides the base `Shape.volume` method. ```TypeScript volume(): number ``` -------------------------------- ### Setting Up Sphere-Particle Collision Scene in CANNON.js Source: https://github.com/pmndrs/cannon-es/blob/master/examples/stacks.html This scene demonstrates the interaction between a sphere and a massless `CANNON.Particle`. It creates a `CANNON.Sphere` and a `CANNON.Particle` body, positions them, adds them to the physics world, and registers them for visualization to observe their collision behavior. ```JavaScript demo.addScene('sphere/particle', () => { const world = setupWorld(demo) // Sphere const sphereShape = new CANNON.Sphere(size * 0.5) const body = new CANNON.Body({ mass }) body.addShape(sphereShape) body.position.set(0, size, 0) world.addBody(body) demo.addVisual(body) // Particle const particle = new CANNON.Body({ mass: 1 }) particle.addShape(new CANNON.Particle()) particle.position.set(-0.02, size * 3, 0) world.addBody(particle) demo.addVisual(particle) }) ``` -------------------------------- ### Getting Vector Length - Vec3 Method - TypeScript Source: https://github.com/pmndrs/cannon-es/blob/master/docs/classes/Vec3.html Retrieves the magnitude (length) of the current Vec3 instance. This is the square root of the sum of the squares of its components. This method does not take any parameters and returns a number representing the vector's length. ```TypeScript length(): number ```