fluid-sim/src/main/java/electrosphere/opencl/CLProgram.java
2023-07-01 09:33:35 -04:00

71 lines
2.3 KiB
Java

package electrosphere.opencl;
import java.util.concurrent.CountDownLatch;
import org.lwjgl.opencl.CL30;
import org.lwjgl.opencl.CLProgramCallback;
import org.lwjgl.system.MemoryUtil;
/**
* Wrapper object for an opencl program
*/
public class CLProgram {
//the pointer to the program
long pointer;
/**
* Creates an opencl program from a context and a source
* @param context The context
* @param source The source
* @return The program
*/
protected static CLProgram createProgram(CLContext context, String source){
CLProgram program = new CLProgram();
//create object
program.pointer = CL30.clCreateProgramWithSource(context.getPointer(), source, context.getErrorCodeBuffer());
CLUtilities.checkCLError(context.getErrorCodeBuffer());
//latch for blocking execution until the program finishes compiling
CountDownLatch latch = new CountDownLatch(1);
//build the program
String options = "";
CLProgramCallback buildCallback;
int errcode = CL30.clBuildProgram(program.pointer, context.getDevice().getId(), options, buildCallback = CLProgramCallback.create((programId, user_data) -> {
System.out.println(String.format(
"The cl_program [0x%X] was built %s",
programId,
CLUtilities.getProgramBuildInfoInt(programId, context.getDevice().getId(), CL30.CL_PROGRAM_BUILD_STATUS) == CL30.CL_SUCCESS ? "successfully" : "unsuccessfully"
));
String log = CLUtilities.getProgramBuildInfoStringASCII(programId, context.getDevice().getId(), CL30.CL_PROGRAM_BUILD_LOG);
if (!log.isEmpty()) {
System.out.println(String.format("BUILD LOG:\n----\n%s\n-----", log));
}
latch.countDown();
}), MemoryUtil.NULL);
CLUtilities.checkCLError(errcode);
//Block execution until the program finishes building
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
buildCallback.free();
return program;
}
/**
* Gets the pointer for this program object
* @return The pointer as a long
*/
public long getPointer(){
return pointer;
}
}