geo-nd 0.6.4

Traits and types particularly for 2D and 3D geometry with implementations for [float] and optionally SIMD
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/*a To do

remove indexing from quaternions

Add matrix trait which takes out most of the sqmatrix traits

Document and get transform to work

Fix rotate_x, rotate_y, rotate_z

quaternion distance functions?

*/
//a Documentation
#![warn(missing_docs)]
/*!

# Geometry library

This library provides for N-dimensional geometrical objects,
particularly *Vector*s, *Matrix*, *Quaternion* operations.

The underlying numeric type that must be supported for these
operations is either a type supporting [Num] - which includes integers - or
in most circumstances [Float]. Particularly the latter is
provided by f32 anf f64.

It provides libraries that provide functions that implement vector,
matrix and quaternion operations using arrays of values. For
quaternions this is `[F; 4]`, in the order i, j, k, r.

It additionally provides traits for [Vector], [Quaternion], and
[SqMatrix]. These traits provide consistent means of manipulating such
items, which are expected to be in some manner a wrapper around a
`[F;D]`, but with perhaps greater alignment restrictions. In theory
this could be a SIMD type.

The purpose of these traits is to provide simple access to the vector,
matrix, and quaternion operations using methods, rather than invoking
these operations through explicit function calls. For example,
quaternions can be multiplied together with `a*b`, rather than
invoking quat::multiply.

The library mirrors the operation of 'glm' in some sense.

The desire for the library is that it does not undergo much
development; it provides a stable and simple basis for operations that
are common mathematical operations, with no aim for it to grow into a
larger linear algebra library.

## Caveats

The functions in the library use const generics, but as const generic
evaulations are currently unstable it requires more consts than should
be required. For example, to create an identity square matrix the
`matrix::identity` function has the generic signature `<V:Num, const
D2:usize, const D:usize>`. The value of `D2` *must* equal `D*D`. The
function returns `[V; D2]`.

Ideally the function should just take D as a const generic argument
and the type would be `[V;D*D]`, but that is unstable (and there are
some other issues).

Additionally, the inference of a type for `V` is sometimes required to
be forced, so there may be a small amount of turbofish notation such
as `identity2::<f32>()`.

# Trait method policy

The purpose of the traits is to permit simple operation on arrays such
as `[f32;4]`, without necessarily requiring conversion of those arrays
into a specific type first. For example, it is simple to add `[1,2,3]`
to a Vector type without having to convert that first into a Vector
type - but it must also work for any Vector type too. Hence the
arguments to methods are generally `&[F; D]`.

However, for methods that return a (e.g.) Vector type (that is not
Self), this would force the caller to convert the resultant type back
to the required Vector type. The policy is therefore, for such
methods, to use a generic on the method `T:Deref<Target = [}>`; to
take an argument of type `&T`, and to return a `T`. This usually
requires T to also provide `From<F;D>`. These methods can be described
as 'apply M to type T to produce a modified T'. In general there will
then be a method on the type T that operates on '&mut T' and
explicitly takes a `&M'. These methods also return `&mut self` to
permit chaining.

For example, a matrix `M` can transform a vector `T` by using

```
    use geo_nd::{FArray, FArray2, SqMatrix, Vector};
    let t : FArray::<f32, 3> = [0.0, 1.0, 2.0].into();
    let m = FArray2::<f32, 3, 9>::identity();
    let mut t = m.transform(&t);
    // or
    t.transformed_by_m(&m);

```

The downside to this policy is that one cannot apply a matrix to transform an array `[F;D]`

```ignore
    use geo_nd::{FArray, FArray2, SqMatrix, Vector};
    let m = FArray2::<f32, 3, 9>::identity();
    let t = m.transform(&[1.0,3.0,5.0]);
```


# Function operation

The functions for geometry manipulation are provided in the [vector],
[matrix] and [quat] modules.

## Basic operation

```
use geo_nd::vector;
let y = [0., 1.];
let x = [1., 0.];
assert_eq!( vector::dot(&x, &y), 0., "Dot product of X and Y axis vectors is zero");
let xy = vector::add(x,&y,2.);
assert_eq!( xy, [1., 2.], "x + 2*y");
assert_eq!( vector::length_sq(&xy), (5.), "|x + 2*y|^2 = 5");
assert_eq!( vector::length(&xy), (5.0f64).sqrt(), "|x + 2*y| = sqrt(5)");
```

# Provided traits

The library provides traits for types that can be vectors, matrices, and quaternions.

## Vector

Types that provide [Vector] can be manipulated with negation, addition,
subtraction, and can be scaled with multiplication and division by
their 'float'; their components can be accessed through indexing
(e.g. `a[0]`) immutably and mutably.

 As non-traditional vector operations they can be piece-wise
multiplied and divided also, which can be useful in graphcis
applications; they can also be piece-wise added and subtracted from
using their 'float'.

They also support [Copy], [std::default::Default], [std::fmt::Debug], and [std::fmt::Display],
[serde::Serialize], [serde::Deserialize].

They provide AsRef for float arrays of length 4 and slices for fast import and export from memory structures.

### Vector3

Vector3 types are 3-element vectors, which are expected to usefullt provide a
[Vector::cross_product] method, which may not exist (in a simply
well defined manner) for other vector sizes.

## SqMatrix

Types that provide [SqMatrix] are square matrices that can be
manipulated with negation, addition, subtraction, and multiplicaton, and can be
scaled with multiplication and division by their 'float'; their
components can be accessed through indexing (e.g. `a[0]`) immutably and
mutably. The index is a usize, in row-major order (i.e. \[0\] is row
zero column zero, \[1\] is row 0 column 1, and \[nr\] is row 1 column 0
for a matrixt that is 'nr' by 'nc' rows by columns.)

 They can also be piece-wise added and subtracted from using their
'float'.

They also support [Copy], [std::default::Default], [std::fmt::Debug], and [std::fmt::Display],
[serde::Serialize], [serde::Deserialize].

They provide AsRef for float arrays of length 4 and slices for fast import and export from memory structures.


### SqMatrix4

Types that provide [SqMatrix4] are 4-by-4 matrices. Additional methods
are provided for graphics operations, and so the matrices are treated
as 3-by-3 transformation matrices with a translation vector and the
last element the distance scaling.

They provide [SqMatrix] and additionally support graphically-useful
constructors 'perspective' and 'look_at', and support translation by
vectors.

## Quaternion

Quaternions are a mathematical means for describing a 3 dimensional rotation around
the origin.

Types that provide [Quaternion] can be
manipulated with negation, addition, subtraction, multiplicaton, and division, and can be
scaled with multiplication and division by their 'float'.

They also support [Copy], [std::default::Default], [std::fmt::Debug], and [std::fmt::Display],
[serde::Serialize], [serde::Deserialize].

They Deref to their float arrays of length 4. The mapping of the
arrays is (i, j, k, r).

### Constructors

Types providing the [Quaternion] trait can be constructed from:

* a unit quaternion (1.0 + 0*i + 0*j + 0*k)

* (r,i,j,k) tuples

* the conjugate of another quaternion, i.e. (r,-i,-j,-k)

* a rotation around a `[F; 3]` axis by an angle (in radians)

* a rotation around one of the axes applied to another quaternion

* another quaternion applied to a rotation around one of the axes

* from a square matrix that describes a pure rotation (no scaling)

* that describes a rotation of a camera looking down the negative Z
  axis with the Y axis as up, to one looking along a specified
  direction with a (perpendicular) up direction

* the rotation that provides the shortest great circle path for one
  unit vector to another (the axis of the rotation is the
  perpendicular to both)

* the weighted average of a number of quaternions

The trait provides many application methods for quaternions, perhaps
the most important being [Quaternion::apply3] and
[Quaternion::apply4], which allow the quaternion to be applied to a
3-element or 4-element vector (the latter being common in graphics,
where the fourth element is usually 1 for a point, and 0 for a vector
translation).

# Provided types

The library provides types that simply wrap `f32` and `f64` arrays,
providing imlpementations of the traits and hence supporting vectors, matrices and quaternions. This is perhaps the
simplest way to use the library.

## Vector types

The [FArray] type is a wrapper around an N-element array of floats,
and it supports the [Vector] trait.

## SqMatrix types

The [FArray2] type is a wrapper around an N-by-N-element array of floats,
and it supports the [SqMatrix] trait.

## Quaternion types

The [QArray] type is a wrapper around an 4-element array of floats,
and it supports the [Quaternion] trait.

# Examples

## Two dimensions

```
// Import the traits
use geo_nd::{Vector, SqMatrix};

// Aliases for the types
pub type Point2D = geo_nd::FArray<f64, 2>;
pub type Mat2x2 = geo_nd::FArray2<f64, 2, 4>;

let x : Point2D = [1.0, 0.0].into();
let y : Point2D = [0.0, 1.0].into();

let c = 30.0_f64.to_radians().cos();
let s = 30.0_f64.to_radians().sin();
let rot30 : Mat2x2 = [c, -s, s, c].into();

let rot60 = rot30 * rot30;

// Rotating x anticlockwise by 30 and 60 should turn it into y
let is_it_y = rot60.transform(&rot30.transform(&x));

// Check that the distance between them is tiny
assert!((y-is_it_y).length_sq() < 1.0E-8);

assert!(y.distance(&is_it_y) < 1.0E-8);

let rot90 = rot60 * rot30;
let rot180 = rot90 * rot90;

let xy = x + y;
let is_it_zero = xy + rot180.transform(&xy);
assert!(is_it_zero.length() < 1.0E-8);
```

## Three dimensions

```
// Import the traits
use geo_nd::{Quaternion, SqMatrix, Vector};

// Aliases for the types
pub type Point3D = geo_nd::FArray<f64, 3>;
pub type Mat3x3 = geo_nd::FArray2<f64, 3, 9>;
pub type Point4D = geo_nd::FArray<f64, 4>;
pub type Quat = geo_nd::QArray<f64>;

let x : Point3D = [1., 0., 0.].into();
let y : Point3D = [0., 1., 0.].into();
let z : Point3D = [0., 0., 1.].into();

// qx rotates around the X axis by 90 degrees
// [X,0,0] is unchanged
// [0,1,0] maps to [0,0,1]
// [0,0,1] maps to [0,-1,0]
let qx = Quat::default().rotate_x(90.0_f64.to_radians());
assert!(z.distance(&y.apply_q3(&qx)) < 1.0E-8);
assert!(y.distance(&(-z).apply_q3(&qx)) < 1.0E-8);
assert!(x.distance(&(x).apply_q3(&qx)) < 1.0E-8);

// qy rotates around the Y axis by 90 degrees
// [1,0,0] maps to [0,0,-1]
// [0,Y,0] is unchanged
// [0,0,1] maps to [1,0,0]
let qy = Quat::default().rotate_y(90.0_f64.to_radians());
assert!(x.distance(&(z).apply_q3(&qy)) < 1.0E-8);
assert!(z.distance(&(-x).apply_q3(&qy)) < 1.0E-8);
assert!(y.distance(&(y).apply_q3(&qy)) < 1.0E-8);

// qx * qy applies qx to (qy applied to a vector)
// Hence this chains the qx mapping onto the qy mapping
// [1,0,0] -> [0,0,-1] -> [0,1,0]
// [0,1,0] -> [0,1,0] -> [0,0,1]
// [0,0,1] -> [1,0,0] -> [1,0,0]
//
// This is actually a 120 degree rotation around (1,1,1)
// (qy * qx is a 120 degree rotation around (1,-1,1))
let qxy = qx * qy;
assert!(y.distance(&(x).apply_q3(&qxy)) < 1.0E-8);
assert!(z.distance(&(y).apply_q3(&qxy)) < 1.0E-8);
assert!(x.distance(&(z).apply_q3(&qxy)) < 1.0E-8);

let mut m = Mat3x3::default();
qxy.set_rotation3(&mut m);
// qxy will be [0,0,1,  1,0,0, 0,1,0]
// give or take floating point errors
assert!((m.transform(&x) - y).length() < 1.0E-8);
assert!((m.transform(&y) - z).length() < 1.0E-8);
assert!((m.transform(&z) - x).length() < 1.0E-8);
```

# Trait discussion

The libraries operate on arrays `[F;D]`, and so types that implement
the Vector, Quaternion etc traits are expected to be wrappers around
such array (but perhaps with greater alignment restrictions).

An array `[f32/f64; D]` supports:

 *   `Copy`, `Clone`, `Debug`, `Default`, `PartialEq`, `PartialOrd`

 *   `Index<usize>` and `IndexMut<usize>`

 *   `IntoIterator` for T, &T, &mut T

 *   `PartialEq of` `[U;N]` and `[U]` (where T: PartialEq of U)

 *   `TryFrom` of `&[T]`, `Vec<T, A>`, `Box<[T]>` with mut where appropriate; some times for `&[F; D]` too

 *   `AsRef[T]`, `Borrow[T]` (and mut for those three)

 *   Serialize, Deserialize

Note: Hash is not supported as f32/f64 do not support it

Hence a [Vector] or [Quaternion] should provide:

 *   `Copy`, `Clone`, `Debug`, `Default`, `PartialEq`

 *   `Index<usize>` and `IndexMut<usize>`

 *   `Deref <Target = [F; D]>`, `DerefMut`

 *   `AsRef` and `AsMut of [F; D]`

 *   `From` of `&[F]`, `[F;D]`,  `&[F;D]`

 *   `Into` `[F;D]` (deref provides equivalent of `&[F; D]`)

 *   `TryFrom` of `&[F]`, `Vec<F>`

 *   `Serialize`, `Deserialize`

Note: Not `PartialOrd`, as vectors dont't have an ordering

 Addition/Subtraction/Multiplication/Division

 Add/Sub with Rhs of Self, &Self, Deref<Target = \[F;D\]> are
    *required* for utility; we cannot *require* the last of these, as
    Rust has no syntax for that.

 Mul/Div with Rhs of F, &F are *required* for utility; previous
    versions supported Self to do element-wise operations, which
    has been removed This is in part because it would need to work
    for Deref<Target = \[F;D\]>, but f32/f64 do not implement Deref,
    and they might in the future do so which breaks the F and &F
    operation.

 Not AsRef/Mut of \[F\], as \[F; D\] implement that, and Vector gets it through Deref

 Note AsRef<\[F\]> is implemented through Deref to \[F; D\]

 Note AsMut<\[F\]> is implemented through DerefMut to \[F; D\]

 if required, then it blocks Add<Deref<Target = \[F;D\]>>
!*/

//a Imports
mod macros;
pub(crate) use macros::{
    convert_traits, elementwise_traits, f_const, ref_traits, scale_by_f_traits, serialize_traits,
    unary_traits,
};

mod matrix_op;
mod matrixr_op;
mod quaternion_op;
mod traits;
mod vector_op;

mod farray;
mod farray2;
mod fqarray;
mod qarray;

//a Exports
pub use farray::FArray;
pub use farray2::FArray2;
pub use fqarray::FQArrayTrans;
pub use num_traits::cast;
pub use qarray::QArray;
pub use traits::{
    Float, Geometry2D, Geometry3D, Num, Quaternion, SqMatrix, SqMatrix2, SqMatrix3, SqMatrix4,
    Transform, Vector, Vector2, Vector3, Vector3D, Vector4,
};

/// Vector functions module
///
/// This module provides numerous N-dimensional vector operations operating on [Num; N] (or [Float; N]).
pub mod vector {
    pub use super::vector_op::*;
}

/// Quaternion module
pub mod quat {
    pub use super::quaternion_op::*;
}

/// Matrix library
pub mod matrix {
    pub use super::matrix_op::*;
    pub use super::matrixr_op::*;
}

//a Vector3D and Geometry3D for f32/f64 using FArray/FArray2
//ip Vector3D for f32
impl Vector3D<f32> for f32 {
    type Vec2 = FArray<f32, 2>;
    type Vec3 = FArray<f32, 3>;
    type Vec4 = FArray<f32, 4>;
}

//ip Geometry3D for f32
impl Geometry3D<f32> for f32 {
    type Vec3 = FArray<f32, 3>;
    type Vec4 = FArray<f32, 4>;
    type Mat3 = FArray2<f32, 3, 9>;
    type Mat4 = FArray2<f32, 4, 16>;
    type Quat = QArray<f32>;
    type Trans = FQArrayTrans<f32>;
}

//ip Geometry2D for f32
impl Geometry2D<f32> for f32 {
    type Vec2 = FArray<f32, 2>;
    type Mat2 = FArray2<f32, 2, 4>;
}

//ip Vector3D for f64
impl Vector3D<f64> for f64 {
    type Vec2 = FArray<f64, 2>;
    type Vec3 = FArray<f64, 3>;
    type Vec4 = FArray<f64, 4>;
}

//ip Geometry3D for f64
impl Geometry3D<f64> for f64 {
    type Vec3 = FArray<f64, 3>;
    type Vec4 = FArray<f64, 4>;
    type Mat3 = FArray2<f64, 3, 9>;
    type Mat4 = FArray2<f64, 4, 16>;
    type Quat = QArray<f64>;
    type Trans = FQArrayTrans<f64>;
}

//ip Geometry2D for f64
impl Geometry2D<f64> for f64 {
    type Vec2 = FArray<f64, 2>;
    type Mat2 = FArray2<f64, 2, 4>;
}

//a GLSL-compatible things - bit of a place holder currently
/// The [glsl] module is a place-holder for types that are compatible with GLSL
pub mod glsl {
    /// GLSL 2-component vector of float
    pub type Vec2 = [f32; 2];
    /// GLSL 3-component vector of float
    pub type Vec3 = [f32; 3];
    /// GLSL 4-component vector of float
    pub type Vec4 = [f32; 4];
    /// GLSL 2-component vector of double
    pub type DVec2 = [f64; 2];
    /// GLSL 3-component vector of double
    pub type DVec3 = [f64; 3];
    /// GLSL 4-component vector of double
    pub type DVec4 = [f64; 4];
    /// GLSL 2-component vector of signed integer
    pub type IVec2 = [i32; 2];
    /// GLSL 3-component vector of signed integer
    pub type IVec3 = [i32; 3];
    /// GLSL 4-component vector of signed integer
    pub type IVec4 = [i32; 4];
    /// GLSL 2x2 floating-point matrix
    pub type Mat2 = [f32; 4];
    /// GLSL 3x3 floating-point matrix
    pub type Mat3 = [f32; 9];
    /// GLSL 4x4 floating-point matrix
    pub type Mat4 = [f32; 16];
    /// GLSL 2x2 double-precision floating-point matrix
    pub type DMat2 = [f64; 4];
    /// GLSL 3x3double-precision floating-point matrix
    pub type DMat3 = [f64; 9];
    /// GLSL 4x4 double-precision floating-point matrix
    pub type DMat4 = [f64; 16];
}