Hi, I apologise if my question is too basic, but I cannot find whether there is a way to have a generic 4x4 SIMD matrix? This is straightforward with vectors with SIMD4<T>
where T is the type e.g. Double, Int. But I cannot find something similar such as SIMD4x4<T>
. There are only the specialisations such as simd_double4x4
and so on.
That's correct. What's the question?
Note that the SIMDn<T>
vector types are defined in the standard library and are available on all platforms, but the matrix and quaternion types you refer to are defined in the Apple simd library on macOS, iOS, etc, so aren't actually part of "Swift" proper.
Oh that's good to know. My questions would be
-
Are there simd matrices in the standard library? moreover, generic 4x4 matrices? In that case, how can I import the standard library and not the Apple simd library?
-
If I am allow to ask, how would I achieve a generic 4x4 Simd Matrix in the Apple Simd library?
Thanks!
-
There are no matrix types, SIMD or otherwise, currently in the standard library.
-
This starts to get out of scope for the Swift forums, as it's a question about an Apple library API, but the following are all reasonable options:
a. Request via Feedback Assistant that generic matrix types be added to the Apple simd library.
b. Find a way to do what you want to do without generic matrix types.
c. Use a package that provides a generic small matrix type.
d. Implement your own generic matrix type as a struct built on the Swift vector types:
// Something like this: (note the `FloatingPoint` constraint; you
// mentioned matrices of integers, but that doesn't _quite_ make
// sense as the same thing, because the integers are not a field.
@frozen
struct Matrix4x4<T> where T: SIMDScalar, FloatingPoint {
// layout compatible with concrete SIMD types when T is float
// or double, so you can unsafeBitcast to or from those types.
var columns: (SIMD4<T>, SIMD4<T>, SIMD4<T>, SIMD4<T>)
}
extension Matrix4x4 {
// Properties, inits, methods, etc
}
If you decide to go with an external package, there are a couple of options mentioned in Vectors/Matrix in Swift Numerics that you might find useful.
Thank you for your answer. It was my first question in the forum and your answer gives me a good start
This is interesting, I'm wondering, is unsafeBitcast completely zero cost, and is there any reason that something like this could become layout incompatible with for example simd_float4x4 in the future (and if so, is that likely)?
simd_float4x4
is an ABI-stable type defined in a C header, so its layout is fixed. The layout of @frozen
structs is fixed. Struct layout is not formally defined in Swift, but a frozen struct cannot change, and these happen to be layout-compatible, so they will be layout compatible for all time.