Crate ndarray_cg

Source
Expand description

Ndarray extensions for computer graphics mathematics.

§🎯 ndarray_cg

High-performance computer graphics mathematics built on ndarray

A comprehensive matrix and linear algebra library specifically designed for computer graphics applications. Built on top of the powerful ndarray crate, ndarray_cg provides specialized functionality for 2D/3D transformations, graphics pipelines, and geometric operations with excellent performance characteristics.

§✨ Features

§🔄 Matrix Operations

  • 2D/3D/4D Matrices - Specialized matrix types for graphics (Mat2, Mat3, Mat4)
  • Row & Column Major - Support for both memory layouts
  • Operator Overloading - Natural mathematical syntax (+, -, *, etc.)
  • In-Place Operations - Memory-efficient computations

§🎮 Graphics Transformations

  • Rotation Matrices - 2D/3D rotation operations
  • Translation - Homogeneous coordinate translations
  • Scaling - Uniform and non-uniform scaling
  • Reflection - Mirror transformations
  • Shearing - Skew transformations

§🚀 Performance Optimized

  • SIMD Support - Vectorized operations via ndarray
  • Zero-Copy Views - Efficient memory access patterns
  • Stack Allocation - Small matrices on stack
  • Generic Types - Works with f32, f64, and other numeric types

§🔧 Developer Experience

  • Type Aliases - Convenient F32x2x2, F32x3x3, F32x4x4 types
  • Indexed Iteration - Multiple iteration patterns
  • Debug Support - Rich debugging and display traits

§📦 Installation

Add to your Cargo.toml:

ndarray_cg = { workspace = true, features = ["enabled"] }

§🚀 Quick Start

§Basic Matrix Operations

use ndarray_cg::*;

fn main() {
  // Create a 2x2 matrix using row-major layout
  // [ 1.0, 2.0 ]
  // [ 3.0, 4.0 ]
  let matrix = Mat2::from_row_major([1.0, 2.0, 3.0, 4.0]);
  
  // Create a rotation matrix (45 degrees)
  let rotation = mat2x2::rot(45.0f32.to_radians());
  
  // Apply rotation to the matrix
  let rotated = rotation * matrix;
  
  println!("Original: {:?}", matrix.raw_slice());
  println!("Rotated:  {:?}", rotated.raw_slice());
}

§Common Graphics Transformations

ⓘ
use ndarray_cg::*;
use std::f32::consts::PI;

fn graphics_example() {
  // 2D Rotation (45 degrees)
  let angle = PI / 4.0;
  let rotation = mat2x2::rot(angle);
  
  // 2D Scaling
  let scale = mat2x2::scale([2.0, 3.0]);
  
  // 2D Translation (using homogeneous coordinates)
  let translation = mat2x2h::translate([5.0, 10.0]);
  
  // Reflection across X-axis
  let reflect = mat2x2::reflect_x();
  
  // Shearing transformation
  let shear = mat2x2::shear([1.0, 0.5]);
  
  // Combine transformations
  let transform = translation * scale * rotation;
  println!("Combined transform: {:?}", transform.raw_slice());
}

§Matrix Arithmetic Operations

use ndarray_cg::*;

fn arithmetic_examples() {
  // Matrix addition
  let mat_a = F32x2x2::from_row_major([
    1.0, 2.0,
    3.0, 4.0,
  ]);
  let mat_b = F32x2x2::from_row_major([
    5.0, 6.0,
    7.0, 8.0,
  ]);
  
  // Using operator overloading (recommended)
  let result = &mat_a + &mat_b;
  
  // Or using explicit function calls
  let mut result2 = F32x2x2::default();
  d2::add(&mut result2, &mat_a, &mat_b);
  
  println!("Addition result: {:?}", result.raw_slice());
}

§Matrix Multiplication

use ndarray_cg::*;
use mat::DescriptorOrderRowMajor;

fn multiplication_example() {
  // 1x3 matrix
  let mat_a = Mat::<1, 3, f32, DescriptorOrderRowMajor>::from_row_major([
    1.0, 2.0, 3.0,
  ]);
  
  // 3x2 matrix  
  let mat_b = Mat::<3, 2, f32, DescriptorOrderRowMajor>::from_row_major([
    7.0, 8.0,
    9.0, 10.0,
    11.0, 12.0,
  ]);
  
  // Matrix multiplication: 1x3 * 3x2 = 1x2
  let result = &mat_a * &mat_b;
  println!("Multiplication result: {:?}", result.raw_slice()); // [58.0, 64.0]
}

§📖 API Reference

§Matrix Types

TypeDescriptionUse Case
Mat2 / F32x2x22x2 matrix2D transformations
Mat3 / F32x3x33x3 matrix2D homogeneous coords
Mat4 / F32x4x44x4 matrix3D transformations

§Transformation Functions

FunctionPurposeExample
mat2x2::rot(angle)2D rotationmat2x2::rot(PI / 4.0)
mat2x2::scale([sx, sy])2D scalingmat2x2::scale([2.0, 3.0])
mat2x2h::translate([tx, ty])2D translationmat2x2h::translate([5.0, 10.0])
mat2x2::reflect_x()X-axis reflectionmat2x2::reflect_x()
mat2x2::shear([shx, shy])Shearingmat2x2::shear([1.0, 0.5])

§Advanced Features

use ndarray_cg::*;
use mat::DescriptorOrderRowMajor;

fn advanced_features() {
  // Matrix iteration
  let matrix = Mat::<1, 2, f32, DescriptorOrderRowMajor>::from_row_major([1.0, 2.0]);
  
  // Iterate over matrix lanes (rows/columns)
  for value in matrix.lane_iter(0, 0) {
    println!("Value: {}", value);
  }
  
  // Indexed iteration
  for (index, value) in matrix.iter_indexed_msfirst() {
    println!("Index: {:?}, Value: {}", index, value);
  }
}

§🎯 Use Cases

  • 2D Game Development - Sprite transformations and camera systems
  • 3D Graphics Programming - Model-view-projection matrices
  • Computer Vision - Image transformations and homography
  • Animation Systems - Skeletal animation and keyframe interpolation
  • Physics Simulations - Coordinate system transformations

§🔧 Advanced Configuration

§Features

  • enabled - Core functionality (default)
  • full - All features enabled

§Memory Layout Options

ⓘ
use ndarray_cg::*;
use mat::{DescriptorOrderRowMajor, DescriptorOrderColumnMajor};

// Row-major (default for graphics)
let row_major = Mat::<2, 2, f32, DescriptorOrderRowMajor>::from_row_major([1.0, 2.0, 3.0, 4.0]);

// Column-major (for compatibility with certain graphics APIs)
let col_major = Mat::<2, 2, f32, DescriptorOrderColMajor>::default();

§⚡ Performance Notes

  • Built on ndarray’s highly optimized SIMD operations
  • Zero-cost abstractions over raw array operations
  • Efficient memory layouts for cache performance
  • Generic over numeric types (f32, f64, etc.)

Modules§

_private_phf_reexport_for_macro_if_phf_feature
Rust-PHF is a library to generate efficient lookup tables at compile time using perfect hash functions.
additional_attributes
Documentation for Additional Attributes
approx
Approximate equality for floating-point types can be determined using either relative difference or comparisons based on units in the last place (ULPs). Approximate equality for floating-point types can be determined using either relative difference or comparisons based on units in the last place (ULPs).
clone_dyn
d2
2D entities, like matrix and vector. Not the same as 2D in CG
derive
Derives.
exposed
Exposed namespace of the module.
general
General math traits. General math traits.
index
Multidimensional indices. Indices.
mat
Matrix and all related.
mat2x2
2D entities with 2 along both dimensions. Useful for 2D graphics.
mat2x2h
2D entities with 2+homogenous coordinate along both dimensions. Useful for 2D graphics.
mat3x3
3D entities with 3 along both dimensions. Useful for 3D graphics
mat3x3h
3D entities with 3+homogenous coordinate along both dimensions. Useful for 3D graphics.
mat4x4
General functions for 4x4 matrices
md
Multidimensional space. This module serves as a central interface for accessing and managing data within various structures. It organizes functionalities into distinct layers for clarity and modularity, separating data access from attribute management.
mem
Memort-related things.
nd
Ndarray things.
orphan
Orphan namespace of the module.
own
Own namespace of the module.
prelude
Prelude to use essentials: use my_module::prelude::*.
quaternion
This module defines the core data structure for quaternions, Quat<E>, along with common type aliases. Quaternions are used to represent rotations in 3D space in a compact and efficient manner, avoiding issues like gimbal lock.
vector
Vector things. Indices.

Macros§

abs_diff_eq
Approximate equality of using the absolute difference.
abs_diff_ne
Approximate inequality of using the absolute difference.
array
Create an Array with one, two, three, four, five, or six dimensions.
assert_abs_diff_eq
An assertion that delegates to abs_diff_eq!, and panics with a helpful error on failure.
assert_abs_diff_ne
An assertion that delegates to abs_diff_ne!, and panics with a helpful error on failure.
assert_relative_eq
An assertion that delegates to relative_eq!, and panics with a helpful error on failure.
assert_relative_ne
An assertion that delegates to relative_ne!, and panics with a helpful error on failure.
assert_ulps_eq
An assertion that delegates to ulps_eq!, and panics with a helpful error on failure.
assert_ulps_ne
An assertion that delegates to ulps_ne!, and panics with a helpful error on failure.
azip
Array zip macro: lock step function application across several arrays and producers.
from
Variadic constructor.
relative_eq
Approximate equality using both the absolute difference and relative based comparisons.
relative_ne
Approximate inequality using both the absolute difference and relative based comparisons.
s
Slice argument constructor.
ulps_eq
Approximate equality using both the absolute difference and ULPs (Units in Last Place).
ulps_ne
Approximate inequality using both the absolute difference and ULPs (Units in Last Place).

Structs§

AbsDiff
The requisite parameters for testing for approximate equality using a absolute difference based comparison.
ArrayBase
An n-dimensional array.
Axis
An axis index.
Dim
Dimension description.
Mat
A matrix structure.
NewAxis
Token to represent a new axis in a slice description.
Quat
Represents a quaternion using a 4D vector for its components [x, y, z, w].
Relative
The requisite parameters for testing for approximate equality using a relative based comparison.
Ulps
The requisite parameters for testing for approximate equality using an ULPs based comparison.
Vector
A vector structure.

Enums§

ParseError
The ParseError enum is a collection of all the possible reasons an enum can fail to parse from a string.

Traits§

AbsDiffEq
Equality that is defined using the absolute difference of two numbers.
Add
The addition operator +.
AddAssign
The addition assignment operator +=.
ArrayMut
A trait for accessing a mutable reference to a fixed-size array from a collection.
ArrayRef
A trait for accessing a reference to a fixed-size array from a collection.
AsArray
Argument conversion into an array view
AsBytes
Trait for borrowing data as byte slices. This trait abstracts the conversion of types that implement Pod (or collections thereof) into their raw byte representation as a slice (&[u8]).
AsIx2
Trait for converting a type into a 2-dimensional index (Ix2).
AsIx3
Trait for converting a type into a 3-dimensional index (Ix3).
AsStaticRefDeprecated
A cheap reference-to-reference conversion. Used to convert a value to a reference value with 'static lifetime within generic code.
CloneDyn
A trait to upcast a clonable entity and clone it. It’s implemented for all entities which can be cloned.
Collection
A trait for collections of scalars.
ConstLayout
Trait for setting values in a matrix.
ConstLength
A trait implemented for entities with known length at compile-time.
Dimension
Array shape and index trait.
Div
The division operator /.
DivAssign
The division assignment operator /=.
EnumCount
A trait for capturing the number of variants in Enum. This trait can be autoderived by strum_macros.
EnumMessage
Associates additional pieces of information with an Enum. This can be autoimplemented by deriving EnumMessage and annotating your variants with #[strum(message="...")].
EnumProperty
EnumProperty is a trait that makes it possible to store additional information with enum variants. This trait is designed to be used with the macro of the same name in the strum_macros crate. Currently, the only string literals are supported in attributes, the other methods will be implemented as additional attribute types become stabilized.
Error
Error is a trait representing the basic expectations for error values, i.e., values of type E in Result<T, E>.
From1
Constructor with single argument.
From2
Constructor with two arguments.
From3
Constructor with three arguments.
Indexable
Trait for objects that have an indexable dimension.
IndexingMut
Trait for indexing and iterating over matrix elements with mutable access.
IndexingRef
Trait for indexing and iterating over matrix elements.
Into
A value-to-value conversion that consumes the input value. The opposite of From.
Into1
value-to-value conversion that consumes the input value. Change left and rught, but keep semantic of `From1``.
IntoArray
The IntoArray trait is used to convert a collection into a fixed-size array.
IntoBytes
Trait for consuming data into an owned byte vector. This trait is for types that can be meaningfully converted into a Vec< u8 > by consuming the original value.
IntoEnumIterator
This trait designates that an Enum can be iterated over. It can be auto generated using strum_macros on your behalf.
IntoIterator
Conversion into an Iterator.
IntoVector
A trait for types that can be converted into a Vector.
LinalgScalar
Elements that support linear algebra operations.
MatEl
Trait for indicating that a type can be used as a matrix element.
MatWithShape
A trait indicate that matrix in case of referencing it can be interpreted as such having specified shape ROWS x COLS.
MatWithShapeMut
A trait indicate that matrix in case of mutable referencing it can be interpreted as such having specified shape ROWS x COLS.
Mul
The multiplication operator *.
MulAssign
The multiplication assignment operator *=.
NdFloat
Floating-point element types f32 and f64.
RawSlice
Provides immutable access to the underlying data of a collection as a flat slice.
RawSliceMut
Trait for accessing and modifying the underlying data of a collection as a mutable slice.
RelativeEq
Equality comparisons between two numbers using both the absolute difference and relative based comparisons.
Rotation
Trait for representing and manipulating rotations.
ScalarMut
Trait for setting values in a matrix.
ScalarRef
Trait for setting values in a matrix.
ShapeBuilder
A trait for Shape and D where D: Dimension that allows customizing the memory layout (strides) of an array shape.
StrideTrait
Trait for objects that have a stride.
Sub
The subtraction operator -.
SubAssign
The subtraction assignment operator -=.
Sum
Trait to represent types that can be created by summing up an iterator.
TryInto
An attempted conversion that consumes self, which may or may not be expensive.
UlpsEq
Equality comparisons between two numbers using both the absolute difference and ULPs (Units in Last Place) based comparisons.
VariantIterator
VariantMetadata
VariantNames
A trait for retrieving the names of each variant in Enum. This trait can be autoderived by strum_macros.
VectorIter
Trait to get iterator over elements of a vector. Should be implemented even for scalars.
VectorIterMut
Trait to get iterator over elements of a vector.
VectorIterator
Trait that encapsulates an vector elements iterator with specific characteristics and implemetning CloneDyn.
VectorIteratorRef
Trait that encapsulates an vector elements iterator with specific characteristics and implemetning CloneDyn.
VectorSpace
A marker trait that groups together the essential immutable behaviors of a fixed-size vector.
VectorSpaceMut
A marker trait that extends VectorSpace with mutable iteration capabilities.
VectorWithLength
A trait indicate that entity in case of referencing it can be interpreted as such having specified length LEN.
VectorWithLengthMut
A trait indicate that entity in case of mutable referencing it can be interpreted as such having specified length LEN.
Zero
Defines an additive identity element for Self.

Functions§

Dim
Create a new dimension value.
Ix0
Create a zero-dimensional index
Ix1
Create a one-dimensional index
Ix2
Create a two-dimensional index
Ix3
Create a three-dimensional index
Ix4
Create a four-dimensional index
Ix5
Create a five-dimensional index
Ix6
Create a six-dimensional index
IxDyn
Create a dynamic-dimensional index
arr0
Create a zero-dimensional array with the element x.
arr1
Create a one-dimensional array with elements from xs.
arr2
Create a two-dimensional array with elements from xs.
aview0
Create a zero-dimensional array view borrowing x.
aview1
Create a one-dimensional array view with elements borrowing xs.
aview2
Create a two-dimensional array view with elements borrowing xs.
aview_mut1
Create a one-dimensional read-write array view with elements borrowing xs.
clone
True clone which is applicable not only to clonable entities, but to trait objects implementing CloneDyn.
clone_into_box
Clone boxed dyn.

Type Aliases§

ArcArray
An array where the data has shared ownership and is copy on write.
Array
An array that owns its data uniquely.
Array0
zero-dimensional array
Array1
one-dimensional array
Array2
two-dimensional array
Array3
three-dimensional array
Array4
four-dimensional array
Array5
five-dimensional array
Array6
six-dimensional array
ArrayD
dynamic-dimensional array
ArrayView
A read-only array view.
ArrayView0
zero-dimensional array view
ArrayView1
one-dimensional array view
ArrayView2
two-dimensional array view
ArrayView3
three-dimensional array view
ArrayView4
four-dimensional array view
ArrayView5
five-dimensional array view
ArrayView6
six-dimensional array view
ArrayViewD
dynamic-dimensional array view
ArrayViewMut
A read-write array view.
ArrayViewMut0
zero-dimensional read-write array view
ArrayViewMut1
one-dimensional read-write array view
ArrayViewMut2
two-dimensional read-write array view
ArrayViewMut3
three-dimensional read-write array view
ArrayViewMut4
four-dimensional read-write array view
ArrayViewMut5
five-dimensional read-write array view
ArrayViewMut6
six-dimensional read-write array view
ArrayViewMutD
dynamic-dimensional read-write array view
CowArray
An array with copy-on-write behavior.
F32x1
A 1-dimensional vector of f32s.
F32x2
A 2-dimensional vector of f32s.
F32x3
A 3-dimensional vector of f32s.
F32x4
A 4-dimensional vector of f32s.
F32x2x2
Type aliases for 2x2 f32 column major matrix.
F32x3x3
Type aliases for 3x3 f32 column major matrix.
F32x4x4
Type aliases for 4x4 f32 column major matrix.
F64x1
A 1-dimensional vector of f64s.
F64x2
A 2-dimensional vector of f64s.
F64x3
A 3-dimensional vector of f64s.
F64x4
A 4-dimensional vector of f64s.
F64x2x2
Type aliases for 2x2 f64 column major matrix.
F64x3x3
Type aliases for 3x3 f64 column major matrix.
F64x4x4
Type aliases for 4x4 f64 column major matrix.
I32x1
A 1-dimensional vector of i32s.
I32x2
A 2-dimensional vector of i32s.
I32x3
A 3-dimensional vector of i32s.
I32x4
A 4-dimensional vector of i32s.
I64x1
A 1-dimensional vector of i64s.
I64x2
A 2-dimensional vector of i64s.
I64x3
A 3-dimensional vector of i64s.
I64x4
A 4-dimensional vector of i64s.
Ix
Array index type
Ix0
zero-dimensionial
Ix1
one-dimensional
Ix2
two-dimensional
Ix3
three-dimensional
Ix4
four-dimensional
Ix5
five-dimensional
Ix6
six-dimensional
IxDyn
dynamic-dimensional
Mat2
Type aliases for 2x2 matrix.
Mat3
Type aliases for 3x3 matrix.
Mat4
Type aliases for 4x4 matrix.
QuatF32
A type alias for a quaternion with f32 components.
QuatF64
A type alias for a quaternion with f64 components.
RawArrayView
A read-only array view without a lifetime.
RawArrayViewMut
A mutable array view without a lifetime.
U32x1
A 1-dimensional vector of u32s.
U32x2
A 2-dimensional vector of u32s.
U32x3
A 3-dimensional vector of u32s.
U32x4
A 4-dimensional vector of u32s.
U64x1
A 1-dimensional vector of u64s.
U64x2
A 2-dimensional vector of u64s.
U64x3
A 3-dimensional vector of u64s.
U64x4
A 4-dimensional vector of u64s.

Attribute Macros§

clone_dyn
Derive macro to generate former for a structure. Former is variation of Builder Pattern.
phantom
Provides an automatic PhantomData field for a struct based on its generic types.

Derive Macros§

Add
What #[derive(Add)] generates
AddAssign
What #[derive(AddAssign)] generates
AsMut
Derive macro to implement AsMut when-ever it’s possible to do automatically.
AsRef
Derive macro to implement AsRef when-ever it’s possible to do automatically.
AsRefStr
Converts enum variants to &'static str.
AsStaticStr
Constructor
What #[derive(Constructor)] generates
Deref
Derive macro to implement Deref when-ever it’s possible to do automatically.
DerefMut
Derive macro to implement Deref when-ever it’s possible to do automatically.
Display
Div
What #[derive(Mul)] generates
DivAssign
What #[derive(MulAssign)] generates
EnumCount
Add a constant usize equal to the number of variants.
EnumDiscriminants
Generate a new type with only the discriminant names.
EnumIs
Generated is_*() methods for each variant. E.g. Color.is_red().
EnumIter
Creates a new type that iterates of the variants of an enum.
EnumMessage
Add a verbose message to an enum variant.
EnumProperty
Add custom properties to enum variants.
EnumString
Converts strings to enum variants based on their name.
EnumTryAs
Generated try_as_*() methods for all tuple-style variants. E.g. Message.try_as_write().
EnumVariantNames
Implements Strum::VariantNames which adds an associated constant VARIANTS which is an array of discriminant names.
Error
Using #[derive(Error)]
From
Provides an automatic From implementation for struct wrapping a single value.
FromRepr
Add a function to enum that allows accessing variants by its discriminant
FromStr
Index
Provides an automatic Index trait implementation when-ever it’s possible.
IndexMut
Provides an automatic IndexMut trait implementation when-ever it’s possible.
InnerFrom
Derive macro to implement From converting outer type into inner when-ever it’s possible to do automatically.
Into
What #[derive(Into)] generates
IntoIterator
Using #[derive(IntoIterator)]
IntoStaticStr
Implements From<MyEnum> for &'static str on an enum.
IsVariant
What #[derive(IsVariant)] generates
Mul
What #[derive(Mul)] generates
MulAssign
What #[derive(MulAssign)] generates
New
Provides an automatic new implementation for struct wrapping a single value.
Not
Provides an automatic Not trait implementation for struct.
Sub
What #[derive(Add)] generates
SubAssign
What #[derive(AddAssign)] generates
Sum
Using #[derive(Sum)]
ToString
implements std::string::ToString on an enum
TryInto
What #[derive(TryInto)] generates
Unwrap
What #[derive(Unwrap)] generates
VariadicFrom
The derive_variadic_from macro is designed to provide a way to implement the From-like traits for structs with a variable number of fields, allowing them to be constructed from tuples of different lengths or from individual arguments. This functionality is particularly useful for creating flexible constructors that enable different methods of instantiation for a struct. By automating the implementation of traits, this macro reduces boilerplate code and enhances code readability and maintainability.