user14629932
user14629932

Reputation:

Why do I need to initialize the struct with self.init() even if I assign all of the properties?

In simd_float4x4, columns is the only property, however, this won't work solely because I'm not calling self.init(). Everything would have been initialize anyway. Why is the compiler complaining? I saw something similar in this video, and it was working. Why can't I do it?

extension simd_float4x4 {
    init(ProjectionFrame: CGSize) {
        let Y = FOV(), FarZ = Float((Settings.VisibilityRange+1)*2), Z = FarZ / (NearZ - FarZ)
        columns = (vector_float4(Y / Float(ProjectionFrame.width / ProjectionFrame.height), 0, 0, 0), vector_float4(0, Y, 0, 0), vector_float4(0, 0, Z, -1), vector_float4(0, 0, Z * NearZ, 0))
    }
}

In the video I noticed this.

extension simd_float4x4 {
    init(translationX x: Float, x: Float, x: Float) {
        columns = (
            vector_float4(x, 0, 0, 0),
            vector_float4(0, x, 0, 0),
            vector_float4(0, 0, x, 0),
            vector_float4(0, 0, 0, 1)
        )
    }
}

And the compiler wasn't complaining. How come it's complaining for me?

Upvotes: 0

Views: 328

Answers (2)

user14629932
user14629932

Reputation:

Alternatively I could bridge it to C

#include <simd/simd.h>
matrix_float4x4 ProjectPerspective(const float Ratio) {
    const float Y = 1/tanf(Rad(Settings.FOV+15)), FarZ = (Settings.VisibilityRange+1)*32, Z = FarZ/(NearZ-FarZ);
    return (matrix_float4x4){.columns = {{Y/Ratio, 0, 0, 0}, {0, Y, 0, 0}, {0, 0, Z, -1}, {0, 0, Z*NearZ, 0}}};
}

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54755

Instead of trying to set columns from your init, you should just call self.init(_ columns:) and pass in the 4 vector_float4s as an Array rather than as a tuple.

extension simd_float4x4 {
    init(ProjectionFrame: CGSize) {
        let Y = FOV(), FarZ = Float((Settings.VisibilityRange+1)*2), Z = FarZ / (NearZ - FarZ)
        self.init([vector_float4(Y / Float(ProjectionFrame.width / ProjectionFrame.height), 0, 0, 0), vector_float4(0, Y, 0, 0), vector_float4(0, 0, Z, -1), vector_float4(0, 0, Z * NearZ, 0)])
    }
}

That video is 2 years old and hence uses an older Swift version. The code you link from that video also doesn't compile in Swift 5.

Unrelated to your question, but variable names in Swift should be lowerCamelCase, so projectionFrame is the correct naming.

Upvotes: 2

Related Questions