Skip to content

Repository files navigation

OpenSpatial

License CI codecov

Open-source implementation inspired by Apple's Spatial framework. OpenSpatial is not affiliated with, endorsed by, or maintained by Apple.

Overview

The OpenSpatial module is a lightweight 3D mathematical library that provides a simple API for working with 3D primitives. The API surface mirrors Apple's Spatial framework as closely as possible, so code written against OpenSpatial can be migrated to the official framework with minimal changes.

Goals

OpenSpatial aims to:

  • Provide a fully open-source implementation of common spatial mathematics primitives.
  • Remain API-compatible with Apple's Spatial framework whenever practical.
  • Support Apple and non-Apple platforms equally.
  • Serve as a foundation for graphics, simulation, robotics, game development, and spatial computing projects.

Features

  • Pure Swift 6, no platform-specific dependencies
  • Full Sendable conformance for safe use in Swift Concurrency contexts
  • Codable, Hashable, and Equatable on all value types
  • @frozen structs where applicable for ABI stability
  • Generic arithmetic operators and protocol-driven design (Rotatable3D, Translatable3D, Scalable3D, …)

Available Types

2D Primitives

Type Description
Angle2D A geometric angle

3D Primitives

Type Description
Point3D A point in 3D space
Size3D A 3D size with width, height, and depth
Rect3D An axis-aligned 3D bounding box
Pose3D A combined position and orientation
ScaledPose3D A pose extended with a uniform scale factor
Ray3D An origin and direction defining a ray
Rotation3D A rotation in 3D space (quaternion-backed)
RotationAxis3D A named axis for rotation
Quaternion3D A quaternion for representing rotations
SphericalCoordinates3D A point in spherical coordinates

Transforms

Type Description
AffineTransform3D A 4×4 affine transform (translation, rotation, scale, shear)
ProjectiveTransform3D A full 4×4 projective transform

Coordinate Spaces

Type Description
CoordinateSpace3D A named 3D coordinate space
CoordinateSpaceValue3D A value associated with a coordinate space
WorldReferenceCoordinateSpace The world reference coordinate space

Data Structures & Protocols

Type Description
Vector3D A 3D vector
Axis3D A named axis (x, y, z)
EulerAngles Euler angle representation of a rotation
Primitive3D Protocol for all 3D primitives
Rotatable3D Protocol for types that support rotation
Translatable3D Protocol for types that support translation
Scalable3D Protocol for types that support scaling
Shearable3D Protocol for types that support shearing
Clampable3D Protocol for types that can be clamped to a Rect3D
Volumetric Protocol for types with a volumetric extent

Usage

Working with Points

import OpenSpatial

let origin = Point3D(x: 0, y: 0, z: 0)
let target = Point3D(x: 3, y: 4, z: 0)

let distance = origin.distance(to: target)  // 5.0

let moved = origin.translated(by: Vector3D(x: 1, y: 2, z: 3))
let scaled = origin.uniformlyScaled(by: 2.0)

Working with Rotations and Poses

let rotation = Rotation3D(angle: Angle2D(radians: .pi / 4), axis: RotationAxis3D(x: 0, y: 1, z: 0))
let pose = Pose3D(position: Point3D(x: 1, y: 0, z: 0), rotation: rotation)

let rotatedPoint = Point3D(x: 1, y: 0, z: 0).rotated(by: rotation.quaternion)
let invertedPose = pose.inverse

Applying Transforms

var transform = AffineTransform3D.identity
transform = transform.concatenating(.init(translation: Vector3D(x: 5, y: 0, z: 0)))

let transformedPoint = point.applying(transform)

Working with Rectangles

Rect3D also works for flat (2D) rectangles: keep z and depth at 0.

let plane = Rect3D(origin: .zero, size: Size3D(width: 10, height: 5, depth: 0))
plane.isEmpty   // false: a rectangle is empty only when two or more dimensions are zero

// Transforming a rectangle returns the bounding box of its transformed corners.
let rotation = AffineTransform3D(rotation: Rotation3D(angle: .degrees(90), axis: .z))
let rotated = plane.applying(rotation)   // x: -5...0, y: 0...10

// `Rect3D.null` represents "no rectangle" and is the neutral element of `union`.
var bounds = Rect3D.null
for point in [Point3D(x: 1, y: 2), Point3D(x: 4, y: -1), Point3D(x: 3, y: 5)] {
    bounds = bounds.union(Rect3D(origin: point, size: .zero))
}
// bounds: origin (1, -1, 0), size (3, 6, 0)

Negative sizes. A Rect3D may have a negative size. min and max always return the smallest and largest corner, so intersects(_:), contains(_:), contains(point:), intersection(_:), union(_:) and Point3D.clamped(to:) behave as they do for standardized, and integral and applying(_:) return a rectangle with a non-negative size. == compares origin and size exactly as stored, so use standardized first when you need to compare two rectangles for equality.

JSON and infinite values. Rect3D.null and Rect3D.infinity hold infinite coordinates, which the default JSONEncoder rejects. To encode them, set nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity:negativeInfinity:nan:) on the encoder and the matching nonConformingFloatDecodingStrategy = .convertFromString(...) on the decoder. Avoid storing these sentinel values; prefer nil or check isNull before encoding.

Working with Coordinate Spaces

transform(from:) returns the transform that carries coordinates of the other space into this one. convert(value:from:) brings a value from another space into this one, and convert(value:to:) expresses a value of this space in another space.

Conventions

  • Row vectors. A point is transformed as a row vector, p * M, so the translation of a 4×4 transform is stored in its bottom row ([3, 0], [3, 1], [3, 2]). A * B applies A first and B second. ProjectiveTransform3D.isAffine is true when the last column is [0, 0, 0, 1], so a translation keeps a transform affine.
  • Rotations. Rotations are right-handed and counterclockwise when looking against the axis: a rotation of 90° about z maps x onto y. Rotation3D always stores a unit quaternion; a zero or non-finite quaternion becomes the identity.
  • Euler angles. EulerAngles.Order.xyz rotates about x first, then y, then z. .zxy rotates about z first, then x, then y. Quaternion3D.eulerAngles(order:) reverses them; at gimbal lock the third angle is reported as zero.
  • Scale, rotation and translation. AffineTransform3D(rotation:scale:translation:) rotates, then scales, then translates. A negative scale.width represents a reflection, and rotation is then a proper rotation.
  • Poses. Pose3D and ScaledPose3D map a point p to rotation * (scale * p) + position. Multiplying two scaled poses composes them as functions: (a * b)(p) = a(b(p)).
  • Directions and sizes. Vector3D.applying(_:) and Size3D.applying(_:) use only the linear part of an affine transform (translation does not move a vector), unlike Point3D.applying(_:).

Raycasting

let ray = Ray3D(origin: Point3D(x: 0, y: 0, z: -1), direction: Vector3D(x: 0, y: 0, z: 1))
let box = Rect3D(origin: Point3D(x: -0.5, y: -0.5, z: 0), size: Size3D(width: 1, height: 1, depth: 1))

if ray.intersects(box) {
    print("Hit!")
}

Installation

Swift Package Manager

Add the dependency to your Package.swift:

dependencies: [
    .package(
        url: "https://github.com/helbertgs/OpenSpatial.git",
        from: "0.1.0"
    )
],
targets: [
    .target(
        name: "MyTarget",
        dependencies: [
            .product(name: "OpenSpatial", package: "OpenSpatial")
        ]
    ),
]

Requirements

Component Version
Swift 6.0+

Supported Platforms

The project is continuously tested on:

  • macOS
  • Ubuntu Linux
  • Windows

Additional support is expected to work on:

  • iOS
  • tvOS
  • watchOS
  • WebAssembly (Wasm)
  • Android

Why OpenSpatial?

Feature OpenSpatial Apple Spatial
Open Source ✅ ❌
Linux ✅ ❌
Windows ✅ ❌
Android ✅ ❌
Wasm ✅ ❌

Use Cases

OpenSpatial can be used for:

  • 3D engines
  • CAD applications
  • Robotics
  • Simulators
  • AR/VR applications
  • Scientific visualization
  • Game development

Documentation

Full API documentation is generated with DocC and available in the docs/ folder and also in this link: OpenSpatial. You can also browse it locally by running:

swift package --disable-sandbox preview-documentation --target OpenSpatial

Contributing

Contributions are welcome!

Before contributing, please review:

License

OpenSpatial is released under the MIT License.