phpmath / quaternion
A PHP library to work with immutable quaternions for 3D rotations.
Requires
- php: ^8.4
Requires (Dev)
- phpmath/coding-standard: ^2.0
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-24 12:59:47 UTC
README
A PHP library to work with immutable quaternions for 3D rotations.
Documentation
The full documentation is at https://phpmath.github.io/quaternion/. Every change is listed in the changelog and every release on the releases page.
Install
composer require phpmath/quaternion
Requirements
- PHP 8.4 or newer
Usage
Vectors and matrices are plain float arrays:
a vector is [x, y, z] and a matrix is a list of three rows of three floats.
Every quaternion is an immutable value object. Operations never change the instance they are called on, they return a new instance.
use PHPMath\Quaternion\Quaternion; // Rotate 90 degrees around the Z axis. $rotation = Quaternion::fromAxisAngle([0.0, 0.0, 1.0], M_PI / 2); $rotation->rotate([1.0, 0.0, 0.0]); // [0.0, 1.0, 0.0] (within floating point precision) $rotation->toRotationMatrix(); // [[0, -1, 0], [1, 0, 0], [0, 0, 1]] // Combine rotations with the Hamilton product: the right-hand side is applied first. $combined = $rotation->multiply(Quaternion::fromAxisAngle([1.0, 0.0, 0.0], M_PI / 2)); // Interpolate along the shortest arc. $halfway = Quaternion::identity()->slerp($rotation, 0.5); echo $rotation; // 0.70710678118655 + 0i + 0j + 0.70710678118655k
Conventions
- Right-handed coordinates and the Hamilton convention (
ij = k). Positive angles rotate counter-clockwise when looking along the axis towards the origin. fromEuler($yaw, $pitch, $roll)uses intrinsic Z-Y'-X'' (aerospace) angles in radians: yaw about Z, pitch about Y, roll about X. It equalsqz(yaw) * qy(pitch) * qx(roll).rotate(),toRotationMatrix()andslerp()normalize their input, so they accept non-unit quaternions. They throw aZeroQuaternionExceptionfor the zero quaternion.equals()compares components with an absolute tolerance (default1e-9).qand-qare the same rotation but are not equal, useisSameRotation()to compare rotations.
Features
- Creation with
of(),identity(),fromAxisAngle(),fromAxisComponents()andfromEuler(). - Arithmetic:
add(),subtract(),multiply(),scale(),conjugate()andinverse(). norm(),normalize()anddot().rotate(),toRotationMatrix()andslerp().equals(),isSameRotation()and__toString().
Development
composer test
composer test-coverage
composer analyse
composer check-style
composer fix-style
Contributing
All contributions are welcome. Open an issue or a pull request on GitHub. Please follow the coding standard and add tests.
Security
If you discover a security issue, please create an issue in the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.