I recently got in touch with Java 8 and I'm trying to learn Lambda expressions. I want to do some graphics calculations, my code so far:
IntStream.range(0, (screenSize.width * screenSize.height)).parallel().forEach(id -> {
int x = id % screenSize.width;
int y = ((id-x) / screenSize.width);
/*look up what color this pixel is.*/
});
Now all this Code is for graphics, everything is basic Math (plus, minus, multiply, modulo), except for bufferedImage.getRGB(x, y)
and operations with java.awt.Color
, and it can be done for each pixel seperately.
Now the question: Is it possible to run this on the GPU? Or is this even automatically GPU-based? (I remember reading this somewhere, but I'm not sure)
The JavaVM implementation is free to implement the Java bytecode interpretation however it wants as long as the results are correct. It is free to run anything on the GPU when it wants to. However, I don't know of any Java implementation which does this currently. There is a project to add GPU acceleration to OpenJDK (Project Sumatra), and you guessed correctly: It focuses on the stream API because it was designed to write code which can be parallelized. But this is currently far from production-ready and currently it doesn't seem like there is anyone working on it.
When you want to run computations on the GPU from a Java program today, you will need a library which wraps a GPU computing API like OpenCL using the Java Native Interface (for OpenCL there is JOCL). Be prepared to learn a new programming language, because every GPU computing API takes instructions in a different language and none of them is very similar to Java.
It depends on what you are doing. If those really are general parallel computations, connecting GPGPU things like OpenCL may have its benefits, even though integrating it won't be easy.
However, you are doing graphics computatuons, as you said. It's what shaders are designed for. A vertex shader is run once per vertex, then unseen elements are cut, then the scene is split into fragments (size of a pixel each) and each of them is then run through a fragment shader.
I've worked with GLSL a bit, so I can tell your code looks quite simple in shaders. X and Y for each fragment are calculated in between vertex and a fragment shaders by interpolating vertex coordinates (that's how varying
variables work), texture sampling is done via texture2d
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With