Unity-Technologies / Unity.Mathematics

The C# math library used in Unity providing vector types and math functions with a shader like syntax
Other
1.38k stars 156 forks source link

Is there a reason why sizeof(float4) is not predefined? #216

Closed bitinn closed 2 years ago

bitinn commented 2 years ago

Hi,

I am running into a niche usage issue trying to use sizeof(float4) and feed that into a compute buffer's stride parameter.

And compiler complains the following:

float4 does not have a predefined size, therefore sizeof can only be used in an unsafe context.

Is there a good reason for this? Like would there somehow be float4 with less or more precision?

If I use sizeof(float) * 4 as my compute buffer's stride value, would that have any problematic implications?

Thx!

unpacklo commented 2 years ago

The issue here is the layout of the four floats, not the precision of them. The CLR determines layout at runtime rather than compile time so you don't necessarily know what the exact layout will be until you execute. As to why we didn't do explicit layout, I'm not sure why, but I'll be asking around to see if someone else at Unity knows.

In any case, you can still do sizeof() with the unsafe context. At Unity, we prefer to use UnsafeUtility.SizeOf() https://docs.unity3d.com/ScriptReference/Unity.Collections.LowLevel.Unsafe.UnsafeUtility.SizeOf.html

bitinn commented 2 years ago

Thx