npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@fred3d/physics

v0.0.2

Published

A robust, type-safe abstraction layer for integrating multiple physics engines in the Fred3D framework.

Downloads

9

Readme

Physics Abstraction Layer

A robust, type-safe abstraction layer for integrating multiple physics engines in the Fred3D framework.

Features

  • Type-safe interfaces for physics interactions
  • Support for multiple physics engines (Ammo.js and Cannon.js)
  • Event-based collision and trigger detection
  • Comprehensive error handling with detailed error codes
  • Runtime type validation for physics configurations

Usage

Basic Setup

import { createPhysicsEngine, PhysicsEngineType } from '@fred3d/physics';

// Create a physics engine instance (Ammo.js or Cannon.js)
const physics = await createPhysicsEngine({
  type: PhysicsEngineType.AMMO,
  gravity: new Vector3(0, -9.81, 0)
});

// Initialize the physics world
await physics.init();

// Start simulation
physics.start();

Working with Rigid Bodies

// Create a rigid body
const bodyConfig = {
  type: RigidBodyType.DYNAMIC,
  mass: 1.0,
  position: new Vector3(0, 5, 0)
};

const rigidBody = physics.createRigidBody(bodyConfig);

// Add a collider to the rigid body
const colliderConfig = {
  type: ColliderShapeType.BOX,
  size: new Vector3(1, 1, 1)
};

const collider = physics.createCollider(rigidBody, colliderConfig);

// Apply forces and impulses
rigidBody.applyForce(new Vector3(0, 0, 10));
rigidBody.applyImpulse(new Vector3(5, 0, 0));

Collision Events

// Listen for collision events
physics.on(PhysicsEventType.COLLISION_BEGIN, (data) => {
  const { bodyA, bodyB, contacts } = data;
  console.debug(`Collision between ${bodyA.id} and ${bodyB.id}`);
  console.debug(`Contact point: ${contacts[0].point}`);
});

// Listen for trigger events
physics.on(PhysicsEventType.TRIGGER_ENTER, (data) => {
  const { trigger, body } = data;
  console.debug(`Body ${body.id} entered trigger ${trigger.id}`);
});

Advanced Features

Feature Detection

// Check if a specific feature is supported
if (physics.isFeatureSupported(PhysicsFeature.SOFT_BODIES)) {
  // Use soft body functionality
}

// Get information about the engine
const info = physics.getEngineInfo();
console.debug(`Using ${info.name} version ${info.version}`);

Joint Constraints

// Create a hinge joint between two bodies
const jointConfig = {
  type: JointType.HINGE,
  bodyA: bodyA,
  bodyB: bodyB,
  pivotA: new Vector3(0, 1, 0),
  pivotB: new Vector3(0, -1, 0),
  axisA: new Vector3(0, 0, 1),
  axisB: new Vector3(0, 0, 1)
};

const joint = physics.createJoint(jointConfig);

Optional Tools Module

The physics package includes an optional tools module that provides higher-level utilities for working with physics objects:

import { Tools } from '@fred3d/physics';

// Access the tools
const { PhysicsObjectFactory, PhysicsObjectManager, PhysicsMaterialLibrary } = Tools;

// Create a physics object factory
const factory = new PhysicsObjectFactory(physics);

// Create a box with predefined material
const boxObject = factory.createBox(
  new Vector3(0, 5, 0),       // position
  new Vector3(1, 1, 1),       // size
  RigidBodyType.DYNAMIC,      // body type
  Tools.SurfaceType.WOOD      // material
);

// Create a physics object manager
const manager = new PhysicsObjectManager(physics, physics.getWorld(), scene);

// Add the box to the manager
const boxId = manager.addObject(boxObject, boxMesh, 'box_01', 'dynamic_objects').id;

// In your game loop
function gameLoop() {
  physics.getWorld().step(1/60);
  manager.updateTransforms(); // Updates all object transforms
  requestAnimationFrame(gameLoop);
}

See the Tools Module Documentation for more details.

Type Guards

For runtime validation, the package provides a set of type guards:

import { isValidRigidBodyConfig, isValidColliderConfig } from '@fred3d/physics';

// Validate user input
function createBodyFromUserInput(input: unknown) {
  if (isValidRigidBodyConfig(input)) {
    // Input is valid, safe to use
    return physics.createRigidBody(input);
  } else {
    throw new Error('Invalid rigid body configuration');
  }
}

Error Codes Reference

The physics package uses a standardized error code system for better debugging and error handling.

| Error Code | Error Type | Description | |------------|------------|-------------| | PE000 | PhysicsError | Generic physics error | | PE001 | PhysicsInitializationError | Failed to initialize physics engine | | PE002 | PhysicsConfigurationError | Invalid configuration provided | | PE003 | PhysicsNotInitializedError | Operation attempted before initialization | | PE004 | PhysicsUnsupportedOperationError | Attempted to use unsupported feature | | PE005 | PhysicsInvalidParameterError | Invalid parameter provided to method | | PE006 | PhysicsNotFoundError | Required object not found |

Error Handling Example

try {
  // Physics operation that might fail
  physics.createRigidBody(config);
} catch (error) {
  if (error instanceof PhysicsConfigurationError) {
    console.error(`Configuration error (${error.code}): ${error.message}`);
  } else if (error instanceof PhysicsError) {
    console.error(`Physics error (${error.code}): ${error.message}`);
  } else {
    throw error; // Re-throw unknown errors
  }
}

API Reference

For complete API documentation, see the API Reference generated with TypeDoc.

Testing

Run tests with:

# Run all tests
npm test

# Run tests with coverage report
npm run test:coverage

# Run tests in watch mode during development
npm run test:watch

License

This package is part of the Fred3D framework and is covered by the same license.