Fast vector struct that allows [i] and .xyz-operations in D?

与世无争的帅哥 提交于 2019-12-05 08:37:22

Overall, this looks pretty reasonable. For the purpose of assignment chaining, opAssign should arguably return v. However, in practice this is often overlooked and might cause a performance hit (I don't know). Unlike in D1, you can return static arrays from functions in D2.

As far as performance, the best way to think of this is at the assembly level. Assuming inlining is enabled, x() will almost certainly be inlined. Static arrays are stored directly in the struct without an extra layer of indirection. The instruction return data[0]; will cause the compiler to generate code to read from an offset from the beginning of the struct. This offset will be known at compile time. Therefore, most likely calling x() will generate exactly the same assembly instructions as if x were actually a public member variable.

One other possibility, though, would be to use an anonymous union and struct:

struct vec3f
{
    union {
        float[3] vec;

        struct {
            float x;
            float y;
            float z;
        }
    }

    alias vec this;  // For assignment of a float[3].

}

Note, though that alias this is fairly buggy right now, and you probably shouldn't use it yet unless you're willing to file some bug reports.

You can use opDispatch for swizzling of arbitrary depth. I'd also recommend templating your vector struct on size and type. Here's my version for comparison: tools.vector (D1, so swizzling is a bit more cumbersome).

You can use an array operation to copy the whole array in one shot in opAssign:

data[] = v[];
@property
    {
        float x(float f) { return data[0] = f; }
        float y(float f) { return data[1] = f; }
        float z(float f) { return data[2] = f; }
        float x() { return data[0]; }
        float y() { return data[1]; }
        float z() { return data[2]; }
    }

Why properties ?

I would suggest to drop these lines and make x, y and z public fields. This will also improve performance in non-inline mode. You can use union to have a data[3] array anyway.

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