2

I'm writing an OpenCL raytracer using JOCL (OpenCL bindings for Java). I want to pass an array of structs to my kernel. The struct looks like this:

struct Sphere {
    float3 center;
    float radius;
    int materialIndex;
};

and the kernel takes it as this:

__kernel void raytraceKernel(
    __constant struct Sphere *spheres,
    etc...

What is the best way to do this? Initially, the struct did not have the materialIndex field, so I simply created an array of floats in Java, populated it with center, radius, and padding, and sent it to the kernel. However, when I added materialIndex I decided to convert my program to use NIO buffers, which didn't work (data was corrupted).

Is there a better approach to passing an array of structs to a kernel with JOCL?

adrian
  • 1,439
  • 1
  • 15
  • 23
  • 1
    Does Java have `struct` yet? :) – Nowhere Man May 29 '20 at 17:41
  • @AlexRudenko The website for JOCL does have a `struct` class which supposedly makes passing structs easier, but the description suggests it is not too stable – adrian May 29 '20 at 17:48
  • 3
    For what it's worth, struct-of-arrays (in your case pass 3 arrays or even 5) is frequently faster in vector code than array-of-structs, due to memory access patterns and not needing to unpack values. So if array-of-structs is awkward on the Java side, that seems like another good reason to use multiple arrays of scalars. There are articles out there on the web which articulate the reasons better than I probably just have. [Wikipedia](https://en.wikipedia.org/wiki/AoS_and_SoA) is probably a decent starting point. (I realise this doesn't answer your actual question, hence comment, not answer.) – pmdj May 29 '20 at 18:53
  • @pmdj Thanks for the suggestion. Arrays of vectors does seem to be faster so I think I will go that way. – adrian May 29 '20 at 19:00
  • 2
    @AlexRudenko We're close: https://openjdk.java.net/jeps/359 . And regarding the actual question: pmdj is right: Use a struct-of-arrays for this case. The name look like being part of a ray tracer, and there are things like https://github.com/mambastudio/MambaTracer that (IIRC) use the "JOCL structs" (that have eventually been moved to https://github.com/gpu/JOCLStructs ), but as the README says: The library should be considered to be experimental, because structs are difficult... – Marco13 Jun 14 '20 at 01:51

0 Answers0