Search Unity

(Jobs) Accessing Array of Structures as Array of Components of Structures (Native Slice Stride?)

Discussion in 'Burst' started by deep_deep, Jul 3, 2021.

  1. deep_deep

    deep_deep

    Joined:
    Aug 10, 2019
    Posts:
    16
    I have a structure like
    Code (CSharp):
    1. public struct Placement
    2. {
    3.     public float3 position;
    4.     public float3 forward;
    5.     public float3 up;
    6. }
    I have a
    NativeArray<Placement>
    that is required later. The jobs that fill the position, forward, and up of this struct are different and they require a
    NativeSlice<float3>
    each to write to. I would like to use this array of Placement structs as the input to these jobs (possibly having all 3 run in parallel without dependencies on each other). I DO NOT want to copy this AoS to three separate Arrays and back.

    I think NativeSlice.SliceWithStride comes into play here, but I can't tell from the horrendous documentation.

    Please don't provide me any alternatives. I know they exist, but I'd like a solution that fits the above criteria. Thank you!
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,759
    This has nothing to do with burst but...
    you are on the right track

    Code (CSharp):
    1. NativeArray<Placement> placement = new NativeArray<Placement>(1234, Allocator.Temp);
    2.  
    3. NativeSlice<float3> position = placement.Slice().SliceWithStride<float3>(0);
    4. NativeSlice<float3> forward = placement.Slice().SliceWithStride<float3>(12);
    5. NativeSlice<float3> up = placement.Slice().SliceWithStride<float3>(24);
    You're kind of playing with fire with these magic numbers though, so I'd usually do something like this to be a bit safer.

    Code (CSharp):
    1.     [StructLayout(LayoutKind.Explicit)]
    2.     public struct Placement
    3.     {
    4.         public const int PositionOffset = 0;
    5.         public const int ForwardOffset = 12;
    6.         public const int UpOffset = 24;
    7.    
    8.         [FieldOffset(PositionOffset)]
    9.         public float3 position;
    10.  
    11.         [FieldOffset(ForwardOffset)]
    12.         public float3 forward;
    13.  
    14.         [FieldOffset(UpOffset)]
    15.         public float3 up;
    16.     }
    Code (CSharp):
    1. NativeSlice<float3> position = placement.Slice().SliceWithStride<float3>(Placement.PositionOffset);
    2. NativeSlice<float3> forward = placement.Slice().SliceWithStride<float3>(Placement.ForwardOffset);
    3. NativeSlice<float3> up = placement.Slice().SliceWithStride<float3>(Placement.UpOffset);
     
    Last edited: Jul 4, 2021