Skip to content

Buffer Handling: Array of Structs

Hüseyin Tuğrul BÜYÜKIŞIK edited this page Apr 16, 2017 · 1 revision

As of v1.1.9, array of user-defined structs (such as Unity Game Engine's Vector3) can be wrapped as a ClArray<byte> with ClArray<byte>.wrapArrayOfStructs() method. Example:

Vector3 [] normals = new Vector3[64*64];
normalsGPU = ClArray<byte>.wrapArrayOfStructs(normals);

this pins the array and uses its pointer and releases the pin after it goes out of scope.

Warning: OpenCL kernel-side float3 is implemented as float4 in behind, so don't use it. Use primitives with index multiplication:

  __kernel void waveEquation( __global float *xyz,__global float *xyzn,__global float *xyzo,__global float * arguments)
  {
      int threadId=get_global_id(0);
      if(threadId<arguments[4])
      {
           float dx=xyz[threadId*3]-arguments[2];float dy=xyz[threadId*3+1]-arguments[3];float t=arguments[1];
           float ctr=arguments[0];float wave=0.02f*ctr*sin(40.0f*t+100.0f*sqrt(dx*dx+dy*dy));
           xyzo[threadId*3]=xyz[threadId*3]+xyzn[threadId*3]*wave; // wave equation for all surface vertices
           xyzo[threadId*3+1]=xyz[threadId*3+1]+xyzn[threadId*3+1]*wave; // wave equation for all surface vertices
           xyzo[threadId*3+2]=xyz[threadId*3+2]+xyzn[threadId*3+2]*wave; // wave equation for all surface vertices
      }
   }

in this example, indices are multiplied by 3 for floats instead of using float3s.