How do I rotate an arkit 4x4 matrix around Y using Apple's SIMD library?

左心房为你撑大大i 提交于 2019-12-08 02:01:12

问题


I am trying to implement some code based on an ARKit demo where someone used this helper function to place a waypoint

let rotationMatrix = MatrixHelper.rotateAboutY(
    degrees: bearing * -1
)

How can I implement the .rotateAboutY function using the SIMD library and not using GLKit? To make it easier, I could start from the origin point.

I'm not too handy with the matrix math so a more basic explanation would be helpful.


回答1:


The rotation around Y matrix is:

| cos(angle) 0 sin(angle)|
|      0    1    0       |
|-sin(angle) 0 cos(angle)|

Rotation counter-clockwise around Y:

|cos(angle) 0 -sin(angle)|
|    0      1       0    |
|sin(angle) 0  cos(angle)|

So, we can easily construct the matrix using simd (Accelerate Framework):

func makeRotationYMatrix(angle: Float) -> simd_float3x3 {
    let rows = [
        simd_float3(cos(angle), 0, -sin(angle)),
        simd_float3(0, 1, 0),
        simd_float3(-sin(angle), 0, cos(angle))
    ]

    return float3x3(rows: rows)
}

The angle here is in radians. More info here.




回答2:


Probably the best way to leverage the built-in SIMD library for such operations (at least, with "best" meaning "do the least math yourself") is to express rotations with quaternions and convert to matrices when needed.

  1. Construct a simd_quatf representing the axis-angle rotation you want to apply.
  2. Convert that quaternion to a 4x4 matrix.

You can do that with a one-line call :

let rotationMatrix = float4x4(simd_quatf(angle: radians, axis: axis))

Expanding to your "rotateAboutY" case:

let radians = degreesToRadians(-bearing) // degrees * .pi / 180
let yAxis = float3(0, 1, 0)
let rotationMatrix = float4x4(simd_quatf(angle: radians, axis: yAxis))

Of course, once you have a rotation matrix, you can apply it using the * or *= operator:

someNode.simdTransform *= rotationMatrix

If you find yourself doing something like this often, you might want to write an extension on float4x4.

Tip: By the way, in Swift (or C++ or Metal shader language) you don't need the simd_ prefix on most (but not all) SIMD types and global functions.



来源:https://stackoverflow.com/questions/45463627/how-do-i-rotate-an-arkit-4x4-matrix-around-y-using-apples-simd-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!